001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 */
018package org.nuxeo.ecm.webengine.invite;
019
020import java.io.Serializable;
021import java.util.HashMap;
022import java.util.Map;
023
024import javax.ws.rs.GET;
025import javax.ws.rs.POST;
026import javax.ws.rs.Path;
027import javax.ws.rs.PathParam;
028import javax.ws.rs.Produces;
029
030import org.apache.commons.logging.Log;
031import org.apache.commons.logging.LogFactory;
032import org.nuxeo.ecm.platform.usermanager.exceptions.InvalidPasswordException;
033import org.nuxeo.ecm.platform.web.common.vh.VirtualHostHelper;
034import org.nuxeo.ecm.user.invite.AlreadyProcessedRegistrationException;
035import org.nuxeo.ecm.user.invite.DefaultInvitationUserFactory;
036import org.nuxeo.ecm.user.invite.UserInvitationService;
037import org.nuxeo.ecm.user.invite.UserRegistrationException;
038import org.nuxeo.ecm.webengine.forms.FormData;
039import org.nuxeo.ecm.webengine.model.Template;
040import org.nuxeo.ecm.webengine.model.WebObject;
041import org.nuxeo.ecm.webengine.model.impl.ModuleRoot;
042import org.nuxeo.runtime.api.Framework;
043
044/**
045 * @author <a href="mailto:akervern@nuxeo.com">Arnaud Kervern</a>
046 */
047@Path("/userInvitation")
048@Produces("text/html;charset=UTF-8")
049@WebObject(type = "userRegistration")
050public class UserInvitationObject extends ModuleRoot {
051    private static final Log log = LogFactory.getLog(UserInvitationObject.class);
052
053    @POST
054    @Path("validate")
055    public Object validateTrialForm() {
056        UserInvitationService usr = fetchService();
057
058        FormData formData = getContext().getForm();
059        String requestId = formData.getString("RequestId");
060        String configurationName = formData.getString("ConfigurationName");
061        String password = formData.getString("Password");
062        String passwordConfirmation = formData.getString("PasswordConfirmation");
063
064        // Check if the requestId is an existing one
065        try {
066            usr.checkRequestId(requestId);
067        } catch (AlreadyProcessedRegistrationException ape) {
068            return getView("ValidationErrorTemplate").arg("exceptionMsg",
069                    ctx.getMessage("label.error.requestAlreadyProcessed"));
070        } catch (UserRegistrationException ue) {
071            return getView("ValidationErrorTemplate").arg("exceptionMsg",
072                    ctx.getMessage("label.error.requestNotExisting", requestId));
073        }
074
075        // Check if both entered passwords are correct
076        if (password == null || "".equals(password.trim())) {
077            return redisplayFormWithErrorMessage("EnterPassword",
078                    ctx.getMessage("label.registerForm.validation.password"), formData);
079        }
080        if (passwordConfirmation == null || "".equals(passwordConfirmation.trim())) {
081            return redisplayFormWithErrorMessage("EnterPassword",
082                    ctx.getMessage("label.registerForm.validation.passwordconfirmation"), formData);
083        }
084        password = password.trim();
085        passwordConfirmation = passwordConfirmation.trim();
086        if (!password.equals(passwordConfirmation)) {
087            return redisplayFormWithErrorMessage("EnterPassword",
088                    ctx.getMessage("label.registerForm.validation.passwordvalidation"), formData);
089        }
090        Map<String, Serializable> registrationData = new HashMap<String, Serializable>();
091        try {
092            Map<String, Serializable> additionalInfo = buildAdditionalInfos();
093
094            // Add the entered password to the document model
095            additionalInfo.put(DefaultInvitationUserFactory.PASSWORD_KEY, password);
096            // Validate the creation of the user
097            registrationData = usr.validateRegistration(requestId, additionalInfo);
098
099        } catch (AlreadyProcessedRegistrationException ape) {
100            log.info("Try to validate an already processed registration");
101            return getView("ValidationErrorTemplate").arg("exceptionMsg",
102                    ctx.getMessage("label.error.requestAlreadyProcessed"));
103        } catch (UserRegistrationException ue) {
104            log.warn("Unable to validate registration request", ue);
105            return getView("ValidationErrorTemplate").arg("exceptionMsg",
106                    ctx.getMessage("label.errror.requestNotAccepted"));
107        } catch (InvalidPasswordException ive) {
108            return getView("ValidationErrorTemplate").arg("exceptionMsg",
109                ctx.getMessage("label.registerForm.validation.invalidpassword"));
110        }
111        // User redirected to the logout page after validating the password
112        String webappName = VirtualHostHelper.getWebAppName(getContext().getRequest());
113        String logoutUrl = "/" + webappName + "/logout";
114        return getView("UserCreated").arg("data", registrationData).arg("logout", logoutUrl);
115    }
116
117    protected UserInvitationService fetchService() {
118        UserInvitationService usr = Framework.getService(UserInvitationService.class);
119        return usr;
120    }
121
122    @GET
123    @Path("enterpassword/{configurationName}/{requestId}")
124    public Object validatePasswordForm(@PathParam("requestId") String requestId,
125            @PathParam("configurationName") String configurationName) {
126
127        UserInvitationService usr = fetchService();
128        try {
129            usr.checkRequestId(requestId);
130        } catch (AlreadyProcessedRegistrationException ape) {
131            return getView("ValidationErrorTemplate").arg("exceptionMsg",
132                    ctx.getMessage("label.error.requestAlreadyProcessed"));
133        } catch (UserRegistrationException ue) {
134            return getView("ValidationErrorTemplate").arg("exceptionMsg",
135                    ctx.getMessage("label.error.requestNotExisting", requestId));
136        }
137
138        Map<String, String> data = new HashMap<String, String>();
139        data.put("RequestId", requestId);
140        data.put("ConfigurationName", configurationName);
141        String webappName = VirtualHostHelper.getWebAppName(getContext().getRequest());
142        String validationRelUrl = usr.getConfiguration(configurationName).getValidationRelUrl();
143        String valUrl = "/" + webappName + "/" + validationRelUrl;
144        data.put("ValidationUrl", valUrl);
145        return getView("EnterPassword").arg("data", data);
146    }
147
148    protected Map<String, Serializable> buildAdditionalInfos() {
149        return new HashMap<String, Serializable>();
150    }
151
152    protected Template redisplayFormWithMessage(String messageType, String formName, String message, FormData data) {
153        Map<String, String> savedData = new HashMap<String, String>();
154        for (String key : data.getKeys()) {
155            savedData.put(key, data.getString(key));
156        }
157        return getView(formName).arg("data", savedData).arg(messageType, message);
158    }
159
160    protected Template redisplayFormWithInfoMessage(String formName, String message, FormData data) {
161        return redisplayFormWithMessage("info", formName, message, data);
162    }
163
164    protected Template redisplayFormWithErrorMessage(String formName, String message, FormData data) {
165        return redisplayFormWithMessage("err", formName, message, data);
166    }
167
168}