Search in sources :

Example 66 with AccessControlList

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

the class AbstractEventEndpoint method applyAclToEvent.

@POST
@Path("{eventId}/access")
@RestQuery(name = "applyAclToEvent", description = "Immediate application of an ACL to an event", returnDescription = "Status code", pathParameters = { @RestParameter(name = "eventId", isRequired = true, description = "The event ID", type = STRING) }, restParameters = { @RestParameter(name = "acl", isRequired = true, description = "The ACL to apply", type = STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "The ACL has been successfully applied"), @RestResponse(responseCode = SC_BAD_REQUEST, description = "Unable to parse the given ACL"), @RestResponse(responseCode = SC_NOT_FOUND, description = "The the event has not been found"), @RestResponse(responseCode = SC_UNAUTHORIZED, description = "Not authorized to perform this action"), @RestResponse(responseCode = SC_INTERNAL_SERVER_ERROR, description = "Internal error") })
public Response applyAclToEvent(@PathParam("eventId") String eventId, @FormParam("acl") String acl) throws NotFoundException, UnauthorizedException, SearchIndexException, IndexServiceException {
    final AccessControlList accessControlList;
    try {
        accessControlList = AccessControlParser.parseAcl(acl);
    } catch (Exception e) {
        logger.warn("Unable to parse ACL '{}'", acl);
        return badRequest();
    }
    try {
        final Opt<Event> optEvent = getIndexService().getEvent(eventId, getIndex());
        if (optEvent.isNone()) {
            logger.warn("Unable to find the event '{}'", eventId);
            return notFound();
        }
        Source eventSource = getIndexService().getEventSource(optEvent.get());
        if (eventSource == Source.ARCHIVE) {
            if (getAclService().applyAclToEpisode(eventId, accessControlList, Option.<ConfiguredWorkflowRef>none())) {
                return ok();
            } else {
                logger.warn("Unable to find the event '{}'", eventId);
                return notFound();
            }
        } else if (eventSource == Source.WORKFLOW) {
            logger.warn("An ACL cannot be edited while an event is part of a current workflow because it might" + " lead to inconsistent ACLs i.e. changed after distribution so that the old ACL is still " + "being used by the distribution channel.");
            JSONObject json = new JSONObject();
            json.put("Error", "Unable to edit an ACL for a current workflow.");
            return conflict(json.toJSONString());
        } else {
            MediaPackage mediaPackage = getIndexService().getEventMediapackage(optEvent.get());
            mediaPackage = getAuthorizationService().setAcl(mediaPackage, AclScope.Episode, accessControlList).getA();
            getSchedulerService().updateEvent(eventId, Opt.<Date>none(), Opt.<Date>none(), Opt.<String>none(), Opt.<Set<String>>none(), some(mediaPackage), Opt.<Map<String, String>>none(), Opt.<Map<String, String>>none(), Opt.<Opt<Boolean>>none(), SchedulerService.ORIGIN);
            return ok();
        }
    } catch (AclServiceException e) {
        logger.error("Error applying acl '{}' to event '{}' because: {}", accessControlList, eventId, ExceptionUtils.getStackTrace(e));
        return serverError();
    } catch (SchedulerException e) {
        logger.error("Error applying ACL to scheduled event {} because {}", eventId, ExceptionUtils.getStackTrace(e));
        return serverError();
    }
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) Set(java.util.Set) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) 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) Source(org.opencastproject.index.service.api.IndexService.Source) Date(java.util.Date) Opt(com.entwinemedia.fn.data.Opt) JSONObject(org.json.simple.JSONObject) MediaPackage(org.opencastproject.mediapackage.MediaPackage) Event(org.opencastproject.index.service.impl.index.event.Event) Map(java.util.Map) HashMap(java.util.HashMap) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 67 with AccessControlList

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

the class AbstractEventEndpoint method getEventAccessInformation.

@GET
@Path("{eventId}/access.json")
@SuppressWarnings("unchecked")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "getEventAccessInformation", description = "Get the access information of an event", returnDescription = "The access information", pathParameters = { @RestParameter(name = "eventId", isRequired = true, description = "The event identifier", type = RestParameter.Type.STRING) }, reponses = { @RestResponse(responseCode = SC_BAD_REQUEST, description = "The required form params were missing in the request."), @RestResponse(responseCode = SC_NOT_FOUND, description = "If the event has not been found."), @RestResponse(responseCode = SC_OK, description = "The access information ") })
public Response getEventAccessInformation(@PathParam("eventId") String eventId) throws Exception {
    Opt<Event> optEvent = getIndexService().getEvent(eventId, getIndex());
    if (optEvent.isNone())
        return notFound("Cannot find an event with id '%s'.", eventId);
    // Add all available ACLs to the response
    JSONArray systemAclsJson = new JSONArray();
    List<ManagedAcl> acls = getAclService().getAcls();
    for (ManagedAcl acl : acls) {
        systemAclsJson.add(AccessInformationUtil.serializeManagedAcl(acl));
    }
    // Get the episode ACL
    final TransitionQuery q = TransitionQuery.query().withId(eventId).withScope(AclScope.Episode);
    List<EpisodeACLTransition> episodeTransistions;
    JSONArray transitionsJson = new JSONArray();
    try {
        episodeTransistions = getAclService().getTransitions(q).getEpisodeTransistions();
        for (EpisodeACLTransition trans : episodeTransistions) {
            transitionsJson.add(AccessInformationUtil.serializeEpisodeACLTransition(trans));
        }
    } catch (AclServiceException e) {
        logger.error("There was an error while trying to get the ACL transitions for series '{}' from the ACL service: {}", eventId, ExceptionUtils.getStackTrace(e));
        return RestUtil.R.serverError();
    }
    AccessControlList activeAcl = new AccessControlList();
    try {
        if (optEvent.get().getAccessPolicy() != null)
            activeAcl = AccessControlParser.parseAcl(optEvent.get().getAccessPolicy());
    } catch (Exception e) {
        logger.error("Unable to parse access policy because: {}", ExceptionUtils.getStackTrace(e));
    }
    Option<ManagedAcl> currentAcl = AccessInformationUtil.matchAcls(acls, activeAcl);
    JSONObject episodeAccessJson = new JSONObject();
    episodeAccessJson.put("current_acl", currentAcl.isSome() ? currentAcl.get().getId() : 0L);
    episodeAccessJson.put("acl", AccessControlParser.toJsonSilent(activeAcl));
    episodeAccessJson.put("privileges", AccessInformationUtil.serializePrivilegesByRole(activeAcl));
    episodeAccessJson.put("transitions", transitionsJson);
    if (StringUtils.isNotBlank(optEvent.get().getWorkflowState()) && WorkflowUtil.isActive(WorkflowInstance.WorkflowState.valueOf(optEvent.get().getWorkflowState())))
        episodeAccessJson.put("locked", true);
    JSONObject jsonReturnObj = new JSONObject();
    jsonReturnObj.put("episode_access", episodeAccessJson);
    jsonReturnObj.put("system_acls", systemAclsJson);
    return Response.ok(jsonReturnObj.toString()).build();
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) JSONArray(org.json.simple.JSONArray) ManagedAcl(org.opencastproject.authorization.xacml.manager.api.ManagedAcl) 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) TransitionQuery(org.opencastproject.authorization.xacml.manager.api.TransitionQuery) Event(org.opencastproject.index.service.impl.index.event.Event) EpisodeACLTransition(org.opencastproject.authorization.xacml.manager.api.EpisodeACLTransition) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 68 with AccessControlList

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

the class AclEndpoint method updateAcl.

@PUT
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "updateacl", description = "Update an ACL", returnDescription = "Update an ACL", pathParameters = { @RestParameter(name = "id", isRequired = true, description = "The ACL identifier", type = INTEGER) }, restParameters = { @RestParameter(name = "name", isRequired = true, description = "The ACL name", type = STRING), @RestParameter(name = "acl", isRequired = true, description = "The access control list", type = STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "The ACL has successfully been updated"), @RestResponse(responseCode = SC_NOT_FOUND, description = "The ACL has not been found"), @RestResponse(responseCode = SC_BAD_REQUEST, description = "Unable to parse the ACL") })
public Response updateAcl(@PathParam("id") long aclId, @FormParam("name") String name, @FormParam("acl") String accessControlList) throws NotFoundException {
    final Organization org = securityService.getOrganization();
    final AccessControlList acl = parseAcl.apply(accessControlList);
    final ManagedAclImpl managedAcl = new ManagedAclImpl(aclId, name, org.getId(), acl);
    if (!aclService().updateAcl(managedAcl)) {
        logger.info("No ACL with id '{}' could be found under organization '{}'", aclId, org.getId());
        throw new NotFoundException();
    }
    return RestUtils.okJson(full(managedAcl));
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) Organization(org.opencastproject.security.api.Organization) ManagedAclImpl(org.opencastproject.authorization.xacml.manager.impl.ManagedAclImpl) 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)

Example 69 with AccessControlList

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

the class SeriesEndpoint method getSeriesAccessInformation.

@GET
@Path("{seriesId}/access.json")
@SuppressWarnings("unchecked")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "getseriesaccessinformation", description = "Get the access information of a series", returnDescription = "The access information", pathParameters = { @RestParameter(name = "seriesId", isRequired = true, description = "The series identifier", type = Type.STRING) }, reponses = { @RestResponse(responseCode = SC_BAD_REQUEST, description = "The required form params were missing in the request."), @RestResponse(responseCode = SC_NOT_FOUND, description = "If the series has not been found."), @RestResponse(responseCode = SC_OK, description = "The access information ") })
public Response getSeriesAccessInformation(@PathParam("seriesId") String seriesId) throws NotFoundException {
    if (StringUtils.isBlank(seriesId))
        return RestUtil.R.badRequest("Path parameter series ID is missing");
    boolean hasProcessingEvents = hasProcessingEvents(seriesId);
    // Add all available ACLs to the response
    JSONArray systemAclsJson = new JSONArray();
    List<ManagedAcl> acls = getAclService().getAcls();
    for (ManagedAcl acl : acls) {
        systemAclsJson.add(AccessInformationUtil.serializeManagedAcl(acl));
    }
    final TransitionQuery q = TransitionQuery.query().withId(seriesId).withScope(AclScope.Series);
    List<SeriesACLTransition> seriesTransistions;
    JSONArray transitionsJson = new JSONArray();
    try {
        seriesTransistions = getAclService().getTransitions(q).getSeriesTransistions();
        for (SeriesACLTransition trans : seriesTransistions) {
            transitionsJson.add(AccessInformationUtil.serializeSeriesACLTransition(trans));
        }
    } catch (AclServiceException e) {
        logger.error("There was an error while trying to get the ACL transitions for serie '{}' from the ACL service: {}", seriesId, e);
        return RestUtil.R.serverError();
    }
    JSONObject seriesAccessJson = new JSONObject();
    try {
        AccessControlList seriesAccessControl = seriesService.getSeriesAccessControl(seriesId);
        Option<ManagedAcl> currentAcl = AccessInformationUtil.matchAcls(acls, seriesAccessControl);
        seriesAccessJson.put("current_acl", currentAcl.isSome() ? currentAcl.get().getId() : 0);
        seriesAccessJson.put("privileges", AccessInformationUtil.serializePrivilegesByRole(seriesAccessControl));
        seriesAccessJson.put("acl", AccessControlParser.toJsonSilent(seriesAccessControl));
        seriesAccessJson.put("transitions", transitionsJson);
        seriesAccessJson.put("locked", hasProcessingEvents);
    } catch (SeriesException e) {
        logger.error("Unable to get ACL from series {}: {}", seriesId, ExceptionUtils.getStackTrace(e));
        return RestUtil.R.serverError();
    }
    JSONObject jsonReturnObj = new JSONObject();
    jsonReturnObj.put("system_acls", systemAclsJson);
    jsonReturnObj.put("series_access", seriesAccessJson);
    return Response.ok(jsonReturnObj.toString()).build();
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) AclServiceException(org.opencastproject.authorization.xacml.manager.api.AclServiceException) SeriesACLTransition(org.opencastproject.authorization.xacml.manager.api.SeriesACLTransition) JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) ManagedAcl(org.opencastproject.authorization.xacml.manager.api.ManagedAcl) TransitionQuery(org.opencastproject.authorization.xacml.manager.api.TransitionQuery) SeriesException(org.opencastproject.series.api.SeriesException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 70 with AccessControlList

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

the class EventsEndpoint method eventToJSON.

/**
 * Transform an {@link Event} to Json
 *
 * @param event
 *          The event to transform into json
 * @param withAcl
 *          Whether to add the acl information for the event
 * @param withMetadata
 *          Whether to add all the metadata for the event
 * @param withPublications
 *          Whether to add the publications
 * @param withSignedUrls
 *          Whether to sign the urls if they are protected by stream security.
 * @return The event in json format.
 * @throws IndexServiceException
 *           Thrown if unable to get the metadata for the event.
 * @throws SearchIndexException
 *           Thrown if unable to get event publications from search service
 * @throws NotFoundException
 *           Thrown if unable to find all of the metadata
 */
protected JValue eventToJSON(Event event, Boolean withAcl, Boolean withMetadata, Boolean withPublications, Boolean withSignedUrls) throws IndexServiceException, SearchIndexException, NotFoundException {
    List<Field> fields = new ArrayList<>();
    if (event.getArchiveVersion() != null)
        fields.add(f("archive_version", v(event.getArchiveVersion())));
    fields.add(f("created", v(event.getCreated(), Jsons.BLANK)));
    fields.add(f("creator", v(event.getCreator(), Jsons.BLANK)));
    fields.add(f("contributor", arr($(event.getContributors()).map(Functions.stringToJValue))));
    fields.add(f("description", v(event.getDescription(), Jsons.BLANK)));
    fields.add(f("has_previews", v(event.hasPreview())));
    fields.add(f("identifier", v(event.getIdentifier(), BLANK)));
    fields.add(f("location", v(event.getLocation(), BLANK)));
    fields.add(f("presenter", arr($(event.getPresenters()).map(Functions.stringToJValue))));
    List<JValue> publicationIds = new ArrayList<>();
    if (event.getPublications() != null) {
        for (Publication publication : event.getPublications()) {
            publicationIds.add(v(publication.getChannel()));
        }
    }
    fields.add(f("publication_status", arr(publicationIds)));
    fields.add(f("processing_state", v(event.getWorkflowState(), BLANK)));
    fields.add(f("start", v(event.getTechnicalStartTime(), BLANK)));
    if (event.getTechnicalEndTime() != null) {
        long duration = new DateTime(event.getTechnicalEndTime()).getMillis() - new DateTime(event.getTechnicalStartTime()).getMillis();
        fields.add(f("duration", v(duration)));
    }
    if (StringUtils.trimToNull(event.getSubject()) != null) {
        fields.add(f("subjects", arr(splitSubjectIntoArray(event.getSubject()))));
    } else {
        fields.add(f("subjects", arr()));
    }
    fields.add(f("title", v(event.getTitle(), BLANK)));
    if (withAcl != null && withAcl) {
        AccessControlList acl = getAclFromEvent(event);
        fields.add(f("acl", arr(AclUtils.serializeAclToJson(acl))));
    }
    if (withMetadata != null && withMetadata) {
        try {
            Opt<MetadataList> metadata = getEventMetadata(event);
            if (metadata.isSome()) {
                fields.add(f("metadata", metadata.get().toJSON()));
            }
        } catch (Exception e) {
            logger.error("Unable to get metadata for event '{}' because: {}", event.getIdentifier(), ExceptionUtils.getStackTrace(e));
            throw new IndexServiceException("Unable to add metadata to event", e);
        }
    }
    if (withPublications != null && withPublications) {
        List<JValue> publications = getPublications(event, withSignedUrls);
        fields.add(f("publications", arr(publications)));
    }
    return obj(fields);
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) ArrayList(java.util.ArrayList) Publication(org.opencastproject.mediapackage.Publication) DateTime(org.joda.time.DateTime) SchedulerException(org.opencastproject.scheduler.api.SchedulerException) IngestException(org.opencastproject.ingest.api.IngestException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException) ConfigurationException(org.osgi.service.cm.ConfigurationException) SearchIndexException(org.opencastproject.matterhorn.search.SearchIndexException) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) ParseException(org.json.simple.parser.ParseException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) MetadataList(org.opencastproject.index.service.catalog.adapter.MetadataList) Field(com.entwinemedia.fn.data.json.Field) MetadataField(org.opencastproject.metadata.dublincore.MetadataField) JValue(com.entwinemedia.fn.data.json.JValue) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException)

Aggregations

AccessControlList (org.opencastproject.security.api.AccessControlList)108 NotFoundException (org.opencastproject.util.NotFoundException)46 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)38 AccessControlEntry (org.opencastproject.security.api.AccessControlEntry)30 MediaPackage (org.opencastproject.mediapackage.MediaPackage)27 Test (org.junit.Test)26 IOException (java.io.IOException)22 Organization (org.opencastproject.security.api.Organization)22 User (org.opencastproject.security.api.User)21 DublinCoreCatalog (org.opencastproject.metadata.dublincore.DublinCoreCatalog)19 ArrayList (java.util.ArrayList)18 SeriesException (org.opencastproject.series.api.SeriesException)18 ManagedAcl (org.opencastproject.authorization.xacml.manager.api.ManagedAcl)16 MediaPackageException (org.opencastproject.mediapackage.MediaPackageException)16 Date (java.util.Date)15 SchedulerException (org.opencastproject.scheduler.api.SchedulerException)14 Path (javax.ws.rs.Path)13 RestQuery (org.opencastproject.util.doc.rest.RestQuery)13 WebApplicationException (javax.ws.rs.WebApplicationException)12 File (java.io.File)10