Stop fetching and checking the user affiliation, since we are not going to use it...
[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.hasAcceptedPolicy()) {
172                                 String policyUrl = "policy.jsp";
173                                 if (request.getQueryString() != null)
174                                         policyUrl += "?user=" + username + "&" + request.getQueryString();
175                                 response.sendRedirect(policyUrl);
176                                 return;
177                         }
178                         user.setName(name);
179                         user.setEmail(mail);
180                         user.setIdentityProvider(idp);
181                         user.setIdentityProviderId(idpid);
182                         user.setLastLogin(new Date());
183                         if (user.getAuthToken() == null)
184                                 user = getService().updateUserToken(user.getId());
185                         // Set WebDAV password to token if it's never been set.
186                         if (user.getWebDAVPassword() == null || user.getWebDAVPassword().length() == 0) {
187                                 String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
188                                 user.setWebDAVPassword(tokenEncoded);
189                         }
190                         // Set the default user class if none was set.
191                         if (user.getUserClass() == null)
192                                 user.setUserClass(getService().getUserClasses().get(0));
193                         getService().updateUser(user);
194                 } catch (RpcException e) {
195                         String error = "An error occurred while communicating with the service";
196                         logger.error(error, e);
197                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
198                         return;
199                 } catch (DuplicateNameException e) {
200                         String error = "User with username " + username + " already exists";
201                         logger.error(error, e);
202                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
203                         return;
204                 } catch (ObjectNotFoundException e) {
205                         String error = "No username was provided";
206                         logger.error(error, e);
207                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
208                         return;
209                 }
210                 String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
211                 String userEncoded = URLEncoder.encode(user.getUsername(), "US-ASCII");
212                 if (logger.isDebugEnabled())
213                         logger.debug("user: "+userEncoded+" token: "+tokenEncoded);
214                 if (nextUrl != null && !nextUrl.isEmpty()) {
215                         URI next;
216                         if (gwtServer != null)
217                                 nextUrl += '?' + GWT_SERVER_PARAM + '=' + gwtServer;
218                         try {
219                                 next = new URI(nextUrl);
220                         } catch (URISyntaxException e) {
221                                 response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
222                                 return;
223                         }
224                         if ("x-gr-ebs-igss".equalsIgnoreCase(next.getScheme()))
225                                 nextUrl += "?u=" + userEncoded + "&t=" + tokenEncoded;
226                         else {
227                                 String domain = next.getHost();
228                                 String path = getServletContext().getContextPath() + '/';
229                                 Cookie cookie = new Cookie(AUTH_COOKIE, userEncoded + COOKIE_SEPARATOR +
230                                                         tokenEncoded);
231                                 cookie.setMaxAge(-1);
232                                 cookie.setDomain(domain);
233                                 cookie.setPath(path);
234                             response.addCookie(cookie);
235                             cookie = new Cookie(WEBDAV_COOKIE, user.getWebDAVPassword());
236                                 cookie.setMaxAge(-1);
237                                 cookie.setDomain(domain);
238                                 cookie.setPath(path);
239                                 response.addCookie(cookie);
240                         }
241                     response.sendRedirect(nextUrl);
242                 } else if (nonce != null) {
243                         nonce = URLEncoder.encode(nonce, "US-ASCII");
244                         Nonce n = null;
245                         try {
246                                 if (logger.isDebugEnabled())
247                                         logger.debug("user: "+user.getId()+" nonce: "+nonce);
248                                 n = getService().getNonce(nonce, user.getId());
249                         } catch (ObjectNotFoundException e) {
250                             PrintWriter out = response.getWriter();
251                             out.println("<HTML>");
252                             out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
253                                         "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
254                             out.println("<BODY><CENTER><P>");
255                             out.println("The supplied nonce could not be found!");
256                             out.println("</CENTER></BODY></HTML>");
257                             return;
258                         } catch (RpcException e) {
259                                 String error = "An error occurred while communicating with the service";
260                                 logger.error(error, e);
261                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
262                                 return;
263                         }
264                         try {
265                                 getService().activateUserNonce(user.getId(), nonce, n.getNonceExpiryDate());
266                         } catch (ObjectNotFoundException e) {
267                                 String error = "Unable to find user";
268                                 logger.error(error, e);
269                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
270                                 return;
271                         } catch (RpcException e) {
272                                 String error = "An error occurred while communicating with the service";
273                                 logger.error(error, e);
274                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
275                                 return;
276                         }
277                         try {
278                                 getService().removeNonce(n.getId());
279                         } catch (ObjectNotFoundException e) {
280                                 logger.info("Nonce already removed!", e);
281                         } catch (RpcException e) {
282                                 logger.warn("Could not remove nonce from data store", e);
283                         }
284                     PrintWriter out = response.getWriter();
285                     out.println("<HTML>");
286                     out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
287                                 "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
288                     out.println("<BODY><CENTER><P>");
289                     out.println("You can now close this browser window and return to your application.");
290                     out.println("</CENTER></BODY></HTML>");
291                 } else {
292                     PrintWriter out = response.getWriter();
293                     out.println("<HTML>");
294                     out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
295                                 "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
296                     out.println("<BODY><CENTER><P>");
297                     out.println("Name: " + user.getName() + "<BR>");
298                     out.println("E-mail: " + user.getEmail() + "<BR><P>");
299                     out.println("Username: " + user.getUsername() + "<BR>");
300                     out.println("Athentication token: " + tokenEncoded + "<BR>");
301                     out.println("</CENTER></BODY></HTML>");
302                 }
303         }
304 }