Remove the redundant gss top-level directory.
[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 logger.
83          */
84         private static Log logger = LogFactory.getLog(Login.class);
85
86         /**
87          * A helper method that retrieves a reference to the ExternalAPI bean and
88          * stores it for future use.
89          *
90          * @return an ExternalAPI instance
91          * @throws RpcException in case an error occurs
92          */
93         private ExternalAPI getService() throws RpcException {
94                 try {
95                         final Context ctx = new InitialContext();
96                         final Object ref = ctx.lookup(getConfiguration().getString("externalApiPath"));
97                         return (ExternalAPI) PortableRemoteObject.narrow(ref, ExternalAPI.class);
98                 } catch (final NamingException e) {
99                         logger.error("Unable to retrieve the ExternalAPI EJB", e);
100                         throw new RpcException("An error occurred while contacting the naming service");
101                 }
102         }
103
104         /**
105          * Return the name of the service.
106          */
107         private String getServiceName() {
108                 return getConfiguration().getString("serviceName", "GSS");
109         }
110
111         @Override
112         public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
113                 // Fetch the next URL to display, if any.
114                 String nextUrl = request.getParameter(NEXT_URL_PARAM);
115                 // Fetch the supplied nonce, if any.
116                 String nonce = request.getParameter(NONCE_PARAM);
117                 String[] attrs = new String[] {"REMOTE_USER", "HTTP_SHIB_INETORGPERSON_DISPLAYNAME",
118                                         "HTTP_SHIB_INETORGPERSON_GIVENNAME", "HTTP_SHIB_PERSON_COMMONNAME",
119                                         "HTTP_SHIB_PERSON_SURNAME", "HTTP_SHIB_INETORGPERSON_MAIL",
120                                         "HTTP_SHIB_EP_UNSCOPEDAFFILIATION"};
121                 StringBuilder buf = new StringBuilder("Shibboleth Attributes\n");
122                 for (String attr: attrs)
123                         buf.append(attr+": ").append(request.getAttribute(attr)).append('\n');
124                 logger.info(buf);
125                 if (logger.isDebugEnabled()) {
126                         buf = new StringBuilder("Shibboleth Attributes as bytes\n");
127                         for (String attr: attrs)
128                                 if (request.getAttribute(attr) != null)
129                                         buf.append(attr+": ").append(getHexString(request.getAttribute(attr).toString().getBytes("UTF-8"))).append('\n');
130                         logger.debug(buf);
131                 }
132                 User user = null;
133                 response.setContentType("text/html");
134                 Object usernameAttr = request.getAttribute("REMOTE_USER");
135                 Object nameAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_DISPLAYNAME");
136                 Object givennameAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_GIVENNAME"); // Multi-valued
137                 Object cnAttr = request.getAttribute("HTTP_SHIB_PERSON_COMMONNAME"); // Multi-valued
138                 Object snAttr = request.getAttribute("HTTP_SHIB_PERSON_SURNAME"); // Multi-valued
139                 Object mailAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_MAIL"); // Multi-valued
140                 Object userclassAttr = request.getAttribute("HTTP_SHIB_EP_UNSCOPEDAFFILIATION"); // Multi-valued
141                 if (usernameAttr == null) {
142                         String authErrorUrl = "authenticationError.jsp";
143                         authErrorUrl += "?name=" + (nameAttr==null? "-": nameAttr.toString());
144                         authErrorUrl += "&givenname=" + (givennameAttr==null? "-": givennameAttr.toString());
145                         authErrorUrl += "&sn=" + (snAttr==null? "-": snAttr.toString());
146                         authErrorUrl += "&cn=" + (cnAttr==null? "-": cnAttr.toString());
147                         authErrorUrl += "&mail=" + (mailAttr==null? "-": mailAttr.toString());
148                         authErrorUrl += "&userclass=" + (userclassAttr==null? "-": userclassAttr.toString());
149                         response.sendRedirect(authErrorUrl);
150                         return;
151                 }
152                 String username = decodeAttribute(usernameAttr);
153                 String name;
154                 if (nameAttr != null && !nameAttr.toString().isEmpty())
155                         name = decodeAttribute(nameAttr);
156                 else if (cnAttr != null && !cnAttr.toString().isEmpty()) {
157                         name = decodeAttribute(cnAttr);
158                         if (name.indexOf(';') != -1)
159                                 name = name.substring(0, name.indexOf(';'));
160                 } else if (givennameAttr != null && snAttr != null && !givennameAttr.toString().isEmpty() && !snAttr.toString().isEmpty()) {
161                         String givenname = decodeAttribute(givennameAttr);
162                         if (givenname.indexOf(';') != -1)
163                                 givenname = givenname.substring(0, givenname.indexOf(';'));
164                         String sn = decodeAttribute(snAttr);
165                         if (sn.indexOf(';') != -1)
166                                 sn = sn.substring(0, sn.indexOf(';'));
167                         name = givenname + ' ' + sn;
168                 } else if (givennameAttr == null && snAttr != null && !snAttr.toString().isEmpty()) {
169                         name = decodeAttribute(snAttr);
170                         if (name.indexOf(';') != -1)
171                                 name = name.substring(0, name.indexOf(';'));
172                 } else
173                         name = username;
174                 String mail = mailAttr != null ? mailAttr.toString() : username;
175                 if (mail.indexOf(';') != -1)
176                         mail = mail.substring(0, mail.indexOf(';'));
177                 // XXX we are not using the user class currently
178                 String userclass = userclassAttr != null ? userclassAttr.toString() : "";
179                 if (userclass.indexOf(';') != -1)
180                         userclass = userclass.substring(0, userclass.indexOf(';'));
181                 try {
182                         user = getService().findUser(username);
183                         if (user == null)
184                                 user = getService().createUser(username, name, mail);
185                         if (!user.hasAcceptedPolicy()) {
186                                 String policyUrl = "policy.jsp";
187                                 if (request.getQueryString() != null)
188                                         policyUrl += "?user=" + username + "&" + request.getQueryString();
189                                 response.sendRedirect(policyUrl);
190                                 return;
191                         }
192                         // Update the user name and e-mail if modified.
193                         if (!user.getName().equals(name) || !user.getEmail().equals(mail))
194                                 user = getService().updateUser(username, name, mail);
195                         if (user.getAuthToken() == null)
196                                 user = getService().updateUserToken(user.getId());
197                 } catch (RpcException e) {
198                         String error = "An error occurred while communicating with the service";
199                         logger.error(error, e);
200                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
201                         return;
202                 } catch (DuplicateNameException e) {
203                         String error = "User with username " + username + " already exists";
204                         logger.error(error, e);
205                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
206                         return;
207                 } catch (ObjectNotFoundException e) {
208                         String error = "No username was provided";
209                         logger.error(error, e);
210                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
211                         return;
212                 }
213                 String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
214                 String userEncoded = URLEncoder.encode(user.getUsername(), "US-ASCII");
215                 if (logger.isDebugEnabled())
216                         logger.debug("user: "+userEncoded+" token: "+tokenEncoded);
217                 if (nextUrl != null) {
218                         URL next = new URL(nextUrl);
219                         String domain = next.getHost();
220                         String path = next.getPath();
221                         Cookie cookie = new Cookie(AUTH_COOKIE, userEncoded + COOKIE_SEPARATOR +
222                                                 tokenEncoded);
223                         cookie.setMaxAge(-1);
224                         cookie.setDomain(domain);
225                         cookie.setPath(path);
226                     response.addCookie(cookie);
227                     response.sendRedirect(nextUrl);
228                 } else if (nonce != null) {
229                         nonce = URLEncoder.encode(nonce, "US-ASCII");
230                         Nonce n = null;
231                         try {
232                                 if (logger.isDebugEnabled())
233                                         logger.debug("user: "+user.getId()+" nonce: "+nonce);
234                                 n = getService().getNonce(nonce, user.getId());
235                         } catch (ObjectNotFoundException e) {
236                             PrintWriter out = response.getWriter();
237                             out.println("<HTML>");
238                             out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
239                                         "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
240                             out.println("<BODY><CENTER><P>");
241                             out.println("The supplied nonce could not be found!");
242                             out.println("</CENTER></BODY></HTML>");
243                             return;
244                         } catch (RpcException e) {
245                                 String error = "An error occurred while communicating with the service";
246                                 logger.error(error, e);
247                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
248                                 return;
249                         }
250                         try {
251                                 getService().activateUserNonce(user.getId(), nonce, n.getNonceExpiryDate());
252                         } catch (ObjectNotFoundException e) {
253                                 String error = "Unable to find user";
254                                 logger.error(error, e);
255                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
256                                 return;
257                         } catch (RpcException e) {
258                                 String error = "An error occurred while communicating with the service";
259                                 logger.error(error, e);
260                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
261                                 return;
262                         }
263                         try {
264                                 getService().removeNonce(n.getId());
265                         } catch (ObjectNotFoundException e) {
266                                 logger.info("Nonce already removed!", e);
267                         } catch (RpcException e) {
268                                 logger.warn("Could not remove nonce from data store", e);
269                         }
270                     PrintWriter out = response.getWriter();
271                     out.println("<HTML>");
272                     out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
273                                 "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
274                     out.println("<BODY><CENTER><P>");
275                     out.println("You can now close this browser window and return to your application.");
276                     out.println("</CENTER></BODY></HTML>");
277                 } else {
278                     PrintWriter out = response.getWriter();
279                     out.println("<HTML>");
280                     out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
281                                 "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
282                     out.println("<BODY><CENTER><P>");
283                     out.println("Name: " + user.getName() + "<BR>");
284                     out.println("E-mail: " + user.getEmail() + "<BR><P>");
285                     out.println("Username: " + user.getUsername() + "<BR>");
286                     out.println("Athentication token: " + tokenEncoded + "<BR>");
287                     out.println("</CENTER></BODY></HTML>");
288                 }
289         }
290
291         /**
292          * Decode the request attribute provided by the container to a UTF-8
293          * string, since GSS assumes all data to be encoded in UTF-8. The
294          * servlet container's encoding can be specified in gss.properties.
295          */
296         private String decodeAttribute(Object attribute) throws UnsupportedEncodingException {
297                 return new String(attribute.toString().getBytes(getConfiguration().getString("requestAttributeEncoding")), "UTF-8");
298         }
299
300         /**
301          * A helper method that converts a byte buffer to a printable list of
302          * hexadecimal numbers.
303          */
304         private String getHexString(byte[] buffer) {
305                 StringBuilder sb = new StringBuilder();
306                 Formatter formatter = new Formatter(sb);
307                 for (int i=0; i<buffer.length; i++)
308                         formatter.format("0x%x, ", buffer[i]);
309                 return sb.toString();
310         }
311
312 }