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");
}
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();
}
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);
}
}
Aggregations