LoginServlet.java 10.6 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.crx.security.token.TokenCookie
 *  com.day.crx.security.token.TokenCookie$Info
 *  javax.jcr.Credentials
 *  javax.jcr.GuestCredentials
 *  javax.jcr.LoginException
 *  javax.jcr.NoSuchWorkspaceException
 *  javax.jcr.Repository
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.SimpleCredentials
 *  javax.jcr.Workspace
 *  javax.servlet.ServletConfig
 *  javax.servlet.ServletContext
 *  javax.servlet.ServletException
 *  javax.servlet.http.HttpServlet
 *  javax.servlet.http.HttpServletRequest
 *  javax.servlet.http.HttpServletResponse
 *  org.apache.jackrabbit.api.security.authentication.token.TokenCredentials
 *  org.apache.jackrabbit.util.Text
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.crx.explorer.impl.j2ee;

import com.day.crx.explorer.impl.j2ee.CRXContext;
import com.day.crx.explorer.impl.j2ee.CRXCredentialsProvider;
import com.day.crx.explorer.impl.j2ee.CRXHttpServletRequest;
import com.day.crx.explorer.impl.j2ee.CRXHttpServletResponse;
import com.day.crx.security.token.TokenCookie;
import java.io.IOException;
import java.util.UUID;
import javax.jcr.Credentials;
import javax.jcr.GuestCredentials;
import javax.jcr.LoginException;
import javax.jcr.NoSuchWorkspaceException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.Workspace;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.jackrabbit.api.security.authentication.token.TokenCredentials;
import org.apache.jackrabbit.util.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoginServlet
extends HttpServlet {
    private static Logger log = LoggerFactory.getLogger(LoginServlet.class);
    public static final String PARAM_USER = "UserId";
    public static final String PARAM_PASS = "Password";
    public static final String PARAM_WORKSPACE = "Workspace";
    public static final String PARAM_TOKEN = ".token";
    public static final String PARAM_REDIRECT = "redirect";
    public static final String COOKIE_WORKSPACE = "login-workspace";
    public static final String COOKIE_IMPERSONATE = "login-impersonate";
    private static final String REPO_DESC_ID = "crx.repository.systemid";
    private static final String REPO_DESC_CLUSTER_ID = "crx.cluster.id";
    private static String repositoryId;

    static void initRepositoryId(Repository repository) {
        String id = repository.getDescriptor("crx.cluster.id");
        if (id == null && (id = repository.getDescriptor("crx.repository.systemid")) == null) {
            id = UUID.randomUUID().toString();
            log.error("activate: Failure to acquire unique ID for this token authenticator. Using random UUID {}", (Object)id);
        }
        repositoryId = id;
        log.info("activate: Supporting tokens bound to Repository (Cluster) {}", (Object)repositoryId);
    }

    private static String getRepositoryId() {
        return repositoryId;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CRXHttpServletRequest crxRequest;
        if (request instanceof CRXHttpServletRequest) {
            crxRequest = (CRXHttpServletRequest)request;
        } else {
            CRXContext ctx = CRXContext.getInstance(this.getServletConfig().getServletContext(), request, true);
            crxRequest = new CRXHttpServletRequest(ctx);
        }
        Session session = null;
        try {
            session = LoginServlet.login(crxRequest, response);
            if (session == null) {
                response.sendError(401);
            } else {
                LoginServlet.setLoginCookies(session, request, response);
                String redirect = crxRequest.getParameter("redirect");
                if (redirect != null) {
                    response.sendRedirect(redirect);
                }
            }
        }
        catch (LoginException e) {
            response.sendError(403, "Authentication failed: " + e.getMessage());
        }
        catch (NoSuchWorkspaceException e) {
            response.sendError(404, "Login failed: " + e.getMessage());
        }
        catch (RepositoryException e) {
            throw new ServletException((Throwable)e);
        }
        finally {
            if (session != null) {
                session.logout();
            }
        }
    }

    public static Session login(CRXHttpServletRequest request, HttpServletResponse response) throws RepositoryException, ServletException {
        String imp;
        Credentials creds = new CRXCredentialsProvider("guestcredentials").getCredentials((HttpServletRequest)request);
        String workspaceName = LoginServlet.getWorkspaceName((HttpServletRequest)request);
        Session session = request.getCtx().getRepository().login(creds, workspaceName);
        if (log.isDebugEnabled()) {
            log.debug("User '" + session.getUserID() + "' logged in. Workspace=" + session.getWorkspace().getName());
        }
        if (response != null) {
            String token = null;
            if (creds instanceof SimpleCredentials) {
                Object a = ((SimpleCredentials)creds).getAttribute(".token");
                if (a != null) {
                    token = a.toString();
                }
            } else if (creds instanceof TokenCredentials) {
                token = ((TokenCredentials)creds).getToken();
            }
            if (token != null && token.length() > 0) {
                TokenCookie.update((HttpServletRequest)request, (HttpServletResponse)response, (String)repositoryId, (String)token, (String)session.getWorkspace().getName(), (boolean)false);
            } else {
                TokenCookie.update((HttpServletRequest)request, (HttpServletResponse)response, (String)repositoryId, (String)null, (String)null, (boolean)false);
            }
        }
        if ((imp = TokenCookie.getCookie((HttpServletRequest)request, (String)"login-impersonate")) != null) {
            try {
                Session impSession = session.impersonate((Credentials)new SimpleCredentials(imp, new char[0]));
                log.error("Impersonated {} to {}.", (Object)session.getUserID(), (Object)imp);
                session.logout();
                session = impSession;
            }
            catch (LoginException e) {
                log.error("Impersonation to {} failed. Using original session: {}", (Object)imp, (Object)e.toString());
            }
        }
        return session;
    }

    public static Session login(CRXContext ctx, HttpServletResponse response) throws RepositoryException, ServletException {
        CRXHttpServletRequest crxRequest = ctx.getRequest() instanceof CRXHttpServletRequest ? (CRXHttpServletRequest)ctx.getRequest() : new CRXHttpServletRequest(ctx);
        return LoginServlet.login(crxRequest, response);
    }

    public static String getWorkspaceName(HttpServletRequest request) {
        String workspaceName = request.getParameter("Workspace");
        if (workspaceName == null) {
            workspaceName = LoginServlet.getWorkspaceFromCookies(request);
        } else if ("".equals(workspaceName)) {
            workspaceName = null;
        }
        return workspaceName;
    }

    public static String getWorkspaceFromCookies(HttpServletRequest request) {
        String wsp = TokenCookie.getTokenInfo((HttpServletRequest)request, (String)LoginServlet.getRepositoryId()).workspace;
        if (wsp == null) {
            wsp = TokenCookie.getCookie((HttpServletRequest)request, (String)"login-workspace");
        }
        return wsp;
    }

    public static String getLoginTokenFromCookies(HttpServletRequest request) {
        return TokenCookie.getTokenInfo((HttpServletRequest)request, (String)LoginServlet.getRepositoryId()).token;
    }

    public static void setLoginCookies(Session session, HttpServletRequest request, HttpServletResponse response) {
        String path = request.getContextPath();
        if (path == null || path.length() == 0) {
            path = "/";
        }
        String repositoryId = LoginServlet.getRepositoryId();
        if (session == null) {
            TokenCookie.update((HttpServletRequest)request, (HttpServletResponse)response, (String)repositoryId, (String)null, (String)null, (boolean)false);
            TokenCookie.setCookie((HttpServletResponse)response, (String)"login-workspace", (String)"", (int)0, (String)path, (String)null, (boolean)false, (boolean)request.isSecure());
        } else {
            TokenCookie.setCookie((HttpServletResponse)response, (String)"login-workspace", (String)session.getWorkspace().getName(), (int)-1, (String)path, (String)null, (boolean)false, (boolean)request.isSecure());
        }
        TokenCookie.setCookie((HttpServletResponse)response, (String)"login-impersonate", (String)"", (int)0, (String)path, (String)null, (boolean)false, (boolean)request.isSecure());
    }

    public static void setImpersonationCookie(Session session, HttpServletRequest request, HttpServletResponse response) {
        if (session != null) {
            String path = request.getContextPath();
            if (path == null || path.length() == 0) {
                path = "/";
            }
            TokenCookie.setCookie((HttpServletResponse)response, (String)"login-impersonate", (String)session.getUserID(), (int)-1, (String)path, (String)null, (boolean)false, (boolean)request.isSecure());
        }
    }

    public static boolean redirectToLogin(CRXHttpServletRequest request, CRXHttpServletResponse response) throws IOException {
        Session s = request.getJcrSession();
        if (s == null || !s.isLive()) {
            Credentials creds = null;
            try {
                creds = new CRXCredentialsProvider("guestcredentials").getCredentials((HttpServletRequest)request);
            }
            catch (Exception e) {
                // empty catch block
            }
            String msg = creds == null || creds instanceof GuestCredentials ? "Anonymous access not allowed. Please login." : "Your CRX session has expired. Please login again.";
            StringBuilder uri = new StringBuilder(request.getContextPath());
            uri.append("/login.jsp?error=");
            uri.append(Text.escape((String)msg));
            uri.append("&redirect=");
            uri.append(Text.escape((String)request.getRequestURI()));
            response.sendRedirect(uri.toString());
            return true;
        }
        return false;
    }
}