Search in sources :

Example 1 with TemporaryKey

use of org.olat.registration.TemporaryKey in project OpenOLAT by OpenOLAT.

the class ProfileFormController method formOK.

@Override
protected void formOK(final UserRequest ureq) {
    User user = identityToModify.getUser();
    // update each user field
    for (UserPropertyHandler userPropertyHandler : userPropertyHandlers) {
        FormItem formItem = formItems.get(userPropertyHandler.getName());
        if (formItem.isEnabled()) {
            userPropertyHandler.updateUserFromFormItem(user, formItem);
        }
    }
    if (portraitDeleted) {
        File img = dps.getLargestPortrait(identityToModify.getName());
        if (img != null) {
            dps.deletePortrait(identityToModify);
            notifyPortraitChanged();
        }
    }
    File uploadedImage = portraitUpload.getUploadFile();
    String uploadedFilename = portraitUpload.getUploadFileName();
    if (uploadedImage != null) {
        dps.setPortrait(uploadedImage, uploadedFilename, identityToModify.getName());
        notifyPortraitChanged();
    }
    if (logoDeleted) {
        File img = dps.getLargestLogo(identityToModify.getName());
        if (img != null) {
            dps.deleteLogo(identityToModify);
            notifyPortraitChanged();
        }
    }
    if (logoUpload != null) {
        File uploadedLogo = logoUpload.getUploadFile();
        String uploadedLogoname = logoUpload.getUploadFileName();
        if (uploadedLogo != null) {
            dps.setLogo(uploadedLogo, uploadedLogoname, identityToModify.getName());
            notifyPortraitChanged();
        }
    }
    // Store the "about me" text.
    HomePageConfig conf = hpcm.loadConfigFor(identityToModify.getName());
    conf.setTextAboutMe(textAboutMe.getValue());
    hpcm.saveConfigTo(identityToModify.getName(), conf);
    // fire the appropriate event
    fireEvent(ureq, Event.DONE_EVENT);
    // update the user profile data
    CoordinatorManager.getInstance().getCoordinator().getSyncer().doInSync(OresHelper.createOLATResourceableInstance(Identity.class, identityToModify.getKey()), new SyncerExecutor() {

        @Override
        public void execute() {
            UserManager um = UserManager.getInstance();
            identityToModify = (Identity) DBFactory.getInstance().loadObject(identityToModify);
            currentEmail = identityToModify.getUser().getProperty("email", null);
            identityToModify = updateIdentityFromFormData(identityToModify);
            changedEmail = identityToModify.getUser().getProperty("email", null);
            emailChanged = false;
            if ((currentEmail == null && StringHelper.containsNonWhitespace(changedEmail)) || (currentEmail != null && !currentEmail.equals(changedEmail))) {
                if (isAllowedToChangeEmailWithoutVerification(ureq) || !StringHelper.containsNonWhitespace(changedEmail)) {
                    String key = identityToModify.getUser().getProperty("emchangeKey", null);
                    TemporaryKey tempKey = rm.loadTemporaryKeyByRegistrationKey(key);
                    if (tempKey != null) {
                        rm.deleteTemporaryKey(tempKey);
                    }
                    securityManager.deleteInvalidAuthenticationsByEmail(currentEmail);
                } else {
                    emailChanged = true;
                    // change email address to old address until it is verified
                    identityToModify.getUser().setProperty("email", currentEmail);
                }
            }
            if (!um.updateUserFromIdentity(identityToModify)) {
                getWindowControl().setInfo(translate("profile.unsuccessful"));
                // reload user data from db
                identityToModify = BaseSecurityManager.getInstance().loadIdentityByKey(identityToModify.getKey());
            }
            OLATResourceable modRes = OresHelper.createOLATResourceableInstance(Identity.class, identityToModify.getKey());
            CoordinatorManager.getInstance().getCoordinator().getEventBus().fireEventToListenersOf(new MultiUserEvent("changed"), modRes);
            if (!emailChanged) {
                fireEvent(ureq, Event.FAILED_EVENT);
            }
        }
    });
    if (emailChanged) {
        removeAsListenerAndDispose(dialogCtr);
        String dialogText = "";
        if (identityToModify.equals(ureq.getIdentity())) {
            dialogText = translate("email.change.dialog.text");
        } else {
            dialogText = translate("email.change.dialog.text.usermanager");
        }
        dialogCtr = DialogBoxUIFactory.createYesNoDialog(ureq, getWindowControl(), translate("email.change.dialog.title"), dialogText);
        listenTo(dialogCtr);
        dialogCtr.activate();
    }
}
Also used : User(org.olat.core.id.User) OLATResourceable(org.olat.core.id.OLATResourceable) FormItem(org.olat.core.gui.components.form.flexible.FormItem) TemporaryKey(org.olat.registration.TemporaryKey) SyncerExecutor(org.olat.core.util.coordinate.SyncerExecutor) Identity(org.olat.core.id.Identity) File(java.io.File) MultiUserEvent(org.olat.core.util.event.MultiUserEvent) UserPropertyHandler(org.olat.user.propertyhandlers.UserPropertyHandler)

Example 2 with TemporaryKey

use of org.olat.registration.TemporaryKey in project OpenOLAT by OpenOLAT.

the class RegistrationWebService method register.

/**
 * Register with the specified email
 * @response.representation.200.doc Registration successful
 * @response.representation.304.doc Already registered, HTTP-Header location set to redirect
 * @response.representation.400.doc Email address not allowed
 * @param email The email address
 * @param request The HTTP Request
 * @return
 */
@PUT
public Response register(@QueryParam("email") String email, @Context HttpServletRequest request) {
    if (!CoreSpringFactory.getImpl(RegistrationModule.class).isSelfRegistrationEnabled()) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    }
    ResponseBuilder response;
    Locale locale = getLocale(request);
    Translator translator = getTranslator(locale);
    MailManager mailM = CoreSpringFactory.getImpl(MailManager.class);
    UserManager userManager = UserManager.getInstance();
    RegistrationManager rm = CoreSpringFactory.getImpl(RegistrationManager.class);
    boolean foundUser = userManager.findUniqueIdentityByEmail(email) != null;
    boolean noNewUserWithEmail = !userManager.isEmailAllowed(email);
    String serverpath = Settings.getServerContextPathURI();
    if (foundUser && noNewUserWithEmail) {
        // redirect
        URI redirectUri = UriBuilder.fromUri(Settings.getServerContextPathURI()).build();
        response = Response.ok().status(Status.NOT_MODIFIED).location(redirectUri);
    } else if (userManager.isEmailAllowed(email)) {
        String ip = request.getRemoteAddr();
        TemporaryKey tk = null;
        UserModule userModule = CoreSpringFactory.getImpl(UserModule.class);
        if (userModule.isEmailUnique()) {
            tk = rm.loadTemporaryKeyByEmail(email);
        }
        if (tk == null) {
            tk = rm.loadOrCreateTemporaryKeyByEmail(email, ip, RegistrationManager.REGISTRATION);
        }
        String today = DateFormat.getDateInstance(DateFormat.LONG, locale).format(new Date());
        String[] bodyAttrs = new String[] { serverpath, tk.getRegistrationKey(), CoreSpringFactory.getImpl(I18nModule.class).getLocaleKey(locale) };
        String[] whereFromAttrs = new String[] { serverpath, today, ip };
        String body = translator.translate("reg.body", bodyAttrs) + SEPARATOR + translator.translate("reg.wherefrom", whereFromAttrs);
        try {
            MailBundle bundle = new MailBundle();
            bundle.setTo(email);
            bundle.setContent(translator.translate("reg.subject"), body);
            MailerResult result = mailM.sendExternMessage(bundle, null, true);
            if (result.isSuccessful()) {
                response = Response.ok();
            } else {
                response = Response.serverError().status(Status.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            response = Response.serverError().status(Status.INTERNAL_SERVER_ERROR);
            log.error("", e);
        }
    } else {
        response = Response.serverError().status(Status.BAD_REQUEST);
    }
    return response.build();
}
Also used : Locale(java.util.Locale) RestSecurityHelper.getLocale(org.olat.restapi.security.RestSecurityHelper.getLocale) RegistrationManager(org.olat.registration.RegistrationManager) MailerResult(org.olat.core.util.mail.MailerResult) TemporaryKey(org.olat.registration.TemporaryKey) URI(java.net.URI) Date(java.util.Date) Translator(org.olat.core.gui.translator.Translator) UserManager(org.olat.user.UserManager) MailManager(org.olat.core.util.mail.MailManager) UserModule(org.olat.user.UserModule) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) MailBundle(org.olat.core.util.mail.MailBundle) PUT(javax.ws.rs.PUT)

Example 3 with TemporaryKey

use of org.olat.registration.TemporaryKey in project openolat by klemens.

the class SendTokenToUserForm method sendToken.

private void sendToken(UserRequest ureq, String text) {
    // mailer configuration
    // We allow creation of password token when user has no password so far or when he as an OpenOLAT Password.
    // For other cases such as Shibboleth, LDAP, oAuth etc. we don't allow creation of token as this is most
    // likely not a desired action.
    List<Authentication> authentications = BaseSecurityManager.getInstance().getAuthentications(user);
    boolean isOOpwdAllowed = (authentications.size() == 0);
    for (Authentication authentication : authentications) {
        if (authentication.getProvider().equals(BaseSecurityModule.getDefaultAuthProviderIdentifier())) {
            isOOpwdAllowed = true;
        }
    }
    if (!isOOpwdAllowed) {
        showWarning("sendtoken.wrong.auth");
        return;
    }
    Preferences prefs = user.getUser().getPreferences();
    Locale locale = i18nManager.getLocaleOrDefault(prefs.getLanguage());
    String emailAdress = user.getUser().getProperty(UserConstants.EMAIL, locale);
    String ip = ureq.getHttpReq().getRemoteAddr();
    TemporaryKey tk = registrationManager.createAndDeleteOldTemporaryKey(user.getKey(), emailAdress, ip, RegistrationManager.PW_CHANGE);
    if (text.indexOf(dummyKey) < 0) {
        showWarning("changeuserpwd.failed");
        logWarn("Can not replace temporary registration token in change pwd mail token dialog, user probably changed temporary token in mai template", null);
        return;
    }
    String body = text.replace(dummyKey, tk.getRegistrationKey());
    Translator userTrans = Util.createPackageTranslator(RegistrationManager.class, locale);
    MailBundle bundle = new MailBundle();
    bundle.setToId(user);
    bundle.setContent(userTrans.translate("pwchange.subject"), body);
    MailerResult result = mailManager.sendExternMessage(bundle, null, false);
    if (result.getReturnCode() == 0) {
        showInfo("email.sent");
    } else {
        showInfo("email.notsent");
    }
}
Also used : Locale(java.util.Locale) Translator(org.olat.core.gui.translator.Translator) MailerResult(org.olat.core.util.mail.MailerResult) Authentication(org.olat.basesecurity.Authentication) TemporaryKey(org.olat.registration.TemporaryKey) Preferences(org.olat.core.id.Preferences) MailBundle(org.olat.core.util.mail.MailBundle)

Example 4 with TemporaryKey

use of org.olat.registration.TemporaryKey in project OpenOLAT by OpenOLAT.

the class UserDeletionManager method deleteIdentity.

/**
 * Delete all user-data in registered deleteable resources.
 * @param identity
 * @return true
 */
public void deleteIdentity(Identity identity) {
    logInfo("Start deleteIdentity for identity=" + identity);
    String newName = getBackupStringWithDate(identity.getName());
    logInfo("Start Deleting user=" + identity);
    File archiveFilePath = getArchivFilePath(identity);
    Map<String, UserDataDeletable> userDataDeletableResourcesMap = CoreSpringFactory.getBeansOfType(UserDataDeletable.class);
    List<UserDataDeletable> userDataDeletableResources = new ArrayList<>(userDataDeletableResourcesMap.values());
    Collections.sort(userDataDeletableResources, new UserDataDeletableComparator());
    for (UserDataDeletable element : userDataDeletableResources) {
        logInfo("UserDataDeletable-Loop element=" + element);
        element.deleteUserData(identity, newName, archiveFilePath);
    }
    // Delete all authentications for certain identity
    List<Authentication> authentications = securityManager.getAuthentications(identity);
    for (Authentication auth : authentications) {
        logInfo("deleteAuthentication auth=" + auth);
        securityManager.deleteAuthentication(auth);
        logDebug("Delete auth=" + auth + "  of identity=" + identity);
    }
    // remove identity from its security groups
    List<SecurityGroup> securityGroups = securityManager.getSecurityGroupsForIdentity(identity);
    for (SecurityGroup secGroup : securityGroups) {
        securityManager.removeIdentityFromSecurityGroup(identity, secGroup);
        logInfo("Removing user=" + identity + " from security group=" + secGroup.toString());
    }
    // remove identity from groups
    groupDao.removeMemberships(identity);
    String key = identity.getUser().getProperty("emchangeKey", null);
    TemporaryKey tempKey = registrationManager.loadTemporaryKeyByRegistrationKey(key);
    if (tempKey != null) {
        registrationManager.deleteTemporaryKey(tempKey);
    }
    identity = securityManager.loadIdentityByKey(identity.getKey());
    // keep login-name only -> change email
    User persistedUser = identity.getUser();
    List<UserPropertyHandler> userPropertyHandlers = UserManager.getInstance().getAllUserPropertyHandlers();
    for (UserPropertyHandler userPropertyHandler : userPropertyHandlers) {
        String actualProperty = userPropertyHandler.getName();
        if (userPropertyHandler.isDeletable() && !(keepUserEmailAfterDeletion && UserConstants.EMAIL.equals(actualProperty))) {
            persistedUser.setProperty(actualProperty, null);
        }
        if ((!keepUserEmailAfterDeletion && UserConstants.EMAIL.equals(actualProperty))) {
            String oldEmail = userPropertyHandler.getUserProperty(persistedUser, null);
            String newEmail = "";
            if (StringHelper.containsNonWhitespace(oldEmail)) {
                newEmail = getBackupStringWithDate(oldEmail);
            }
            logInfo("Update user-property user=" + persistedUser);
            userPropertyHandler.setUserProperty(persistedUser, newEmail);
        }
    }
    UserManager.getInstance().updateUserFromIdentity(identity);
    logInfo("deleteUserProperties user=" + persistedUser);
    dbInstance.commit();
    identity = securityManager.loadIdentityByKey(identity.getKey());
    // keep email only -> change login-name
    if (!keepUserEmailAfterDeletion) {
        identity = securityManager.saveIdentityName(identity, newName, null);
    }
    // keep everything, change identity.status to deleted
    logInfo("Change stater identity=" + identity);
    identity = securityManager.saveIdentityStatus(identity, Identity.STATUS_DELETED);
    LifeCycleManager.createInstanceFor(identity).deleteTimestampFor(SEND_DELETE_EMAIL_ACTION);
    LifeCycleManager.createInstanceFor(identity).markTimestampFor(USER_DELETED_ACTION, createLifeCycleLogDataFor(identity));
    logAudit("User-Deletion: Delete all userdata for identity=" + identity);
}
Also used : User(org.olat.core.id.User) TemporaryKey(org.olat.registration.TemporaryKey) ArrayList(java.util.ArrayList) SecurityGroup(org.olat.basesecurity.SecurityGroup) Authentication(org.olat.basesecurity.Authentication) UserDataDeletable(org.olat.user.UserDataDeletable) File(java.io.File) UserPropertyHandler(org.olat.user.propertyhandlers.UserPropertyHandler)

Example 5 with TemporaryKey

use of org.olat.registration.TemporaryKey in project openolat by klemens.

the class ChangePasswordWebService method register.

/**
 * @param identityKey
 * @param request
 * @return
 */
@PUT
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response register(@QueryParam("identityKey") Long identityKey, @Context HttpServletRequest request) {
    if (!isUserManager(request)) {
        return Response.serverError().status(Status.UNAUTHORIZED).build();
    }
    BaseSecurity securityManager = CoreSpringFactory.getImpl(BaseSecurity.class);
    Identity identity = securityManager.loadIdentityByKey(identityKey);
    if (identity == null) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    } else if (!CoreSpringFactory.getImpl(UserModule.class).isPwdChangeAllowed(identity)) {
        return Response.serverError().status(Status.FORBIDDEN).build();
    }
    RegistrationManager rm = CoreSpringFactory.getImpl(RegistrationManager.class);
    String emailAdress = identity.getUser().getProperty(UserConstants.EMAIL, null);
    String ip = request.getRemoteAddr();
    TemporaryKey tk = rm.createAndDeleteOldTemporaryKey(identity.getKey(), emailAdress, ip, RegistrationManager.PW_CHANGE);
    return Response.ok(new TemporaryKeyVO(tk)).build();
}
Also used : RegistrationManager(org.olat.registration.RegistrationManager) TemporaryKey(org.olat.registration.TemporaryKey) UserModule(org.olat.user.UserModule) Identity(org.olat.core.id.Identity) BaseSecurity(org.olat.basesecurity.BaseSecurity) Produces(javax.ws.rs.Produces) PUT(javax.ws.rs.PUT)

Aggregations

TemporaryKey (org.olat.registration.TemporaryKey)16 User (org.olat.core.id.User)8 File (java.io.File)6 MailBundle (org.olat.core.util.mail.MailBundle)6 MailerResult (org.olat.core.util.mail.MailerResult)6 UserPropertyHandler (org.olat.user.propertyhandlers.UserPropertyHandler)6 XStream (com.thoughtworks.xstream.XStream)4 Date (java.util.Date)4 HashMap (java.util.HashMap)4 Locale (java.util.Locale)4 PUT (javax.ws.rs.PUT)4 Authentication (org.olat.basesecurity.Authentication)4 FormItem (org.olat.core.gui.components.form.flexible.FormItem)4 Translator (org.olat.core.gui.translator.Translator)4 Identity (org.olat.core.id.Identity)4 RegistrationManager (org.olat.registration.RegistrationManager)4 UserModule (org.olat.user.UserModule)4 URI (java.net.URI)2 ArrayList (java.util.ArrayList)2 Calendar (java.util.Calendar)2