If no WebDAV password has ever been generated, copy token to it at initial login...
[pithos] / src / gr / ebs / gss / server / Login.java
1 /*
2  * Copyright 2008, 2009 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.Nonce;
26 import gr.ebs.gss.server.domain.User;
27 import gr.ebs.gss.server.ejb.ExternalAPI;
28
29 import java.io.IOException;
30 import java.io.PrintWriter;
31 import java.io.UnsupportedEncodingException;
32 import java.net.URL;
33 import java.net.URLEncoder;
34 import java.util.Formatter;
35
36 import javax.naming.Context;
37 import javax.naming.InitialContext;
38 import javax.naming.NamingException;
39 import javax.rmi.PortableRemoteObject;
40 import javax.servlet.http.Cookie;
41 import javax.servlet.http.HttpServlet;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
44
45 import org.apache.commons.codec.binary.Base64;
46 import org.apache.commons.logging.Log;
47 import org.apache.commons.logging.LogFactory;
48
49 /**
50  * The servlet that handles user logins.
51  *
52  * @author past
53  */
54 public class Login extends HttpServlet {
55         /**
56          * The request parameter name for the nonce.
57          */
58         private static final String NONCE_PARAM = "nonce";
59
60         /**
61          * The request parameter name for the URL to redirect
62          * to after authentication.
63          */
64         private static final String NEXT_URL_PARAM = "next";
65
66         /**
67          * The serial version UID of the class.
68          */
69         private static final long serialVersionUID = 1L;
70
71         /**
72          * The name of the authentication cookie.
73          */
74         private static final String AUTH_COOKIE = "_gss_a";
75
76         /**
77          * The separator character for the authentication cookie.
78          */
79         private static final char COOKIE_SEPARATOR = '|';
80
81         /**
82          * The name of the the webdav cookie.
83          */
84         public static final String WEBDAV_COOKIE = "_gss_wd";
85
86         /**
87          * The logger.
88          */
89         private static Log logger = LogFactory.getLog(Login.class);
90
91         /**
92          * A helper method that retrieves a reference to the ExternalAPI bean and
93          * stores it for future use.
94          *
95          * @return an ExternalAPI instance
96          * @throws RpcException in case an error occurs
97          */
98         private ExternalAPI getService() throws RpcException {
99                 try {
100                         final Context ctx = new InitialContext();
101                         final Object ref = ctx.lookup(getConfiguration().getString("externalApiPath"));
102                         return (ExternalAPI) PortableRemoteObject.narrow(ref, ExternalAPI.class);
103                 } catch (final NamingException e) {
104                         logger.error("Unable to retrieve the ExternalAPI EJB", e);
105                         throw new RpcException("An error occurred while contacting the naming service");
106                 }
107         }
108
109         /**
110          * Return the name of the service.
111          */
112         private String getServiceName() {
113                 return getConfiguration().getString("serviceName", "GSS");
114         }
115
116         @Override
117         public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
118                 // Fetch the next URL to display, if any.
119                 String nextUrl = request.getParameter(NEXT_URL_PARAM);
120                 // Fetch the supplied nonce, if any.
121                 String nonce = request.getParameter(NONCE_PARAM);
122                 String[] attrs = new String[] {"REMOTE_USER", "HTTP_SHIB_INETORGPERSON_DISPLAYNAME",
123                                         "HTTP_SHIB_INETORGPERSON_GIVENNAME", "HTTP_SHIB_PERSON_COMMONNAME",
124                                         "HTTP_SHIB_PERSON_SURNAME", "HTTP_SHIB_INETORGPERSON_MAIL",
125                                         "HTTP_SHIB_EP_UNSCOPEDAFFILIATION"};
126                 StringBuilder buf = new StringBuilder("Shibboleth Attributes\n");
127                 for (String attr: attrs)
128                         buf.append(attr+": ").append(request.getAttribute(attr)).append('\n');
129                 logger.info(buf);
130                 if (logger.isDebugEnabled()) {
131                         buf = new StringBuilder("Shibboleth Attributes as bytes\n");
132                         for (String attr: attrs)
133                                 if (request.getAttribute(attr) != null)
134                                         buf.append(attr+": ").append(getHexString(request.getAttribute(attr).toString().getBytes("UTF-8"))).append('\n');
135                         logger.debug(buf);
136                 }
137                 User user = null;
138                 response.setContentType("text/html");
139                 Object usernameAttr = request.getAttribute("REMOTE_USER");
140                 Object nameAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_DISPLAYNAME");
141                 Object givennameAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_GIVENNAME"); // Multi-valued
142                 Object cnAttr = request.getAttribute("HTTP_SHIB_PERSON_COMMONNAME"); // Multi-valued
143                 Object snAttr = request.getAttribute("HTTP_SHIB_PERSON_SURNAME"); // Multi-valued
144                 Object mailAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_MAIL"); // Multi-valued
145                 Object userclassAttr = request.getAttribute("HTTP_SHIB_EP_UNSCOPEDAFFILIATION"); // Multi-valued
146                 if (usernameAttr == null) {
147                         String authErrorUrl = "authenticationError.jsp";
148                         authErrorUrl += "?name=" + (nameAttr==null? "-": nameAttr.toString());
149                         authErrorUrl += "&givenname=" + (givennameAttr==null? "-": givennameAttr.toString());
150                         authErrorUrl += "&sn=" + (snAttr==null? "-": snAttr.toString());
151                         authErrorUrl += "&cn=" + (cnAttr==null? "-": cnAttr.toString());
152                         authErrorUrl += "&mail=" + (mailAttr==null? "-": mailAttr.toString());
153                         authErrorUrl += "&userclass=" + (userclassAttr==null? "-": userclassAttr.toString());
154                         response.sendRedirect(authErrorUrl);
155                         return;
156                 }
157                 String username = decodeAttribute(usernameAttr);
158                 String name;
159                 if (nameAttr != null && !nameAttr.toString().isEmpty())
160                         name = decodeAttribute(nameAttr);
161                 else if (cnAttr != null && !cnAttr.toString().isEmpty()) {
162                         name = decodeAttribute(cnAttr);
163                         if (name.indexOf(';') != -1)
164                                 name = name.substring(0, name.indexOf(';'));
165                 } else if (givennameAttr != null && snAttr != null && !givennameAttr.toString().isEmpty() && !snAttr.toString().isEmpty()) {
166                         String givenname = decodeAttribute(givennameAttr);
167                         if (givenname.indexOf(';') != -1)
168                                 givenname = givenname.substring(0, givenname.indexOf(';'));
169                         String sn = decodeAttribute(snAttr);
170                         if (sn.indexOf(';') != -1)
171                                 sn = sn.substring(0, sn.indexOf(';'));
172                         name = givenname + ' ' + sn;
173                 } else if (givennameAttr == null && snAttr != null && !snAttr.toString().isEmpty()) {
174                         name = decodeAttribute(snAttr);
175                         if (name.indexOf(';') != -1)
176                                 name = name.substring(0, name.indexOf(';'));
177                 } else
178                         name = username;
179                 String mail = mailAttr != null ? mailAttr.toString() : username;
180                 if (mail.indexOf(';') != -1)
181                         mail = mail.substring(0, mail.indexOf(';'));
182                 // XXX we are not using the user class currently
183                 String userclass = userclassAttr != null ? userclassAttr.toString() : "";
184                 if (userclass.indexOf(';') != -1)
185                         userclass = userclass.substring(0, userclass.indexOf(';'));
186                 try {
187                         user = getService().findUser(username);
188                         if (user == null)
189                                 user = getService().createUser(username, name, mail);
190                         if (!user.hasAcceptedPolicy()) {
191                                 String policyUrl = "policy.jsp";
192                                 if (request.getQueryString() != null)
193                                         policyUrl += "?user=" + username + "&" + request.getQueryString();
194                                 response.sendRedirect(policyUrl);
195                                 return;
196                         }
197                         // Update the user name and e-mail if modified.
198                         boolean update = false;
199                         if (!user.getName().equals(name)) {
200                                 user.setName(name);
201                                 update = true;
202                         }
203                         if (!user.getEmail().equals(mail)) {
204                                 user.setEmail(mail);
205                                 update = true;
206                         }
207                         if (user.getAuthToken() == null)
208                                 user = getService().updateUserToken(user.getId());
209                         // Set WebDAV password to token if it's never been set.
210                         if (user.getWebDAVPassword()==null || user.getWebDAVPassword().length()==0) {
211                                 String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
212                                 user.setWebDAVPassword(tokenEncoded);
213                                 update = true;
214                         }
215                         if (update)
216                                 getService().updateUser(user);
217                 } catch (RpcException e) {
218                         String error = "An error occurred while communicating with the service";
219                         logger.error(error, e);
220                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
221                         return;
222                 } catch (DuplicateNameException e) {
223                         String error = "User with username " + username + " already exists";
224                         logger.error(error, e);
225                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
226                         return;
227                 } catch (ObjectNotFoundException e) {
228                         String error = "No username was provided";
229                         logger.error(error, e);
230                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
231                         return;
232                 }
233                 String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
234                 String userEncoded = URLEncoder.encode(user.getUsername(), "US-ASCII");
235                 if (logger.isDebugEnabled())
236                         logger.debug("user: "+userEncoded+" token: "+tokenEncoded);
237                 if (nextUrl != null) {
238                         URL next = new URL(nextUrl);
239                         String domain = next.getHost();
240                         String path = next.getPath();
241                         Cookie cookie = new Cookie(AUTH_COOKIE, userEncoded + COOKIE_SEPARATOR +
242                                                 tokenEncoded);
243                         cookie.setMaxAge(-1);
244                         cookie.setDomain(domain);
245                         cookie.setPath(path);
246                     response.addCookie(cookie);
247                     cookie = new Cookie(WEBDAV_COOKIE, user.getWebDAVPassword());
248                         cookie.setMaxAge(-1);
249                         cookie.setDomain(domain);
250                         cookie.setPath(path);
251                     response.addCookie(cookie);
252                     response.sendRedirect(nextUrl);
253                 } else if (nonce != null) {
254                         nonce = URLEncoder.encode(nonce, "US-ASCII");
255                         Nonce n = null;
256                         try {
257                                 if (logger.isDebugEnabled())
258                                         logger.debug("user: "+user.getId()+" nonce: "+nonce);
259                                 n = getService().getNonce(nonce, user.getId());
260                         } catch (ObjectNotFoundException e) {
261                             PrintWriter out = response.getWriter();
262                             out.println("<HTML>");
263                             out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
264                                         "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
265                             out.println("<BODY><CENTER><P>");
266                             out.println("The supplied nonce could not be found!");
267                             out.println("</CENTER></BODY></HTML>");
268                             return;
269                         } catch (RpcException e) {
270                                 String error = "An error occurred while communicating with the service";
271                                 logger.error(error, e);
272                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
273                                 return;
274                         }
275                         try {
276                                 getService().activateUserNonce(user.getId(), nonce, n.getNonceExpiryDate());
277                         } catch (ObjectNotFoundException e) {
278                                 String error = "Unable to find user";
279                                 logger.error(error, e);
280                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
281                                 return;
282                         } catch (RpcException e) {
283                                 String error = "An error occurred while communicating with the service";
284                                 logger.error(error, e);
285                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
286                                 return;
287                         }
288                         try {
289                                 getService().removeNonce(n.getId());
290                         } catch (ObjectNotFoundException e) {
291                                 logger.info("Nonce already removed!", e);
292                         } catch (RpcException e) {
293                                 logger.warn("Could not remove nonce from data store", e);
294                         }
295                     PrintWriter out = response.getWriter();
296                     out.println("<HTML>");
297                     out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
298                                 "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
299                     out.println("<BODY><CENTER><P>");
300                     out.println("You can now close this browser window and return to your application.");
301                     out.println("</CENTER></BODY></HTML>");
302                 } else {
303                     PrintWriter out = response.getWriter();
304                     out.println("<HTML>");
305                     out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
306                                 "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
307                     out.println("<BODY><CENTER><P>");
308                     out.println("Name: " + user.getName() + "<BR>");
309                     out.println("E-mail: " + user.getEmail() + "<BR><P>");
310                     out.println("Username: " + user.getUsername() + "<BR>");
311                     out.println("Athentication token: " + tokenEncoded + "<BR>");
312                     out.println("</CENTER></BODY></HTML>");
313                 }
314         }
315
316         /**
317          * Decode the request attribute provided by the container to a UTF-8
318          * string, since GSS assumes all data to be encoded in UTF-8. The
319          * servlet container's encoding can be specified in gss.properties.
320          */
321         private String decodeAttribute(Object attribute) throws UnsupportedEncodingException {
322                 return new String(attribute.toString().getBytes(getConfiguration().getString("requestAttributeEncoding")), "UTF-8");
323         }
324
325         /**
326          * A helper method that converts a byte buffer to a printable list of
327          * hexadecimal numbers.
328          */
329         private String getHexString(byte[] buffer) {
330                 StringBuilder sb = new StringBuilder();
331                 Formatter formatter = new Formatter(sb);
332                 for (int i=0; i<buffer.length; i++)
333                         formatter.format("0x%x, ", buffer[i]);
334                 return sb.toString();
335         }
336
337 }