Search in sources :

Example 1 with PermissionDeniedException

use of edu.stanford.bmir.protege.web.shared.permissions.PermissionDeniedException in project webprotege by protegeproject.

the class DispatchServiceCallbackWithProgress_TestCase method shouldCall_handlePermissionDeniedException.

@Test
public void shouldCall_handlePermissionDeniedException() {
    PermissionDeniedException exception = mock(PermissionDeniedException.class);
    UserInSession userInSession = mock(UserInSession.class);
    when(userInSession.isGuest()).thenReturn(false);
    when(exception.getUserInSession()).thenReturn(userInSession);
    callback.onFailure(exception);
    verify(callback, times(1)).handlePermissionDeniedException(exception);
    verify(messageDisplay, times(1)).displayPermissionDeniedErrorMessage();
}
Also used : PermissionDeniedException(edu.stanford.bmir.protege.web.shared.permissions.PermissionDeniedException) UserInSession(edu.stanford.bmir.protege.web.shared.app.UserInSession) Test(org.junit.Test)

Example 2 with PermissionDeniedException

use of edu.stanford.bmir.protege.web.shared.permissions.PermissionDeniedException in project webprotege by protegeproject.

the class DispatchServiceExecutorImpl method execute.

@Override
public <A extends Action<R>, R extends Result> DispatchServiceResultContainer execute(A action, RequestContext requestContext, ExecutionContext executionContext) throws ActionExecutionException, PermissionDeniedException {
    ActionHandler<A, R> actionHandler = null;
    final Thread thread = Thread.currentThread();
    String threadName = thread.getName();
    if (action instanceof ProjectAction) {
        ProjectAction projectAction = (ProjectAction) action;
        ProjectId projectId = projectAction.getProjectId();
        setTemporaryThreadName(thread, action, projectId);
        ProjectActionHandlerRegistry actionHanderRegistry = projectManager.getActionHandlerRegistry(projectId);
        actionHandler = actionHanderRegistry.getActionHandler(action);
    } else {
        setTemporaryThreadName(thread, action, null);
        actionHandler = handlerRegistry.getActionHandler(action);
    }
    RequestValidator validator = actionHandler.getRequestValidator(action, requestContext);
    RequestValidationResult validationResult = validator.validateAction();
    if (!validationResult.isValid()) {
        throw getPermissionDeniedException(requestContext.getUserId(), validationResult);
    }
    try {
        R result = actionHandler.execute(action, executionContext);
        return new DispatchServiceResultContainer(result);
    } catch (PermissionDeniedException e) {
        throw e;
    } catch (Exception e) {
        logger.error("An error occurred whilst executing an action", e);
        throw new ActionExecutionException(e);
    } finally {
        thread.setName(threadName);
    }
}
Also used : HasProjectId(edu.stanford.bmir.protege.web.shared.project.HasProjectId) ProjectId(edu.stanford.bmir.protege.web.shared.project.ProjectId) PermissionDeniedException(edu.stanford.bmir.protege.web.shared.permissions.PermissionDeniedException) PermissionDeniedException(edu.stanford.bmir.protege.web.shared.permissions.PermissionDeniedException)

Example 3 with PermissionDeniedException

use of edu.stanford.bmir.protege.web.shared.permissions.PermissionDeniedException in project webprotege by protegeproject.

the class CreateNewProjectActionHandler method execute.

@Nonnull
@Override
public CreateNewProjectResult execute(@Nonnull CreateNewProjectAction action, @Nonnull ExecutionContext executionContext) {
    try {
        UserId userId = executionContext.getUserId();
        if (!accessManager.hasPermission(forUser(userId), ApplicationResource.get(), CREATE_EMPTY_PROJECT)) {
            throw new PermissionDeniedException("You do not have permission to create new projects", userInSessionFactory.getUserInSession(userId));
        }
        NewProjectSettings newProjectSettings = action.getNewProjectSettings();
        if (newProjectSettings.hasSourceDocument()) {
            if (!accessManager.hasPermission(forUser(userId), ApplicationResource.get(), UPLOAD_PROJECT)) {
                throw new PermissionDeniedException("You do not have permission to upload projects", userInSessionFactory.getUserInSession(userId));
            }
        }
        ProjectId projectId = pm.createNewProject(newProjectSettings);
        if (!projectDetailsManager.isExistingProject(projectId)) {
            projectDetailsManager.registerProject(projectId, newProjectSettings);
            applyDefaultPermissions(projectId, userId);
        }
        return new CreateNewProjectResult(projectDetailsManager.getProjectDetails(projectId));
    } catch (OWLOntologyCreationException | OWLOntologyStorageException | IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : OWLOntologyCreationException(org.semanticweb.owlapi.model.OWLOntologyCreationException) NewProjectSettings(edu.stanford.bmir.protege.web.shared.project.NewProjectSettings) UserId(edu.stanford.bmir.protege.web.shared.user.UserId) ProjectId(edu.stanford.bmir.protege.web.shared.project.ProjectId) PermissionDeniedException(edu.stanford.bmir.protege.web.shared.permissions.PermissionDeniedException) CreateNewProjectResult(edu.stanford.bmir.protege.web.shared.project.CreateNewProjectResult) IOException(java.io.IOException) OWLOntologyStorageException(org.semanticweb.owlapi.model.OWLOntologyStorageException) Nonnull(javax.annotation.Nonnull)

Example 4 with PermissionDeniedException

use of edu.stanford.bmir.protege.web.shared.permissions.PermissionDeniedException in project webprotege by protegeproject.

the class DispatchServiceCallback_TestCase method shouldCall_handlePermissionDeniedException.

@Test
public void shouldCall_handlePermissionDeniedException() {
    PermissionDeniedException exception = mock(PermissionDeniedException.class);
    UserInSession userInSession = mock(UserInSession.class);
    when(userInSession.isGuest()).thenReturn(false);
    when(exception.getUserInSession()).thenReturn(userInSession);
    callback.onFailure(exception);
    verify(callback, times(1)).handlePermissionDeniedException(exception);
    verify(messageDisplay, times(1)).displayPermissionDeniedErrorMessage();
}
Also used : PermissionDeniedException(edu.stanford.bmir.protege.web.shared.permissions.PermissionDeniedException) UserInSession(edu.stanford.bmir.protege.web.shared.app.UserInSession) Test(org.junit.Test)

Example 5 with PermissionDeniedException

use of edu.stanford.bmir.protege.web.shared.permissions.PermissionDeniedException in project webprotege by protegeproject.

the class ChangeManager method applyChanges.

/**
 * Applies ontology changes to the ontologies contained within a project.
 *
 * @param userId                     The userId of the user applying the changes.  Not {@code null}.
 * @param changeListGenerator        A generator which creates a list of changes (based on the state of the project at
 *                                   the time of change application).  The idea behind passing in a change generator is that the list of changes to
 *                                   be applied can be created based on the state of the project immediately before they are applied.  This is
 *                                   necessary where the changes depend on the structure/state of the ontology.  This method guarantees that no third
 *                                   party
 *                                   ontology changes will take place between the {@link ChangeListGenerator#generateChanges(ChangeGenerationContext)}
 *                                   method being called and the changes being applied.
 * @return A {@link ChangeApplicationResult} that describes the changes which took place an any renaminings.
 * @throws NullPointerException      if any parameters are {@code null}.
 * @throws PermissionDeniedException if the user identified by {@code userId} does not have permssion to write to
 *                                   ontologies in this project.
 */
@Override
public <R> ChangeApplicationResult<R> applyChanges(final UserId userId, final ChangeListGenerator<R> changeListGenerator) throws PermissionDeniedException {
    // noinspection ResultOfMethodCallIgnored
    checkNotNull(userId);
    // noinspection ResultOfMethodCallIgnored
    checkNotNull(changeListGenerator);
    // Final check of whether the user can actually edit the project
    Subject subject = forUser(userId);
    ProjectResource projectResource = new ProjectResource(projectId);
    if (!accessManager.hasPermission(subject, projectResource, EDIT_ONTOLOGY.getActionId())) {
        throw new PermissionDeniedException("You do not have permission to edit this project", userInSessionFactory.getUserInSession(userId));
    }
    final List<OWLOntologyChange> appliedChanges;
    final ChangeApplicationResult<R> finalResult;
    // with true entity IRIs
    try {
        // Compute the changes that need to take place.  We don't allow any other writes here because the
        // generation of the changes may depend upon the state of the project
        changeProcesssingLock.lock();
        final ChangeGenerationContext context = new ChangeGenerationContext(userId);
        OntologyChangeList<R> gen = changeListGenerator.generateChanges(context);
        // We have our changes
        List<OWLOntologyChange> changes = gen.getChanges();
        // We coin fresh entities for places where tmp: is the scheme - the name for the entity comes from
        // the fragment
        final Map<IRI, IRI> iriRenameMap = new HashMap<>();
        final ChangeSetEntityCrudSession session = getEntityCrudKitHandler().createChangeSetSession();
        Set<OWLOntologyChange> changesToRename = new HashSet<>();
        List<OWLOntologyChange> freshEntityChanges = new ArrayList<>();
        for (OWLOntologyChange change : changes) {
            for (OWLEntity entity : change.getSignature()) {
                if (DataFactory.isFreshEntity(entity)) {
                    if (entity.isOWLClass()) {
                        if (!accessManager.hasPermission(subject, projectResource, CREATE_CLASS.getActionId())) {
                            throw new PermissionDeniedException("You do not have permission to create new classes", userInSessionFactory.getUserInSession(userId));
                        }
                    } else if (entity.isOWLObjectProperty() || entity.isOWLDataProperty() || entity.isOWLAnnotationProperty()) {
                        if (!accessManager.hasPermission(subject, projectResource, CREATE_PROPERTY.getActionId())) {
                            throw new PermissionDeniedException("You do not have permission to create new properties", userInSessionFactory.getUserInSession(userId));
                        }
                    } else if (entity.isOWLNamedIndividual()) {
                        if (!accessManager.hasPermission(subject, projectResource, CREATE_INDIVIDUAL.getActionId())) {
                            throw new PermissionDeniedException("You do not have permission to create new individuals", userInSessionFactory.getUserInSession(userId));
                        }
                    } else if (entity.isOWLDatatype()) {
                        if (!accessManager.hasPermission(subject, projectResource, CREATE_DATATYPE.getActionId())) {
                            throw new PermissionDeniedException("You do not have permission to create new datatypes", userInSessionFactory.getUserInSession(userId));
                        }
                    }
                    changesToRename.add(change);
                    IRI currentIRI = entity.getIRI();
                    if (!iriRenameMap.containsKey(currentIRI)) {
                        String shortName = DataFactory.getFreshEntityShortName(entity);
                        OWLEntityCreator<? extends OWLEntity> creator = getEntityCreator(session, userId, shortName, (EntityType<? extends OWLEntity>) entity.getEntityType());
                        freshEntityChanges.addAll(creator.getChanges());
                        IRI replacementIRI = creator.getEntity().getIRI();
                        iriRenameMap.put(currentIRI, replacementIRI);
                    }
                }
            }
        }
        List<OWLOntologyChange> allChangesIncludingRenames = new ArrayList<>();
        final OWLObjectDuplicator duplicator = new OWLObjectDuplicator(dataFactory, iriRenameMap);
        for (OWLOntologyChange change : changes) {
            if (changesToRename.contains(change)) {
                OWLOntologyChange replacementChange = getRenamedChange(change, duplicator);
                allChangesIncludingRenames.add(replacementChange);
            } else {
                allChangesIncludingRenames.add(change);
            }
        }
        allChangesIncludingRenames.addAll(freshEntityChanges);
        List<OWLOntologyChange> minimisedChanges = getMinimisedChanges(allChangesIncludingRenames);
        final EventTranslatorManager eventTranslatorManager = eventTranslatorManagerProvider.get();
        eventTranslatorManager.prepareForOntologyChanges(minimisedChanges);
        // Now we do the actual changing, so we lock the project here.  No writes or reads can take place whilst
        // we apply the changes
        final Optional<Revision> revision;
        try {
            projectChangeWriteLock.lock();
            ProjectOWLOntologyManager manager = ((ProjectOWLOntologyManager) rootOntology.getOWLOntologyManager());
            List<OWLOntologyChange> effectiveChanges = getEffectiveChanges(minimisedChanges);
            manager.getDelegate().applyChanges(effectiveChanges);
            appliedChanges = effectiveChanges;
            final RenameMap renameMap = new RenameMap(iriRenameMap);
            R renamedResult = getRenamedResult(changeListGenerator, gen.getResult(), renameMap);
            finalResult = new ChangeApplicationResult<>(renamedResult, appliedChanges, renameMap);
            if (!appliedChanges.isEmpty()) {
                Revision rev = logAndBroadcastAppliedChanges(userId, changeListGenerator, finalResult);
                revision = Optional.of(rev);
                projectDetailsRepository.setModified(projectId, rev.getTimestamp(), userId);
            } else {
                revision = Optional.empty();
            }
        } finally {
            // Release for reads
            projectChangeWriteLock.unlock();
        }
        if (revision.isPresent() && !(changeListGenerator instanceof SilentChangeListGenerator)) {
            List<ProjectEvent<?>> highLevelEvents = new ArrayList<>();
            Revision rev = revision.get();
            eventTranslatorManager.translateOntologyChanges(rev, finalResult, highLevelEvents);
            if (changeListGenerator instanceof HasHighLevelEvents) {
                highLevelEvents.addAll(((HasHighLevelEvents) changeListGenerator).getHighLevelEvents());
            }
            projectEventManager.postEvents(highLevelEvents);
            projectChangedWebhookInvoker.invoke(userId, rev.getRevisionNumber(), rev.getTimestamp());
        }
    } finally {
        changeProcesssingLock.unlock();
    }
    return finalResult;
}
Also used : OWLObjectDuplicator(org.semanticweb.owlapi.util.OWLObjectDuplicator) EventTranslatorManager(edu.stanford.bmir.protege.web.server.events.EventTranslatorManager) Subject(edu.stanford.bmir.protege.web.server.access.Subject) Revision(edu.stanford.bmir.protege.web.server.revision.Revision) ProjectResource(edu.stanford.bmir.protege.web.server.access.ProjectResource) PermissionDeniedException(edu.stanford.bmir.protege.web.shared.permissions.PermissionDeniedException) RenameMap(edu.stanford.bmir.protege.web.server.owlapi.RenameMap) ProjectEvent(edu.stanford.bmir.protege.web.shared.event.ProjectEvent)

Aggregations

PermissionDeniedException (edu.stanford.bmir.protege.web.shared.permissions.PermissionDeniedException)6 UserInSession (edu.stanford.bmir.protege.web.shared.app.UserInSession)3 ProjectId (edu.stanford.bmir.protege.web.shared.project.ProjectId)2 Test (org.junit.Test)2 Place (com.google.gwt.place.shared.Place)1 ProjectResource (edu.stanford.bmir.protege.web.server.access.ProjectResource)1 Subject (edu.stanford.bmir.protege.web.server.access.Subject)1 EventTranslatorManager (edu.stanford.bmir.protege.web.server.events.EventTranslatorManager)1 RenameMap (edu.stanford.bmir.protege.web.server.owlapi.RenameMap)1 Revision (edu.stanford.bmir.protege.web.server.revision.Revision)1 ProjectEvent (edu.stanford.bmir.protege.web.shared.event.ProjectEvent)1 CreateNewProjectResult (edu.stanford.bmir.protege.web.shared.project.CreateNewProjectResult)1 HasProjectId (edu.stanford.bmir.protege.web.shared.project.HasProjectId)1 NewProjectSettings (edu.stanford.bmir.protege.web.shared.project.NewProjectSettings)1 UserId (edu.stanford.bmir.protege.web.shared.user.UserId)1 IOException (java.io.IOException)1 Nonnull (javax.annotation.Nonnull)1 OWLOntologyCreationException (org.semanticweb.owlapi.model.OWLOntologyCreationException)1 OWLOntologyStorageException (org.semanticweb.owlapi.model.OWLOntologyStorageException)1 OWLObjectDuplicator (org.semanticweb.owlapi.util.OWLObjectDuplicator)1