Search in sources :

Example 96 with UnauthorizedException

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

the class UserEndpoint method createUser.

@POST
@Path("/")
@RestQuery(name = "createUser", description = "Create a new  user", returnDescription = "Location of the new ressource", restParameters = { @RestParameter(name = "username", description = "The username.", isRequired = true, type = STRING), @RestParameter(name = "password", description = "The password.", isRequired = true, type = STRING), @RestParameter(name = "name", description = "The name.", isRequired = false, type = STRING), @RestParameter(name = "email", description = "The email.", isRequired = false, type = STRING), @RestParameter(name = "roles", description = "The user roles as a json array, for example: [\"ROLE_USER\", \"ROLE_ADMIN\"]", isRequired = false, type = STRING) }, reponses = { @RestResponse(responseCode = SC_BAD_REQUEST, description = "Malformed request syntax."), @RestResponse(responseCode = SC_CREATED, description = "User has been created."), @RestResponse(responseCode = SC_CONFLICT, description = "An user with this username already exist."), @RestResponse(responseCode = SC_FORBIDDEN, description = "Not enough permissions to create a user with the admin role.") })
public Response createUser(@FormParam("username") String username, @FormParam("password") String password, @FormParam("name") String name, @FormParam("email") String email, @FormParam("roles") String roles) {
    if (jpaUserAndRoleProvider.loadUser(username) != null) {
        return Response.status(SC_CONFLICT).build();
    }
    try {
        Set<JpaRole> rolesSet = parseRoles(roles);
        /* Add new user */
        logger.debug("Updating user {}", username);
        JpaOrganization organization = (JpaOrganization) securityService.getOrganization();
        JpaUser user = new JpaUser(username, password, organization, name, email, jpaUserAndRoleProvider.getName(), true, rolesSet);
        try {
            jpaUserAndRoleProvider.addUser(user);
            return Response.created(uri(endpointBaseUrl, user.getUsername() + ".json")).build();
        } catch (UnauthorizedException ex) {
            logger.debug("Create user failed", ex);
            return Response.status(Response.Status.FORBIDDEN).build();
        }
    } catch (IllegalArgumentException e) {
        logger.debug("Request with malformed ROLE data: {}", roles);
        return Response.status(SC_BAD_REQUEST).build();
    }
}
Also used : JpaOrganization(org.opencastproject.security.impl.jpa.JpaOrganization) JpaRole(org.opencastproject.security.impl.jpa.JpaRole) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 97 with UnauthorizedException

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

the class UserEndpoint method setUser.

@PUT
@Path("{username}.json")
@RestQuery(name = "updateUser", description = "Update an user", returnDescription = "Status ok", restParameters = { @RestParameter(name = "password", description = "The password.", isRequired = true, type = STRING), @RestParameter(name = "name", description = "The name.", isRequired = false, type = STRING), @RestParameter(name = "email", description = "The email.", isRequired = false, type = STRING), @RestParameter(name = "roles", description = "The user roles as a json array, for example: [\"ROLE_USER\", \"ROLE_ADMIN\"]", isRequired = false, type = STRING) }, pathParameters = @RestParameter(name = "username", description = "The username", isRequired = true, type = STRING), reponses = { @RestResponse(responseCode = SC_BAD_REQUEST, description = "Malformed request syntax."), @RestResponse(responseCode = SC_FORBIDDEN, description = "Not enough permissions to update a user with the admin role."), @RestResponse(responseCode = SC_OK, description = "User has been updated.") })
public Response setUser(@PathParam("username") String username, @FormParam("password") String password, @FormParam("name") String name, @FormParam("email") String email, @FormParam("roles") String roles) {
    try {
        User user = jpaUserAndRoleProvider.loadUser(username);
        if (user == null) {
            return createUser(username, password, name, email, roles);
        }
        Set<JpaRole> rolesSet = parseRoles(roles);
        logger.debug("Updating user {}", username);
        JpaOrganization organization = (JpaOrganization) securityService.getOrganization();
        jpaUserAndRoleProvider.updateUser(new JpaUser(username, password, organization, name, email, jpaUserAndRoleProvider.getName(), true, rolesSet));
        return Response.status(SC_OK).build();
    } catch (NotFoundException e) {
        logger.debug("User {} not found.", username);
        return Response.status(SC_NOT_FOUND).build();
    } catch (UnauthorizedException e) {
        logger.debug("Update user failed", e);
        return Response.status(Response.Status.FORBIDDEN).build();
    } catch (IllegalArgumentException e) {
        logger.debug("Request with malformed ROLE data: {}", roles);
        return Response.status(SC_BAD_REQUEST).build();
    }
}
Also used : User(org.opencastproject.security.api.User) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) JaxbUser(org.opencastproject.security.api.JaxbUser) JpaOrganization(org.opencastproject.security.impl.jpa.JpaOrganization) JpaRole(org.opencastproject.security.impl.jpa.JpaRole) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) Path(javax.ws.rs.Path) RestQuery(org.opencastproject.util.doc.rest.RestQuery) PUT(javax.ws.rs.PUT)

Example 98 with UnauthorizedException

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

the class JpaUserProviderTest method testDeleteUserNotAllowedAsNonAdmin.

@Test(expected = UnauthorizedException.class)
public void testDeleteUserNotAllowedAsNonAdmin() throws UnauthorizedException, Exception {
    JpaUser adminUser = createUserWithRoles(org1, "admin", "ROLE_ADMIN");
    JpaUser nonAdminUser = createUserWithRoles(org1, "user1", "ROLE_USER");
    try {
        provider.addUser(adminUser);
        provider.addUser(nonAdminUser);
    } catch (UnauthorizedException ex) {
        fail("The user shuld be created");
    }
    provider.setSecurityService(mockSecurityServiceWithUser(nonAdminUser));
    provider.deleteUser(adminUser.getUsername(), org1.getId());
    fail("An non admin user may not delete an admin user");
}
Also used : UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) Test(org.junit.Test)

Example 99 with UnauthorizedException

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

the class SchedulerRestService method updateEvent.

@PUT
@Path("{id}")
@RestQuery(name = "updaterecordings", description = "Updates specified event", returnDescription = "Status OK is returned if event was successfully updated, NOT FOUND if specified event does not exist or BAD REQUEST if data is missing or invalid", pathParameters = { @RestParameter(name = "id", description = "ID of event to be updated", isRequired = true, type = Type.STRING) }, restParameters = { @RestParameter(name = "start", isRequired = false, description = "Updated start date for event", type = Type.INTEGER), @RestParameter(name = "end", isRequired = false, description = "Updated end date for event", type = Type.INTEGER), @RestParameter(name = "agent", isRequired = false, description = "Updated agent for event", type = Type.STRING), @RestParameter(name = "users", isRequired = false, type = Type.STRING, description = "Updated comma separated list of user ids (speakers/lecturers) for the event"), @RestParameter(name = "mediaPackage", isRequired = false, description = "Updated media package for event", type = Type.TEXT), @RestParameter(name = "wfproperties", isRequired = false, description = "Workflow configuration properties", type = Type.TEXT), @RestParameter(name = "agentparameters", isRequired = false, description = "Updated Capture Agent properties", type = Type.TEXT), @RestParameter(name = "updateOptOut", isRequired = true, defaultValue = "false", description = "Whether to update the opt out status", type = Type.BOOLEAN), @RestParameter(name = "optOut", isRequired = false, description = "Update opt out status", type = Type.BOOLEAN), @RestParameter(name = "origin", isRequired = false, description = "The origin", type = Type.STRING) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_OK, description = "Event was successfully updated"), @RestResponse(responseCode = HttpServletResponse.SC_NOT_FOUND, description = "Event with specified ID does not exist"), @RestResponse(responseCode = HttpServletResponse.SC_CONFLICT, description = "Unable to update event, conflicting events found (ConflicsFound)"), @RestResponse(responseCode = HttpServletResponse.SC_CONFLICT, description = "Unable to update event, event locked by a transaction (TransactionLock)"), @RestResponse(responseCode = HttpServletResponse.SC_FORBIDDEN, description = "Event with specified ID cannot be updated"), @RestResponse(responseCode = HttpServletResponse.SC_UNAUTHORIZED, description = "You do not have permission to update the event. Maybe you need to authenticate."), @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "Data is missing or invalid") })
public Response updateEvent(@PathParam("id") String eventID, @FormParam("start") Long startTime, @FormParam("end") Long endTime, @FormParam("agent") String agentId, @FormParam("users") String users, @FormParam("mediaPackage") String mediaPackageXml, @FormParam("wfproperties") String workflowProperties, @FormParam("agentparameters") String agentParameters, @FormParam("updateOptOut") boolean updateOptOut, @FormParam("optOut") Boolean optOutBoolean, @FormParam("origin") String origin) throws UnauthorizedException {
    if (StringUtils.isBlank(origin))
        origin = SchedulerService.ORIGIN;
    if (startTime != null) {
        if (startTime < 0) {
            logger.debug("Cannot add event with negative start time ({} < 0)", startTime);
            return RestUtil.R.badRequest("Cannot add event with negative start time");
        }
        if (endTime != null && endTime <= startTime) {
            logger.debug("Cannot add event without proper end time ({} <= {})", startTime, endTime);
            return RestUtil.R.badRequest("Cannot add event without proper end time");
        }
    }
    MediaPackage mediaPackage = null;
    if (StringUtils.isNotBlank(mediaPackageXml)) {
        try {
            mediaPackage = MediaPackageParser.getFromXml(mediaPackageXml);
        } catch (Exception e) {
            logger.debug("Could not parse media packagey", e);
            return Response.status(Status.BAD_REQUEST).build();
        }
    }
    Map<String, String> caProperties = null;
    if (StringUtils.isNotBlank(agentParameters)) {
        try {
            Properties prop = parseProperties(agentParameters);
            caProperties = new HashMap<>();
            caProperties.putAll((Map) prop);
        } catch (Exception e) {
            logger.debug("Could not parse capture agent properties: {}", agentParameters, e);
            return Response.status(Status.BAD_REQUEST).build();
        }
    }
    Map<String, String> wfProperties = null;
    if (StringUtils.isNotBlank(workflowProperties)) {
        try {
            Properties prop = parseProperties(workflowProperties);
            wfProperties = new HashMap<>();
            wfProperties.putAll((Map) prop);
        } catch (IOException e) {
            logger.debug("Could not parse workflow configuration properties: {}", workflowProperties, e);
            return Response.status(Status.BAD_REQUEST).build();
        }
    }
    Set<String> userIds = null;
    String[] ids = StringUtils.split(StringUtils.trimToNull(users), ",");
    if (ids != null) {
        userIds = new HashSet<>(Arrays.asList(ids));
    }
    Date startDate = null;
    if (startTime != null) {
        startDate = new DateTime(startTime).toDateTime(DateTimeZone.UTC).toDate();
    }
    Date endDate = null;
    if (endTime != null) {
        endDate = new DateTime(endTime).toDateTime(DateTimeZone.UTC).toDate();
    }
    final Opt<Opt<Boolean>> optOut;
    if (updateOptOut) {
        optOut = Opt.some(Opt.nul(optOutBoolean));
    } else {
        optOut = Opt.none();
    }
    try {
        service.updateEvent(eventID, Opt.nul(startDate), Opt.nul(endDate), Opt.nul(StringUtils.trimToNull(agentId)), Opt.nul(userIds), Opt.nul(mediaPackage), Opt.nul(wfProperties), Opt.nul(caProperties), optOut, origin);
        return Response.ok().build();
    } catch (SchedulerTransactionLockException | SchedulerConflictException e) {
        return Response.status(Status.CONFLICT).entity(generateErrorResponse(e)).type(MediaType.APPLICATION_JSON).build();
    } catch (SchedulerException e) {
        logger.warn("Error updating event with id '{}'", eventID, e);
        return Response.status(Status.FORBIDDEN).build();
    } catch (NotFoundException e) {
        logger.info("Event with id '{}' does not exist.", eventID);
        return Response.status(Status.NOT_FOUND).build();
    } catch (UnauthorizedException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Unable to update event with id '{}'", eventID, e);
        return Response.serverError().build();
    }
}
Also used : SchedulerException(org.opencastproject.scheduler.api.SchedulerException) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) Properties(java.util.Properties) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) ParseException(java.text.ParseException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) Date(java.util.Date) DateTime(org.joda.time.DateTime) Opt(com.entwinemedia.fn.data.Opt) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) MediaPackage(org.opencastproject.mediapackage.MediaPackage) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) Path(javax.ws.rs.Path) RestQuery(org.opencastproject.util.doc.rest.RestQuery) PUT(javax.ws.rs.PUT)

Example 100 with UnauthorizedException

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

the class SchedulerRestService method prolongCapture.

@PUT
@Path("capture/{agent}/prolong")
@Produces(MediaType.TEXT_PLAIN)
@RestQuery(name = "prolongcapture", description = "Prolong an immediate capture.", returnDescription = "OK if event were successfully prolonged", pathParameters = { @RestParameter(name = "agent", isRequired = true, description = "The agent identifier", type = Type.STRING) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_OK, description = "Recording prolonged"), @RestResponse(responseCode = HttpServletResponse.SC_NOT_FOUND, description = "No recording found for prolonging"), @RestResponse(responseCode = HttpServletResponse.SC_UNAUTHORIZED, description = "You do not have permission to prolong this immediate capture. Maybe you need to authenticate."), @RestResponse(responseCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE, description = "The agent is not ready to communicate") })
public Response prolongCapture(@PathParam("agent") String agentId) throws NotFoundException, UnauthorizedException {
    if (service == null || agentService == null || prolongingService == null)
        return Response.serverError().status(Response.Status.SERVICE_UNAVAILABLE).entity("Scheduler service is unavailable, please wait...").build();
    try {
        MediaPackage event = prolongingService.getCurrentRecording(agentId);
        Opt<DublinCoreCatalog> dc = DublinCoreUtil.loadEpisodeDublinCore(workspace, event);
        prolongingService.prolongEvent(event, dc.get(), agentId);
        return Response.ok().build();
    } catch (NotFoundException e) {
        throw e;
    } catch (UnauthorizedException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Unable to prolong the immediate recording for agent '{}': {}", agentId, e);
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) MediaPackage(org.opencastproject.mediapackage.MediaPackage) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) SchedulerConflictException(org.opencastproject.scheduler.api.SchedulerConflictException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) SchedulerTransactionLockException(org.opencastproject.scheduler.api.SchedulerTransactionLockException) ParseException(java.text.ParseException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) 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