001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 */
016package org.nuxeo.ecm.webengine.invite;
017
018import java.io.Serializable;
019import java.util.HashMap;
020import java.util.Map;
021
022import javax.ws.rs.GET;
023import javax.ws.rs.POST;
024import javax.ws.rs.Path;
025import javax.ws.rs.PathParam;
026import javax.ws.rs.Produces;
027
028import org.apache.commons.logging.Log;
029import org.apache.commons.logging.LogFactory;
030import org.nuxeo.ecm.platform.web.common.vh.VirtualHostHelper;
031import org.nuxeo.ecm.user.invite.AlreadyProcessedRegistrationException;
032import org.nuxeo.ecm.user.invite.DefaultInvitationUserFactory;
033import org.nuxeo.ecm.user.invite.UserInvitationService;
034import org.nuxeo.ecm.user.invite.UserRegistrationException;
035import org.nuxeo.ecm.webengine.forms.FormData;
036import org.nuxeo.ecm.webengine.model.Template;
037import org.nuxeo.ecm.webengine.model.WebObject;
038import org.nuxeo.ecm.webengine.model.impl.ModuleRoot;
039import org.nuxeo.runtime.api.Framework;
040
041/**
042 * @author <a href="mailto:akervern@nuxeo.com">Arnaud Kervern</a>
043 */
044@Path("/userInvitation")
045@Produces("text/html;charset=UTF-8")
046@WebObject(type = "userRegistration")
047public class UserInvitationObject extends ModuleRoot {
048    private static final Log log = LogFactory.getLog(UserInvitationObject.class);
049
050    @POST
051    @Path("validate")
052    public Object validateTrialForm() {
053        UserInvitationService usr = fetchService();
054
055        FormData formData = getContext().getForm();
056        String requestId = formData.getString("RequestId");
057        String configurationName = formData.getString("ConfigurationName");
058        String password = formData.getString("Password");
059        String passwordConfirmation = formData.getString("PasswordConfirmation");
060
061        // Check if the requestId is an existing one
062        try {
063            usr.checkRequestId(requestId);
064        } catch (AlreadyProcessedRegistrationException ape) {
065            return getView("ValidationErrorTemplate").arg("exceptionMsg",
066                    ctx.getMessage("label.error.requestAlreadyProcessed"));
067        } catch (UserRegistrationException ue) {
068            return getView("ValidationErrorTemplate").arg("exceptionMsg",
069                    ctx.getMessage("label.error.requestNotExisting", requestId));
070        }
071
072        // Check if both entered passwords are correct
073        if (password == null || "".equals(password.trim())) {
074            return redisplayFormWithErrorMessage("EnterPassword",
075                    ctx.getMessage("label.registerForm.validation.password"), formData);
076        }
077        if (passwordConfirmation == null || "".equals(passwordConfirmation.trim())) {
078            return redisplayFormWithErrorMessage("EnterPassword",
079                    ctx.getMessage("label.registerForm.validation.passwordconfirmation"), formData);
080        }
081        password = password.trim();
082        passwordConfirmation = passwordConfirmation.trim();
083        if (!password.equals(passwordConfirmation)) {
084            return redisplayFormWithErrorMessage("EnterPassword",
085                    ctx.getMessage("label.registerForm.validation.passwordvalidation"), formData);
086        }
087        Map<String, Serializable> registrationData = new HashMap<String, Serializable>();
088        try {
089            Map<String, Serializable> additionalInfo = buildAdditionalInfos();
090
091            // Add the entered password to the document model
092            additionalInfo.put(DefaultInvitationUserFactory.PASSWORD_KEY, password);
093            // Validate the creation of the user
094            registrationData = usr.validateRegistration(requestId, additionalInfo);
095
096        } catch (AlreadyProcessedRegistrationException ape) {
097            log.info("Try to validate an already processed registration");
098            return getView("ValidationErrorTemplate").arg("exceptionMsg",
099                    ctx.getMessage("label.error.requestAlreadyProcessed"));
100        } catch (UserRegistrationException ue) {
101            log.warn("Unable to validate registration request", ue);
102            return getView("ValidationErrorTemplate").arg("exceptionMsg",
103                    ctx.getMessage("label.errror.requestNotAccepted"));
104        }
105        // User redirected to the logout page after validating the password
106        String webappName = VirtualHostHelper.getWebAppName(getContext().getRequest());
107        String logoutUrl = "/" + webappName + "/logout";
108        return getView("UserCreated").arg("data", registrationData).arg("logout", logoutUrl);
109    }
110
111    protected UserInvitationService fetchService() {
112        UserInvitationService usr = Framework.getLocalService(UserInvitationService.class);
113        return usr;
114    }
115
116    @GET
117    @Path("enterpassword/{configurationName}/{requestId}")
118    public Object validatePasswordForm(@PathParam("requestId") String requestId,
119            @PathParam("configurationName") String configurationName) {
120
121        UserInvitationService usr = fetchService();
122        try {
123            usr.checkRequestId(requestId);
124        } catch (AlreadyProcessedRegistrationException ape) {
125            return getView("ValidationErrorTemplate").arg("exceptionMsg",
126                    ctx.getMessage("label.error.requestAlreadyProcessed"));
127        } catch (UserRegistrationException ue) {
128            return getView("ValidationErrorTemplate").arg("exceptionMsg",
129                    ctx.getMessage("label.error.requestNotExisting", requestId));
130        }
131
132        Map<String, String> data = new HashMap<String, String>();
133        data.put("RequestId", requestId);
134        data.put("ConfigurationName", configurationName);
135        String webappName = VirtualHostHelper.getWebAppName(getContext().getRequest());
136        String validationRelUrl = usr.getConfiguration(configurationName).getValidationRelUrl();
137        String valUrl = "/" + webappName + "/" + validationRelUrl;
138        data.put("ValidationUrl", valUrl);
139        return getView("EnterPassword").arg("data", data);
140    }
141
142    protected Map<String, Serializable> buildAdditionalInfos() {
143        return new HashMap<String, Serializable>();
144    }
145
146    protected Template redisplayFormWithMessage(String messageType, String formName, String message, FormData data) {
147        Map<String, String> savedData = new HashMap<String, String>();
148        for (String key : data.getKeys()) {
149            savedData.put(key, data.getString(key));
150        }
151        return getView(formName).arg("data", savedData).arg(messageType, message);
152    }
153
154    protected Template redisplayFormWithInfoMessage(String formName, String message, FormData data) {
155        return redisplayFormWithMessage("info", formName, message, data);
156    }
157
158    protected Template redisplayFormWithErrorMessage(String formName, String message, FormData data) {
159        return redisplayFormWithMessage("err", formName, message, data);
160    }
161
162}