Search in sources :

Example 21 with Organization

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

the class VideoEditorTest method setUp.

/**
 * Setup for the video editor service, including creation of a mock workspace and all dependencies.
 *
 * @throws Exception
 *           if setup fails
 */
@Before
public void setUp() throws Exception {
    File tmpDir = folder.newFolder(getClass().getName());
    // output file
    tempFile1 = new File(tmpDir, "testoutput.mp4");
    /* mock the workspace for the input/output file */
    // workspace.get(new URI(sourceTrackUri));
    Workspace workspace = EasyMock.createMock(Workspace.class);
    EasyMock.expect(workspace.rootDirectory()).andReturn(tmpDir.getAbsolutePath());
    EasyMock.expect(workspace.get(track1.getURI())).andReturn(new File(track1.getURI())).anyTimes();
    EasyMock.expect(workspace.get(track2.getURI())).andReturn(new File(track2.getURI())).anyTimes();
    EasyMock.expect(workspace.putInCollection(EasyMock.anyString(), EasyMock.anyString(), EasyMock.anyObject(InputStream.class))).andAnswer(() -> {
        InputStream in = (InputStream) EasyMock.getCurrentArguments()[2];
        IOUtils.copy(in, new FileOutputStream(tempFile1));
        return tempFile1.toURI();
    });
    /* mock the role/org/security dependencies */
    User anonymous = new JaxbUser("anonymous", "test", new DefaultOrganization(), new JaxbRole(DefaultOrganization.DEFAULT_ORGANIZATION_ANONYMOUS, new DefaultOrganization()));
    UserDirectoryService userDirectoryService = EasyMock.createMock(UserDirectoryService.class);
    EasyMock.expect(userDirectoryService.loadUser((String) EasyMock.anyObject())).andReturn(anonymous).anyTimes();
    Organization organization = new DefaultOrganization();
    OrganizationDirectoryService organizationDirectoryService = EasyMock.createMock(OrganizationDirectoryService.class);
    EasyMock.expect(organizationDirectoryService.getOrganization((String) EasyMock.anyObject())).andReturn(organization).anyTimes();
    SecurityService securityService = EasyMock.createNiceMock(SecurityService.class);
    EasyMock.expect(securityService.getUser()).andReturn(anonymous).anyTimes();
    EasyMock.expect(securityService.getOrganization()).andReturn(organization).anyTimes();
    /* mock the osgi init for the video editor itself */
    BundleContext bc = EasyMock.createNiceMock(BundleContext.class);
    File storageDir = folder.newFolder();
    logger.info("storageDir: {}", storageDir);
    EasyMock.expect(bc.getProperty("org.opencastproject.storage.dir")).andReturn(storageDir.getPath()).anyTimes();
    EasyMock.expect(bc.getProperty("org.opencastproject.composer.ffmpegpath")).andReturn(FFMPEG_BINARY).anyTimes();
    EasyMock.expect(bc.getProperty(FFmpegAnalyzer.FFPROBE_BINARY_CONFIG)).andReturn("ffprobe").anyTimes();
    ComponentContext cc = EasyMock.createNiceMock(ComponentContext.class);
    EasyMock.expect(cc.getBundleContext()).andReturn(bc).anyTimes();
    EasyMock.replay(bc, cc, workspace, userDirectoryService, organizationDirectoryService, securityService);
    /* mock inspector output so that the job will alway pass */
    String sourceTrackXml = "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>" + "<track xmlns=\"http://mediapackage.opencastproject.org\" type='presentation/source' id='deadbeef-a926-4ba9-96d9-2fafbcc30d2a'>" + "<audio id='audio-1'><encoder type='MP3 (MPEG audio layer 3)'/><channels>2</channels>" + "<bitrate>96000.0</bitrate></audio><video id='video-1'><device/>" + "<encoder type='FLV / Sorenson Spark / Sorenson H.263 (Flash Video)'/>" + "<bitrate>512000.0</bitrate><framerate>15.0</framerate>" + "<resolution>854x480</resolution></video>" + "<mimetype>video/mpeg</mimetype><url>video.mp4</url></track>";
    inspectedTrack = (Track) MediaPackageElementParser.getFromXml(sourceTrackXml);
    veditor = new VideoEditorServiceImpl() {

        @Override
        protected Job inspect(Job job, URI workspaceURI) throws MediaInspectionException, ProcessFailedException {
            Job inspectionJob = EasyMock.createNiceMock(Job.class);
            try {
                EasyMock.expect(inspectionJob.getPayload()).andReturn(MediaPackageElementParser.getAsXml(inspectedTrack));
            } catch (MediaPackageException e) {
                throw new MediaInspectionException(e);
            }
            EasyMock.replay(inspectionJob);
            return inspectionJob;
        }
    };
    /* set up video editor */
    veditor.activate(cc);
    veditor.setWorkspace(workspace);
    veditor.setSecurityService(securityService);
    veditor.setUserDirectoryService(userDirectoryService);
    veditor.setSmilService(smilService);
    veditor.setOrganizationDirectoryService(organizationDirectoryService);
    serviceRegistry = EasyMock.createMock(ServiceRegistry.class);
    final Capture<String> type = EasyMock.newCapture();
    final Capture<String> operation = EasyMock.newCapture();
    final Capture<List<String>> args = EasyMock.newCapture();
    EasyMock.expect(serviceRegistry.createJob(capture(type), capture(operation), capture(args), EasyMock.anyFloat())).andAnswer(() -> {
        Job job = new JobImpl(0);
        logger.error("type: {}", type.getValue());
        job.setJobType(type.getValue());
        job.setOperation(operation.getValue());
        job.setArguments(args.getValue());
        job.setPayload(veditor.process(job));
        return job;
    }).anyTimes();
    EasyMock.replay(serviceRegistry);
    veditor.setServiceRegistry(serviceRegistry);
}
Also used : User(org.opencastproject.security.api.User) JaxbUser(org.opencastproject.security.api.JaxbUser) Organization(org.opencastproject.security.api.Organization) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) JaxbUser(org.opencastproject.security.api.JaxbUser) URI(java.net.URI) MediaInspectionException(org.opencastproject.inspection.api.MediaInspectionException) SecurityService(org.opencastproject.security.api.SecurityService) List(java.util.List) ArrayList(java.util.ArrayList) Job(org.opencastproject.job.api.Job) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) JobImpl(org.opencastproject.job.api.JobImpl) ComponentContext(org.osgi.service.component.ComponentContext) InputStream(java.io.InputStream) UserDirectoryService(org.opencastproject.security.api.UserDirectoryService) JaxbRole(org.opencastproject.security.api.JaxbRole) FileOutputStream(java.io.FileOutputStream) ServiceRegistry(org.opencastproject.serviceregistry.api.ServiceRegistry) ProcessFailedException(org.opencastproject.videoeditor.api.ProcessFailedException) File(java.io.File) Workspace(org.opencastproject.workspace.api.Workspace) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) OrganizationDirectoryService(org.opencastproject.security.api.OrganizationDirectoryService) BundleContext(org.osgi.framework.BundleContext) Before(org.junit.Before)

Example 22 with Organization

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

the class LdapUserProviderFactory method updated.

/**
 * {@inheritDoc}
 *
 * @see org.osgi.service.cm.ManagedServiceFactory#updated(java.lang.String, java.util.Dictionary)
 */
@Override
public void updated(String pid, Dictionary properties) throws ConfigurationException {
    logger.debug("Updating LdapUserProviderFactory");
    String organization = (String) properties.get(ORGANIZATION_KEY);
    if (StringUtils.isBlank(organization))
        throw new ConfigurationException(ORGANIZATION_KEY, "is not set");
    String searchBase = (String) properties.get(SEARCH_BASE_KEY);
    if (StringUtils.isBlank(searchBase))
        throw new ConfigurationException(SEARCH_BASE_KEY, "is not set");
    String searchFilter = (String) properties.get(SEARCH_FILTER_KEY);
    if (StringUtils.isBlank(searchFilter))
        throw new ConfigurationException(SEARCH_FILTER_KEY, "is not set");
    String url = (String) properties.get(LDAP_URL_KEY);
    if (StringUtils.isBlank(url))
        throw new ConfigurationException(LDAP_URL_KEY, "is not set");
    String instanceId = (String) properties.get(INSTANCE_ID_KEY);
    if (StringUtils.isBlank(instanceId))
        throw new ConfigurationException(INSTANCE_ID_KEY, "is not set");
    String userDn = (String) properties.get(SEARCH_USER_DN);
    String password = (String) properties.get(SEARCH_PASSWORD);
    String roleAttributes = (String) properties.get(ROLE_ATTRIBUTES_KEY);
    String rolePrefix = (String) properties.get(ROLE_PREFIX_KEY);
    String[] excludePrefixes = null;
    String strExcludePrefixes = (String) properties.get(EXCLUDE_PREFIXES_KEY);
    if (StringUtils.isNotBlank(strExcludePrefixes)) {
        excludePrefixes = strExcludePrefixes.split(",");
    }
    // Make sure that property convertToUppercase is true by default
    String strUppercase = (String) properties.get(UPPERCASE_KEY);
    boolean convertToUppercase = StringUtils.isBlank(strUppercase) ? true : Boolean.valueOf(strUppercase);
    String[] extraRoles = new String[0];
    String strExtraRoles = (String) properties.get(EXTRA_ROLES_KEY);
    if (StringUtils.isNotBlank(strExtraRoles)) {
        extraRoles = strExtraRoles.split(",");
    }
    int cacheSize = 1000;
    logger.debug("Using cache size {} for {}", properties.get(CACHE_SIZE), LdapUserProviderFactory.class.getName());
    try {
        if (properties.get(CACHE_SIZE) != null) {
            Integer configuredCacheSize = Integer.parseInt(properties.get(CACHE_SIZE).toString());
            if (configuredCacheSize != null) {
                cacheSize = configuredCacheSize.intValue();
            }
        }
    } catch (Exception e) {
        logger.warn("{} could not be loaded, default value is used: {}", CACHE_SIZE, cacheSize);
    }
    int cacheExpiration = 1;
    try {
        if (properties.get(CACHE_EXPIRATION) != null) {
            Integer configuredCacheExpiration = Integer.parseInt(properties.get(CACHE_EXPIRATION).toString());
            if (configuredCacheExpiration != null) {
                cacheExpiration = configuredCacheExpiration.intValue();
            }
        }
    } catch (Exception e) {
        logger.warn("{} could not be loaded, default value is used: {}", CACHE_EXPIRATION, cacheExpiration);
    }
    // Now that we have everything we need, go ahead and activate a new provider, removing an old one if necessary
    ServiceRegistration existingRegistration = providerRegistrations.remove(pid);
    if (existingRegistration != null) {
        existingRegistration.unregister();
    }
    Organization org;
    try {
        org = orgDirectory.getOrganization(organization);
    } catch (NotFoundException e) {
        logger.warn("Organization {} not found!", organization);
        throw new ConfigurationException(ORGANIZATION_KEY, "not found");
    }
    // Dictionary to include a property to identify this LDAP instance in the security.xml file
    Hashtable<String, String> dict = new Hashtable<>();
    dict.put(INSTANCE_ID_SERVICE_PROPERTY_KEY, instanceId);
    // Instantiate this LDAP instance and register it as such
    LdapUserProviderInstance provider = new LdapUserProviderInstance(pid, org, searchBase, searchFilter, url, userDn, password, roleAttributes, rolePrefix, extraRoles, excludePrefixes, convertToUppercase, cacheSize, cacheExpiration, securityService);
    providerRegistrations.put(pid, bundleContext.registerService(UserProvider.class.getName(), provider, null));
    OpencastLdapAuthoritiesPopulator authoritiesPopulator = new OpencastLdapAuthoritiesPopulator(roleAttributes, rolePrefix, excludePrefixes, convertToUppercase, org, securityService, groupRoleProvider, extraRoles);
    // Also, register this instance as LdapAuthoritiesPopulator so that it can be used within the security.xml file
    authoritiesPopulatorRegistrations.put(pid, bundleContext.registerService(LdapAuthoritiesPopulator.class.getName(), authoritiesPopulator, dict));
}
Also used : Organization(org.opencastproject.security.api.Organization) Hashtable(java.util.Hashtable) NotFoundException(org.opencastproject.util.NotFoundException) NotFoundException(org.opencastproject.util.NotFoundException) MalformedObjectNameException(javax.management.MalformedObjectNameException) ConfigurationException(org.osgi.service.cm.ConfigurationException) ConfigurationException(org.osgi.service.cm.ConfigurationException) ServiceRegistration(org.osgi.framework.ServiceRegistration)

Example 23 with Organization

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

the class OrganizationRoleProvider method findRoles.

/**
 * @see org.opencastproject.security.api.RoleProvider#findRoles(String, Role.Target, int, int)
 */
@Override
public Iterator<Role> findRoles(String query, Role.Target target, int offset, int limit) {
    if (query == null)
        throw new IllegalArgumentException("Query must be set");
    Organization organization = securityService.getOrganization();
    HashSet<Role> foundRoles = new HashSet<Role>();
    for (Iterator<Role> it = getRoles(); it.hasNext(); ) {
        Role role = it.next();
        // Anonymous roles are not relevant for adding to users or groups
        if ((target == Role.Target.USER) && role.getName().equals(organization.getAnonymousRole()))
            continue;
        if (like(role.getName(), query) || like(role.getDescription(), query))
            foundRoles.add(role);
    }
    return offsetLimitCollection(offset, limit, foundRoles).iterator();
}
Also used : Role(org.opencastproject.security.api.Role) JaxbRole(org.opencastproject.security.api.JaxbRole) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) Organization(org.opencastproject.security.api.Organization) HashSet(java.util.HashSet)

Example 24 with Organization

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

the class UserAndRoleDirectoryServiceImpl method getRoles.

/**
 * {@inheritDoc}
 *
 * @see org.opencastproject.security.api.RoleDirectoryService#getRoles()
 */
@Override
@SuppressWarnings("unchecked")
public Iterator<Role> getRoles() {
    Organization org = securityService.getOrganization();
    if (org == null)
        throw new IllegalStateException("No organization is set");
    Stream<Role> roles = Stream.empty();
    for (RoleProvider roleProvider : roleProviders) {
        String providerOrgId = roleProvider.getOrganization();
        if (!ALL_ORGANIZATIONS.equals(providerOrgId) && !org.getId().equals(providerOrgId))
            continue;
        roles = roles.append(IteratorUtils.toList(roleProvider.getRoles())).sort(roleComparator);
    }
    return roles.iterator();
}
Also used : JaxbRole(org.opencastproject.security.api.JaxbRole) Role(org.opencastproject.security.api.Role) Organization(org.opencastproject.security.api.Organization) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) RoleProvider(org.opencastproject.security.api.RoleProvider)

Example 25 with Organization

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

the class UserAndRoleDirectoryServiceImpl method getUsers.

/**
 * {@inheritDoc}
 *
 * @see org.opencastproject.security.api.UserDirectoryService#getUsers()
 */
@Override
@SuppressWarnings("unchecked")
public Iterator<User> getUsers() {
    Organization org = securityService.getOrganization();
    if (org == null)
        throw new IllegalStateException("No organization is set");
    // Find all users from the user providers
    Stream<User> users = Stream.empty();
    for (final UserProvider userProvider : userProviders) {
        String providerOrgId = userProvider.getOrganization();
        if (!ALL_ORGANIZATIONS.equals(providerOrgId) && !org.getId().equals(providerOrgId))
            continue;
        users = users.append(IteratorUtils.toList(userProvider.getUsers())).sort(userComparator);
    }
    return users.iterator();
}
Also used : Organization(org.opencastproject.security.api.Organization) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) User(org.opencastproject.security.api.User) JaxbUser(org.opencastproject.security.api.JaxbUser) UserProvider(org.opencastproject.security.api.UserProvider)

Aggregations

Organization (org.opencastproject.security.api.Organization)135 User (org.opencastproject.security.api.User)60 DefaultOrganization (org.opencastproject.security.api.DefaultOrganization)46 NotFoundException (org.opencastproject.util.NotFoundException)43 JaxbOrganization (org.opencastproject.security.api.JaxbOrganization)29 SecurityService (org.opencastproject.security.api.SecurityService)29 IOException (java.io.IOException)24 Before (org.junit.Before)24 ArrayList (java.util.ArrayList)23 AccessControlList (org.opencastproject.security.api.AccessControlList)22 OrganizationDirectoryService (org.opencastproject.security.api.OrganizationDirectoryService)22 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)22 JaxbRole (org.opencastproject.security.api.JaxbRole)21 MediaPackage (org.opencastproject.mediapackage.MediaPackage)20 JaxbUser (org.opencastproject.security.api.JaxbUser)20 UserDirectoryService (org.opencastproject.security.api.UserDirectoryService)19 File (java.io.File)18 HashMap (java.util.HashMap)17 WorkflowInstance (org.opencastproject.workflow.api.WorkflowInstance)17 Test (org.junit.Test)15