Search in sources :

Example 6 with TemporaryKey

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

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 7 with TemporaryKey

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

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 8 with TemporaryKey

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

the class OLATAuthManager method findIdentInChangingEmailWorkflow.

private Identity findIdentInChangingEmailWorkflow(String login) {
    List<TemporaryKey> tk = registrationManager.loadTemporaryKeyByAction(RegistrationManager.EMAIL_CHANGE);
    if (tk != null) {
        for (TemporaryKey temporaryKey : tk) {
            @SuppressWarnings("unchecked") Map<String, String> mails = (Map<String, String>) XStreamHelper.createXStreamInstance().fromXML(temporaryKey.getEmailAddress());
            String currentEmail = mails.get("currentEMail");
            String changedEmail = mails.get("changedEMail");
            if (login.equals(changedEmail) && StringHelper.containsNonWhitespace(currentEmail)) {
                return securityManager.findIdentityByName(currentEmail);
            }
        }
    }
    return null;
}
Also used : TemporaryKey(org.olat.registration.TemporaryKey) Map(java.util.Map)

Example 9 with TemporaryKey

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

the class ProfileFormController method createChangeEmailWorkflow.

private void createChangeEmailWorkflow(UserRequest ureq) {
    // send email
    changedEmail = changedEmail.trim();
    String body = null;
    String subject = null;
    // get remote address
    String ip = ureq.getHttpReq().getRemoteAddr();
    String today = DateFormat.getDateInstance(DateFormat.LONG, ureq.getLocale()).format(new Date());
    // mailer configuration
    String serverpath = Settings.getServerContextPathURI();
    String servername = ureq.getHttpReq().getServerName();
    logDebug("this servername is " + servername + " and serverpath is " + serverpath, null);
    // load or create temporary key
    Map<String, String> mailMap = new HashMap<>();
    mailMap.put("currentEMail", currentEmail);
    mailMap.put("changedEMail", changedEmail);
    XStream xml = XStreamHelper.createXStreamInstance();
    String serMailMap = xml.toXML(mailMap);
    TemporaryKey tk = rm.createAndDeleteOldTemporaryKey(identityToModify.getKey(), serMailMap, ip, RegistrationManager.EMAIL_CHANGE);
    // create date, time string
    Calendar cal = Calendar.getInstance();
    cal.setTime(tk.getCreationDate());
    cal.add(Calendar.DAY_OF_WEEK, ChangeEMailController.TIME_OUT);
    String time = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, ureq.getLocale()).format(cal.getTime());
    // create body and subject for email
    String link = serverpath + "/dmz/emchange/index.html?key=" + tk.getRegistrationKey() + "&language=" + ureq.getLocale().getLanguage();
    if (Settings.isDebuging()) {
        logInfo(link, null);
    }
    String currentEmailDisplay = userManager.getUserDisplayEmail(currentEmail, getLocale());
    String changedEmaildisplay = userManager.getUserDisplayEmail(changedEmail, getLocale());
    body = translate("email.change.body", new String[] { link, time, currentEmailDisplay, changedEmaildisplay }) + SEPARATOR + translate("email.change.wherefrom", new String[] { serverpath, today, ip });
    subject = translate("email.change.subject");
    // send email
    try {
        MailBundle bundle = new MailBundle();
        bundle.setFrom(WebappHelper.getMailConfig("mailReplyTo"));
        bundle.setTo(changedEmail);
        bundle.setContent(subject, body);
        MailerResult result = mailManager.sendMessage(bundle);
        boolean isMailSent = result.isSuccessful();
        if (isMailSent) {
            tk.setMailSent(true);
            // set key
            User user = this.identityToModify.getUser();
            user.setProperty("emchangeKey", tk.getRegistrationKey());
            UserManager.getInstance().updateUser(user);
            getWindowControl().setInfo(translate("email.sent"));
        } else {
            tk.setMailSent(false);
            rm.deleteTemporaryKeyWithId(tk.getRegistrationKey());
            getWindowControl().setError(translate("email.notsent"));
        }
    } catch (Exception e) {
        rm.deleteTemporaryKeyWithId(tk.getRegistrationKey());
        getWindowControl().setError(translate("email.notsent"));
    }
}
Also used : User(org.olat.core.id.User) HashMap(java.util.HashMap) MailerResult(org.olat.core.util.mail.MailerResult) XStream(com.thoughtworks.xstream.XStream) TemporaryKey(org.olat.registration.TemporaryKey) Calendar(java.util.Calendar) MailBundle(org.olat.core.util.mail.MailBundle) Date(java.util.Date)

Example 10 with TemporaryKey

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

the class ProfileFormController method initForm.

@Override
protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) {
    User user = identityToModify.getUser();
    // show a form element for each property handler
    boolean first = true;
    for (UserPropertyHandler userPropertyHandler : userPropertyHandlers) {
        if (userPropertyHandler == null) {
            continue;
        }
        // add spacer if necessary (i.e. when group name changes)
        String group = userPropertyHandler.getGroup();
        String formId = "group." + group;
        FormLayoutContainer groupContainer = (FormLayoutContainer) formLayout.getFormComponent(formId);
        if (groupContainer == null) {
            groupContainer = FormLayoutContainer.createDefaultFormLayout(formId, getTranslator());
            groupContainer.setFormTitle(translate("form.group." + group));
            if (first) {
                groupContainer.setFormContextHelp("Configuration");
                first = false;
            }
            formItems.put(formId, groupContainer);
            formLayout.add(groupContainer);
        }
        // add input field to container
        FormItem formItem = userPropertyHandler.addFormItem(getLocale(), user, usageIdentifier, isAdministrativeUser, groupContainer);
        String propertyName = userPropertyHandler.getName();
        formItems.put(propertyName, formItem);
        if (formItem instanceof TextElement) {
            // it's a text field, so get the value of this property into the text field
            TextElement textElement = (TextElement) formItem;
            textElement.setValue(user.getProperty(propertyName, getLocale()));
        } else if (formItem instanceof MultipleSelectionElement) {
            // it's a checkbox, so set the box to checked if the corresponding property is set to "true"
            MultipleSelectionElement checkbox = (MultipleSelectionElement) formItem;
            String value = user.getProperty(propertyName, getLocale());
            if (value != null) {
                checkbox.select(propertyName, value.equals("true"));
            } else {
                // assume "false" if the property is not present
                checkbox.select(propertyName, false);
            }
        }
        // special case for email field
        if (userPropertyHandler.getName().equals("email")) {
            String key = user.getProperty("emchangeKey", null);
            TemporaryKey tempKey = rm.loadTemporaryKeyByRegistrationKey(key);
            if (tempKey != null) {
                XStream xml = XStreamHelper.createXStreamInstance();
                @SuppressWarnings("unchecked") HashMap<String, String> mails = (HashMap<String, String>) xml.fromXML(tempKey.getEmailAddress());
                formItem.setExampleKey("email.change.form.info", new String[] { mails.get("changedEMail") });
            }
            if (!userModule.isEmailMandatory()) {
                formItem.setMandatory(false);
            }
        }
    }
    // add the "about me" text field.
    FormLayoutContainer groupContainer = FormLayoutContainer.createDefaultFormLayout("group.about", getTranslator());
    groupContainer.setFormTitle(translate("form.group.about"));
    groupContainer.setElementCssClass("o_user_aboutme");
    formLayout.add(groupContainer);
    HomePageConfig conf = hpcm.loadConfigFor(identityToModify.getName());
    textAboutMe = uifactory.addRichTextElementForStringData("form.text", "form.text", conf.getTextAboutMe(), 10, -1, false, null, null, groupContainer, ureq.getUserSession(), getWindowControl());
    textAboutMe.setMaxLength(10000);
    // upload image
    groupContainer = FormLayoutContainer.createDefaultFormLayout("portraitupload", getTranslator());
    groupContainer.setFormTitle(translate("ul.header"));
    formLayout.add(groupContainer);
    File portraitFile = dps.getLargestPortrait(identityToModify.getName());
    // Init upload controller
    Set<String> mimeTypes = new HashSet<>();
    mimeTypes.add("image/gif");
    mimeTypes.add("image/jpg");
    mimeTypes.add("image/jpeg");
    mimeTypes.add("image/png");
    portraitUpload = uifactory.addFileElement(getWindowControl(), "ul.select", "ul.select", groupContainer);
    portraitUpload.setMaxUploadSizeKB(10000, null, null);
    portraitUpload.setPreview(ureq.getUserSession(), true);
    portraitUpload.addActionListener(FormEvent.ONCHANGE);
    portraitUpload.setHelpTextKey("ul.select.fhelp", null);
    portraitUpload.setDeleteEnabled(true);
    if (portraitFile != null) {
        portraitUpload.setInitialFile(portraitFile);
    }
    portraitUpload.limitToMimeType(mimeTypes, null, null);
    if (logoEnabled) {
        // upload image
        groupContainer = FormLayoutContainer.createDefaultFormLayout("logoupload", getTranslator());
        groupContainer.setFormTitle(translate("logo.header"));
        formLayout.add(groupContainer);
        File logoFile = dps.getLargestLogo(identityToModify.getName());
        logoUpload = uifactory.addFileElement(getWindowControl(), "logo.select", "logo.select", groupContainer);
        logoUpload.setMaxUploadSizeKB(10000, null, null);
        logoUpload.setPreview(ureq.getUserSession(), true);
        logoUpload.addActionListener(FormEvent.ONCHANGE);
        logoUpload.setHelpTextKey("ul.select.fhelp", null);
        logoUpload.setDeleteEnabled(true);
        if (logoFile != null) {
            logoUpload.setInitialFile(logoFile);
        }
        logoUpload.limitToMimeType(mimeTypes, null, null);
    }
    // Create submit and cancel buttons
    FormLayoutContainer buttonLayoutWrappper = FormLayoutContainer.createDefaultFormLayout("buttonLayoutWrappper", getTranslator());
    formLayout.add(buttonLayoutWrappper);
    FormLayoutContainer buttonLayout = FormLayoutContainer.createButtonLayout("buttonLayoutInner", getTranslator());
    buttonLayoutWrappper.add(buttonLayout);
    uifactory.addFormSubmitButton("save", buttonLayout);
    uifactory.addFormCancelButton("cancel", buttonLayout, ureq, getWindowControl());
}
Also used : User(org.olat.core.id.User) HashMap(java.util.HashMap) FormItem(org.olat.core.gui.components.form.flexible.FormItem) TemporaryKey(org.olat.registration.TemporaryKey) XStream(com.thoughtworks.xstream.XStream) FormLayoutContainer(org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer) RichTextElement(org.olat.core.gui.components.form.flexible.elements.RichTextElement) TextElement(org.olat.core.gui.components.form.flexible.elements.TextElement) MultipleSelectionElement(org.olat.core.gui.components.form.flexible.elements.MultipleSelectionElement) File(java.io.File) UserPropertyHandler(org.olat.user.propertyhandlers.UserPropertyHandler) HashSet(java.util.HashSet)

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