Fixed query syntax in case of empty group list
[pithos] / src / gr / ebs / gss / server / Login.java
index b0a715f..e94ecc4 100644 (file)
@@ -24,22 +24,16 @@ import gr.ebs.gss.client.exceptions.ObjectNotFoundException;
 import gr.ebs.gss.client.exceptions.RpcException;
 import gr.ebs.gss.server.domain.Nonce;
 import gr.ebs.gss.server.domain.User;
-import gr.ebs.gss.server.ejb.ExternalAPI;
+import gr.ebs.gss.server.domain.UserLogin;
 
 import java.io.IOException;
 import java.io.PrintWriter;
-import java.io.UnsupportedEncodingException;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.net.URLEncoder;
-import java.util.Formatter;
+import java.util.Date;
 
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import javax.rmi.PortableRemoteObject;
 import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
@@ -52,7 +46,7 @@ import org.apache.commons.logging.LogFactory;
  *
  * @author past
  */
-public class Login extends HttpServlet {
+public class Login extends BaseServlet {
        /**
         * The request parameter name for the nonce.
         */
@@ -65,12 +59,6 @@ public class Login extends HttpServlet {
        private static final String NEXT_URL_PARAM = "next";
 
        /**
-        * The request parameter name for the GWT code server URL, used when
-        * debugging.
-        */
-       private static final String GWT_SERVER_PARAM = "gwt.codesvr";
-
-       /**
         * The serial version UID of the class.
         */
        private static final long serialVersionUID = 1L;
@@ -78,12 +66,12 @@ public class Login extends HttpServlet {
        /**
         * The name of the authentication cookie.
         */
-       private static final String AUTH_COOKIE = "_gss_a";
+       public static final String AUTH_COOKIE = "_gss_a";
 
        /**
         * The separator character for the authentication cookie.
         */
-       private static final char COOKIE_SEPARATOR = '|';
+       public static final char COOKIE_SEPARATOR = '|';
 
        /**
         * The name of the the webdav cookie.
@@ -95,31 +83,6 @@ public class Login extends HttpServlet {
         */
        private static Log logger = LogFactory.getLog(Login.class);
 
-       /**
-        * A helper method that retrieves a reference to the ExternalAPI bean and
-        * stores it for future use.
-        *
-        * @return an ExternalAPI instance
-        * @throws RpcException in case an error occurs
-        */
-       private ExternalAPI getService() throws RpcException {
-               try {
-                       final Context ctx = new InitialContext();
-                       final Object ref = ctx.lookup(getConfiguration().getString("externalApiPath"));
-                       return (ExternalAPI) PortableRemoteObject.narrow(ref, ExternalAPI.class);
-               } catch (final NamingException e) {
-                       logger.error("Unable to retrieve the ExternalAPI EJB", e);
-                       throw new RpcException("An error occurred while contacting the naming service");
-               }
-       }
-
-       /**
-        * Return the name of the service.
-        */
-       private String getServiceName() {
-               return getConfiguration().getString("serviceName", "GSS");
-       }
-
        @Override
        public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
                // Fetch the next URL to display, if any.
@@ -129,7 +92,7 @@ public class Login extends HttpServlet {
                String[] attrs = new String[] {"REMOTE_USER", "HTTP_SHIB_INETORGPERSON_DISPLAYNAME",
                                        "HTTP_SHIB_INETORGPERSON_GIVENNAME", "HTTP_SHIB_PERSON_COMMONNAME",
                                        "HTTP_SHIB_PERSON_SURNAME", "HTTP_SHIB_INETORGPERSON_MAIL",
-                                       "HTTP_SHIB_EP_UNSCOPEDAFFILIATION"};
+                                       "HTTP_SHIB_EP_UNSCOPEDAFFILIATION", "HTTP_PERSISTENT_ID"};
                StringBuilder buf = new StringBuilder("Shibboleth Attributes\n");
                for (String attr: attrs)
                        buf.append(attr+": ").append(request.getAttribute(attr)).append('\n');
@@ -149,7 +112,7 @@ public class Login extends HttpServlet {
                Object cnAttr = request.getAttribute("HTTP_SHIB_PERSON_COMMONNAME"); // Multi-valued
                Object snAttr = request.getAttribute("HTTP_SHIB_PERSON_SURNAME"); // Multi-valued
                Object mailAttr = request.getAttribute("HTTP_SHIB_INETORGPERSON_MAIL"); // Multi-valued
-               Object userclassAttr = request.getAttribute("HTTP_SHIB_EP_UNSCOPEDAFFILIATION"); // Multi-valued
+               Object persistentIdAttr = request.getAttribute("HTTP_PERSISTENT_ID");
                // Use a configured test username if found, as a shortcut for development deployments.
                String gwtServer = null;
                if (getConfiguration().getString("testUsername") != null) {
@@ -164,7 +127,6 @@ public class Login extends HttpServlet {
                        authErrorUrl += "&sn=" + (snAttr==null? "-": snAttr.toString());
                        authErrorUrl += "&cn=" + (cnAttr==null? "-": cnAttr.toString());
                        authErrorUrl += "&mail=" + (mailAttr==null? "-": mailAttr.toString());
-                       authErrorUrl += "&userclass=" + (userclassAttr==null? "-": userclassAttr.toString());
                        response.sendRedirect(authErrorUrl);
                        return;
                }
@@ -193,14 +155,25 @@ public class Login extends HttpServlet {
                String mail = mailAttr != null ? mailAttr.toString() : username;
                if (mail.indexOf(';') != -1)
                        mail = mail.substring(0, mail.indexOf(';'));
-               // XXX we are not using the user class currently
-               String userclass = userclassAttr != null ? userclassAttr.toString() : "";
-               if (userclass.indexOf(';') != -1)
-                       userclass = userclass.substring(0, userclass.indexOf(';'));
+               String persistentId = persistentIdAttr != null ? persistentIdAttr.toString() : "";
+               String idp = "";
+               String idpid = "";
+               if (!persistentId.isEmpty()) {
+                       int bang = persistentId.indexOf('!');
+                       if (bang > -1) {
+                               idp = persistentId.substring(0, bang);
+                               idpid = persistentId.substring(bang + 1);
+                       }
+               }
                try {
                        user = getService().findUser(username);
                        if (user == null)
-                               user = getService().createUser(username, name, mail);
+                               user = getService().createUser(username, name, mail, idp, idpid);
+                       if (!user.isActive()) {
+                               logger.info("Disabled user " + username + " tried to login.");
+                               response.sendError(HttpServletResponse.SC_FORBIDDEN, "This account is disabled");
+                               return;
+                       }
                        if (!user.hasAcceptedPolicy()) {
                                String policyUrl = "policy.jsp";
                                if (request.getQueryString() != null)
@@ -208,26 +181,26 @@ public class Login extends HttpServlet {
                                response.sendRedirect(policyUrl);
                                return;
                        }
-                       // Update the user name and e-mail if modified.
-                       boolean update = false;
-                       if (!user.getName().equals(name)) {
-                               user.setName(name);
-                               update = true;
-                       }
-                       if (!user.getEmail().equals(mail)) {
-                               user.setEmail(mail);
-                               update = true;
-                       }
+                       user.setName(name);
+                       user.setEmail(mail);
+                       user.setIdentityProvider(idp);
+                       user.setIdentityProviderId(idpid);
+                       
+                       UserLogin userLogin = new UserLogin();
+                       userLogin.setLoginDate(new Date());
+                       userLogin.setUser(user);
                        if (user.getAuthToken() == null)
                                user = getService().updateUserToken(user.getId());
                        // Set WebDAV password to token if it's never been set.
-                       if (user.getWebDAVPassword()==null || user.getWebDAVPassword().length()==0) {
+                       if (user.getWebDAVPassword() == null || user.getWebDAVPassword().length() == 0) {
                                String tokenEncoded = new String(Base64.encodeBase64(user.getAuthToken()), "US-ASCII");
                                user.setWebDAVPassword(tokenEncoded);
-                               update = true;
                        }
-                       if (update)
-                               getService().updateUser(user);
+                       // Set the default user class if none was set.
+                       if (user.getUserClass() == null)
+                               user.setUserClass(getService().getUserClasses().get(0));                        
+                       getService().updateUser(user);
+                       getService().addUserLogin(userLogin);           
                } catch (RpcException e) {
                        String error = "An error occurred while communicating with the service";
                        logger.error(error, e);
@@ -262,7 +235,7 @@ public class Login extends HttpServlet {
                                nextUrl += "?u=" + userEncoded + "&t=" + tokenEncoded;
                        else {
                                String domain = next.getHost();
-                               String path = next.getPath();
+                               String path = getServletContext().getContextPath() + '/';
                                Cookie cookie = new Cookie(AUTH_COOKIE, userEncoded + COOKIE_SEPARATOR +
                                                        tokenEncoded);
                                cookie.setMaxAge(-1);
@@ -338,26 +311,4 @@ public class Login extends HttpServlet {
                    out.println("</CENTER></BODY></HTML>");
                }
        }
-
-       /**
-        * Decode the request attribute provided by the container to a UTF-8
-        * string, since GSS assumes all data to be encoded in UTF-8. The
-        * servlet container's encoding can be specified in gss.properties.
-        */
-       private String decodeAttribute(Object attribute) throws UnsupportedEncodingException {
-               return new String(attribute.toString().getBytes(getConfiguration().getString("requestAttributeEncoding")), "UTF-8");
-       }
-
-       /**
-        * A helper method that converts a byte buffer to a printable list of
-        * hexadecimal numbers.
-        */
-       private String getHexString(byte[] buffer) {
-               StringBuilder sb = new StringBuilder();
-               Formatter formatter = new Formatter(sb);
-               for (int i=0; i<buffer.length; i++)
-                       formatter.format("0x%x, ", buffer[i]);
-               return sb.toString();
-       }
-
 }