Search in sources :

Example 6 with JaxbUser

use of org.opencastproject.security.api.JaxbUser 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 7 with JaxbUser

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

the class LdapUserProviderInstance method loadUserFromLdap.

/**
 * Loads a user from LDAP.
 *
 * @param userName
 *          the username
 * @return the user
 */
protected User loadUserFromLdap(String userName) {
    if (delegate == null || cache == null) {
        throw new IllegalStateException("The LDAP user detail service has not yet been configured");
    }
    ldapLoads.incrementAndGet();
    UserDetails userDetails = null;
    Thread currentThread = Thread.currentThread();
    ClassLoader originalClassloader = currentThread.getContextClassLoader();
    try {
        currentThread.setContextClassLoader(LdapUserProviderFactory.class.getClassLoader());
        try {
            userDetails = delegate.loadUserByUsername(userName);
        } catch (UsernameNotFoundException e) {
            cache.put(userName, nullToken);
            return null;
        }
        JaxbOrganization jaxbOrganization = JaxbOrganization.fromOrganization(organization);
        // Get the roles and add the extra roles
        Collection<GrantedAuthority> authorities = new HashSet<>();
        authorities.addAll(userDetails.getAuthorities());
        authorities.addAll(setExtraRoles);
        Set<JaxbRole> roles = new HashSet<>();
        if (authorities != null) {
            /*
         * Please note the prefix logic for roles:
         *
         * - Roles that start with any of the "exclude prefixes" are left intact
         * - In any other case, the "role prefix" is prepended to the roles read from LDAP
         *
         * This only applies to the prefix addition. The conversion to uppercase is independent from these
         * considerations
         */
            for (GrantedAuthority authority : authorities) {
                String strAuthority = authority.getAuthority();
                boolean hasExcludePrefix = false;
                for (String excludePrefix : setExcludePrefixes) {
                    if (strAuthority.startsWith(excludePrefix)) {
                        hasExcludePrefix = true;
                        break;
                    }
                }
                if (!hasExcludePrefix) {
                    strAuthority = rolePrefix + strAuthority;
                }
                // Finally, add the role itself
                roles.add(new JaxbRole(strAuthority, jaxbOrganization));
            }
        }
        User user = new JaxbUser(userDetails.getUsername(), PROVIDER_NAME, jaxbOrganization, roles);
        cache.put(userName, user);
        return user;
    } finally {
        currentThread.setContextClassLoader(originalClassloader);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) User(org.opencastproject.security.api.User) JaxbUser(org.opencastproject.security.api.JaxbUser) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) JaxbUser(org.opencastproject.security.api.JaxbUser) UserDetails(org.springframework.security.core.userdetails.UserDetails) JaxbRole(org.opencastproject.security.api.JaxbRole) HashSet(java.util.HashSet)

Example 8 with JaxbUser

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

the class MoodleUserProviderInstance method loadUserFromMoodle.

// ///////////////
// Helper methods
/**
 * Loads a user from Moodle.
 *
 * @param username The username.
 * @return The user.
 */
private User loadUserFromMoodle(String username) {
    logger.debug("loadUserFromMoodle({})", username);
    if (cache == null)
        throw new IllegalStateException("The Moodle user detail service has not yet been configured");
    // Don't answer for admin, anonymous or empty user
    if ("admin".equals(username) || "".equals(username) || "anonymous".equals(username)) {
        logger.debug("We don't answer for: " + username);
        return null;
    }
    JaxbOrganization jaxbOrganization = JaxbOrganization.fromOrganization(organization);
    // update cache statistics
    moodleWebServiceRequests.incrementAndGet();
    Thread currentThread = Thread.currentThread();
    ClassLoader originalClassloader = currentThread.getContextClassLoader();
    try {
        // Load user
        List<MoodleUser> moodleUsers = client.coreUserGetUsersByField(CoreUserGetUserByFieldFilters.username, Collections.singletonList(username));
        if (moodleUsers.isEmpty()) {
            logger.debug("User {} not found in Moodle system", username);
            return null;
        }
        MoodleUser moodleUser = moodleUsers.get(0);
        // Load Roles
        List<String> courseIdsInstructor = client.toolOpencastGetCoursesForInstructor(username);
        List<String> courseIdsLearner = client.toolOpencastGetCoursesForLearner(username);
        // Create Opencast Objects
        Set<JaxbRole> roles = new HashSet<>();
        roles.add(new JaxbRole(Group.ROLE_PREFIX + "MOODLE", jaxbOrganization, "Moodle Users", Role.Type.EXTERNAL_GROUP));
        for (String courseId : courseIdsInstructor) {
            roles.add(new JaxbRole(courseId + "_" + INSTRUCTOR_ROLE_SUFFIX, jaxbOrganization, "Moodle external role", Role.Type.EXTERNAL));
        }
        for (String courseId : courseIdsLearner) {
            roles.add(new JaxbRole(courseId + "_" + LEARNER_ROLE_SUFFIX, jaxbOrganization, "Moodle external role", Role.Type.EXTERNAL));
        }
        return new JaxbUser(moodleUser.getUsername(), null, moodleUser.getFullname(), moodleUser.getEmail(), this.getName(), true, jaxbOrganization, roles);
    } catch (Exception e) {
        logger.warn("Exception loading Moodle user {} at {}: {}", username, client.getURL(), e.getMessage());
    } finally {
        currentThread.setContextClassLoader(originalClassloader);
    }
    return null;
}
Also used : JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) JaxbUser(org.opencastproject.security.api.JaxbUser) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) InstanceNotFoundException(javax.management.InstanceNotFoundException) PatternSyntaxException(java.util.regex.PatternSyntaxException) JaxbRole(org.opencastproject.security.api.JaxbRole) HashSet(java.util.HashSet)

Example 9 with JaxbUser

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

the class SakaiUserProviderInstance method loadUserFromSakai.

/**
 * Loads a user from Sakai.
 *
 * @param userName
 *          the username
 * @return the user
 */
protected User loadUserFromSakai(String userName) {
    if (cache == null) {
        throw new IllegalStateException("The Sakai user detail service has not yet been configured");
    }
    // Don't answer for admin, anonymous or empty user
    if ("admin".equals(userName) || "".equals(userName) || "anonymous".equals(userName)) {
        cache.put(userName, nullToken);
        logger.debug("we don't answer for: " + userName);
        return null;
    }
    logger.debug("In loadUserFromSakai, currently processing user : {}", userName);
    JaxbOrganization jaxbOrganization = JaxbOrganization.fromOrganization(organization);
    // update cache statistics
    sakaiLoads.incrementAndGet();
    Thread currentThread = Thread.currentThread();
    ClassLoader originalClassloader = currentThread.getContextClassLoader();
    try {
        // Sakai userId (internal id), email address and display name
        String[] sakaiUser = getSakaiUser(userName);
        if (sakaiUser == null) {
            // user not known to this provider
            logger.debug("User {} not found in Sakai system", userName);
            cache.put(userName, nullToken);
            return null;
        }
        String userId = sakaiUser[0];
        String email = sakaiUser[1];
        String displayName = sakaiUser[2];
        // Get the set of Sakai roles for the user
        String[] sakaiRoles = getRolesFromSakai(userId);
        // if Sakai doesn't know about this user we need to return
        if (sakaiRoles == null) {
            cache.put(userName, nullToken);
            return null;
        }
        logger.debug("Sakai roles for eid " + userName + " id " + userId + ": " + Arrays.toString(sakaiRoles));
        Set<JaxbRole> roles = new HashSet<JaxbRole>();
        boolean isInstructor = false;
        for (String r : sakaiRoles) {
            roles.add(new JaxbRole(r, jaxbOrganization, "Sakai external role", Role.Type.EXTERNAL));
            if (r.endsWith(LTI_INSTRUCTOR_ROLE))
                isInstructor = true;
        }
        // Group role for all Sakai users
        roles.add(new JaxbRole(Group.ROLE_PREFIX + "SAKAI", jaxbOrganization, "Sakai Users", Role.Type.EXTERNAL_GROUP));
        // Group role for Sakai users who are an instructor in one more sites
        if (isInstructor)
            roles.add(new JaxbRole(Group.ROLE_PREFIX + "SAKAI_INSTRUCTOR", jaxbOrganization, "Sakai Instructors", Role.Type.EXTERNAL_GROUP));
        logger.debug("Returning JaxbRoles: " + roles);
        // JaxbUser(String userName, String password, String name, String email, String provider, boolean canLogin, JaxbOrganization organization, Set<JaxbRole> roles)
        User user = new JaxbUser(userName, null, displayName, email, PROVIDER_NAME, true, jaxbOrganization, roles);
        cache.put(userName, user);
        logger.debug("Returning user {}", userName);
        return user;
    } finally {
        currentThread.setContextClassLoader(originalClassloader);
    }
}
Also used : JaxbRole(org.opencastproject.security.api.JaxbRole) User(org.opencastproject.security.api.User) JaxbUser(org.opencastproject.security.api.JaxbUser) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) JaxbUser(org.opencastproject.security.api.JaxbUser) HashSet(java.util.HashSet)

Example 10 with JaxbUser

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

the class UserAndRoleDirectoryServiceImplTest method setUp.

@Before
public void setUp() throws Exception {
    org = new DefaultOrganization();
    userName = "sampleUser";
    role1 = new JaxbRole("role1", org);
    role2 = new JaxbRole("role2", org);
    role3 = new JaxbRole("role3", org);
    JaxbUser user1 = new JaxbUser(userName, "matterhorn", org, role1, role2);
    user1.setManageable(true);
    User user2 = new JaxbUser(userName, "secret", "test", true, org, role2, role3);
    User user3 = new JaxbUser("userSample", "test", org, role2, role3);
    List<User> users = new ArrayList<User>();
    users.add(user1);
    UserProvider provider1 = EasyMock.createNiceMock(UserProvider.class);
    EasyMock.expect(provider1.getOrganization()).andReturn(org.getId()).anyTimes();
    EasyMock.expect(provider1.loadUser((String) EasyMock.anyObject())).andReturn(user1).anyTimes();
    EasyMock.expect(provider1.findUsers("%mple%", 0, 0)).andReturn(users.iterator()).once();
    EasyMock.expect(provider1.findUsers("%mple%", 0, 0)).andReturn(users.iterator()).once();
    EasyMock.expect(provider1.getUsers()).andReturn(users.iterator()).once();
    EasyMock.expect(provider1.getName()).andReturn("test").once();
    List<User> users2 = new ArrayList<User>();
    users2.add(user3);
    UserProvider provider2 = EasyMock.createNiceMock(UserProvider.class);
    EasyMock.expect(provider2.getOrganization()).andReturn(org.getId()).anyTimes();
    EasyMock.expect(provider2.loadUser((String) EasyMock.anyObject())).andReturn(user2).anyTimes();
    EasyMock.expect(provider2.findUsers("%mple%", 0, 0)).andReturn(users2.iterator()).once();
    EasyMock.expect(provider2.findUsers("%mple%", 0, 0)).andReturn(users2.iterator()).once();
    EasyMock.expect(provider2.getUsers()).andReturn(users2.iterator()).once();
    EasyMock.expect(provider2.getName()).andReturn("matterhorn").once();
    List<Role> roles1 = new ArrayList<Role>();
    roles1.add(new JaxbRole("ROLE_ASTRO_2011", org));
    roles1.add(new JaxbRole("ROLE_ASTRO_2012", org));
    List<Role> rolesForUser1 = new ArrayList<Role>();
    rolesForUser1.add(new JaxbRole("ROLE_ASTRO_2012", org));
    List<Role> findRoles1 = new ArrayList<Role>();
    findRoles1.add(new JaxbRole("ROLE_ASTRO_2012", org));
    RoleProvider roleProvider1 = EasyMock.createNiceMock(RoleProvider.class);
    EasyMock.expect(roleProvider1.getOrganization()).andReturn(org.getId()).anyTimes();
    EasyMock.expect(roleProvider1.getRoles()).andReturn(roles1.iterator()).anyTimes();
    EasyMock.expect(roleProvider1.getRolesForUser((String) EasyMock.anyObject())).andReturn(rolesForUser1).anyTimes();
    EasyMock.expect(roleProvider1.findRoles("%2012%", Role.Target.ALL, 0, 0)).andReturn(findRoles1.iterator()).once();
    EasyMock.expect(roleProvider1.findRoles("%2012%", Role.Target.ALL, 0, 0)).andReturn(findRoles1.iterator()).once();
    List<Role> roles2 = new ArrayList<Role>();
    roles2.add(new JaxbRole("ROLE_MATH_2011", org));
    roles2.add(new JaxbRole("ROLE_MATH_2012", org));
    List<Role> rolesForUser2 = new ArrayList<Role>();
    rolesForUser2.add(new JaxbRole("ROLE_MATH_2012", org));
    List<Role> findRoles2 = new ArrayList<Role>();
    findRoles2.add(new JaxbRole("ROLE_MATH_2012", org));
    RoleProvider roleProvider2 = EasyMock.createNiceMock(RoleProvider.class);
    EasyMock.expect(roleProvider2.getOrganization()).andReturn(org.getId()).anyTimes();
    EasyMock.expect(roleProvider2.getRoles()).andReturn(roles2.iterator()).anyTimes();
    EasyMock.expect(roleProvider2.getRolesForUser((String) EasyMock.anyObject())).andReturn(rolesForUser2).anyTimes();
    EasyMock.expect(roleProvider2.findRoles("%2012%", Role.Target.ALL, 0, 0)).andReturn(findRoles2.iterator()).once();
    EasyMock.expect(roleProvider2.findRoles("%2012%", Role.Target.ALL, 0, 0)).andReturn(findRoles2.iterator()).once();
    RoleProvider otherOrgRoleProvider = EasyMock.createNiceMock(RoleProvider.class);
    EasyMock.expect(otherOrgRoleProvider.getOrganization()).andReturn("otherOrg").anyTimes();
    EasyMock.expect(otherOrgRoleProvider.getRoles()).andReturn(roles2.iterator()).anyTimes();
    EasyMock.expect(otherOrgRoleProvider.getRolesForUser((String) EasyMock.anyObject())).andReturn(rolesForUser2).anyTimes();
    EasyMock.expect(otherOrgRoleProvider.findRoles("%2012%", Role.Target.ALL, 0, 0)).andReturn(new ArrayList<Role>().iterator()).anyTimes();
    SecurityService securityService = EasyMock.createNiceMock(SecurityService.class);
    EasyMock.expect(securityService.getOrganization()).andReturn(org).anyTimes();
    EasyMock.replay(provider1, provider2, roleProvider1, roleProvider2, otherOrgRoleProvider, securityService);
    directory = new UserAndRoleDirectoryServiceImpl();
    directory.activate(null);
    directory.setSecurityService(securityService);
    directory.addUserProvider(provider1);
    directory.addUserProvider(provider2);
    directory.addRoleProvider(roleProvider1);
    directory.addRoleProvider(roleProvider2);
    directory.addRoleProvider(otherOrgRoleProvider);
}
Also used : User(org.opencastproject.security.api.User) JaxbUser(org.opencastproject.security.api.JaxbUser) ArrayList(java.util.ArrayList) JaxbUser(org.opencastproject.security.api.JaxbUser) RoleProvider(org.opencastproject.security.api.RoleProvider) Role(org.opencastproject.security.api.Role) JaxbRole(org.opencastproject.security.api.JaxbRole) JaxbRole(org.opencastproject.security.api.JaxbRole) UserProvider(org.opencastproject.security.api.UserProvider) SecurityService(org.opencastproject.security.api.SecurityService) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) Before(org.junit.Before)

Aggregations

JaxbUser (org.opencastproject.security.api.JaxbUser)63 JaxbRole (org.opencastproject.security.api.JaxbRole)54 User (org.opencastproject.security.api.User)47 DefaultOrganization (org.opencastproject.security.api.DefaultOrganization)46 SecurityService (org.opencastproject.security.api.SecurityService)44 Before (org.junit.Before)34 JaxbOrganization (org.opencastproject.security.api.JaxbOrganization)21 OrganizationDirectoryService (org.opencastproject.security.api.OrganizationDirectoryService)19 UserDirectoryService (org.opencastproject.security.api.UserDirectoryService)19 Test (org.junit.Test)15 Organization (org.opencastproject.security.api.Organization)15 Workspace (org.opencastproject.workspace.api.Workspace)15 HashSet (java.util.HashSet)14 URI (java.net.URI)12 BundleContext (org.osgi.framework.BundleContext)12 ComponentContext (org.osgi.service.component.ComponentContext)12 ServiceRegistryInMemoryImpl (org.opencastproject.serviceregistry.api.ServiceRegistryInMemoryImpl)11 File (java.io.File)10 Job (org.opencastproject.job.api.Job)8 InputStream (java.io.InputStream)7