use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class AbstractEventEndpoint method deleteWorkflow.
@DELETE
@Path("{eventId}/workflows/{workflowId}")
@RestQuery(name = "deleteWorkflow", description = "Deletes a workflow", returnDescription = "The method doesn't return any content", pathParameters = { @RestParameter(name = "eventId", isRequired = true, description = "The event identifier", type = RestParameter.Type.STRING), @RestParameter(name = "workflowId", isRequired = true, description = "The workflow identifier", type = RestParameter.Type.INTEGER) }, reponses = { @RestResponse(responseCode = SC_BAD_REQUEST, description = "When trying to delete the latest workflow of the event."), @RestResponse(responseCode = SC_NOT_FOUND, description = "If the event or the workflow has not been found."), @RestResponse(responseCode = SC_NO_CONTENT, description = "The method does not return any content") })
public Response deleteWorkflow(@PathParam("eventId") String id, @PathParam("workflowId") long wfId) throws SearchIndexException {
final Opt<Event> optEvent = getIndexService().getEvent(id, getIndex());
try {
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 (wfId == optEvent.get().getWorkflowId()) {
return badRequest(String.format("Cannot delete current workflow %s from event %s." + " Only older workflows can be deleted.", wfId, id));
}
getWorkflowService().remove(wfId);
return Response.noContent().build();
} catch (WorkflowStateException e) {
return badRequest("Deleting is not allowed for current workflow state. EventId: " + id);
} catch (NotFoundException e) {
return notFound("Workflow not found: '%d'.", wfId);
} catch (UnauthorizedException e) {
return forbidden();
} catch (Exception e) {
return serverError();
}
}
use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class SeriesEndpoint method getSeries.
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("series.json")
@RestQuery(name = "listSeriesAsJson", description = "Returns the series matching the query parameters", returnDescription = "Returns the series search results as JSON", restParameters = { @RestParameter(name = "sortorganizer", isRequired = false, description = "The sort type to apply to the series organizer or organizers either Ascending or Descending.", type = STRING), @RestParameter(name = "sort", description = "The order instructions used to sort the query result. Must be in the form '<field name>:(ASC|DESC)'", isRequired = false, type = STRING), @RestParameter(name = "filter", isRequired = false, description = "The filter used for the query. They should be formated like that: 'filter1:value1,filter2,value2'", type = STRING), @RestParameter(name = "offset", isRequired = false, description = "The page offset", type = INTEGER, defaultValue = "0"), @RestParameter(name = "optedOut", isRequired = false, description = "Whether this series is opted out", type = BOOLEAN), @RestParameter(name = "limit", isRequired = false, description = "Results per page (max 100)", type = INTEGER, defaultValue = "100") }, reponses = { @RestResponse(responseCode = SC_OK, description = "The access control list."), @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If the current user is not authorized to perform this action") })
public Response getSeries(@QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("offset") int offset, @QueryParam("limit") int limit, @QueryParam("optedOut") Boolean optedOut) throws UnauthorizedException {
try {
logger.debug("Requested series list");
SeriesSearchQuery query = new SeriesSearchQuery(securityService.getOrganization().getId(), securityService.getUser());
Option<String> optSort = Option.option(trimToNull(sort));
if (offset != 0) {
query.withOffset(offset);
}
// If limit is 0, we set the default limit
query.withLimit(limit == 0 ? DEFAULT_LIMIT : limit);
if (optedOut != null)
query.withOptedOut(optedOut);
Map<String, String> filters = RestUtils.parseFilter(filter);
for (String name : filters.keySet()) {
if (SeriesListQuery.FILTER_ACL_NAME.equals(name)) {
query.withManagedAcl(filters.get(name));
} else if (SeriesListQuery.FILTER_CONTRIBUTORS_NAME.equals(name)) {
query.withContributor(filters.get(name));
} else if (SeriesListQuery.FILTER_CREATIONDATE_NAME.equals(name)) {
try {
Tuple<Date, Date> fromAndToCreationRange = RestUtils.getFromAndToDateRange(filters.get(name));
query.withCreatedFrom(fromAndToCreationRange.getA());
query.withCreatedTo(fromAndToCreationRange.getB());
} catch (IllegalArgumentException e) {
return RestUtil.R.badRequest(e.getMessage());
}
} else if (SeriesListQuery.FILTER_CREATOR_NAME.equals(name)) {
query.withCreator(filters.get(name));
} else if (SeriesListQuery.FILTER_TEXT_NAME.equals(name)) {
query.withText(QueryPreprocessor.sanitize(filters.get(name)));
} else if (SeriesListQuery.FILTER_LANGUAGE_NAME.equals(name)) {
query.withLanguage(filters.get(name));
} else if (SeriesListQuery.FILTER_LICENSE_NAME.equals(name)) {
query.withLicense(filters.get(name));
} else if (SeriesListQuery.FILTER_ORGANIZERS_NAME.equals(name)) {
query.withOrganizer(filters.get(name));
} else if (SeriesListQuery.FILTER_SUBJECT_NAME.equals(name)) {
query.withSubject(filters.get(name));
} else if (SeriesListQuery.FILTER_TITLE_NAME.equals(name)) {
query.withTitle(filters.get(name));
}
}
if (optSort.isSome()) {
Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
for (SortCriterion criterion : sortCriteria) {
switch(criterion.getFieldName()) {
case SeriesIndexSchema.TITLE:
query.sortByTitle(criterion.getOrder());
break;
case SeriesIndexSchema.CONTRIBUTORS:
query.sortByContributors(criterion.getOrder());
break;
case SeriesIndexSchema.CREATOR:
query.sortByOrganizers(criterion.getOrder());
break;
case SeriesIndexSchema.CREATED_DATE_TIME:
query.sortByCreatedDateTime(criterion.getOrder());
break;
case SeriesIndexSchema.MANAGED_ACL:
query.sortByManagedAcl(criterion.getOrder());
break;
default:
logger.info("Unknown filter criteria {}", criterion.getFieldName());
return Response.status(SC_BAD_REQUEST).build();
}
}
}
logger.trace("Using Query: " + query.toString());
SearchResult<Series> result = searchIndex.getByQuery(query);
if (logger.isDebugEnabled()) {
logger.debug("Found {} results in {} ms", result.getDocumentCount(), result.getSearchTime());
}
List<JValue> series = new ArrayList<>();
for (SearchResultItem<Series> item : result.getItems()) {
List<Field> fields = new ArrayList<>();
Series s = item.getSource();
String sId = s.getIdentifier();
fields.add(f("id", v(sId)));
fields.add(f("optedOut", v(s.isOptedOut())));
fields.add(f("title", v(s.getTitle(), Jsons.BLANK)));
fields.add(f("organizers", arr($(s.getOrganizers()).map(Functions.stringToJValue))));
fields.add(f("contributors", arr($(s.getContributors()).map(Functions.stringToJValue))));
if (s.getCreator() != null) {
fields.add(f("createdBy", v(s.getCreator())));
}
if (s.getCreatedDateTime() != null) {
fields.add(f("creation_date", v(toUTC(s.getCreatedDateTime().getTime()), Jsons.BLANK)));
}
if (s.getLanguage() != null) {
fields.add(f("language", v(s.getLanguage())));
}
if (s.getLicense() != null) {
fields.add(f("license", v(s.getLicense())));
}
if (s.getRightsHolder() != null) {
fields.add(f("rightsHolder", v(s.getRightsHolder())));
}
if (StringUtils.isNotBlank(s.getManagedAcl())) {
fields.add(f("managedAcl", v(s.getManagedAcl())));
}
series.add(obj(fields));
}
logger.debug("Request done");
return okJsonList(series, offset, limit, result.getHitCount());
} catch (Exception e) {
logger.warn("Could not perform search query: {}", ExceptionUtils.getStackTrace(e));
throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
}
}
use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class SeriesEndpoint method getSeriesPropertiesAsJson.
@SuppressWarnings("unchecked")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/properties")
@RestQuery(name = "getSeriesProperties", description = "Returns the series properties", returnDescription = "Returns the series properties as JSON", pathParameters = { @RestParameter(name = "id", description = "ID of series", isRequired = true, type = Type.STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "The access control list."), @RestResponse(responseCode = SC_UNAUTHORIZED, description = "If the current user is not authorized to perform this action") })
public Response getSeriesPropertiesAsJson(@PathParam("id") String seriesId) throws UnauthorizedException, NotFoundException {
if (StringUtils.isBlank(seriesId)) {
logger.warn("Series id parameter is blank '{}'.", seriesId);
return Response.status(BAD_REQUEST).build();
}
try {
Map<String, String> properties = seriesService.getSeriesProperties(seriesId);
JSONArray jsonProperties = new JSONArray();
for (String name : properties.keySet()) {
JSONObject property = new JSONObject();
property.put(name, properties.get(name));
jsonProperties.add(property);
}
return Response.ok(jsonProperties.toString()).build();
} catch (UnauthorizedException e) {
throw e;
} catch (NotFoundException e) {
throw e;
} catch (Exception e) {
logger.warn("Could not perform search query: {}", e.getMessage());
}
throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
}
use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class UsersEndpoint method deleteUser.
@DELETE
@Path("{username}.json")
@RestQuery(name = "deleteUser", description = "Deleter a new user", returnDescription = "Status ok", pathParameters = @RestParameter(name = "username", type = STRING, isRequired = true, description = "The username"), reponses = { @RestResponse(responseCode = SC_OK, description = "User has been deleted."), @RestResponse(responseCode = SC_FORBIDDEN, description = "Not enough permissions to delete a user with admin role."), @RestResponse(responseCode = SC_NOT_FOUND, description = "User not found.") })
public Response deleteUser(@PathParam("username") String username) throws NotFoundException {
Organization organization = securityService.getOrganization();
try {
jpaUserAndRoleProvider.deleteUser(username, organization.getId());
userDirectoryService.invalidate(username);
} catch (NotFoundException e) {
logger.error("User {} not found.", username);
return Response.status(SC_NOT_FOUND).build();
} catch (UnauthorizedException e) {
return Response.status(SC_FORBIDDEN).build();
} catch (Exception e) {
logger.error("Error during deletion of user {}: {}", username, e);
return Response.status(SC_INTERNAL_SERVER_ERROR).build();
}
logger.debug("User {} removed.", username);
return Response.status(SC_OK).build();
}
use of org.opencastproject.security.api.UnauthorizedException in project opencast by opencast.
the class UsersEndpoint method createUser.
@POST
@Path("/")
@RestQuery(name = "createUser", description = "Create a new user", returnDescription = "The location of the new ressource", restParameters = { @RestParameter(description = "The username.", isRequired = true, name = "username", type = STRING), @RestParameter(description = "The password.", isRequired = true, 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") }, reponses = { @RestResponse(responseCode = SC_CREATED, description = "User has been created."), @RestResponse(responseCode = SC_FORBIDDEN, description = "Not enough permissions to create a user with a admin role."), @RestResponse(responseCode = SC_CONFLICT, description = "An user with this username already exist.") })
public Response createUser(@FormParam("username") String username, @FormParam("password") String password, @FormParam("name") String name, @FormParam("email") String email, @FormParam("roles") String roles) throws NotFoundException {
if (StringUtils.isBlank(username))
return RestUtil.R.badRequest("No username set");
if (StringUtils.isBlank(password))
return RestUtil.R.badRequest("No password set");
User existingUser = jpaUserAndRoleProvider.loadUser(username);
if (existingUser != null) {
return Response.status(SC_CONFLICT).build();
}
JpaOrganization organization = (JpaOrganization) securityService.getOrganization();
Option<JSONArray> rolesArray = Option.none();
if (StringUtils.isNotBlank(roles)) {
rolesArray = Option.option((JSONArray) JSONValue.parse(roles));
}
Set<JpaRole> rolesSet = new HashSet<>();
// Add the roles given
if (rolesArray.isSome()) {
// Add the roles given
for (Object role : rolesArray.get()) {
JSONObject roleAsJson = (JSONObject) role;
Role.Type roletype = Role.Type.valueOf((String) roleAsJson.get("type"));
rolesSet.add(new JpaRole(roleAsJson.get("id").toString(), organization, null, roletype));
}
} else {
rolesSet.add(new JpaRole(organization.getAnonymousRole(), organization));
}
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 e) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
Aggregations