Don't allow usernames with spaces.
[pithos] / src / gr / ebs / gss / server / Registration.java
1 /*
2  * Copyright 2010 Electronic Business Systems Ltd.
3  *
4  * This file is part of GSS.
5  *
6  * GSS is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * GSS is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with GSS.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 package gr.ebs.gss.server;
20
21 import static gr.ebs.gss.server.configuration.GSSConfigurationFactory.getConfiguration;
22 import gr.ebs.gss.client.exceptions.DuplicateNameException;
23 import gr.ebs.gss.client.exceptions.ObjectNotFoundException;
24 import gr.ebs.gss.client.exceptions.RpcException;
25 import gr.ebs.gss.server.domain.User;
26 import gr.ebs.gss.server.domain.dto.UserDTO;
27 import gr.ebs.gss.server.ejb.ExternalAPI;
28 import gr.ebs.gss.server.ejb.TransactionHelper;
29
30 import java.io.IOException;
31 import java.io.UnsupportedEncodingException;
32 import java.net.URLEncoder;
33 import java.util.concurrent.Callable;
34
35 import javax.naming.Context;
36 import javax.naming.InitialContext;
37 import javax.naming.NamingException;
38 import javax.rmi.PortableRemoteObject;
39 import javax.servlet.http.HttpServlet;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.servlet.http.HttpServletResponse;
42
43 import org.apache.commons.logging.Log;
44 import org.apache.commons.logging.LogFactory;
45
46 /**
47  * The servlet that handles user registration.
48  *
49  * @author past
50  */
51 public class Registration extends HttpServlet {
52         /**
53          * The request parameter name for the acceptance flag.
54          */
55         private static final String ACCEPT_PARAM = "accept";
56
57         /**
58          * The request parameter name for the firstname.
59          */
60         private static final String FIRSTNAME_PARAM = "firstname";
61
62         /**
63          * The request parameter name for the lastname.
64          */
65         private static final String LASTNAME_PARAM = "lastname";
66
67         /**
68          * The request parameter name for the username.
69          */
70         private static final String USERNAME_PARAM = "username";
71
72         /**
73          * The request parameter name for the e-mail.
74          */
75         private static final String EMAIL_PARAM = "email";
76
77         /**
78          * The request parameter name for the password.
79          */
80         private static final String PASSWORD_PARAM = "password";
81
82         /**
83          * The request parameter name for the password confirmation.
84          */
85         private static final String PASSWORD2_PARAM = "password2";
86
87         /**
88          * The serial version UID of the class.
89          */
90         private static final long serialVersionUID = 1L;
91
92         /**
93          * The logger.
94          */
95         private static Log logger = LogFactory.getLog(Registration.class);
96
97         /**
98          * A helper method that retrieves a reference to the ExternalAPI bean and
99          * stores it for future use.
100          *
101          * @return an ExternalAPI instance
102          * @throws RpcException in case an error occurs
103          */
104         protected ExternalAPI getService() throws RpcException {
105                 try {
106                         final Context ctx = new InitialContext();
107                         final Object ref = ctx.lookup(getConfiguration().getString("externalApiPath"));
108                         return (ExternalAPI) PortableRemoteObject.narrow(ref, ExternalAPI.class);
109                 } catch (final NamingException e) {
110                         logger.error("Unable to retrieve the ExternalAPI EJB", e);
111                         throw new RpcException("An error occurred while contacting the naming service");
112                 }
113         }
114
115         @Override
116         public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
117                 if (getConfiguration().getBoolean("onlyRegisterWithCode"))
118                         response.sendRedirect("invites.jsp");
119                 else
120                         response.sendRedirect("register.jsp");
121         }
122
123         @Override
124         public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
125                 final String firstname = request.getParameter(FIRSTNAME_PARAM);
126                 final String lastname = request.getParameter(LASTNAME_PARAM);
127                 final String email = request.getParameter(EMAIL_PARAM);
128                 final String username = request.getParameter(USERNAME_PARAM);
129                 String password = request.getParameter(PASSWORD_PARAM);
130                 String password2 = request.getParameter(PASSWORD2_PARAM);
131                 String accept = request.getParameter(ACCEPT_PARAM);
132                 response.setContentType("text/html");
133
134                 // Validate input parameters.
135                 if (username == null || username.isEmpty()) {
136                         String error = encode("No username was specified");
137                         String errorUrl = "register.jsp?username=&error=" + error;
138                         errorUrl += "&firstname=" + (firstname == null? "": encode(firstname));
139                         errorUrl += "&lastname=" + (lastname == null? "": encode(lastname));
140                         errorUrl += "&email=" + (email == null? "": encode(email));
141                         response.sendRedirect(errorUrl);
142                         return;
143                 } else if (username.indexOf(' ') != -1) {
144                         String error = encode("Spaces in username are not allowed");
145                         String errorUrl = "register.jsp?username=&error=" + error;
146                         errorUrl += "&firstname=" + (firstname == null? "": encode(firstname));
147                         errorUrl += "&lastname=" + (lastname == null? "": encode(lastname));
148                         errorUrl += "&email=" + (email == null? "": encode(email));
149                         response.sendRedirect(errorUrl);
150                         return;
151                 } else if (firstname == null || firstname.isEmpty()) {
152                         String error = encode("No firstname was specified");
153                         String errorUrl = "register.jsp?firstname=&error=" + error;
154                         errorUrl += "&username=" + encode(username);
155                         errorUrl += "&lastname=" + (lastname == null? "": encode(lastname));
156                         errorUrl += "&email=" + (email == null? "": encode(email));
157                         response.sendRedirect(errorUrl);
158                         return;
159                 } else if (lastname == null || lastname.isEmpty()) {
160                         String error = encode("No lastname was specified");
161                         String errorUrl = "register.jsp?lastname=&error=" + error;
162                         errorUrl += "&username=" + encode(username);
163                         errorUrl += "&firstname=" + encode(firstname);
164                         errorUrl += "&email=" + (email == null? "": encode(email));
165                         response.sendRedirect(errorUrl);
166                         return;
167                 } else if (email == null || email.isEmpty()) {
168                         String error = encode("No e-mail was specified");
169                         String errorUrl = "register.jsp?email=&error=" + error;
170                         errorUrl += "&username=" + encode(username);
171                         errorUrl += "&firstname=" + encode(firstname);
172                         errorUrl += "&lastname=" + encode(lastname);
173                         response.sendRedirect(errorUrl);
174                         return;
175                 } else if (password == null || password.isEmpty()) {
176                         String error = encode("No password was specified");
177                         String errorUrl = "register.jsp?error=" + error;
178                         errorUrl += "&username=" + encode(username);
179                         errorUrl += "&firstname=" + encode(firstname);
180                         errorUrl += "&lastname=" + encode(lastname);
181                         errorUrl += "&email=" + encode(email);
182                         response.sendRedirect(errorUrl);
183                         return;
184                 } else if (!password.equals(password2)) {
185                         String error = encode("Passwords do not match");
186                         String errorUrl = "register.jsp?error=" + error;
187                         errorUrl += "&username=" + encode(username);
188                         errorUrl += "&firstname=" + encode(firstname);
189                         errorUrl += "&lastname=" + encode(lastname);
190                         errorUrl += "&email=" + encode(email);
191                         response.sendRedirect(errorUrl);
192                         return;
193                 } else if (!"on".equalsIgnoreCase(accept)) {
194                         String error = encode("You must accept the terms and conditions");
195                         String errorUrl = "register.jsp?error=" + error;
196                         errorUrl += "&username=" + encode(username);
197                         errorUrl += "&firstname=" + encode(firstname);
198                         errorUrl += "&lastname=" + encode(lastname);
199                         errorUrl += "&email=" + encode(email);
200                         response.sendRedirect(errorUrl);
201                         return;
202                 }
203
204                 User user = null;
205                 try {
206                         user = getService().findUser(username);
207                         if (user != null) {
208                                 String error = encode("The username already exists");
209                                 String errorUrl = "register.jsp?username=&error=" + error;
210                                 errorUrl += "&firstname=" + encode(firstname);
211                                 errorUrl += "&lastname=" + encode(lastname);
212                                 errorUrl += "&email=" + encode(email);
213                                 response.sendRedirect(errorUrl);
214                                 return;
215                         }
216                         try {
217                                 getService().createLdapUser(username, firstname, lastname, email, password);
218                         } catch (Exception e) {
219                                 logger.error(e);
220                                 handleException(response, e.getMessage());
221                                 return;
222                         }
223                         final UserDTO userDto = new TransactionHelper<UserDTO>().tryExecute(new Callable<UserDTO>() {
224                                 @Override
225                                 public UserDTO call() throws Exception {
226                                         return getService().createUser(username, firstname + " " + lastname, email, "", "").getDTO();
227                                 }
228
229                         });
230                         new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
231                                 @Override
232                                 public Void call() throws Exception {
233                                         getService().updateUserPolicyAcceptance(userDto.getId(), true);
234                                         return null;
235                                 }
236
237                         });
238                         response.sendRedirect("registered.jsp");
239                 } catch (RpcException e) {
240                         logger.error(e);
241                         handleException(response, "An error occurred while communicating with the service");
242                 } catch (DuplicateNameException e) {
243                         // Can't happen, but this is more user-friendly than an assert.
244                         logger.error(e);
245                         handleException(response, "The username already exists");
246                 } catch (ObjectNotFoundException e) {
247                         // Can't happen, but this is more user-friendly than an assert.
248                         logger.error(e);
249                         handleException(response, "No username or name was specified");
250                 } catch (Exception e) {
251                         logger.error(e);
252                         handleException(response, e.getMessage());
253                 }
254         }
255
256         private void handleException(HttpServletResponse response, String error) throws IOException {
257                 String errorUrl = "register.jsp?username=&firstname=&lastname=&email=&error=" + encode(error);
258                 response.sendRedirect(errorUrl);
259         }
260
261         protected String encode(String parameter) throws UnsupportedEncodingException {
262                 return URLEncoder.encode(parameter, "UTF-8");
263         }
264 }