Search in sources :

Example 26 with UnauthorizedException

use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.

the class JpaUserProviderTest method testDuplicateUser.

@Test
public void testDuplicateUser() {
    Set<JpaRole> authorities1 = set(new JpaRole("ROLE_COOL_ONE", org1));
    Set<JpaRole> authorities2 = set(new JpaRole("ROLE_COOL_ONE", org2));
    try {
        provider.addUser(createUserWithRoles(org1, "user1", "ROLE_COOL_ONE"));
        provider.addUser(createUserWithRoles(org1, "user2", "ROLE_COOL_ONE"));
        provider.addUser(createUserWithRoles(org2, "user1", "ROLE_COOL_ONE"));
    } catch (UnauthorizedException e) {
        fail("User should be created");
    }
    try {
        provider.addUser(createUserWithRoles(org1, "user1", "ROLE_COOL_ONE"));
        fail("Duplicate user");
    } catch (Exception ignore) {
    }
}
Also used : JpaRole(org.opencastproject.security.impl.jpa.JpaRole) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) Test(org.junit.Test)

Example 27 with UnauthorizedException

use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.

the class AbstractEventEndpoint method updateEventWorkflow.

@PUT
@Path("{eventId}/workflows")
@RestQuery(name = "updateEventWorkflow", description = "Update the workflow configuration for the scheduled event with the given id", pathParameters = { @RestParameter(name = "eventId", description = "The event id", isRequired = true, type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(name = "configuration", isRequired = true, description = "The workflow configuration as JSON", type = RestParameter.Type.TEXT) }, reponses = { @RestResponse(description = "Request executed succesfully", responseCode = HttpServletResponse.SC_NO_CONTENT), @RestResponse(description = "No event with this identifier was found.", responseCode = HttpServletResponse.SC_NOT_FOUND) }, returnDescription = "The method does not retrun any content.")
public Response updateEventWorkflow(@PathParam("eventId") String id, @FormParam("configuration") String configuration) throws SearchIndexException, UnauthorizedException {
    Opt<Event> optEvent = getIndexService().getEvent(id, getIndex());
    if (optEvent.isNone())
        return notFound("Cannot find an event with id '%s'.", id);
    if (!optEvent.get().hasRecordingStarted()) {
        try {
            JSONObject configJSON;
            try {
                configJSON = (JSONObject) new JSONParser().parse(configuration);
            } catch (Exception e) {
                logger.warn("Unable to parse the workflow configuration {}", configuration);
                return badRequest();
            }
            Opt<Map<String, String>> caMetadataOpt = Opt.none();
            Opt<Map<String, String>> workflowConfigOpt = Opt.none();
            String workflowId = (String) configJSON.get("id");
            Map<String, String> caMetadata = new HashMap<>(getSchedulerService().getCaptureAgentConfiguration(id));
            if (!workflowId.equals(caMetadata.get(CaptureParameters.INGEST_WORKFLOW_DEFINITION))) {
                caMetadata.put(CaptureParameters.INGEST_WORKFLOW_DEFINITION, workflowId);
                caMetadataOpt = Opt.some(caMetadata);
            }
            Map<String, String> workflowConfig = new HashMap<>((JSONObject) configJSON.get("configuration"));
            Map<String, String> oldWorkflowConfig = new HashMap<>(getSchedulerService().getWorkflowConfig(id));
            if (!oldWorkflowConfig.equals(workflowConfig))
                workflowConfigOpt = Opt.some(workflowConfig);
            if (caMetadataOpt.isNone() && workflowConfigOpt.isNone())
                return Response.noContent().build();
            getSchedulerService().updateEvent(id, Opt.<Date>none(), Opt.<Date>none(), Opt.<String>none(), Opt.<Set<String>>none(), Opt.<MediaPackage>none(), workflowConfigOpt, caMetadataOpt, Opt.<Opt<Boolean>>none(), SchedulerService.ORIGIN);
            return Response.noContent().build();
        } catch (NotFoundException e) {
            return notFound("Cannot find event %s in scheduler service", id);
        } catch (SchedulerException e) {
            logger.error("Unable to update scheduling workflow data for event with id {}", id);
            throw new WebApplicationException(e, SC_INTERNAL_SERVER_ERROR);
        }
    } else {
        return badRequest(String.format("Event %s workflow can not be updated as the recording already started.", id));
    }
}
Also used : SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) NotFoundException(org.opencastproject.util.NotFoundException) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) EventCommentException(org.opencastproject.event.comment.EventCommentException) JSONException(org.codehaus.jettison.json.JSONException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowStateException(org.opencastproject.workflow.api.WorkflowStateException) JSONObject(org.json.simple.JSONObject) Event(org.opencastproject.index.service.impl.index.event.Event) JSONParser(org.json.simple.parser.JSONParser) Map(java.util.Map) HashMap(java.util.HashMap) Path(javax.ws.rs.Path) RestQuery(org.opencastproject.util.doc.rest.RestQuery) PUT(javax.ws.rs.PUT)

Example 28 with UnauthorizedException

use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.

the class AbstractEventEndpoint method workflowAction.

@PUT
@Path("{eventId}/workflows/{workflowId}/action/{action}")
@RestQuery(name = "workflowAction", description = "Performs the given action for the given workflow.", returnDescription = "", pathParameters = { @RestParameter(name = "eventId", description = "The id of the media package", isRequired = true, type = RestParameter.Type.STRING), @RestParameter(name = "workflowId", description = "The id of the workflow", isRequired = true, type = RestParameter.Type.STRING), @RestParameter(name = "action", description = "The action to take: STOP, RETRY or NONE (abort processing)", isRequired = true, type = RestParameter.Type.STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "Workflow resumed."), @RestResponse(responseCode = SC_NOT_FOUND, description = "Event or workflow instance not found."), @RestResponse(responseCode = SC_BAD_REQUEST, description = "Invalid action entered."), @RestResponse(responseCode = SC_UNAUTHORIZED, description = "You do not have permission to perform the action. Maybe you need to authenticate."), @RestResponse(responseCode = SC_INTERNAL_SERVER_ERROR, description = "An exception occurred.") })
public Response workflowAction(@PathParam("eventId") String id, @PathParam("workflowId") long wfId, @PathParam("action") String action) {
    if (StringUtils.isEmpty(id) || StringUtils.isEmpty(action)) {
        return badRequest();
    }
    try {
        final Opt<Event> optEvent = getIndexService().getEvent(id, getIndex());
        if (optEvent.isNone()) {
            return notFound("Cannot find an event with id '%s'.", id);
        }
        final WorkflowInstance wfInstance = getWorkflowService().getWorkflowById(wfId);
        if (!wfInstance.getMediaPackage().getIdentifier().toString().equals(id)) {
            return badRequest(String.format("Workflow %s is not associated to event %s", wfId, id));
        }
        if (RetryStrategy.NONE.toString().equalsIgnoreCase(action) || RetryStrategy.RETRY.toString().equalsIgnoreCase(action)) {
            getWorkflowService().resume(wfId, Collections.singletonMap("retryStrategy", action));
            return ok();
        }
        if (WORKFLOW_ACTION_STOP.equalsIgnoreCase(action)) {
            getWorkflowService().stop(wfId);
            return ok();
        }
        return badRequest("Action not supported: " + action);
    } catch (NotFoundException e) {
        return notFound("Workflow not found: '%d'.", wfId);
    } catch (IllegalStateException e) {
        return badRequest(String.format("Action %s not allowed for current workflow state. EventId: %s", action, id));
    } catch (UnauthorizedException e) {
        return forbidden();
    } catch (Exception e) {
        return serverError();
    }
}
Also used : UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) Event(org.opencastproject.index.service.impl.index.event.Event) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowInstance(org.opencastproject.workflow.api.WorkflowInstance) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) WebApplicationException(javax.ws.rs.WebApplicationException) EventCommentException(org.opencastproject.event.comment.EventCommentException) JSONException(org.codehaus.jettison.json.JSONException) JobEndpointException(org.opencastproject.adminui.exception.JobEndpointException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) ParseException(java.text.ParseException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) WorkflowDatabaseException(org.opencastproject.workflow.api.WorkflowDatabaseException) WorkflowStateException(org.opencastproject.workflow.api.WorkflowStateException) Path(javax.ws.rs.Path) RestQuery(org.opencastproject.util.doc.rest.RestQuery) PUT(javax.ws.rs.PUT)

Example 29 with UnauthorizedException

use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.

the class Protector method protect.

/**
 * Evaluate a product if the current user is authorized to perform the given actions.
 */
public <A> Protected<A> protect(final AccessControlList acl, List<String> actions, P1<A> p) {
    final User user = secSvc.getUser();
    final Organization org = secSvc.getOrganization();
    final Pred<String> isAuthorizedToDo = new Pred<String>() {

        @Override
        public Boolean apply(String action) {
            return AccessControlUtil.isAuthorized(acl, user, org, action);
        }
    };
    final boolean isAuthorized = $(actions).map(isAuthorizedToDo).foldl(false, or);
    return isAuthorized ? Protected.granted(p.get1()) : Protected.<A>rejected(new UnauthorizedException(user, $(actions).mkString(",")));
}
Also used : User(org.opencastproject.security.api.User) Organization(org.opencastproject.security.api.Organization) Pred(com.entwinemedia.fn.Pred) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException)

Example 30 with UnauthorizedException

use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.

the class UsersEndpoint method updateUser.

@PUT
@Path("{username}.json")
@RestQuery(name = "updateUser", description = "Update an user", returnDescription = "Status ok", restParameters = { @RestParameter(description = "The password.", isRequired = false, name = "password", type = STRING), @RestParameter(description = "The name.", isRequired = false, name = "name", type = STRING), @RestParameter(description = "The email.", isRequired = false, name = "email", type = STRING), @RestParameter(name = "roles", type = STRING, isRequired = false, description = "The user roles as a json array") }, pathParameters = @RestParameter(name = "username", type = STRING, isRequired = true, description = "The username"), reponses = { @RestResponse(responseCode = SC_OK, description = "User has been updated."), @RestResponse(responseCode = SC_FORBIDDEN, description = "Not enough permissions to update a user with admin role."), @RestResponse(responseCode = SC_NOT_FOUND, description = "User not found.") })
public Response updateUser(@PathParam("username") String username, @FormParam("password") String password, @FormParam("name") String name, @FormParam("email") String email, @FormParam("roles") String roles) throws NotFoundException {
    User user = jpaUserAndRoleProvider.loadUser(username);
    if (user == null) {
        throw new NotFoundException("User " + username + " does not exist.");
    }
    JpaOrganization organization = (JpaOrganization) securityService.getOrganization();
    Set<JpaRole> rolesSet = new HashSet<>();
    Option<JSONArray> rolesArray = Option.none();
    if (StringUtils.isNotBlank(roles)) {
        rolesArray = Option.some((JSONArray) JSONValue.parse(roles));
    }
    if (rolesArray.isSome()) {
        // Add the roles given
        for (Object roleObj : rolesArray.get()) {
            JSONObject role = (JSONObject) roleObj;
            String rolename = (String) role.get("id");
            Role.Type roletype = Role.Type.valueOf((String) role.get("type"));
            rolesSet.add(new JpaRole(rolename, organization, null, roletype));
        }
    } else {
        // Or the use the one from the user if no one is given
        for (Role role : user.getRoles()) {
            rolesSet.add(new JpaRole(role.getName(), organization, role.getDescription(), role.getType()));
        }
    }
    try {
        jpaUserAndRoleProvider.updateUser(new JpaUser(username, password, organization, name, email, jpaUserAndRoleProvider.getName(), true, rolesSet));
        userDirectoryService.invalidate(username);
        return Response.status(SC_OK).build();
    } catch (UnauthorizedException ex) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }
}
Also used : JpaUser(org.opencastproject.security.impl.jpa.JpaUser) User(org.opencastproject.security.api.User) JpaOrganization(org.opencastproject.security.impl.jpa.JpaOrganization) JSONArray(org.json.simple.JSONArray) NotFoundException(org.opencastproject.util.NotFoundException) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) Role(org.opencastproject.security.api.Role) JpaRole(org.opencastproject.security.impl.jpa.JpaRole) JSONObject(org.json.simple.JSONObject) JpaRole(org.opencastproject.security.impl.jpa.JpaRole) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) JSONObject(org.json.simple.JSONObject) JObject(com.entwinemedia.fn.data.json.JObject) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) RestQuery(org.opencastproject.util.doc.rest.RestQuery) PUT(javax.ws.rs.PUT)

Aggregations

UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)133 NotFoundException (org.opencastproject.util.NotFoundException)109 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)52 IOException (java.io.IOException)42 SchedulerConflictException (org.opencastproject.scheduler.api.SchedulerConflictException)39 SchedulerTransactionLockException (org.opencastproject.scheduler.api.SchedulerTransactionLockException)38 HttpResponse (org.apache.http.HttpResponse)37 SeriesException (org.opencastproject.series.api.SeriesException)36 WebApplicationException (javax.ws.rs.WebApplicationException)33 Path (javax.ws.rs.Path)29 RestQuery (org.opencastproject.util.doc.rest.RestQuery)29 ParseException (java.text.ParseException)28 MediaPackage (org.opencastproject.mediapackage.MediaPackage)27 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)26 AccessControlList (org.opencastproject.security.api.AccessControlList)22 ArrayList (java.util.ArrayList)21 User (org.opencastproject.security.api.User)21 WorkflowDatabaseException (org.opencastproject.workflow.api.WorkflowDatabaseException)21 HttpGet (org.apache.http.client.methods.HttpGet)19 Date (java.util.Date)18