Search in sources :

Example 16 with UnauthorizedException

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

the class SearchServiceDatabaseImpl method getOrganizationId.

/**
 * {@inheritDoc}
 *
 * @see org.opencastproject.search.impl.persistence.SearchServiceDatabase#getOrganizationId(String)
 */
@Override
public String getOrganizationId(String mediaPackageId) throws NotFoundException, SearchServiceDatabaseException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        SearchEntity searchEntity = getSearchEntity(mediaPackageId, em);
        if (searchEntity == null)
            throw new NotFoundException("No media package with id=" + mediaPackageId + " exists");
        // Ensure this user is allowed to read this media package
        String accessControlXml = searchEntity.getAccessControl();
        if (accessControlXml != null) {
            AccessControlList acl = AccessControlParser.parseAcl(accessControlXml);
            User currentUser = securityService.getUser();
            Organization currentOrg = securityService.getOrganization();
            if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, READ.toString()))
                throw new UnauthorizedException(currentUser + " is not authorized to read media package " + mediaPackageId);
        }
        return searchEntity.getOrganization();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not get deletion date {}: {}", mediaPackageId, e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SearchServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}
Also used : AccessControlList(org.opencastproject.security.api.AccessControlList) EntityTransaction(javax.persistence.EntityTransaction) EntityManager(javax.persistence.EntityManager) User(org.opencastproject.security.api.User) Organization(org.opencastproject.security.api.Organization) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) NoResultException(javax.persistence.NoResultException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException)

Example 17 with UnauthorizedException

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

the class SeriesRestService method getAllSeriesIdTitle.

@GET
@Path("allSeriesIdTitle.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "getAll", description = "Returns a list of identifier and title of all series", returnDescription = "Json list of identifier and title of all series", reponses = { @RestResponse(responseCode = SC_OK, description = "A list with series"), @RestResponse(responseCode = SC_FORBIDDEN, description = "A user is not allowed to list all series"), @RestResponse(responseCode = SC_INTERNAL_SERVER_ERROR, description = "Error while processing the request") })
public Response getAllSeriesIdTitle() {
    try {
        Map<String, String> allSeries = seriesService.getIdTitleMapOfAllSeries();
        JSONArray seriesJsonArr = new JSONArray();
        for (String seriesId : allSeries.keySet()) {
            JSONObject seriesJsonObj = new JSONObject();
            seriesJsonObj.put("identifier", seriesId);
            seriesJsonObj.put("title", allSeries.get(seriesId));
            seriesJsonArr.add(seriesJsonObj);
        }
        JSONObject resultJson = new JSONObject();
        resultJson.put("series", seriesJsonArr);
        return Response.ok(resultJson.toJSONString()).build();
    } catch (SeriesException ex) {
        return R.serverError();
    } catch (UnauthorizedException ex) {
        return R.forbidden();
    }
}
Also used : JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) 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 18 with UnauthorizedException

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

the class SeriesRestService method getSeriesPropertiesAsJson.

@SuppressWarnings("unchecked")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("{id}/properties.json")
@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(Response.Status.INTERNAL_SERVER_ERROR);
}
Also used : JSONObject(org.json.simple.JSONObject) WebApplicationException(javax.ws.rs.WebApplicationException) JSONArray(org.json.simple.JSONArray) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) ParseException(java.text.ParseException) SeriesException(org.opencastproject.series.api.SeriesException) WebApplicationException(javax.ws.rs.WebApplicationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) NotFoundException(org.opencastproject.util.NotFoundException) IOException(java.io.IOException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 19 with UnauthorizedException

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

the class UserAndSeriesLoader method loadLdapUser.

/**
 * Load a user for testing the ldap provider
 *
 * @param organizationId
 *          the organization
 */
protected void loadLdapUser(String organizationId) {
    Set<JpaRole> ldapUserRoles = new HashSet<>();
    ldapUserRoles.add(new JpaRole(USER_ROLE, getOrganization(organizationId)));
    // This is the public identifier for Josh Holtzman in the UC Berkeley Directory, which is available for anonymous
    // binding.
    String ldapUserId = "231693";
    if (jpaUserProvider.loadUser(ldapUserId, organizationId) == null) {
        try {
            jpaUserProvider.addUser(new JpaUser(ldapUserId, "ldap", getOrganization(organizationId), jpaUserProvider.getName(), true, ldapUserRoles));
            logger.debug("Added ldap user '{}' into organization '{}'", ldapUserId, organizationId);
        } catch (UnauthorizedException ex) {
            logger.error("Unable to add an administrative user because you have not enough permissions.");
        }
    }
}
Also used : JpaRole(org.opencastproject.security.impl.jpa.JpaRole) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) HashSet(java.util.HashSet)

Example 20 with UnauthorizedException

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

the class SeriesUpdatedEventHandler method handleEvent.

public void handleEvent(final SeriesItem seriesItem) {
    // A series or its ACL has been updated. Find any mediapackages with that series, and update them.
    logger.debug("Handling {}", seriesItem);
    String seriesId = seriesItem.getSeriesId();
    // We must be an administrative user to make this query
    final User prevUser = securityService.getUser();
    final Organization prevOrg = securityService.getOrganization();
    try {
        securityService.setUser(SecurityUtil.createSystemUser(systemAccount, prevOrg));
        SearchQuery q = new SearchQuery().withSeriesId(seriesId);
        SearchResult result = searchService.getForAdministrativeRead(q);
        for (SearchResultItem item : result.getItems()) {
            MediaPackage mp = item.getMediaPackage();
            Organization org = organizationDirectoryService.getOrganization(item.getOrganization());
            securityService.setOrganization(org);
            // to the distribution channels as well
            if (SeriesItem.Type.UpdateAcl.equals(seriesItem.getType())) {
                // Build a new XACML file for this mediapackage
                Attachment fileRepoCopy = authorizationService.setAcl(mp, AclScope.Series, seriesItem.getAcl()).getB();
                // Distribute the updated XACML file
                Job distributionJob = distributionService.distribute(CHANNEL_ID, mp, fileRepoCopy.getIdentifier());
                JobBarrier barrier = new JobBarrier(null, serviceRegistry, distributionJob);
                Result jobResult = barrier.waitForJobs();
                if (jobResult.getStatus().get(distributionJob).equals(FINISHED)) {
                    mp.remove(fileRepoCopy);
                    mp.add(getFromXml(serviceRegistry.getJob(distributionJob.getId()).getPayload()));
                } else {
                    logger.error("Unable to distribute XACML {}", fileRepoCopy.getIdentifier());
                    continue;
                }
            }
            // Update the series dublin core
            if (SeriesItem.Type.UpdateCatalog.equals(seriesItem.getType())) {
                DublinCoreCatalog seriesDublinCore = seriesItem.getMetadata();
                mp.setSeriesTitle(seriesDublinCore.getFirst(DublinCore.PROPERTY_TITLE));
                // Update the series dublin core
                Catalog[] seriesCatalogs = mp.getCatalogs(MediaPackageElements.SERIES);
                if (seriesCatalogs.length == 1) {
                    Catalog c = seriesCatalogs[0];
                    String filename = FilenameUtils.getName(c.getURI().toString());
                    URI uri = workspace.put(mp.getIdentifier().toString(), c.getIdentifier(), filename, dublinCoreService.serialize(seriesDublinCore));
                    c.setURI(uri);
                    // setting the URI to a new source so the checksum will most like be invalid
                    c.setChecksum(null);
                    // Distribute the updated series dc
                    Job distributionJob = distributionService.distribute(CHANNEL_ID, mp, c.getIdentifier());
                    JobBarrier barrier = new JobBarrier(null, serviceRegistry, distributionJob);
                    Result jobResult = barrier.waitForJobs();
                    if (jobResult.getStatus().get(distributionJob).equals(FINISHED)) {
                        mp.remove(c);
                        mp.add(getFromXml(serviceRegistry.getJob(distributionJob.getId()).getPayload()));
                    } else {
                        logger.error("Unable to distribute series catalog {}", c.getIdentifier());
                        continue;
                    }
                }
            }
            // Remove the series catalog and isPartOf from episode catalog
            if (SeriesItem.Type.Delete.equals(seriesItem.getType())) {
                mp.setSeries(null);
                mp.setSeriesTitle(null);
                boolean retractSeriesCatalog = retractSeriesCatalog(mp);
                boolean updateEpisodeCatalog = updateEpisodeCatalog(mp);
                if (!retractSeriesCatalog || !updateEpisodeCatalog)
                    continue;
            }
            // Update the search index with the modified mediapackage
            Job searchJob = searchService.add(mp);
            JobBarrier barrier = new JobBarrier(null, serviceRegistry, searchJob);
            barrier.waitForJobs();
        }
    } catch (SearchException e) {
        logger.warn("Unable to find mediapackages in search: ", e.getMessage());
    } catch (UnauthorizedException e) {
        logger.warn(e.getMessage());
    } catch (MediaPackageException e) {
        logger.warn(e.getMessage());
    } catch (ServiceRegistryException e) {
        logger.warn(e.getMessage());
    } catch (NotFoundException e) {
        logger.warn(e.getMessage());
    } catch (IOException e) {
        logger.warn(e.getMessage());
    } catch (DistributionException e) {
        logger.warn(e.getMessage());
    } finally {
        securityService.setOrganization(prevOrg);
        securityService.setUser(prevUser);
    }
}
Also used : SearchQuery(org.opencastproject.search.api.SearchQuery) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) User(org.opencastproject.security.api.User) Organization(org.opencastproject.security.api.Organization) SearchResultItem(org.opencastproject.search.api.SearchResultItem) SearchException(org.opencastproject.search.api.SearchException) NotFoundException(org.opencastproject.util.NotFoundException) SearchResult(org.opencastproject.search.api.SearchResult) Attachment(org.opencastproject.mediapackage.Attachment) IOException(java.io.IOException) JobBarrier(org.opencastproject.job.api.JobBarrier) URI(java.net.URI) Catalog(org.opencastproject.mediapackage.Catalog) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) Result(org.opencastproject.job.api.JobBarrier.Result) SearchResult(org.opencastproject.search.api.SearchResult) MediaPackage(org.opencastproject.mediapackage.MediaPackage) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) DistributionException(org.opencastproject.distribution.api.DistributionException) Job(org.opencastproject.job.api.Job) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog)

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