Properly update others shares when refreshing / expanding tree after other user has...
[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                         if (!user.getName().equals(name) || !user.getEmail().equals(mail))
199                                 user = getService().updateUser(username, name, mail);
200                         if (user.getAuthToken() == null)
201                                 user = getService().updateUserToken(user.getId());
202                 } catch (RpcException e) {
203                         String error = "An error occurred while communicating with the service";
204                         logger.error(error, e);
205                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
206                         return;
207                 } catch (DuplicateNameException e) {
208                         String error = "User with username " + username + " already exists";
209                         logger.error(error, e);
210                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
211                         return;
212                 } catch (ObjectNotFoundException e) {
213                         String error = "No username was provided";
214                         logger.error(error, e);
215                         response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
216                         return;
217                 }
218                 String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
219                 String userEncoded = URLEncoder.encode(user.getUsername(), "US-ASCII");
220                 if (logger.isDebugEnabled())
221                         logger.debug("user: "+userEncoded+" token: "+tokenEncoded);
222                 if (nextUrl != null) {
223                         URL next = new URL(nextUrl);
224                         String domain = next.getHost();
225                         String path = next.getPath();
226                         Cookie cookie = new Cookie(AUTH_COOKIE, userEncoded + COOKIE_SEPARATOR +
227                                                 tokenEncoded);
228                         cookie.setMaxAge(-1);
229                         cookie.setDomain(domain);
230                         cookie.setPath(path);
231                     response.addCookie(cookie);
232                     cookie = new Cookie(WEBDAV_COOKIE, user.getWebDAVPassword());
233                         cookie.setMaxAge(-1);
234                         cookie.setDomain(domain);
235                         cookie.setPath(path);
236                     response.addCookie(cookie);
237                     response.sendRedirect(nextUrl);
238                 } else if (nonce != null) {
239                         nonce = URLEncoder.encode(nonce, "US-ASCII");
240                         Nonce n = null;
241                         try {
242                                 if (logger.isDebugEnabled())
243                                         logger.debug("user: "+user.getId()+" nonce: "+nonce);
244                                 n = getService().getNonce(nonce, user.getId());
245                         } catch (ObjectNotFoundException e) {
246                             PrintWriter out = response.getWriter();
247                             out.println("<HTML>");
248                             out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
249                                         "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
250                             out.println("<BODY><CENTER><P>");
251                             out.println("The supplied nonce could not be found!");
252                             out.println("</CENTER></BODY></HTML>");
253                             return;
254                         } catch (RpcException e) {
255                                 String error = "An error occurred while communicating with the service";
256                                 logger.error(error, e);
257                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
258                                 return;
259                         }
260                         try {
261                                 getService().activateUserNonce(user.getId(), nonce, n.getNonceExpiryDate());
262                         } catch (ObjectNotFoundException e) {
263                                 String error = "Unable to find user";
264                                 logger.error(error, e);
265                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
266                                 return;
267                         } catch (RpcException e) {
268                                 String error = "An error occurred while communicating with the service";
269                                 logger.error(error, e);
270                                 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
271                                 return;
272                         }
273                         try {
274                                 getService().removeNonce(n.getId());
275                         } catch (ObjectNotFoundException e) {
276                                 logger.info("Nonce already removed!", e);
277                         } catch (RpcException e) {
278                                 logger.warn("Could not remove nonce from data store", e);
279                         }
280                     PrintWriter out = response.getWriter();
281                     out.println("<HTML>");
282                     out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
283                                 "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
284                     out.println("<BODY><CENTER><P>");
285                     out.println("You can now close this browser window and return to your application.");
286                     out.println("</CENTER></BODY></HTML>");
287                 } else {
288                     PrintWriter out = response.getWriter();
289                     out.println("<HTML>");
290                     out.println("<HEAD><TITLE>" + getServiceName() + " Authentication</TITLE>" +
291                                 "<LINK TYPE='text/css' REL='stylesheet' HREF='gss.css'></HEAD>");
292                     out.println("<BODY><CENTER><P>");
293                     out.println("Name: " + user.getName() + "<BR>");
294                     out.println("E-mail: " + user.getEmail() + "<BR><P>");
295                     out.println("Username: " + user.getUsername() + "<BR>");
296                     out.println("Athentication token: " + tokenEncoded + "<BR>");
297                     out.println("</CENTER></BODY></HTML>");
298                 }
299         }
300
301         /**
302          * Decode the request attribute provided by the container to a UTF-8
303          * string, since GSS assumes all data to be encoded in UTF-8. The
304          * servlet container's encoding can be specified in gss.properties.
305          */
306         private String decodeAttribute(Object attribute) throws UnsupportedEncodingException {
307                 return new String(attribute.toString().getBytes(getConfiguration().getString("requestAttributeEncoding")), "UTF-8");
308         }
309
310         /**
311          * A helper method that converts a byte buffer to a printable list of
312          * hexadecimal numbers.
313          */
314         private String getHexString(byte[] buffer) {
315                 StringBuilder sb = new StringBuilder();
316                 Formatter formatter = new Formatter(sb);
317                 for (int i=0; i<buffer.length; i++)
318                         formatter.format("0x%x, ", buffer[i]);
319                 return sb.toString();
320         }
321
322 }