Forbid logins from disabled users.
[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
28 import java.io.IOException;
29 import java.io.PrintWriter;
30 import java.net.URI;
31 import java.net.URISyntaxException;
32 import java.net.URLEncoder;
33 import java.util.Date;
34
35 import javax.servlet.http.Cookie;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse;
38
39 import org.apache.commons.codec.binary.Base64;
40 import org.apache.commons.logging.Log;
41 import org.apache.commons.logging.LogFactory;
42
43 /**
44  * The servlet that handles user logins.
45  *
46  * @author past
47  */
48 public class Login extends BaseServlet {
49         /**
50          * The request parameter name for the nonce.
51          */
52         private static final String NONCE_PARAM = "nonce";
53
54         /**
55          * The request parameter name for the URL to redirect
56          * to after authentication.
57          */
58         private static final String NEXT_URL_PARAM = "next";
59
60         /**
61          * The serial version UID of the class.
62          */
63         private static final long serialVersionUID = 1L;
64
65         /**
66          * The name of the authentication cookie.
67          */
68         public static final String AUTH_COOKIE = "_gss_a";
69
70         /**
71          * The separator character for the authentication cookie.
72          */
73         public static final char COOKIE_SEPARATOR = '|';
74
75         /**
76          * The name of the the webdav cookie.
77          */
78         public static final String WEBDAV_COOKIE = "_gss_wd";
79
80         /**
81          * The logger.
82          */
83         private static Log logger = LogFactory.getLog(Login.class);
84
85         @Override
86         public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
87                 // Fetch the next URL to display, if any.
88                 String nextUrl = request.getParameter(NEXT_URL_PARAM);
89                 // Fetch the supplied nonce, if any.
90                 String nonce = request.getParameter(NONCE_PARAM);
91                 String[] attrs = new String[] {"REMOTE_USER", "HTTP_SHIB_INETORGPERSON_DISPLAYNAME",
92                                         "HTTP_SHIB_INETORGPERSON_GIVENNAME", "HTTP_SHIB_PERSON_COMMONNAME",
93                                         "HTTP_SHIB_PERSON_SURNAME", "HTTP_SHIB_INETORGPERSON_MAIL",
94                                         "HTTP_SHIB_EP_UNSCOPEDAFFILIATION", "HTTP_PERSISTENT_ID"};
95                 StringBuilder buf = new StringBuilder("Shibboleth Attributes\n");
96                 for (String attr: attrs)
97                         buf.append(attr+": ").append(request.getAttribute(attr)).append('\n');
98                 logger.info(buf);
99                 if (logger.isDebugEnabled()) {
100                         buf = new StringBuilder("Shibboleth Attributes as bytes\n");
101                         for (String attr: attrs)
102                                 if (request.getAttribute(attr) != null)
103                                         buf.append(attr+": ").append(getHexString(request.getAttribute(attr).toString().getBytes("UTF-8"))).append('\n');
104                         logger.debug(buf);
105                 }
106                 User user = null;
107                 response.setContentType("text/html");
108                 Object usernameAttr = request.getAttribute("REMOTE_USER");
109                 Object nameAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_DISPLAYNAME");
110                 Object givennameAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_GIVENNAME"); // Multi-valued
111                 Object cnAttr = request.getAttribute("HTTP_SHIB_PERSON_COMMONNAME"); // Multi-valued
112                 Object snAttr = request.getAttribute("HTTP_SHIB_PERSON_SURNAME"); // Multi-valued
113                 Object mailAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_MAIL"); // Multi-valued
114                 Object persistentIdAttr = request.getAttribute("HTTP_PERSISTENT_ID");
115                 // Use a configured test username if found, as a shortcut for development deployments.
116                 String gwtServer = null;
117                 if (getConfiguration().getString("testUsername") != null) {
118                         usernameAttr = getConfiguration().getString("testUsername");
119                         // Fetch the GWT code server URL, if any.
120                         gwtServer = request.getParameter(GWT_SERVER_PARAM);
121                 }
122                 if (usernameAttr == null) {
123                         String authErrorUrl = "authenticationError.jsp";
124                         authErrorUrl += "?name=" + (nameAttr==null? "-": nameAttr.toString());
125                         authErrorUrl += "&givenname=" + (givennameAttr==null? "-": givennameAttr.toString());
126                         authErrorUrl += "&sn=" + (snAttr==null? "-": snAttr.toString());
127                         authErrorUrl += "&cn=" + (cnAttr==null? "-": cnAttr.toString());
128                         authErrorUrl += "&mail=" + (mailAttr==null? "-": mailAttr.toString());
129                         response.sendRedirect(authErrorUrl);
130                         return;
131                 }
132                 String username = decodeAttribute(usernameAttr);
133                 String name;
134                 if (nameAttr != null && !nameAttr.toString().isEmpty())
135                         name = decodeAttribute(nameAttr);
136                 else if (cnAttr != null && !cnAttr.toString().isEmpty()) {
137                         name = decodeAttribute(cnAttr);
138                         if (name.indexOf(';') != -1)
139                                 name = name.substring(0, name.indexOf(';'));
140                 } else if (givennameAttr != null && snAttr != null && !givennameAttr.toString().isEmpty() && !snAttr.toString().isEmpty()) {
141                         String givenname = decodeAttribute(givennameAttr);
142                         if (givenname.indexOf(';') != -1)
143                                 givenname = givenname.substring(0, givenname.indexOf(';'));
144                         String sn = decodeAttribute(snAttr);
145                         if (sn.indexOf(';') != -1)
146                                 sn = sn.substring(0, sn.indexOf(';'));
147                         name = givenname + ' ' + sn;
148                 } else if (givennameAttr == null && snAttr != null && !snAttr.toString().isEmpty()) {
149                         name = decodeAttribute(snAttr);
150                         if (name.indexOf(';') != -1)
151                                 name = name.substring(0, name.indexOf(';'));
152                 } else
153                         name = username;
154                 String mail = mailAttr != null ? mailAttr.toString() : username;
155                 if (mail.indexOf(';') != -1)
156                         mail = mail.substring(0, mail.indexOf(';'));
157                 String persistentId = persistentIdAttr != null ? persistentIdAttr.toString() : "";
158                 String idp = "";
159                 String idpid = "";
160                 if (!persistentId.isEmpty()) {
161                         int bang = persistentId.indexOf('!');
162                         if (bang > -1) {
163                                 idp = persistentId.substring(0, bang);
164                                 idpid = persistentId.substring(bang + 1);
165                         }
166                 }
167                 try {
168                         user = getService().findUser(username);
169                         if (user == null)
170                                 user = getService().createUser(username, name, mail, idp, idpid);
171                         if (!user.isActive()) {
172                                 logger.info("Disabled user " + username + " tried to login.");
173                                 response.sendError(HttpServletResponse.SC_FORBIDDEN, "This account is disabled");
174                                 return;
175                         }
176                         if (!user.hasAcceptedPolicy()) {
177                                 String policyUrl = "policy.jsp";
178                                 if (request.getQueryString() != null)
179                                         policyUrl += "?user=" + username + "&" + request.getQueryString();
180                                 response.sendRedirect(policyUrl);
181                                 return;
182                         }
183                         user.setName(name);
184                         user.setEmail(mail);
185                         user.setIdentityProvider(idp);
186                         user.setIdentityProviderId(idpid);
187                         user.setLastLogin(new Date());
188                         if (user.getAuthToken() == null)
189                                 user = getService().updateUserToken(user.getId());
190                         // Set WebDAV password to token if it's never been set.
191                         if (user.getWebDAVPassword() == null || user.getWebDAVPassword().length() == 0) {
192                                 String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
193                                 user.setWebDAVPassword(tokenEncoded);
194                         }
195                         // Set the default user class if none was set.
196                         if (user.getUserClass() == null)
197                                 user.setUserClass(getService().getUserClasses().get(0));
198                         getService().updateUser(user);
199                 } catch (RpcException e) {
200                         String error = "An error occurred while communicating with the service";
201                         logger.error(error, e);
202                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
203                         return;
204                 } catch (DuplicateNameException e) {
205                         String error = "User with username " + username + " already exists";
206                         logger.error(error, e);
207                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
208                         return;
209                 } catch (ObjectNotFoundException e) {
210                         String error = "No username was provided";
211                         logger.error(error, e);
212                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
213                         return;
214                 }
215                 String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
216                 String userEncoded = URLEncoder.encode(user.getUsername(), "US-ASCII");
217                 if (logger.isDebugEnabled())
218                         logger.debug("user: "+userEncoded+" token: "+tokenEncoded);
219                 if (nextUrl != null && !nextUrl.isEmpty()) {
220                         URI next;
221                         if (gwtServer != null)
222                                 nextUrl += '?' + GWT_SERVER_PARAM + '=' + gwtServer;
223                         try {
224                                 next = new URI(nextUrl);
225                         } catch (URISyntaxException e) {
226                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
227                                 return;
228                         }
229                         if ("x-gr-ebs-igss".equalsIgnoreCase(next.getScheme()))
230                                 nextUrl += "?u=" + userEncoded + "&t=" + tokenEncoded;
231                         else {
232                                 String domain = next.getHost();
233                                 String path = getServletContext().getContextPath() + '/';
234                                 Cookie cookie = new Cookie(AUTH_COOKIE, userEncoded + COOKIE_SEPARATOR +
235                                                         tokenEncoded);
236                                 cookie.setMaxAge(-1);
237                                 cookie.setDomain(domain);
238                                 cookie.setPath(path);
239                             response.addCookie(cookie);
240                             cookie = new Cookie(WEBDAV_COOKIE, user.getWebDAVPassword());
241                                 cookie.setMaxAge(-1);
242                                 cookie.setDomain(domain);
243                                 cookie.setPath(path);
244                                 response.addCookie(cookie);
245                         }
246                     response.sendRedirect(nextUrl);
247                 } else if (nonce != null) {
248                         nonce = URLEncoder.encode(nonce, "US-ASCII");
249                         Nonce n = null;
250                         try {
251                                 if (logger.isDebugEnabled())
252                                         logger.debug("user: "+user.getId()+" nonce: "+nonce);
253                                 n = getService().getNonce(nonce, user.getId());
254                         } catch (ObjectNotFoundException e) {
255                             PrintWriter out = response.getWriter();
256                             out.println("<HTML>");
257                             out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
258                                         "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
259                             out.println("<BODY><CENTER><P>");
260                             out.println("The supplied nonce could not be found!");
261                             out.println("</CENTER></BODY></HTML>");
262                             return;
263                         } catch (RpcException e) {
264                                 String error = "An error occurred while communicating with the service";
265                                 logger.error(error, e);
266                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
267                                 return;
268                         }
269                         try {
270                                 getService().activateUserNonce(user.getId(), nonce, n.getNonceExpiryDate());
271                         } catch (ObjectNotFoundException e) {
272                                 String error = "Unable to find user";
273                                 logger.error(error, e);
274                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
275                                 return;
276                         } catch (RpcException e) {
277                                 String error = "An error occurred while communicating with the service";
278                                 logger.error(error, e);
279                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
280                                 return;
281                         }
282                         try {
283                                 getService().removeNonce(n.getId());
284                         } catch (ObjectNotFoundException e) {
285                                 logger.info("Nonce already removed!", e);
286                         } catch (RpcException e) {
287                                 logger.warn("Could not remove nonce from data store", e);
288                         }
289                     PrintWriter out = response.getWriter();
290                     out.println("<HTML>");
291                     out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
292                                 "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
293                     out.println("<BODY><CENTER><P>");
294                     out.println("You can now close this browser window and return to your application.");
295                     out.println("</CENTER></BODY></HTML>");
296                 } else {
297                     PrintWriter out = response.getWriter();
298                     out.println("<HTML>");
299                     out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
300                                 "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
301                     out.println("<BODY><CENTER><P>");
302                     out.println("Name: " + user.getName() + "<BR>");
303                     out.println("E-mail: " + user.getEmail() + "<BR><P>");
304                     out.println("Username: " + user.getUsername() + "<BR>");
305                     out.println("Athentication token: " + tokenEncoded + "<BR>");
306                     out.println("</CENTER></BODY></HTML>");
307                 }
308         }
309 }