Search in sources :

Example 1 with AlreadyLoggedInException

use of fi.internetix.smvc.AlreadyLoggedInException in project pyramus by otavanopisto.

the class LoginJSONRequestController method process.

/**
 * Processes the request to log in. Authorizes the given credentials and if they match a user,
 * stores the user into the session (keys <code>loggedUserId</code>, <code>loggedUserName</code>,
 * and <code>loggedUserRole</code>).
 * <p/>
 * If the session contains a <code>loginRedirectUrl</code> key, redirects the user to that URL.
 * Otherwise, redirects back to the index page of the application.
 * <p/>
 * If the user is already logged in or the authentication fails, a <code>PyramusRuntimeException</code>
 * is thrown with a localized message stating so.
 *
 * @param jsonRequestContext The JSON request context
 */
public void process(JSONRequestContext jsonRequestContext) {
    // Fields submitted from the web page
    String username = jsonRequestContext.getRequest().getParameter("username");
    String password = jsonRequestContext.getRequest().getParameter("password");
    Locale locale = jsonRequestContext.getRequest().getLocale();
    // Ensure that the user trying to login isn't already logged in
    HttpSession session = jsonRequestContext.getRequest().getSession(true);
    if (!session.isNew() && session.getAttribute("loggedUserId") != null) {
        String msg = Messages.getInstance().getText(locale, "users.login.alreadyLoggedIn");
        throw new AlreadyLoggedInException(PyramusStatusCode.ALREADY_LOGGED_IN, msg);
    }
    for (InternalAuthenticationProvider provider : AuthenticationProviderVault.getInstance().getInternalAuthenticationProviders()) {
        try {
            User user = provider.getUser(username, password);
            if (user != null && !user.getArchived() && !Role.CLOSED.equals(user.getRole())) {
                // User has been authorized, so store him in the session
                session.setAttribute("loggedUserId", user.getId());
                session.setAttribute("loggedUserName", user.getFullName());
                session.setAttribute("authenticationProvider", provider.getName());
                if (user instanceof StaffMember) {
                    session.setAttribute("loggedUserRole", UserRole.valueOf(((StaffMember) user).getRole().name()));
                }
                try {
                    DAOFactory.getInstance().getLoginLogDAO().create(user, new Date());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                if (session.getAttribute("loginRedirectUrl") != null) {
                    String url = (String) session.getAttribute("loginRedirectUrl");
                    session.removeAttribute("loginRedirectUrl");
                    jsonRequestContext.setRedirectURL(url);
                } else {
                    jsonRequestContext.setRedirectURL(jsonRequestContext.getRequest().getContextPath() + "/index.page");
                }
                return;
            }
        } catch (LocalUserMissingException lume) {
            throw new SmvcRuntimeException(PyramusStatusCode.LOCAL_USER_MISSING, Messages.getInstance().getText(locale, "users.login.localUserMissing", new String[] { lume.getExternalUser() }));
        } catch (AuthenticationException ae) {
            throw new SmvcRuntimeException(ae);
        }
    }
    // Reaching this point means no authentication provider authorized the user, so throw a login exception
    String msg = Messages.getInstance().getText(jsonRequestContext.getRequest().getLocale(), "users.login.loginFailed");
    throw new InvalidLoginException(msg);
}
Also used : Locale(java.util.Locale) User(fi.otavanopisto.pyramus.domainmodel.users.User) AuthenticationException(fi.otavanopisto.pyramus.plugin.auth.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) AlreadyLoggedInException(fi.internetix.smvc.AlreadyLoggedInException) StaffMember(fi.otavanopisto.pyramus.domainmodel.users.StaffMember) Date(java.util.Date) LocalUserMissingException(fi.otavanopisto.pyramus.plugin.auth.LocalUserMissingException) AuthenticationException(fi.otavanopisto.pyramus.plugin.auth.AuthenticationException) AlreadyLoggedInException(fi.internetix.smvc.AlreadyLoggedInException) InvalidLoginException(fi.internetix.smvc.InvalidLoginException) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) LocalUserMissingException(fi.otavanopisto.pyramus.plugin.auth.LocalUserMissingException) InternalAuthenticationProvider(fi.otavanopisto.pyramus.plugin.auth.InternalAuthenticationProvider) InvalidLoginException(fi.internetix.smvc.InvalidLoginException)

Example 2 with AlreadyLoggedInException

use of fi.internetix.smvc.AlreadyLoggedInException in project pyramus by otavanopisto.

the class Servlet method doService.

private void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {
        userTransaction.begin();
    } catch (Exception e) {
        Logging.logException(e);
        throw new ServletException(e);
    }
    RequestContext requestContext = null;
    RequestController requestController;
    RequestDispatchContext dispatchContext;
    if (requestDispatcher != null && requestDispatcher.canHandle(request, response)) {
        dispatchContext = requestDispatcher.getContext(request, response);
        requestController = dispatchContext.getRequestController();
    } else {
        String uri = request.getRequestURI();
        String ctxPath = request.getContextPath();
        String controllerName = uri.substring(ctxPath.length() + 1);
        if (StringUtils.isNotBlank(applicationPath)) {
            controllerName = controllerName.substring(applicationPath.length());
        }
        requestController = RequestControllerMapper.getRequestController(controllerName);
        dispatchContext = new RequestDispatchContext(requestController, new DefaultParameterHandlerImpl(request, decodeGETUtf));
    }
    int statusCode = StatusCode.OK;
    try {
        if (requestController == null) {
            requestContext = new PageRequestContext(dispatchContext, request, response, getServletContext(), errorJspPage);
            throw new PageNotFoundException(request.getLocale());
        } else if (requestController instanceof PageController) {
            requestContext = new PageRequestContext(dispatchContext, request, response, getServletContext(), errorJspPage);
        } else if (requestController instanceof JSONRequestController) {
            requestContext = new JSONRequestContext(dispatchContext, request, response, getServletContext());
        } else if (requestController instanceof BinaryRequestController) {
            requestContext = new BinaryRequestContext(dispatchContext, request, response, getServletContext());
        }
        // Let the controller authorize the request. Most common exceptions thrown include
        // LoginRequiredException and AccessDeniedException
        requestController.authorize(requestContext);
        if (requestController instanceof PageController) {
            ((PageController) requestController).process((PageRequestContext) requestContext);
        } else if (requestController instanceof JSONRequestController) {
            ((JSONRequestController) requestController).process((JSONRequestContext) requestContext);
        } else if (requestController instanceof BinaryRequestController) {
            ((BinaryRequestController) requestController).process((BinaryRequestContext) requestContext);
        }
    } catch (LoginRequiredException lre) {
        if (platformErrorListener != null)
            platformErrorListener.onLoginRequiredException(request, response, lre);
        Logging.logInfo("Login required for " + getCurrentUrl(request, true));
        if (requestController instanceof PageController) {
            HttpSession session = requestContext.getRequest().getSession(true);
            session.setAttribute("loginRedirectUrl", lre.getRedirectUrl());
            if (lre.getContextType() != null && lre.getContextId() != null) {
                session.setAttribute("loginContextType", lre.getContextType());
                session.setAttribute("loginContextId", lre.getContextId());
            }
            requestContext.setRedirectURL(loginUrl);
        } else {
            // TODO LoginRequiredException for requests other than pages?
            statusCode = lre.getStatusCode();
            requestContext.addMessage(Severity.WARNING, lre.getMessage());
        }
    } catch (PageNotFoundException pnfe) {
        if (platformErrorListener != null)
            platformErrorListener.onPageNotFoundException(request, response, pnfe);
        Logging.logInfo("404 - " + getCurrentUrl(request, true));
        statusCode = pnfe.getStatusCode();
        if (requestContext != null) {
            requestContext.getResponse().setStatus(HttpServletResponse.SC_NOT_FOUND);
            requestContext.addMessage(Severity.WARNING, pnfe.getMessage());
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } catch (AccessDeniedException ade) {
        if (platformErrorListener != null)
            platformErrorListener.onAccessDeniedException(request, response, ade);
        Logging.logInfo("403 - " + getCurrentUrl(request, true) + " - " + requestContext.getLoggedUserId());
        statusCode = ade.getStatusCode();
        requestContext.getResponse().setStatus(HttpServletResponse.SC_FORBIDDEN);
        requestContext.addMessage(Severity.WARNING, ade.getMessage());
    } catch (InvalidLoginException ile) {
        Logging.logInfo("Invalid login credentials");
        statusCode = ile.getStatusCode();
        requestContext.addMessage(Severity.ERROR, ile.getMessage());
    } catch (AlreadyLoggedInException ile) {
        Logging.logInfo("Already logged in");
        statusCode = ile.getStatusCode();
        requestContext.addMessage(Severity.ERROR, ile.getMessage());
    } catch (SmvcRuntimeException pre) {
        if (platformErrorListener != null)
            platformErrorListener.onSmvcRuntimeException(request, response, pre);
        Logging.logException(pre);
        statusCode = pre.getStatusCode();
        requestContext.addMessage(Severity.ERROR, pre.getMessage());
    } catch (Exception e) {
        if (platformErrorListener != null)
            platformErrorListener.onUncontrolledException(request, response, e);
        // All other exceptions are considered to be fatal and unexpected, so the request
        // transaction is rolled back, the stack trace of the exception is printed out, and
        // an error view is shown
        Logging.logException(e);
        statusCode = StatusCode.UNDEFINED;
        requestContext.addMessage(Severity.CRITICAL, e.getMessage());
    } finally {
        try {
            // Pre-commit response
            requestContext.writePreCommitResponse(statusCode);
            if (statusCode == StatusCode.OK) {
                userTransaction.commit();
            } else {
                userTransaction.rollback();
            }
            // Post-commit response
            requestContext.writePostCommitResponse(statusCode);
        } catch (Exception e) {
            if (platformErrorListener != null)
                platformErrorListener.onTransactionCommitException(request, response, e);
            Logging.logException(e);
            throw new ServletException(e);
        }
    }
}
Also used : LoginRequiredException(fi.internetix.smvc.LoginRequiredException) AccessDeniedException(fi.internetix.smvc.AccessDeniedException) HttpSession(javax.servlet.http.HttpSession) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) AlreadyLoggedInException(fi.internetix.smvc.AlreadyLoggedInException) BinaryRequestContext(fi.internetix.smvc.controllers.BinaryRequestContext) LoginRequiredException(fi.internetix.smvc.LoginRequiredException) ServletException(javax.servlet.ServletException) AlreadyLoggedInException(fi.internetix.smvc.AlreadyLoggedInException) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) PageNotFoundException(fi.internetix.smvc.PageNotFoundException) InvalidLoginException(fi.internetix.smvc.InvalidLoginException) AccessDeniedException(fi.internetix.smvc.AccessDeniedException) ServletException(javax.servlet.ServletException) JSONRequestController(fi.internetix.smvc.controllers.JSONRequestController) PageNotFoundException(fi.internetix.smvc.PageNotFoundException) PageController(fi.internetix.smvc.controllers.PageController) BinaryRequestController(fi.internetix.smvc.controllers.BinaryRequestController) BinaryRequestController(fi.internetix.smvc.controllers.BinaryRequestController) RequestController(fi.internetix.smvc.controllers.RequestController) JSONRequestController(fi.internetix.smvc.controllers.JSONRequestController) InvalidLoginException(fi.internetix.smvc.InvalidLoginException) BinaryRequestContext(fi.internetix.smvc.controllers.BinaryRequestContext) JSONRequestContext(fi.internetix.smvc.controllers.JSONRequestContext) RequestContext(fi.internetix.smvc.controllers.RequestContext) PageRequestContext(fi.internetix.smvc.controllers.PageRequestContext) PageRequestContext(fi.internetix.smvc.controllers.PageRequestContext) JSONRequestContext(fi.internetix.smvc.controllers.JSONRequestContext)

Example 3 with AlreadyLoggedInException

use of fi.internetix.smvc.AlreadyLoggedInException in project pyramus by otavanopisto.

the class ExternalLoginLoginViewController method process.

// TODO: Does not support multiple external strategies
public void process(PageRequestContext requestContext) {
    // Ensure that the user trying to login isn't already logged in
    Locale locale = requestContext.getRequest().getLocale();
    HttpSession session = requestContext.getRequest().getSession(true);
    if (!session.isNew() && session.getAttribute("loggedUserId") != null) {
        String msg = Messages.getInstance().getText(locale, "users.login.alreadyLoggedIn");
        throw new AlreadyLoggedInException(PyramusStatusCode.ALREADY_LOGGED_IN, msg);
    }
    AuthenticationProviderVault authenticationProviders = AuthenticationProviderVault.getInstance();
    try {
        ExternalAuthenticationProvider authenticationProvider = authenticationProviders.getExternalAuthenticationProviders().get(0);
        User user = authenticationProvider.processResponse(requestContext);
        if (user != null && !Role.CLOSED.equals(user.getRole())) {
            // User has been authorized, so store him in the session
            session.setAttribute("loggedUserId", user.getId());
            session.setAttribute("loggedUserName", user.getFullName());
            session.setAttribute("authenticationProvider", authenticationProvider.getName());
            if (user instanceof StaffMember) {
                session.setAttribute("loggedUserRole", UserRole.valueOf(((StaffMember) user).getRole().name()));
            }
            try {
                DAOFactory.getInstance().getLoginLogDAO().create(user, new Date());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            if (session.getAttribute("loginRedirectUrl") != null) {
                String url = (String) session.getAttribute("loginRedirectUrl");
                session.removeAttribute("loginRedirectUrl");
                requestContext.setRedirectURL(url);
            } else {
                requestContext.setRedirectURL(requestContext.getRequest().getContextPath() + "/index.page");
            }
        } else {
            String msg = Messages.getInstance().getText(requestContext.getRequest().getLocale(), "users.login.loginFailed");
            throw new SmvcRuntimeException(PyramusStatusCode.UNAUTHORIZED, msg);
        }
    } catch (LocalUserMissingException lume) {
        List<InternalAuthenticationProvider> internalAuthenticationProviders = authenticationProviders.getInternalAuthenticationProviders();
        List<ExternalAuthenticationProvider> externalAuthenticationProviders = authenticationProviders.getExternalAuthenticationProviders();
        if (!internalAuthenticationProviders.isEmpty() || externalAuthenticationProviders.size() > 1) {
            try {
                requestContext.setRedirectURL(String.format("%s/users/login.page?localUserMissing=%s", requestContext.getRequest().getContextPath(), URLEncoder.encode(lume.getExternalUser(), "UTF-8")));
            } catch (UnsupportedEncodingException e) {
                throw new SmvcRuntimeException(e);
            }
        } else {
            throw new SmvcRuntimeException(PyramusStatusCode.LOCAL_USER_MISSING, Messages.getInstance().getText(locale, "users.login.localUserMissing", new String[] { lume.getExternalUser() }));
        }
    } catch (AuthenticationException ae) {
        throw new SmvcRuntimeException(ae);
    }
}
Also used : Locale(java.util.Locale) AuthenticationProviderVault(fi.otavanopisto.pyramus.plugin.auth.AuthenticationProviderVault) User(fi.otavanopisto.pyramus.domainmodel.users.User) AuthenticationException(fi.otavanopisto.pyramus.plugin.auth.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) ExternalAuthenticationProvider(fi.otavanopisto.pyramus.plugin.auth.ExternalAuthenticationProvider) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AlreadyLoggedInException(fi.internetix.smvc.AlreadyLoggedInException) StaffMember(fi.otavanopisto.pyramus.domainmodel.users.StaffMember) Date(java.util.Date) LocalUserMissingException(fi.otavanopisto.pyramus.plugin.auth.LocalUserMissingException) AuthenticationException(fi.otavanopisto.pyramus.plugin.auth.AuthenticationException) AlreadyLoggedInException(fi.internetix.smvc.AlreadyLoggedInException) SmvcRuntimeException(fi.internetix.smvc.SmvcRuntimeException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) LocalUserMissingException(fi.otavanopisto.pyramus.plugin.auth.LocalUserMissingException) List(java.util.List)

Aggregations

AlreadyLoggedInException (fi.internetix.smvc.AlreadyLoggedInException)3 SmvcRuntimeException (fi.internetix.smvc.SmvcRuntimeException)3 HttpSession (javax.servlet.http.HttpSession)3 InvalidLoginException (fi.internetix.smvc.InvalidLoginException)2 StaffMember (fi.otavanopisto.pyramus.domainmodel.users.StaffMember)2 User (fi.otavanopisto.pyramus.domainmodel.users.User)2 AuthenticationException (fi.otavanopisto.pyramus.plugin.auth.AuthenticationException)2 LocalUserMissingException (fi.otavanopisto.pyramus.plugin.auth.LocalUserMissingException)2 Date (java.util.Date)2 Locale (java.util.Locale)2 AccessDeniedException (fi.internetix.smvc.AccessDeniedException)1 LoginRequiredException (fi.internetix.smvc.LoginRequiredException)1 PageNotFoundException (fi.internetix.smvc.PageNotFoundException)1 BinaryRequestContext (fi.internetix.smvc.controllers.BinaryRequestContext)1 BinaryRequestController (fi.internetix.smvc.controllers.BinaryRequestController)1 JSONRequestContext (fi.internetix.smvc.controllers.JSONRequestContext)1 JSONRequestController (fi.internetix.smvc.controllers.JSONRequestController)1 PageController (fi.internetix.smvc.controllers.PageController)1 PageRequestContext (fi.internetix.smvc.controllers.PageRequestContext)1 RequestContext (fi.internetix.smvc.controllers.RequestContext)1