Search in sources :

Example 51 with User

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

the class ServiceRegistrationTest method setUp.

@Before
public void setUp() throws Exception {
    serviceRegistry = new ServiceRegistryJpaImpl();
    serviceRegistry.setEntityManagerFactory(PersistenceUtil.newTestEntityManagerFactory(ServiceRegistryJpaImpl.PERSISTENCE_UNIT));
    serviceRegistry.activate(null);
    Organization organization = new DefaultOrganization();
    OrganizationDirectoryService organizationDirectoryService = EasyMock.createMock(OrganizationDirectoryService.class);
    expect(organizationDirectoryService.getOrganization((String) anyObject())).andReturn(organization).anyTimes();
    EasyMock.replay(organizationDirectoryService);
    serviceRegistry.setOrganizationDirectoryService(organizationDirectoryService);
    JaxbOrganization jaxbOrganization = JaxbOrganization.fromOrganization(organization);
    User anonymous = new JaxbUser("anonymous", "test", jaxbOrganization, new JaxbRole(jaxbOrganization.getAnonymousRole(), jaxbOrganization));
    SecurityService securityService = EasyMock.createNiceMock(SecurityService.class);
    expect(securityService.getUser()).andReturn(anonymous).anyTimes();
    expect(securityService.getOrganization()).andReturn(organization).anyTimes();
    EasyMock.replay(securityService);
    serviceRegistry.setSecurityService(securityService);
    // The service registry will automatically register this host with the available number of processors.
    // This is potentially ruining our test setup.
    serviceRegistry.unregisterHost(LOCALHOST);
    // register the hosts
    serviceRegistry.registerHost(LOCALHOST, "127.0.0.1", 1024, 1, 1);
    serviceRegistry.registerHost(REMOTEHOST_1, "127.0.0.1", 1024, 1, 1);
    serviceRegistry.registerHost(REMOTEHOST_2, "127.0.0.1", 1024, 1, 1);
    // register some service instances
    regType1Localhost = (ServiceRegistrationJpaImpl) serviceRegistry.registerService(JOB_TYPE_1, LOCALHOST, PATH_1);
    regType1Remotehost1 = (ServiceRegistrationJpaImpl) serviceRegistry.registerService(JOB_TYPE_1, REMOTEHOST_1, PATH_1);
    regType1Remotehost2 = (ServiceRegistrationJpaImpl) serviceRegistry.registerService(JOB_TYPE_1, REMOTEHOST_2, PATH_2);
}
Also used : Organization(org.opencastproject.security.api.Organization) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) User(org.opencastproject.security.api.User) JaxbUser(org.opencastproject.security.api.JaxbUser) JaxbRole(org.opencastproject.security.api.JaxbRole) SecurityService(org.opencastproject.security.api.SecurityService) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) JaxbUser(org.opencastproject.security.api.JaxbUser) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) OrganizationDirectoryService(org.opencastproject.security.api.OrganizationDirectoryService) Before(org.junit.Before)

Example 52 with User

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

the class ServiceRegistryJpaImplTest method setUpServiceRegistryJpaImpl.

public void setUpServiceRegistryJpaImpl() throws PropertyVetoException, NotFoundException, TrustedHttpClientException {
    serviceRegistryJpaImpl = new ServiceRegistryJpaImpl();
    serviceRegistryJpaImpl.setEntityManagerFactory(emf);
    Organization organization = new DefaultOrganization();
    OrganizationDirectoryService organizationDirectoryService = EasyMock.createMock(OrganizationDirectoryService.class);
    EasyMock.expect(organizationDirectoryService.getOrganization((String) EasyMock.anyObject())).andReturn(organization).anyTimes();
    EasyMock.replay(organizationDirectoryService);
    serviceRegistryJpaImpl.setOrganizationDirectoryService(organizationDirectoryService);
    JaxbOrganization jaxbOrganization = JaxbOrganization.fromOrganization(organization);
    User anonymous = new JaxbUser("anonymous", "test", jaxbOrganization, new JaxbRole(jaxbOrganization.getAnonymousRole(), jaxbOrganization));
    SecurityService securityService = EasyMock.createNiceMock(SecurityService.class);
    EasyMock.expect(securityService.getUser()).andReturn(anonymous).anyTimes();
    EasyMock.expect(securityService.getOrganization()).andReturn(organization).anyTimes();
    EasyMock.replay(securityService);
    serviceRegistryJpaImpl.setSecurityService(securityService);
    UserDirectoryService userDirectoryService = EasyMock.createNiceMock(UserDirectoryService.class);
    EasyMock.expect(userDirectoryService.loadUser(EasyMock.anyString())).andReturn(anonymous).anyTimes();
    EasyMock.replay(userDirectoryService);
    serviceRegistryJpaImpl.setUserDirectoryService(userDirectoryService);
    final Capture<HttpUriRequest> request = EasyMock.newCapture();
    final BasicHttpResponse successRespone = new BasicHttpResponse(new BasicStatusLine(new HttpVersion(1, 1), HttpStatus.SC_NO_CONTENT, "No message"));
    final BasicHttpResponse unavailableResponse = new BasicHttpResponse(new BasicStatusLine(new HttpVersion(1, 1), HttpStatus.SC_SERVICE_UNAVAILABLE, "No message"));
    TrustedHttpClient trustedHttpClient = EasyMock.createNiceMock(TrustedHttpClient.class);
    EasyMock.expect(trustedHttpClient.execute(EasyMock.capture(request))).andAnswer(new IAnswer<HttpResponse>() {

        @Override
        public HttpResponse answer() throws Throwable {
            if (!request.hasCaptured())
                return unavailableResponse;
            if (request.getValue().getURI().toString().contains(TEST_PATH))
                return unavailableResponse;
            if (request.getValue().getURI().toString().contains(TEST_PATH_3))
                return unavailableResponse;
            return successRespone;
        }
    }).anyTimes();
    EasyMock.replay(trustedHttpClient);
    serviceRegistryJpaImpl.setTrustedHttpClient(trustedHttpClient);
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) TrustedHttpClient(org.opencastproject.security.api.TrustedHttpClient) Organization(org.opencastproject.security.api.Organization) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) User(org.opencastproject.security.api.User) JaxbUser(org.opencastproject.security.api.JaxbUser) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) JaxbUser(org.opencastproject.security.api.JaxbUser) UserDirectoryService(org.opencastproject.security.api.UserDirectoryService) BasicStatusLine(org.apache.http.message.BasicStatusLine) IAnswer(org.easymock.IAnswer) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) JaxbRole(org.opencastproject.security.api.JaxbRole) SecurityService(org.opencastproject.security.api.SecurityService) HttpVersion(org.apache.http.HttpVersion) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) OrganizationDirectoryService(org.opencastproject.security.api.OrganizationDirectoryService)

Example 53 with User

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

the class SoxServiceTest method setUp.

@Before
public void setUp() throws Exception {
    if (!soxInstalled)
        return;
    // Copy an existing media file to a temp file
    File f = new File("src/test/resources/audio-test.flac");
    source = File.createTempFile(FilenameUtils.getBaseName(f.getName()), ".flac");
    FileUtils.copyFile(f, source);
    f = null;
    JaxbOrganization org = new DefaultOrganization();
    User user = new JaxbUser("admin", "test", org, new JaxbRole(DefaultOrganization.DEFAULT_ORGANIZATION_ADMIN, org));
    OrganizationDirectoryService orgDirectory = EasyMock.createNiceMock(OrganizationDirectoryService.class);
    EasyMock.expect(orgDirectory.getOrganization((String) EasyMock.anyObject())).andReturn(org).anyTimes();
    UserDirectoryService userDirectory = EasyMock.createNiceMock(UserDirectoryService.class);
    EasyMock.expect(userDirectory.loadUser("admin")).andReturn(user).anyTimes();
    SecurityService securityService = EasyMock.createNiceMock(SecurityService.class);
    EasyMock.expect(securityService.getOrganization()).andReturn(org).anyTimes();
    EasyMock.expect(securityService.getUser()).andReturn(user).anyTimes();
    Workspace workspace = EasyMock.createNiceMock(Workspace.class);
    EasyMock.expect(workspace.get((URI) EasyMock.anyObject())).andReturn(source).anyTimes();
    BundleContext bc = EasyMock.createNiceMock(BundleContext.class);
    EasyMock.expect(bc.getProperty(SoxServiceImpl.CONFIG_SOX_PATH)).andReturn(SOX_BINARY).anyTimes();
    ComponentContext cc = EasyMock.createNiceMock(ComponentContext.class);
    EasyMock.expect(cc.getBundleContext()).andReturn(bc).anyTimes();
    IncidentService incidentService = EasyMock.createNiceMock(IncidentService.class);
    // Finish setting up the mocks
    EasyMock.replay(bc, cc, orgDirectory, userDirectory, securityService, workspace, incidentService);
    // Create and populate the composer service
    soxService = new SoxServiceImpl();
    serviceRegistry = new ServiceRegistryInMemoryImpl(soxService, securityService, userDirectory, orgDirectory, incidentService);
    soxService.setOrganizationDirectoryService(orgDirectory);
    soxService.setSecurityService(securityService);
    soxService.setServiceRegistry(serviceRegistry);
    soxService.setUserDirectoryService(userDirectory);
    soxService.setWorkspace(workspace);
    soxService.activate(cc);
}
Also used : IncidentService(org.opencastproject.serviceregistry.api.IncidentService) User(org.opencastproject.security.api.User) JaxbUser(org.opencastproject.security.api.JaxbUser) ComponentContext(org.osgi.service.component.ComponentContext) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) JaxbUser(org.opencastproject.security.api.JaxbUser) URI(java.net.URI) UserDirectoryService(org.opencastproject.security.api.UserDirectoryService) JaxbRole(org.opencastproject.security.api.JaxbRole) SecurityService(org.opencastproject.security.api.SecurityService) File(java.io.File) ServiceRegistryInMemoryImpl(org.opencastproject.serviceregistry.api.ServiceRegistryInMemoryImpl) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) OrganizationDirectoryService(org.opencastproject.security.api.OrganizationDirectoryService) Workspace(org.opencastproject.workspace.api.Workspace) BundleContext(org.osgi.framework.BundleContext) Before(org.junit.Before)

Example 54 with User

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

the class UsersEndpoint method getUsers.

@GET
@Path("users.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "allusers", description = "Returns a list of users", returnDescription = "Returns a JSON representation of the list of user accounts", restParameters = { @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 = "sort", isRequired = false, description = "The sort order. May include any of the following: STATUS, NAME OR LAST_UPDATED.  Add '_DESC' to reverse the sort order (e.g. STATUS_DESC).", type = STRING), @RestParameter(defaultValue = "100", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "The user accounts.") })
public Response getUsers(@QueryParam("filter") String filter, @QueryParam("sort") String sort, @QueryParam("limit") int limit, @QueryParam("offset") int offset) throws IOException {
    if (limit < 1)
        limit = 100;
    Option<String> optSort = Option.option(trimToNull(sort));
    Option<String> filterName = Option.none();
    Option<String> filterRole = Option.none();
    Option<String> filterProvider = Option.none();
    Option<String> filterText = Option.none();
    Map<String, String> filters = RestUtils.parseFilter(filter);
    for (String name : filters.keySet()) {
        String value = filters.get(name);
        if (UsersListQuery.FILTER_NAME_NAME.equals(name)) {
            filterName = Option.some(value);
        } else if (UsersListQuery.FILTER_ROLE_NAME.equals(name)) {
            filterRole = Option.some(value);
        } else if (UsersListQuery.FILTER_PROVIDER_NAME.equals(name)) {
            filterProvider = Option.some(value);
        } else if ((UsersListQuery.FILTER_TEXT_NAME.equals(name)) && (StringUtils.isNotBlank(value))) {
            filterText = Option.some(value);
        }
    }
    // Filter users by filter criteria
    List<User> filteredUsers = new ArrayList<>();
    for (Iterator<User> i = userDirectoryService.getUsers(); i.hasNext(); ) {
        User user = i.next();
        // Filter list
        if (filterName.isSome() && !filterName.get().equals(user.getName()) || (filterRole.isSome() && !Stream.$(user.getRoles()).map(getRoleName).toSet().contains(filterRole.get())) || (filterProvider.isSome() && !filterProvider.get().equals(user.getProvider())) || (filterText.isSome() && !TextFilter.match(filterText.get(), user.getUsername(), user.getName(), user.getEmail(), user.getProvider()) && !TextFilter.match(filterText.get(), Stream.$(user.getRoles()).map(getRoleName).mkString(" ")))) {
            continue;
        }
        filteredUsers.add(user);
    }
    int total = filteredUsers.size();
    // Sort by name, description or role
    if (optSort.isSome()) {
        final Set<SortCriterion> sortCriteria = RestUtils.parseSortQueryParameter(optSort.get());
        Collections.sort(filteredUsers, new Comparator<User>() {

            @Override
            public int compare(User user1, User user2) {
                for (SortCriterion criterion : sortCriteria) {
                    Order order = criterion.getOrder();
                    switch(criterion.getFieldName()) {
                        case "name":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getName()), trimToEmpty(user1.getName()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getName()), trimToEmpty(user2.getName()));
                        case "username":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getUsername()), trimToEmpty(user1.getUsername()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getUsername()), trimToEmpty(user2.getUsername()));
                        case "email":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getEmail()), trimToEmpty(user1.getEmail()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getEmail()), trimToEmpty(user2.getEmail()));
                        case "roles":
                            String roles1 = Stream.$(user1.getRoles()).map(getRoleName).sort(sortByName).mkString(",");
                            String roles2 = Stream.$(user2.getRoles()).map(getRoleName).sort(sortByName).mkString(",");
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(roles2), trimToEmpty(roles1));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(roles1), trimToEmpty(roles2));
                        case "provider":
                            if (order.equals(Order.Descending))
                                return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user2.getProvider()), trimToEmpty(user1.getProvider()));
                            return CASE_INSENSITIVE_ORDER.compare(trimToEmpty(user1.getProvider()), trimToEmpty(user2.getProvider()));
                        default:
                            logger.info("Unkown sort type: {}", criterion.getFieldName());
                            return 0;
                    }
                }
                return 0;
            }
        });
    }
    // Apply Limit and offset
    filteredUsers = new SmartIterator<User>(limit, offset).applyLimitAndOffset(filteredUsers);
    List<JValue> usersJSON = new ArrayList<>();
    for (User user : filteredUsers) {
        usersJSON.add(generateJsonUser(user));
    }
    return okJsonList(usersJSON, offset, limit, total);
}
Also used : Order(org.opencastproject.matterhorn.search.SearchQuery.Order) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) User(org.opencastproject.security.api.User) SmartIterator(org.opencastproject.util.SmartIterator) ArrayList(java.util.ArrayList) SortCriterion(org.opencastproject.matterhorn.search.SortCriterion) JValue(com.entwinemedia.fn.data.json.JValue) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 55 with User

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

the class UsersEndpoint method updateUser.

@PUT
@Path("{username}.json")
@RestQuery(name = "updateUser", description = "Update an user", returnDescription = "Status ok", restParameters = { @RestParameter(description = "The password.", isRequired = false, 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") }, pathParameters = @RestParameter(name = "username", type = STRING, isRequired = true, description = "The username"), reponses = { @RestResponse(responseCode = SC_OK, description = "User has been updated."), @RestResponse(responseCode = SC_FORBIDDEN, description = "Not enough permissions to update a user with admin role."), @RestResponse(responseCode = SC_NOT_FOUND, description = "User not found.") })
public Response updateUser(@PathParam("username") String username, @FormParam("password") String password, @FormParam("name") String name, @FormParam("email") String email, @FormParam("roles") String roles) throws NotFoundException {
    User user = jpaUserAndRoleProvider.loadUser(username);
    if (user == null) {
        throw new NotFoundException("User " + username + " does not exist.");
    }
    JpaOrganization organization = (JpaOrganization) securityService.getOrganization();
    Set<JpaRole> rolesSet = new HashSet<>();
    Option<JSONArray> rolesArray = Option.none();
    if (StringUtils.isNotBlank(roles)) {
        rolesArray = Option.some((JSONArray) JSONValue.parse(roles));
    }
    if (rolesArray.isSome()) {
        // Add the roles given
        for (Object roleObj : rolesArray.get()) {
            JSONObject role = (JSONObject) roleObj;
            String rolename = (String) role.get("id");
            Role.Type roletype = Role.Type.valueOf((String) role.get("type"));
            rolesSet.add(new JpaRole(rolename, organization, null, roletype));
        }
    } else {
        // Or the use the one from the user if no one is given
        for (Role role : user.getRoles()) {
            rolesSet.add(new JpaRole(role.getName(), organization, role.getDescription(), role.getType()));
        }
    }
    try {
        jpaUserAndRoleProvider.updateUser(new JpaUser(username, password, organization, name, email, jpaUserAndRoleProvider.getName(), true, rolesSet));
        userDirectoryService.invalidate(username);
        return Response.status(SC_OK).build();
    } catch (UnauthorizedException ex) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }
}
Also used : JpaUser(org.opencastproject.security.impl.jpa.JpaUser) User(org.opencastproject.security.api.User) JpaOrganization(org.opencastproject.security.impl.jpa.JpaOrganization) JSONArray(org.json.simple.JSONArray) NotFoundException(org.opencastproject.util.NotFoundException) JpaUser(org.opencastproject.security.impl.jpa.JpaUser) Role(org.opencastproject.security.api.Role) JpaRole(org.opencastproject.security.impl.jpa.JpaRole) JSONObject(org.json.simple.JSONObject) JpaRole(org.opencastproject.security.impl.jpa.JpaRole) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) JSONObject(org.json.simple.JSONObject) JObject(com.entwinemedia.fn.data.json.JObject) HashSet(java.util.HashSet) Path(javax.ws.rs.Path) RestQuery(org.opencastproject.util.doc.rest.RestQuery) PUT(javax.ws.rs.PUT)

Aggregations

User (org.opencastproject.security.api.User)156 Organization (org.opencastproject.security.api.Organization)61 JaxbUser (org.opencastproject.security.api.JaxbUser)60 JaxbRole (org.opencastproject.security.api.JaxbRole)49 DefaultOrganization (org.opencastproject.security.api.DefaultOrganization)44 SecurityService (org.opencastproject.security.api.SecurityService)43 NotFoundException (org.opencastproject.util.NotFoundException)32 Before (org.junit.Before)31 Test (org.junit.Test)27 ArrayList (java.util.ArrayList)26 UnauthorizedException (org.opencastproject.security.api.UnauthorizedException)24 JaxbOrganization (org.opencastproject.security.api.JaxbOrganization)23 AccessControlList (org.opencastproject.security.api.AccessControlList)21 Role (org.opencastproject.security.api.Role)21 UserDirectoryService (org.opencastproject.security.api.UserDirectoryService)21 HashSet (java.util.HashSet)20 OrganizationDirectoryService (org.opencastproject.security.api.OrganizationDirectoryService)18 JpaUser (org.opencastproject.security.impl.jpa.JpaUser)17 IOException (java.io.IOException)16 MediaPackage (org.opencastproject.mediapackage.MediaPackage)16