Search in sources :

Example 6 with EnvironmentRoleArchetype

use of fi.otavanopisto.muikku.model.users.EnvironmentRoleArchetype in project muikku by otavanopisto.

the class PermissionsPluginController method processPermissions.

public void processPermissions() {
    logger.log(Level.INFO, "Starting permission gathering");
    for (SystemRoleType systemRoleType : SystemRoleType.values()) {
        if (systemRoleEntityDAO.findByRoleType(systemRoleType) == null)
            systemRoleEntityDAO.create(systemRoleType.name(), systemRoleType);
    }
    for (MuikkuPermissionCollection collection : permissionCollections) {
        logger.log(Level.INFO, "Processing permission collection " + collection.getClass().getSimpleName());
        List<String> permissions = collection.listPermissions();
        for (String permissionName : permissions) {
            Permission permission = permissionDAO.findByName(permissionName);
            if (permission == null) {
                logger.log(Level.INFO, "Recording new permission " + permissionName);
                try {
                    final String permissionScope = collection.getPermissionScope(permissionName);
                    if (permissionScope != null) {
                        permission = permissionDAO.create(permissionName, permissionScope);
                        if (!PermissionScope.PERSONAL.equals(permissionScope)) {
                            String[] pseudoRoles = collection.getDefaultPseudoRoles(permissionName);
                            EnvironmentRoleArchetype[] environmentRoles = collection.getDefaultEnvironmentRoles(permissionName);
                            WorkspaceRoleArchetype[] workspaceRoles = collection.getDefaultWorkspaceRoles(permissionName);
                            List<RoleEntity> roles = new ArrayList<RoleEntity>();
                            if (pseudoRoles != null) {
                                for (String pseudoRole : pseudoRoles) {
                                    RoleEntity roleEntity = roleEntityDAO.findByName(pseudoRole);
                                    if (roleEntity != null)
                                        roles.add(roleEntity);
                                }
                            }
                            if (environmentRoles != null) {
                                for (EnvironmentRoleArchetype envRole : environmentRoles) {
                                    List<EnvironmentRoleEntity> envRoles = environmentRoleEntityDAO.listByArchetype(envRole);
                                    roles.addAll(envRoles);
                                }
                            }
                            if (workspaceRoles != null) {
                                for (WorkspaceRoleArchetype arc : workspaceRoles) {
                                    List<WorkspaceRoleEntity> wsRoles = workspaceRoleEntityDAO.listByArchetype(arc);
                                    roles.addAll(wsRoles);
                                }
                            }
                            switch(permissionScope) {
                                case PermissionScope.ENVIRONMENT:
                                case PermissionScope.WORKSPACE:
                                    for (RoleEntity role : roles) {
                                        rolePermissionDAO.create(role, permission);
                                    }
                                    break;
                                case PermissionScope.USERGROUP:
                                    List<UserGroupEntity> userGroups = userGroupDAO.listAll();
                                    for (RoleEntity role : roles) {
                                        // TODO Workspace creation & templates - is this necessary and bulletproof?
                                        for (UserGroupEntity userGroup : userGroups) {
                                            userGroupRolePermissionDAO.create(userGroup, role, permission);
                                        }
                                    }
                                    break;
                                default:
                                    permissionDiscoveredEvent.select(new PermissionScopeBinding() {

                                        private static final long serialVersionUID = 9009824962970938515L;

                                        @Override
                                        public String value() {
                                            return permissionScope;
                                        }
                                    }).fire(new PermissionDiscoveredEvent(permission));
                                    break;
                            }
                        }
                    } else
                        logger.log(Level.WARNING, "PermissionScope null for " + permissionName);
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "Permission handling failed for " + permissionName);
                }
            }
        }
    }
    logger.log(Level.INFO, "Finished permission gathering");
}
Also used : EnvironmentRoleEntity(fi.otavanopisto.muikku.model.users.EnvironmentRoleEntity) EnvironmentRoleArchetype(fi.otavanopisto.muikku.model.users.EnvironmentRoleArchetype) SystemRoleType(fi.otavanopisto.muikku.model.users.SystemRoleType) MuikkuPermissionCollection(fi.otavanopisto.muikku.security.MuikkuPermissionCollection) ArrayList(java.util.ArrayList) UserGroupEntity(fi.otavanopisto.muikku.model.users.UserGroupEntity) WorkspaceRoleEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceRoleEntity) RoleEntity(fi.otavanopisto.muikku.model.users.RoleEntity) EnvironmentRoleEntity(fi.otavanopisto.muikku.model.users.EnvironmentRoleEntity) WorkspaceRoleEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceRoleEntity) RolePermission(fi.otavanopisto.muikku.model.security.RolePermission) Permission(fi.otavanopisto.muikku.model.security.Permission) WorkspaceRoleArchetype(fi.otavanopisto.muikku.model.workspace.WorkspaceRoleArchetype)

Example 7 with EnvironmentRoleArchetype

use of fi.otavanopisto.muikku.model.users.EnvironmentRoleArchetype in project muikku by otavanopisto.

the class UserRESTService method searchStaffMembers.

@GET
@Path("/staffMembers")
@RESTPermit(handling = Handling.INLINE)
public Response searchStaffMembers(@QueryParam("searchString") String searchString, @QueryParam("properties") String properties, @QueryParam("workspaceEntityId") Long workspaceEntityId, @QueryParam("firstResult") @DefaultValue("0") Integer firstResult, @QueryParam("maxResults") @DefaultValue("10") Integer maxResults) {
    if (!sessionController.isLoggedIn()) {
        return Response.status(Status.FORBIDDEN).build();
    }
    List<fi.otavanopisto.muikku.rest.model.StaffMember> staffMembers = new ArrayList<>();
    Set<Long> userGroupFilters = null;
    Set<Long> workspaceFilters = workspaceEntityId == null ? null : Collections.singleton(workspaceEntityId);
    List<SchoolDataIdentifier> userIdentifiers = null;
    SearchProvider elasticSearchProvider = getProvider("elastic-search");
    if (elasticSearchProvider != null) {
        String[] fields;
        if (StringUtils.isNumeric(searchString)) {
            fields = new String[] { "firstName", "lastName", "userEntityId", "email" };
        } else {
            fields = new String[] { "firstName", "lastName", "email" };
        }
        List<EnvironmentRoleArchetype> nonStudentArchetypes = new ArrayList<>(Arrays.asList(EnvironmentRoleArchetype.values()));
        nonStudentArchetypes.remove(EnvironmentRoleArchetype.STUDENT);
        SearchResult result = elasticSearchProvider.searchUsers(searchString, fields, nonStudentArchetypes, userGroupFilters, workspaceFilters, userIdentifiers, false, false, false, firstResult, maxResults);
        List<Map<String, Object>> results = result.getResults();
        if (results != null && !results.isEmpty()) {
            WorkspaceEntity workspaceEntity = workspaceEntityId == null ? null : workspaceEntityController.findWorkspaceEntityById(workspaceEntityId);
            String[] propertyArray = StringUtils.isEmpty(properties) ? new String[0] : properties.split(",");
            for (Map<String, Object> o : results) {
                String studentId = (String) o.get("id");
                if (StringUtils.isBlank(studentId)) {
                    logger.severe("Could not process user found from search index because it had a null id");
                    continue;
                }
                String[] studentIdParts = studentId.split("/", 2);
                SchoolDataIdentifier studentIdentifier = studentIdParts.length == 2 ? new SchoolDataIdentifier(studentIdParts[0], studentIdParts[1]) : null;
                if (studentIdentifier == null) {
                    logger.severe(String.format("Could not process user found from search index with id %s", studentId));
                    continue;
                }
                if (studentIdentifier.getIdentifier().startsWith("STUDENT-")) {
                    // the elasticsearch query returns both. We need to filter them after the fact.
                    continue;
                }
                String email = userEmailEntityController.getUserDefaultEmailAddress(studentIdentifier, false);
                Long userEntityId = new Long((Integer) o.get("userEntityId"));
                UserEntity userEntity = userEntityController.findUserEntityById(userEntityId);
                Map<String, String> propertyMap = new HashMap<String, String>();
                if (userEntity != null) {
                    for (int i = 0; i < propertyArray.length; i++) {
                        UserEntityProperty userEntityProperty = userEntityController.getUserEntityPropertyByKey(userEntity, propertyArray[i]);
                        propertyMap.put(propertyArray[i], userEntityProperty == null ? null : userEntityProperty.getValue());
                    }
                }
                if (workspaceEntity != null) {
                    WorkspaceUserEntity workspaceUserEntity = workspaceUserEntityController.findActiveWorkspaceUserByWorkspaceEntityAndUserEntity(workspaceEntity, userEntity);
                    if (workspaceUserEntity == null || workspaceUserEntity.getWorkspaceUserRole().getArchetype() != WorkspaceRoleArchetype.TEACHER) {
                        continue;
                    }
                }
                staffMembers.add(new fi.otavanopisto.muikku.rest.model.StaffMember(studentIdentifier.toId(), new Long((Integer) o.get("userEntityId")), (String) o.get("firstName"), (String) o.get("lastName"), email, propertyMap));
            }
        }
    }
    return Response.ok(staffMembers).build();
}
Also used : SchoolDataIdentifier(fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier) UserSchoolDataIdentifier(fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier) EnvironmentRoleArchetype(fi.otavanopisto.muikku.model.users.EnvironmentRoleArchetype) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) UserEntityProperty(fi.otavanopisto.muikku.model.users.UserEntityProperty) WorkspaceUserEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceUserEntity) SearchProvider(fi.otavanopisto.muikku.search.SearchProvider) SearchResult(fi.otavanopisto.muikku.search.SearchResult) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity) WorkspaceUserEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceUserEntity) WorkspaceEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceEntity) Map(java.util.Map) HashMap(java.util.HashMap) Path(javax.ws.rs.Path) RESTPermit(fi.otavanopisto.security.rest.RESTPermit) GET(javax.ws.rs.GET)

Example 8 with EnvironmentRoleArchetype

use of fi.otavanopisto.muikku.model.users.EnvironmentRoleArchetype in project muikku by otavanopisto.

the class ElasticSearchProvider method searchUsers.

@Override
public SearchResult searchUsers(String text, String[] textFields, Collection<EnvironmentRoleArchetype> archetypes, Collection<Long> groups, Collection<Long> workspaces, Collection<SchoolDataIdentifier> userIdentifiers, Boolean includeInactiveStudents, Boolean includeHidden, Boolean onlyDefaultUsers, int start, int maxResults, Collection<String> fields, Collection<SchoolDataIdentifier> excludeSchoolDataIdentifiers, Date startedStudiesBefore, Date studyTimeEndsBefore) {
    try {
        long now = OffsetDateTime.now().toEpochSecond();
        text = sanitizeSearchString(text);
        BoolQueryBuilder query = boolQuery();
        if (!Boolean.TRUE.equals(includeHidden)) {
            query.mustNot(termQuery("hidden", true));
        }
        if (Boolean.TRUE.equals(onlyDefaultUsers)) {
            query.must(termQuery("isDefaultIdentifier", true));
        }
        if (StringUtils.isNotBlank(text) && !ArrayUtils.isEmpty(textFields)) {
            String[] words = text.split(" ");
            for (int i = 0; i < words.length; i++) {
                if (StringUtils.isNotBlank(words[i])) {
                    BoolQueryBuilder fieldBuilder = boolQuery();
                    for (String textField : textFields) {
                        fieldBuilder.should(prefixQuery(textField, words[i]));
                    }
                    query.must(fieldBuilder);
                }
            }
        }
        if (excludeSchoolDataIdentifiers != null) {
            IdsQueryBuilder excludeIdsQuery = idsQuery("User");
            for (SchoolDataIdentifier excludeSchoolDataIdentifier : excludeSchoolDataIdentifiers) {
                excludeIdsQuery.addIds(String.format("%s/%s", excludeSchoolDataIdentifier.getIdentifier(), excludeSchoolDataIdentifier.getDataSource()));
            }
            query.mustNot(excludeIdsQuery);
        }
        if (startedStudiesBefore != null) {
            query.must(rangeQuery("studyStartDate").lt((long) startedStudiesBefore.getTime() / 1000));
        }
        if (studyTimeEndsBefore != null) {
            query.must(rangeQuery("studyTimeEnd").lt((long) studyTimeEndsBefore.getTime() / 1000));
        }
        if (archetypes != null) {
            List<String> archetypeNames = new ArrayList<>(archetypes.size());
            for (EnvironmentRoleArchetype archetype : archetypes) {
                archetypeNames.add(archetype.name().toLowerCase());
            }
            query.must(termsQuery("archetype", archetypeNames.toArray(new String[0])));
        }
        if (groups != null) {
            query.must(termsQuery("groups", ArrayUtils.toPrimitive(groups.toArray(new Long[0]))));
        }
        if (workspaces != null) {
            query.must(termsQuery("workspaces", ArrayUtils.toPrimitive(workspaces.toArray(new Long[0]))));
        }
        if (userIdentifiers != null) {
            IdsQueryBuilder includeIdsQuery = idsQuery("User");
            for (SchoolDataIdentifier userIdentifier : userIdentifiers) {
                includeIdsQuery.addIds(String.format("%s/%s", userIdentifier.getIdentifier(), userIdentifier.getDataSource()));
            }
            query.must(includeIdsQuery);
        }
        if (includeInactiveStudents == false) {
            /**
             * List only active users.
             *
             * Active user is
             * - staff member (teacher, manager, study guider, study programme leader, administrator)
             * - student that has study start date (in the past) and no study end date
             * - student that has study start date (in the past) and study end date in the future
             * - student that has no study start and end date but belongs to an active workspace
             *
             * Active workspace is
             * - published and
             * - either has no start/end date or current date falls between them
             */
            Set<Long> activeWorkspaceEntityIds = getActiveWorkspaces();
            query.must(boolQuery().should(termsQuery("archetype", EnvironmentRoleArchetype.TEACHER.name().toLowerCase(), EnvironmentRoleArchetype.MANAGER.name().toLowerCase(), EnvironmentRoleArchetype.STUDY_GUIDER.name().toLowerCase(), EnvironmentRoleArchetype.STUDY_PROGRAMME_LEADER.name().toLowerCase(), EnvironmentRoleArchetype.ADMINISTRATOR.name().toLowerCase())).should(boolQuery().must(termQuery("archetype", EnvironmentRoleArchetype.STUDENT.name().toLowerCase())).must(existsQuery("studyStartDate")).must(rangeQuery("studyStartDate").lte(now)).mustNot(existsQuery("studyEndDate"))).should(boolQuery().must(termQuery("archetype", EnvironmentRoleArchetype.STUDENT.name().toLowerCase())).must(existsQuery("studyStartDate")).must(rangeQuery("studyStartDate").lte(now)).must(existsQuery("studyEndDate")).must(rangeQuery("studyEndDate").gte(now))).should(boolQuery().must(termQuery("archetype", EnvironmentRoleArchetype.STUDENT.name().toLowerCase())).mustNot(existsQuery("studyEndDate")).mustNot(existsQuery("studyStartDate")).must(termsQuery("workspaces", ArrayUtils.toPrimitive(activeWorkspaceEntityIds.toArray(new Long[0]))))));
        }
        SearchRequestBuilder requestBuilder = elasticClient.prepareSearch("muikku").setTypes("User").setFrom(start).setSize(maxResults);
        if (CollectionUtils.isNotEmpty(fields)) {
            requestBuilder.addFields(fields.toArray(new String[0]));
        }
        SearchResponse response = requestBuilder.setQuery(query).addSort("_score", SortOrder.DESC).addSort("lastName", SortOrder.ASC).addSort("firstName", SortOrder.ASC).execute().actionGet();
        List<Map<String, Object>> searchResults = new ArrayList<Map<String, Object>>();
        SearchHits searchHits = response.getHits();
        long totalHitCount = searchHits.getTotalHits();
        SearchHit[] results = searchHits.getHits();
        for (SearchHit hit : results) {
            Map<String, Object> hitSource = hit.getSource();
            if (hitSource == null) {
                hitSource = new HashMap<>();
                for (String key : hit.getFields().keySet()) {
                    hitSource.put(key, hit.getFields().get(key).getValue().toString());
                }
            }
            hitSource.put("indexType", hit.getType());
            searchResults.add(hitSource);
        }
        SearchResult result = new SearchResult(start, maxResults, searchResults, totalHitCount);
        return result;
    } catch (Exception e) {
        logger.log(Level.SEVERE, "ElasticSearch query failed unexpectedly", e);
        return new SearchResult(0, 0, new ArrayList<Map<String, Object>>(), 0);
    }
}
Also used : SchoolDataIdentifier(fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier) IdsQueryBuilder(org.elasticsearch.index.query.IdsQueryBuilder) EnvironmentRoleArchetype(fi.otavanopisto.muikku.model.users.EnvironmentRoleArchetype) SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) SearchHit(org.elasticsearch.search.SearchHit) ArrayList(java.util.ArrayList) SearchResult(fi.otavanopisto.muikku.search.SearchResult) UnknownHostException(java.net.UnknownHostException) SearchResponse(org.elasticsearch.action.search.SearchResponse) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) SearchHits(org.elasticsearch.search.SearchHits) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

EnvironmentRoleArchetype (fi.otavanopisto.muikku.model.users.EnvironmentRoleArchetype)8 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)4 Permission (fi.otavanopisto.muikku.model.security.Permission)3 RolePermission (fi.otavanopisto.muikku.model.security.RolePermission)3 EnvironmentRoleEntity (fi.otavanopisto.muikku.model.users.EnvironmentRoleEntity)3 RoleEntity (fi.otavanopisto.muikku.model.users.RoleEntity)3 UserEntity (fi.otavanopisto.muikku.model.users.UserEntity)3 UserGroupEntity (fi.otavanopisto.muikku.model.users.UserGroupEntity)3 WorkspaceEntity (fi.otavanopisto.muikku.model.workspace.WorkspaceEntity)3 SchoolDataIdentifier (fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier)3 SearchResult (fi.otavanopisto.muikku.search.SearchResult)3 Map (java.util.Map)3 EnvironmentUser (fi.otavanopisto.muikku.model.users.EnvironmentUser)2 UserSchoolDataIdentifier (fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier)2 WorkspaceRoleArchetype (fi.otavanopisto.muikku.model.workspace.WorkspaceRoleArchetype)2 WorkspaceRoleEntity (fi.otavanopisto.muikku.model.workspace.WorkspaceRoleEntity)2 WorkspaceUserEntity (fi.otavanopisto.muikku.model.workspace.WorkspaceUserEntity)2 User (fi.otavanopisto.muikku.schooldata.entity.User)2 SearchProvider (fi.otavanopisto.muikku.search.SearchProvider)2