Search in sources :

Example 76 with UserEntity

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

the class AbstractAuthenticationStrategy method login.

private AuthenticationResult login(UserIdentification userIdentification, User user, boolean newAccount) {
    UserEntity userEntity = userIdentification.getUser();
    UserEntity loggedUser = sessionController.getLoggedUserEntity();
    if ((loggedUser == null) || loggedUser.getId().equals(userEntity.getId())) {
        Locale locale = null;
        if (StringUtils.isNotBlank(userEntity.getLocale())) {
            try {
                locale = LocaleUtils.toLocale(userEntity.getLocale());
            } catch (Exception e) {
                logger.log(Level.SEVERE, String.format("Failed to parse locale %s for user entity %d", loggedUser.getLocale(), loggedUser.getId()));
            }
        }
        if (locale == null) {
            locale = new Locale("fi");
        }
        sessionController.setLocale(locale);
        SchoolDataSource schoolDataSource = schoolDataController.findSchoolDataSource(user.getSchoolDataSource());
        userEntityController.updateDefaultSchoolDataSource(userEntity, schoolDataSource);
        userEntityController.updateDefaultIdentifier(userEntity, user.getIdentifier());
        sessionController.login(schoolDataSource.getIdentifier(), user.getIdentifier(), user.getStudyEndDate() == null);
        userEntityController.updateLastLogin(userEntity);
        HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        userLoggedInEvent.fire(new LoginEvent(userEntity.getId(), sessionController.getLoggedUser(), this, req.getRemoteAddr()));
        return new AuthenticationResult(newAccount ? Status.NEW_ACCOUNT : Status.LOGIN);
    } else {
        return new AuthenticationResult(Status.CONFLICT, ConflictReason.LOGGED_IN_AS_DIFFERENT_USER);
    }
}
Also used : Locale(java.util.Locale) HttpServletRequest(javax.servlet.http.HttpServletRequest) SchoolDataSource(fi.otavanopisto.muikku.model.base.SchoolDataSource) LoginEvent(fi.otavanopisto.muikku.events.LoginEvent) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity)

Example 77 with UserEntity

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

the class NoPassedCoursesNotificationStrategy method sendNotifications.

@Override
public void sendNotifications() {
    List<SchoolDataIdentifier> studentsToNotify = getStudentsToNotify();
    for (SchoolDataIdentifier studentIdentifier : studentsToNotify) {
        UserEntity studentEntity = userEntityController.findUserEntityByUserIdentifier(studentIdentifier);
        if (studentEntity != null) {
            Locale studentLocale = localeController.resolveLocale(LocaleUtils.toLocale(studentEntity.getLocale()));
            Map<String, Object> templateModel = new HashMap<>();
            templateModel.put("locale", studentLocale);
            templateModel.put("localeHelper", jadeLocaleHelper);
            String notificationContent = renderNotificationTemplate("no-passed-courses-notification", templateModel);
            notificationController.sendNotification(localeController.getText(studentLocale, "plugin.timednotifications.notification.category"), localeController.getText(studentLocale, "plugin.timednotifications.notification.nopassedcourses.subject"), notificationContent, studentEntity, studentIdentifier, "nopassedcourses");
            noPassedCoursesNotificationController.createNoPassedCoursesNotification(studentIdentifier);
        } else {
            logger.log(Level.SEVERE, String.format("Cannot send notification to student with identifier %s because UserEntity was not found", studentIdentifier.toId()));
        }
    }
}
Also used : SchoolDataIdentifier(fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier) Locale(java.util.Locale) HashMap(java.util.HashMap) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity)

Example 78 with UserEntity

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

the class RequestedAssessmentSupplementationsNotificationStrategy method sendNotifications.

@Override
public void sendNotifications() {
    Collection<Long> groups = getGroups();
    if (groups.isEmpty()) {
        return;
    }
    // Iterate through active students who belong to pre-configured groups (read: study programs)
    SearchResult searchResult = requestedAssessmentSupplementationsNotificationController.searchActiveStudentIds(groups, FIRST_RESULT + offset, MAX_RESULTS);
    logger.log(Level.INFO, String.format("%s processing %d/%d", getClass().getSimpleName(), offset, searchResult.getTotalHitCount()));
    if ((offset + MAX_RESULTS) > searchResult.getTotalHitCount()) {
        offset = 0;
    } else {
        offset += MAX_RESULTS;
    }
    for (Map<String, Object> result : searchResult.getResults()) {
        String studentId = (String) result.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;
        }
        UserEntity studentEntity = userEntityController.findUserEntityByUserIdentifier(studentIdentifier);
        if (studentEntity == null) {
            logger.severe(String.format("UserEntity with identifier %s not found", studentIdentifier));
            continue;
        }
        // Iterate through the workspaces in which the student is currently active
        List<WorkspaceEntity> workspaceEntities = workspaceUserEntityController.listActiveWorkspaceEntitiesByUserIdentifier(studentIdentifier);
        for (WorkspaceEntity workspaceEntity : workspaceEntities) {
            SchoolDataIdentifier workspaceIdentifier = new SchoolDataIdentifier(workspaceEntity.getIdentifier(), workspaceEntity.getDataSource().getIdentifier());
            if (requestedAssessmentSupplementationsNotificationController.countByStudentIdentifierAndWorkspaceIdentifier(studentIdentifier, workspaceIdentifier) == 0) {
                // Skip if workspace doesn't have a supplementation request
                SupplementationRequest supplementationRequest = supplementationRequestDAO.findByStudentAndWorkspace(studentEntity.getId(), workspaceEntity.getId());
                if (supplementationRequest == null) {
                    continue;
                }
                // Skip if workspace assessment is newer than supplementation request
                WorkspaceAssessment workspaceAssessment = gradingController.findLatestWorkspaceAssessment(workspaceIdentifier, studentIdentifier);
                if (workspaceAssessment != null && workspaceAssessment.getDate().getTime() >= supplementationRequest.getRequestDate().getTime()) {
                    continue;
                }
                // Skip if assessment request is newer than supplementation request
                // TODO: At some point, refactor to simply fetch latest request by student + workspace
                WorkspaceAssessmentRequest latestAssesmentRequest = null;
                List<WorkspaceAssessmentRequest> studentAssesmentRequests = gradingController.listWorkspaceAssessmentRequests(workspaceIdentifier.getDataSource(), workspaceIdentifier.getIdentifier(), studentIdentifier.getIdentifier());
                for (WorkspaceAssessmentRequest assessmentRequest : studentAssesmentRequests) {
                    Date assessmentRequestDate = assessmentRequest.getDate();
                    if (assessmentRequestDate != null) {
                        if (latestAssesmentRequest == null || latestAssesmentRequest.getDate().before(assessmentRequestDate)) {
                            latestAssesmentRequest = assessmentRequest;
                        }
                    }
                }
                if (latestAssesmentRequest != null && latestAssesmentRequest.getDate().getTime() >= supplementationRequest.getRequestDate().getTime()) {
                    continue;
                }
                if (!supplementationRequest.getRequestDate().before(Date.from(OffsetDateTime.now().minusDays(NOTIFICATION_THRESHOLD_DAYS).toInstant()))) {
                    continue;
                }
                // If we haven't skipped so far, student needs to be notified
                Workspace workspace = workspaceController.findWorkspace(workspaceIdentifier);
                if (workspace != null) {
                    String workspaceName = StringUtils.isBlank(workspace.getNameExtension()) ? workspace.getName() : String.format("%s (%s)", workspace.getName(), workspace.getNameExtension());
                    Locale studentLocale = localeController.resolveLocale(LocaleUtils.toLocale(studentEntity.getLocale()));
                    Map<String, Object> templateModel = new HashMap<>();
                    templateModel.put("workspaceName", workspaceName);
                    templateModel.put("locale", studentLocale);
                    templateModel.put("localeHelper", jadeLocaleHelper);
                    String notificationContent = renderNotificationTemplate("requested-assessment-supplementation-notification", templateModel);
                    notificationController.sendNotification(localeController.getText(studentLocale, "plugin.timednotifications.notification.category"), localeController.getText(studentLocale, "plugin.timednotifications.notification.requestedassessmentsupplementation.subject"), notificationContent, studentEntity, studentIdentifier, "requestedassessmentsupplementation");
                    // Store notification to avoid duplicates in the future
                    requestedAssessmentSupplementationsNotificationController.createRequestedAssessmentSupplementationNotification(studentIdentifier, workspaceIdentifier);
                } else {
                    logger.log(Level.SEVERE, String.format("Cannot send notification to student with identifier %s because UserEntity or workspace was not found", studentIdentifier.toId()));
                }
            }
        }
    }
}
Also used : SchoolDataIdentifier(fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier) Locale(java.util.Locale) WorkspaceAssessment(fi.otavanopisto.muikku.schooldata.entity.WorkspaceAssessment) HashMap(java.util.HashMap) SearchResult(fi.otavanopisto.muikku.search.SearchResult) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity) Date(java.util.Date) WorkspaceEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceEntity) WorkspaceAssessmentRequest(fi.otavanopisto.muikku.schooldata.entity.WorkspaceAssessmentRequest) SupplementationRequest(fi.otavanopisto.muikku.plugins.evaluation.model.SupplementationRequest) Workspace(fi.otavanopisto.muikku.schooldata.entity.Workspace)

Example 79 with UserEntity

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

the class StudyTimeNotificationStrategy method sendNotifications.

@Override
public void sendNotifications() {
    Collection<Long> groups = getGroups();
    if (groups.isEmpty()) {
        return;
    }
    OffsetDateTime studyTimeEndsOdt = OffsetDateTime.now().plusDays(NOTIFICATION_THRESHOLD_DAYS_LEFT);
    OffsetDateTime sendNotificationIfStudentStartedBefore = OffsetDateTime.now().minusDays(DAYS_UNTIL_FIRST_NOTIFICATION);
    Date studyTimeEnds = Date.from(studyTimeEndsOdt.toInstant());
    Date lastNotifiedThresholdDate = Date.from(OffsetDateTime.now().minusDays(NOTIFICATION_THRESHOLD_DAYS_LEFT + 1).toInstant());
    List<SchoolDataIdentifier> studentIdentifierAlreadyNotified = studyTimeLeftNotificationController.listNotifiedSchoolDataIdentifiersAfter(lastNotifiedThresholdDate);
    SearchResult searchResult = studyTimeLeftNotificationController.searchActiveStudentIds(groups, FIRST_RESULT + offset, MAX_RESULTS, studentIdentifierAlreadyNotified, studyTimeEnds);
    logger.log(Level.INFO, String.format("%s processing %d/%d", getClass().getSimpleName(), offset, searchResult.getTotalHitCount()));
    if ((offset + MAX_RESULTS) > searchResult.getTotalHitCount()) {
        offset = 0;
    } else {
        offset += MAX_RESULTS;
    }
    for (SchoolDataIdentifier studentIdentifier : getStudentIdentifiers(searchResult)) {
        UserEntity studentEntity = userEntityController.findUserEntityByUserIdentifier(studentIdentifier);
        if (studentEntity != null) {
            User student = userController.findUserByIdentifier(studentIdentifier);
            if (student.getStudyStartDate() == null || student.getStudyStartDate().isAfter(sendNotificationIfStudentStartedBefore)) {
                continue;
            }
            if (student.getStudyTimeEnd() == null || student.getStudyTimeEnd().isAfter(studyTimeEndsOdt) || student.getStudyTimeEnd().isBefore(OffsetDateTime.now())) {
                continue;
            }
            Locale studentLocale = localeController.resolveLocale(LocaleUtils.toLocale(studentEntity.getLocale()));
            Map<String, Object> templateModel = new HashMap<>();
            templateModel.put("internetixStudent", student.hasEvaluationFees());
            templateModel.put("locale", studentLocale);
            templateModel.put("localeHelper", jadeLocaleHelper);
            String notificationContent = renderNotificationTemplate("study-time-notification", templateModel);
            notificationController.sendNotification(localeController.getText(studentLocale, "plugin.timednotifications.notification.category"), localeController.getText(studentLocale, "plugin.timednotifications.notification.studytime.subject"), notificationContent, studentEntity, studentIdentifier, "studytime");
            studyTimeLeftNotificationController.createStudyTimeNotification(studentIdentifier);
        } else {
            logger.log(Level.SEVERE, String.format("Cannot send notification to student with identifier %s because UserEntity was not found", studentIdentifier.toId()));
        }
    }
}
Also used : SchoolDataIdentifier(fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier) Locale(java.util.Locale) User(fi.otavanopisto.muikku.schooldata.entity.User) HashMap(java.util.HashMap) SearchResult(fi.otavanopisto.muikku.search.SearchResult) Date(java.util.Date) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity) OffsetDateTime(java.time.OffsetDateTime)

Example 80 with UserEntity

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

the class DefaultSchoolDataUserListener method onSchoolDataUserUpdatedEvent.

public void onSchoolDataUserUpdatedEvent(@Observes SchoolDataUserUpdatedEvent event) {
    Long userEntityId = event.getUserEntityId();
    SchoolDataIdentifier defaultIdentifier = event.getDefaultIdentifier();
    List<SchoolDataIdentifier> discoveredIdentifiers = event.getDiscoveredIdentifiers();
    List<SchoolDataIdentifier> updatedIdentifiers = event.getUpdatedIdentifiers();
    List<SchoolDataIdentifier> removedIdentifiers = event.getRemovedIdentifiers();
    Collection<String> allEmails = event.getAllEmails();
    if (allEmails.isEmpty()) {
        logger.warning("Updating user without email addresses");
    } else {
        // Attempt to find existing users by given emails
        Collection<UserEntity> emailUsers = userEntityController.listUserEntitiesByEmails(allEmails);
        if (emailUsers.isEmpty()) {
        // Could not find any users with given emails
        } else if (emailUsers.size() > 1) {
            logger.log(Level.SEVERE, String.format("Multiple users found with given emails (%s)", StringUtils.join(allEmails, ',')));
            return;
        } else {
            UserEntity emailUser = emailUsers.iterator().next();
            if (userEntityId != null) {
                if (!emailUser.getId().equals(userEntityId)) {
                    logger.log(Level.SEVERE, String.format("One or more of emails %s belong to another user", StringUtils.join(allEmails, ',')));
                    return;
                }
            } else {
                userEntityId = emailUser.getId();
                logger.log(Level.INFO, String.format("Found userEntity (%d) by email, merging user to existing account", userEntityId));
            }
        }
    }
    UserEntity userEntity = null;
    // If it's not an user delete event we need to create / update user into the system
    if (!discoveredIdentifiers.isEmpty() || !updatedIdentifiers.isEmpty()) {
        // UserEntityId has not been defined in the event and could not be found by email, so we create new user
        if (userEntityId == null) {
            userEntity = userEntityController.createUserEntity(defaultIdentifier.getDataSource(), defaultIdentifier.getIdentifier());
        } else {
            // Otherwise we use the existing one
            userEntity = userEntityController.findUserEntityById(userEntityId);
            if (userEntity == null) {
                logger.log(Level.WARNING, "Could not find specified userEntityId %d, aborting synchronization", userEntityId);
                return;
            }
            if (defaultIdentifier != null) {
                if (!StringUtils.equals(userEntity.getDefaultIdentifier(), defaultIdentifier.getIdentifier()) || !StringUtils.equals(userEntity.getDefaultSchoolDataSource().getIdentifier(), defaultIdentifier.getDataSource())) {
                    logger.log(Level.FINE, String.format("Updating default identifier for user #%d into %s", userEntity.getId(), defaultIdentifier));
                    userEntityController.updateDefaultSchoolDataSource(userEntity, defaultIdentifier.getDataSource());
                    userEntityController.updateDefaultIdentifier(userEntity, defaultIdentifier.getIdentifier());
                }
            }
        }
        // Attach discovered identities to user
        for (SchoolDataIdentifier identifier : discoveredIdentifiers) {
            List<String> identifierEmails = event.getEmails().get(identifier);
            UserSchoolDataIdentifier userSchoolDataIdentifier = userSchoolDataIdentifierController.findUserSchoolDataIdentifierByDataSourceAndIdentifierIncludeArchived(identifier.getDataSource(), identifier.getIdentifier());
            if (userSchoolDataIdentifier == null) {
                userSchoolDataIdentifier = userSchoolDataIdentifierController.createUserSchoolDataIdentifier(identifier.getDataSource(), identifier.getIdentifier(), userEntity);
                logger.log(Level.FINE, String.format("Added new identifier %s for user %d", identifier, userEntity.getId()));
            } else if (userSchoolDataIdentifier.getArchived()) {
                userSchoolDataIdentifierController.unarchiveUserSchoolDataIdentifier(userSchoolDataIdentifier);
            }
            userEmailEntityController.setUserEmails(userSchoolDataIdentifier, getValidEmails(identifierEmails));
        }
        for (SchoolDataIdentifier identifier : updatedIdentifiers) {
            List<String> emails = event.getEmails().get(identifier);
            userEmailEntityController.setUserEmails(identifier, getValidEmails(emails));
        }
        for (SchoolDataIdentifier identifier : removedIdentifiers) {
            List<String> emails = event.getEmails().get(identifier);
            userEmailEntityController.setUserEmails(identifier, getValidEmails(emails));
        }
        // Update users environment role
        if (event.getEnvironmentRoleIdentifier() != null) {
            EnvironmentRoleEntity environmentRoleEntity = environmentRoleEntityController.findEnvironmentRoleEntity(event.getEnvironmentRoleIdentifier().getDataSource(), event.getEnvironmentRoleIdentifier().getIdentifier());
            if (environmentRoleEntity != null) {
                EnvironmentUser environmentUser = environmentUserController.findEnvironmentUserByUserEntity(userEntity);
                if (environmentUser == null) {
                    logger.fine(String.format("UserEntity %d did not have an environment user so created new one into role %s", userEntity.getId(), environmentRoleEntity.getName()));
                    environmentUserController.createEnvironmentUser(userEntity, environmentRoleEntity);
                } else {
                    if (environmentUser.getRole() == null || !environmentUser.getRole().getId().equals(environmentRoleEntity.getId())) {
                        logger.fine(String.format("Updated UserEntity %d role into %s", userEntity.getId(), environmentRoleEntity.getName()));
                        environmentUserController.updateEnvironmentUserRole(environmentUser, environmentRoleEntity);
                    }
                }
            } else {
                logger.severe(String.format("Could not find specified environment role entity %s", event.getEnvironmentRoleIdentifier()));
            }
        } else {
            // Users new role has been set to null which means that we need to remove the environment role from the user
            EnvironmentUser environmentUser = environmentUserController.findEnvironmentUserByUserEntity(userEntity);
            if (environmentUser != null) {
                logger.info(String.format("Removed UserEntity %d environment role", userEntity.getId()));
                environmentUserController.updateEnvironmentUserRole(environmentUser, null);
            }
        }
    }
    // Remove identifiers in the removed list
    for (SchoolDataIdentifier identifier : removedIdentifiers) {
        UserSchoolDataIdentifier userSchoolDataIdentifier = userSchoolDataIdentifierController.findUserSchoolDataIdentifierByDataSourceAndIdentifier(identifier.getDataSource(), identifier.getIdentifier());
        if (userSchoolDataIdentifier != null) {
            logger.log(Level.FINE, String.format("Removing user school data identifier %s", identifier));
            userSchoolDataIdentifierController.archiveUserSchoolDataIdentifier(userSchoolDataIdentifier);
            if (userEntity == null) {
                userEntity = userSchoolDataIdentifier.getUserEntity();
            }
        }
    }
    // Finally check if user has any identifiers left, if not archive the user from the system
    if (userEntity != null) {
        if (userSchoolDataIdentifierController.listUserSchoolDataIdentifiersByUserEntity(userEntity).isEmpty()) {
            logger.log(Level.INFO, String.format("UserEntity #%d has no identities left, archiving userEntity", userEntity.getId()));
            userEntityController.archiveUserEntity(userEntity);
        }
    }
}
Also used : SchoolDataIdentifier(fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier) UserSchoolDataIdentifier(fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier) UserSchoolDataIdentifier(fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier) EnvironmentUser(fi.otavanopisto.muikku.model.users.EnvironmentUser) EnvironmentRoleEntity(fi.otavanopisto.muikku.model.users.EnvironmentRoleEntity) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity)

Aggregations

UserEntity (fi.otavanopisto.muikku.model.users.UserEntity)163 Path (javax.ws.rs.Path)101 RESTPermit (fi.otavanopisto.security.rest.RESTPermit)88 WorkspaceUserEntity (fi.otavanopisto.muikku.model.workspace.WorkspaceUserEntity)65 GET (javax.ws.rs.GET)58 SchoolDataIdentifier (fi.otavanopisto.muikku.schooldata.SchoolDataIdentifier)54 WorkspaceEntity (fi.otavanopisto.muikku.model.workspace.WorkspaceEntity)50 User (fi.otavanopisto.muikku.schooldata.entity.User)36 ArrayList (java.util.ArrayList)35 UserSchoolDataIdentifier (fi.otavanopisto.muikku.model.users.UserSchoolDataIdentifier)27 POST (javax.ws.rs.POST)26 Date (java.util.Date)24 CommunicatorMessageId (fi.otavanopisto.muikku.plugins.communicator.model.CommunicatorMessageId)22 HashMap (java.util.HashMap)20 WorkspaceMaterial (fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceMaterial)18 EnvironmentUser (fi.otavanopisto.muikku.model.users.EnvironmentUser)14 CommunicatorMessage (fi.otavanopisto.muikku.plugins.communicator.model.CommunicatorMessage)14 RESTPermitUnimplemented (fi.otavanopisto.muikku.rest.RESTPermitUnimplemented)13 UserGroupEntity (fi.otavanopisto.muikku.model.users.UserGroupEntity)12 PUT (javax.ws.rs.PUT)12