Example usage for javax.servlet.http HttpSession setMaxInactiveInterval

List of usage examples for javax.servlet.http HttpSession setMaxInactiveInterval

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession setMaxInactiveInterval.

Prototype

public void setMaxInactiveInterval(int interval);

Source Link

Document

Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

Usage

From source file:org.codehaus.wadi.web.TestHttpSession.java

public void testMaxInactiveInterval(Manager manager) {
    HttpSession session = ((WADIHttpSession) manager.create(null)).getWrapper();
    {/*from w ww  .  ja  v  a 2s  .  com*/
        int interval = 60 * 60;
        session.setMaxInactiveInterval(interval);
        assertTrue(session.getMaxInactiveInterval() == interval);
    }
    {
        int interval = -1;
        session.setMaxInactiveInterval(interval);
        assertTrue(session.getMaxInactiveInterval() == interval);
    }
}

From source file:org.emr.intercepter.RequestInterceptor.java

public boolean validateSession(HttpServletRequest request, HttpServletResponse response, FactoryBean loginBean)
        throws IOException, JSONException {
    HttpSession session = request.getSession();
    boolean status = true;
    if (session.isNew()) {
        System.out.println("new session found :");
        String username = (String) request.getParameter("username");
        String password = (String) request.getParameter("password");
        ArrayList<FactoryBean> factoryBean = model
                .select("from LoginBean where username = '" + username + "' and password = '" + password + "'");
        if (factoryBean.size() == 0) {
            System.out.println("invalidate session on first request if login failed:");
            session.invalidate();/*  ww  w.j  a v  a  2  s  . c o  m*/
            return false;
        }
        /*
         * get user profile : 
         */
        loginBean = (LoginBean) factoryBean.get(0);
        System.out.println("username : " + username);
        session.setAttribute("loginBean", ((LoginBean) loginBean));
        session.setMaxInactiveInterval(60);
    }
    return status;
}

From source file:org.codice.ddf.security.filter.login.LoginFilter.java

/**
 * Adds SAML assertion to HTTP session.// w  ww  .j  av a2  s. com
 *
 * @param httpRequest   the http request object for this request
 * @param securityToken the SecurityToken object representing the SAML assertion
 */
private void addSamlToSession(HttpServletRequest httpRequest, String realm, SecurityToken securityToken) {
    if (securityToken == null) {
        LOGGER.debug("Cannot add null security token to session.");
        return;
    }

    HttpSession session = sessionFactory.getOrCreateSession(httpRequest);
    SecurityToken sessionToken = getSecurityToken(session, realm);
    if (sessionToken == null) {
        addSecurityToken(session, realm, securityToken);
    }
    int minutes = getExpirationTime();
    //we just want to set this to some non-zero value if the configuration is messed up
    int seconds = 60;
    if (minutes > 0) {
        seconds = minutes * 60;
    }
    session.setMaxInactiveInterval(seconds);
}

From source file:org.lockss.servlet.LockssServlet.java

/** Set the session timeout */
protected void setSessionTimeout(HttpSession session, long time) {
    session.setMaxInactiveInterval((int) (time / Constants.SECOND));
}

From source file:nl.strohalm.cyclos.utils.LoginHelper.java

/**
 * Perform the login itself/*from  w ww. j av  a  2  s .  co m*/
 */
public User login(final Class<? extends User> requiredUserClass, final String principalTypeString,
        final String memberUsername, final String principal, final String password, final String channel,
        final HttpServletRequest request, final HttpServletResponse response) throws LoginException {
    final String remoteAddress = request.getRemoteAddr();

    final PrincipalType principalType = channelService.resolvePrincipalType(channel, principalTypeString);

    // Validate the user
    String usernameToVerify = principal;
    if (principalType.getPrincipal() != Principal.USER) {
        try {
            Member member;
            member = elementService.loadByPrincipal(principalType, principal, Element.Relationships.USER,
                    Element.Relationships.GROUP);
            usernameToVerify = member.getUsername();
        } catch (final EntityNotFoundException e) {
            usernameToVerify = "";
        }
    }
    final User user = accessService.verifyLogin(memberUsername, usernameToVerify, remoteAddress);
    if (!requiredUserClass.isInstance(user)) {
        throw new AccessDeniedException();
    }

    // Find the user nature
    final Group group = user.getElement().getGroup();
    final boolean isAdmin = group instanceof AdminGroup;
    final boolean isMember = group instanceof MemberGroup;
    final boolean isBroker = group instanceof BrokerGroup;
    final boolean isOperator = group instanceof OperatorGroup;
    final boolean isPosWeb = RequestHelper.isPosWeb(request);

    final AccessSettings accessSettings = settingsService.getAccessSettings();

    // Check if the administrator is allowed to login
    if (isAdmin && !accessSettings.getAdministrationWhitelistValidator().isAllowed(request.getRemoteHost(),
            request.getRemoteAddr())) {
        throw new AccessDeniedException();
    }

    // According to the cyclos.properties flag, create a new session or use the current one
    HttpSession session;
    if (newSessionAfterLogin) {
        session = createNewSessionForlogin(request);
    } else {
        session = request.getSession();
    }

    // Login the user
    accessService.login(user, password, channel, isPosWeb, remoteAddress, session.getId());

    // Apply the session timeout
    final TimePeriod timeout = isPosWeb ? accessSettings.getPoswebTimeout()
            : isMember ? accessSettings.getMemberTimeout() : accessSettings.getAdminTimeout();
    int timeoutSeconds = (int) timeout.getValueIn(TimePeriod.Field.SECONDS);
    if (timeoutSeconds <= 0) {
        timeoutSeconds = -1;
    }
    session.setMaxInactiveInterval(timeoutSeconds);

    // If is a member, determine if the member has accounts, documents, loan groups and memberPos
    boolean hasAccounts = false;
    boolean singleAccount = false;
    boolean hasDocuments = false;
    boolean hasLoanGroups = false;
    boolean hasGeneralReferences = false;
    boolean hasTransactionFeedbacks = false;
    boolean hasPin = false;
    boolean hasExternalChannels = false;
    boolean hasCards = false;
    boolean hasPos = false;
    boolean hasCommissionContracts = false;
    if (isMember || isOperator) {
        Member member;
        if (isMember) {
            member = ((MemberUser) user).getMember();

            // Get the accessible channels
            final MemberGroup memberGroup = groupService.load(member.getMemberGroup().getId(),
                    MemberGroup.Relationships.CHANNELS);
            hasPin = groupService.usesPin(memberGroup);
            for (final Channel current : memberGroup.getChannels()) {
                if (!Channel.WEB.equals(current.getInternalName())) {
                    hasExternalChannels = true;
                    break;
                }
            }

            if (!member.getPosDevices().isEmpty()) {
                hasPos = true;
                if (member.getPosDevices().size() == 1) {
                    final Collection<MemberPos> memberPos = member.getPosDevices();
                    for (final MemberPos mpos : memberPos) {
                        session.setAttribute("uniqueMemberPosId ", mpos.getPos().getId());
                    }
                }
            }

        } else {
            member = ((OperatorUser) user).getOperator().getMember();
        }
        // Fetch broker
        member = elementService.load(member.getId(), Member.Relationships.BROKER);
        final MemberGroup memberGroup = member.getMemberGroup();

        // Check if the member has accounts
        final List<? extends Account> accounts = accountService.getAccounts(member);
        hasAccounts = !accounts.isEmpty();
        singleAccount = accounts.size() == 1;
        if (isMember) {
            // Check if the member has documents
            if (permissionService.hasPermission(MemberPermission.DOCUMENTS_VIEW)) {
                hasDocuments = true;
            } else {
                final DocumentQuery documentQuery = new DocumentQuery();
                documentQuery.setNatures(Collections.singleton(Document.Nature.MEMBER));
                documentQuery.setMember(member);
                documentQuery.setPageForCount();
                hasDocuments = PageHelper.hasResults(documentService.search(documentQuery));
            }
            // Check if the member has loan groups
            final LoanGroupQuery lgq = new LoanGroupQuery();
            lgq.setPageForCount();
            lgq.setMember(member);
            hasLoanGroups = PageHelper.hasResults(loanGroupService.search(lgq));

            // Check if the member has commission contracts
            hasCommissionContracts = commissionService.hasBrokerCommissionContracts();
        }
        // Check if the user has references
        final Collection<Nature> referenceNatures = referenceService.getNaturesByGroup(memberGroup);
        hasGeneralReferences = referenceNatures.contains(Nature.GENERAL);
        hasTransactionFeedbacks = referenceNatures.contains(Nature.TRANSACTION);

        // Check if the user can have guarantees
        try {
            final Collection<GuaranteeType.Model> guaranteeModels = guaranteeService
                    .getRelatedGuaranteeModels();
            session.setAttribute("loggedMemberHasGuarantees", guaranteeModels.size() > 0);
        } catch (final Exception e) {
            // Ignore
        }

        // Check if the user has cards
        hasCards = member.getCards().isEmpty() ? false : true;
    }

    if (isAdmin || isBroker) {
        // Retrieve the member record types the logged user can see on the menu
        final MemberRecordTypeQuery query = new MemberRecordTypeQuery();
        if (isAdmin) {
            query.setViewableByAdminGroup((AdminGroup) group);
        } else {
            query.setViewableByBrokerGroup((BrokerGroup) group);
        }
        query.setShowMenuItem(true);
        final List<MemberRecordType> types = memberRecordTypeService.search(query);
        session.setAttribute("memberRecordTypesInMenu", types);
    }

    // When a receipt printer cookie is set, and the printer no longer exists, or belongs to someone else, clear the cookie
    final String receiptPrinterId = RequestHelper.getCookieValue(request, "receiptPrinterId");
    if (StringUtils.isNotEmpty(receiptPrinterId)) {
        final Long id = IdConverter.instance().valueOf(receiptPrinterId);
        if (!receiptPrinterSettingsService.belongsToTheLoggedUser(id)) {
            final Cookie cookie = new Cookie("receiptPrinterId", "");
            cookie.setPath(request.getContextPath());
            response.addCookie(cookie);
        }
    }

    final String actionPrefix = "/" + (isAdmin ? "admin" : isMember ? "member" : "operator");

    // Set the request attributes
    request.setAttribute("loggedUser", user);
    request.setAttribute("loggedElement", user.getElement());

    // Set the session attributes
    session.setAttribute("loggedUserId", user.getId());
    session.setAttribute("isAdmin", isAdmin);
    session.setAttribute("isMember", isMember);
    session.setAttribute("isBroker", isBroker);
    session.setAttribute("isOperator", isOperator);
    session.setAttribute("isBuyer", guaranteeService.isBuyer());
    session.setAttribute("isSeller", guaranteeService.isSeller());
    session.setAttribute("isIssuer", guaranteeService.isIssuer());
    session.setAttribute("loggedMemberHasAccounts", hasAccounts);
    session.setAttribute("loggedMemberHasSingleAccount", singleAccount);
    session.setAttribute("loggedMemberHasDocuments", hasDocuments);
    session.setAttribute("loggedMemberHasLoanGroups", hasLoanGroups);
    session.setAttribute("loggedMemberHasGeneralReferences", hasGeneralReferences);
    session.setAttribute("loggedMemberHasTransactionFeedbacks", hasTransactionFeedbacks);
    session.setAttribute("hasPin", hasPin);
    session.setAttribute("hasCards", hasCards);
    session.setAttribute("hasPos", hasPos);
    session.setAttribute("hasCommissionContracts", hasCommissionContracts);
    session.setAttribute("hasExternalChannels", hasExternalChannels);
    session.setAttribute("actionPrefix", actionPrefix);
    session.setAttribute("pathPrefix", "/do" + actionPrefix);
    session.setAttribute("navigation", Navigation.get(session));

    // Return the logged user
    return user;
}

From source file:org.infoglue.cms.security.InfoGlueAuthenticationFilter.java

/**
 * This filter is basically what secures Infoglue and enforces the authentication framework.
 *///from  w w  w. ja v  a2 s .com
public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc)
        throws ServletException, IOException {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    try {
        if (CmsPropertyHandler.getServletContext() == null) {
            CmsPropertyHandler.setServletContext(httpServletRequest.getContextPath());
        }

        String URI = httpServletRequest.getRequestURI();
        String URL = httpServletRequest.getRequestURL().toString();
        if (logger.isInfoEnabled()) {
            logger.info("URI: + " + URI);
            logger.info("URL: + " + URL);
        }

        String requestURI = URLDecoder.decode(getContextRelativeURI(httpServletRequest), "UTF-8");
        if (URI == null)
            logger.error("URI was null - requestURI:" + requestURI);
        if (URL == null)
            logger.error("URL was null - requestURI:" + requestURI);
        if (requestURI == null)
            logger.error("requestURI was null");

        if (loginUrl == null) {
            logger.error("loginUrl was null - fix this.");
            loginUrl = "Login.action";
        }
        if (invalidLoginUrl == null) {
            logger.error("invalidLoginUrl was null - fix this.");
            invalidLoginUrl = "Login!invalidLogin.action";
        }
        if (logoutUrl == null) {
            logger.error("logoutUrl was null - fix this.");
            logoutUrl = "ExtranetLogin!logout.action";
        }

        if (uriMatcher == null) {
            logger.error("uriMatcher was null - fix this.");
            String filterURIs = filterConfig.getInitParameter(FILTER_URIS_PARAMETER);
            uriMatcher = URIMatcher.compilePatterns(splitString(filterURIs, ","), false);
        }

        if (!CmsPropertyHandler.getIsValidSetup()
                && (URI.indexOf("Install") == -1 && URI.indexOf(".action") > -1)) {
            httpServletResponse.sendRedirect("Install!input.action");
            return;
        }

        //Here are the url:s/paths that must be skipped by the security framework for it to work. Login screens etc must be reachable naturally.
        if (URI != null && URL != null
                && (URI.indexOf(loginUrl) > -1 || URL.indexOf(loginUrl) > -1 || URI.indexOf("Login.action") > -1
                        || URL.indexOf("Login.action") > -1 || URI.indexOf(invalidLoginUrl) > -1
                        || URL.indexOf(invalidLoginUrl) > -1 || URI.indexOf("Login!invalidLogin.action") > -1
                        || URL.indexOf("Login!invalidLogin.action") > -1 || URI.indexOf(logoutUrl) > -1
                        || URI.indexOf("Login!logout.action") > -1 || URL.indexOf(logoutUrl) > -1
                        || URI.indexOf("UpdateCache") > -1 || URI.indexOf("protectedRedirect.jsp") > -1
                        || uriMatcher.matches(requestURI))) {
            fc.doFilter(request, response);
            return;
        }

        // make sure we've got an HTTP request
        if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse))
            throw new ServletException("InfoGlue Filter protects only HTTP resources");

        HttpSession session = ((HttpServletRequest) request).getSession();

        String sessionTimeout = CmsPropertyHandler.getSessionTimeout();
        try {
            Integer.parseInt(sessionTimeout);
        } catch (Exception e) {
            sessionTimeout = "1800";
        }
        if (sessionTimeout == null)
            sessionTimeout = "1800";

        session.setMaxInactiveInterval(new Integer(sessionTimeout).intValue());

        // if our attribute's already present, don't do anything
        //logger.info("User:" + session.getAttribute(INFOGLUE_FILTER_USER));
        if (session != null && session.getAttribute(INFOGLUE_FILTER_USER) != null) {
            //logger.info("Found user in session:" + session.getAttribute(INFOGLUE_FILTER_USER));
            //if(successLoginBaseUrl != null && !URL.startsWith(successLoginBaseUrl))
            //{
            //    checkSuccessRedirect(request, response, URL);
            //}
            //else
            //{
            fc.doFilter(request, response);
            return;
            //}
        }

        // otherwise, we need to authenticate somehow
        boolean isAdministrator = false;

        String userName = request.getParameter("j_username");
        String password = request.getParameter("j_password");

        if (userName != null && password != null) {
            String administratorUserName = CmsPropertyHandler.getAdministratorUserName();

            boolean matchesRootPassword = CmsPropertyHandler.getMatchesAdministratorPassword(password);
            isAdministrator = (userName.equalsIgnoreCase(administratorUserName) && matchesRootPassword) ? true
                    : false;
        }

        //First we check if the user is logged in to the container context
        if (!isAdministrator) {
            logger.info("Principal:" + httpServletRequest.getUserPrincipal());
            if (httpServletRequest.getUserPrincipal() != null
                    && !(httpServletRequest.getUserPrincipal() instanceof InfoGluePrincipal)) {
                userName = httpServletRequest.getUserPrincipal().getName();
                logger.info("Now trusting the container logged in identity...");
            }
        }

        String authenticatedUserName = userName;

        if (!isAdministrator) {
            String encodedUserNameCookie = httpHelper.getCookie(httpServletRequest, "iguserid");
            logger.info("encodedUserNameCookie:" + encodedUserNameCookie);
            if (encodedUserNameCookie != null && !encodedUserNameCookie.equals("")) {
                byte[] bytes = Base64.decodeBase64(encodedUserNameCookie);
                encodedUserNameCookie = new String(bytes, "utf-8");
                //encodedUserNameCookie = encodedUserNameCookie.replaceAll("IGEQ", "=");
                logger.info("encodedUserNameCookie:" + encodedUserNameCookie);
                String servletContextUserName = (String) filterConfig.getServletContext()
                        .getAttribute(encodedUserNameCookie);
                logger.info("servletContextUserName:" + servletContextUserName);
                if (servletContextUserName != null && !servletContextUserName.equals("")) {
                    authenticatedUserName = servletContextUserName;
                } else {
                    Cookie cookie_iguserid = new Cookie("iguserid", "none");
                    cookie_iguserid.setPath("/");
                    cookie_iguserid.setMaxAge(0);
                    httpServletResponse.addCookie(cookie_iguserid);

                    Cookie cookie_igpassword = new Cookie("igpassword", "none");
                    cookie_igpassword.setPath("/");
                    cookie_igpassword.setMaxAge(0);
                    httpServletResponse.addCookie(cookie_igpassword);

                    authenticatedUserName = authenticateUser(httpServletRequest, httpServletResponse, fc);
                }
            } else {
                authenticatedUserName = authenticateUser(httpServletRequest, httpServletResponse, fc);
            }
        }

        logger.info("authenticatedUserName:" + authenticatedUserName);

        if (authenticatedUserName != null) {
            logger.info("Getting the principal from user name:" + authenticatedUserName);

            InfoGluePrincipal user = getAuthenticatedUser(authenticatedUserName);
            if (user == null || (!user.getIsAdministrator() && !hasAuthorizedRole(user))) {
                //throw new Exception("This user is not authorized to log in...");
                httpServletResponse.sendRedirect("unauthorizedLogin.jsp");

                NotificationMessage notificationMessage = new NotificationMessage("Authorization failed:",
                        "Authorization", authenticatedUserName, NotificationMessage.AUTHORIZATION_FAILED,
                        "" + authenticatedUserName, "name");
                TransactionHistoryController.getController().create(notificationMessage);

                return;
            }

            //TODO - we must fix so these caches are individual to the person - now a login will slow down for all
            //CacheController.clearCache("authorizationCache");
            //CacheController.clearCache("personalAuthorizationCache", user.getName());
            CacheController.clearCacheForGroup("personalAuthorizationCache", user.getName());

            // Store the authenticated user in the session
            if (session != null) {
                session.setAttribute(INFOGLUE_FILTER_USER, user);
                setUserProperties(session, user);
            }

            //TEST - transferring auth to deliverworking
            try {
                if (userName != null && password != null) {
                    DesEncryptionHelper encHelper = new DesEncryptionHelper();
                    String encryptedName = encHelper.encrypt(userName);
                    String encryptedPassword = encHelper.encrypt(password);

                    String encryptedNameAsBase64 = Base64
                            .encodeBase64URLSafeString(encryptedName.getBytes("utf-8"));
                    String encryptedPasswordAsBase64 = Base64
                            .encodeBase64URLSafeString(encryptedPassword.getBytes("utf-8"));

                    String deliverBaseUrl = CmsPropertyHandler.getComponentRendererUrl();
                    String[] parts = deliverBaseUrl.split("/");

                    deliverBaseUrl = "/" + parts[parts.length - 1];
                    //logger.info("used cmsBaseUrl:" + cmsBaseUrl);

                    ServletContext servletContext = filterConfig.getServletContext().getContext(deliverBaseUrl);
                    if (servletContext == null) {
                        logger.error("Could not autologin to " + deliverBaseUrl
                                + ". Set cross context = true in Tomcat config.");
                    } else {
                        logger.info("Added encryptedName:" + encryptedName + " = " + user.getName()
                                + " to deliver context");
                        servletContext.setAttribute(encryptedName, user.getName());
                    }

                    int cmsCookieTimeout = 1800; //30 minutes default
                    String cmsCookieTimeoutString = null; //CmsPropertyHandler.getCmsCookieTimeout();
                    if (cmsCookieTimeoutString != null) {
                        try {
                            cmsCookieTimeout = Integer.parseInt(cmsCookieTimeoutString.trim());
                        } catch (Exception e) {
                        }
                    }

                    //Cookie cookie_iguserid = new Cookie("iguserid", encryptedName.replaceAll("=", "IGEQ"));
                    Cookie cookie_iguserid = new Cookie("iguserid", encryptedNameAsBase64);
                    cookie_iguserid.setPath("/");
                    cookie_iguserid.setMaxAge(cmsCookieTimeout);
                    httpServletResponse.addCookie(cookie_iguserid);

                    //Cookie cookie_igpassword = new Cookie ("igpassword", encryptedPassword.replaceAll("=", "IGEQ"));
                    Cookie cookie_igpassword = new Cookie("igpassword", encryptedPasswordAsBase64);
                    cookie_igpassword.setPath("/");
                    cookie_igpassword.setMaxAge(cmsCookieTimeout);
                    httpServletResponse.addCookie(cookie_igpassword);

                    //logger.info(encryptedName + "=" + userName);
                    //logger.info("After attribute:" + servletContext.getAttribute(encryptedName));
                }
            } catch (Exception e) {
                logger.error("Error: " + e.getMessage(), e);
            }
            //END TEST

            String logUserName = userName;
            if (logUserName == null || logUserName.equals("") && user != null)
                logUserName = user.getName();
            if (logUserName == null || logUserName.equals(""))
                logUserName = authenticatedUserName;
            if (logUserName == null || logUserName.equals(""))
                logUserName = "Unknown";

            NotificationMessage notificationMessage = new NotificationMessage("Login success:",
                    "Authentication", logUserName, NotificationMessage.AUTHENTICATION_SUCCESS,
                    "" + authenticatedUserName, "name");
            TransactionHistoryController.getController().create(notificationMessage);

            if (successLoginBaseUrl != null && !URL.startsWith(successLoginBaseUrl)) {
                checkSuccessRedirect(request, response, URL);
            } else {
                fc.doFilter(request, response);
                return;
            }
        } else {
            if (userName != null && !userName.equals("")) {
                NotificationMessage notificationMessage = new NotificationMessage("Login failed:",
                        "Authentication", userName, NotificationMessage.AUTHENTICATION_FAILED, "" + userName,
                        "name");
                TransactionHistoryController.getController().create(notificationMessage);
            }
        }
    } catch (Exception e) {
        logger.error("Error authenticating user:" + e.getMessage(), e);
        httpServletRequest.setAttribute("error", new Exception(
                "Error in authentication filter - look at the server error log (usually catalina.out) for reason but the most common one is problem connecting to the database or a faulty connection user or limited access for that account."));
        httpServletResponse.sendError(500);
        return;
    }
}

From source file:com.kodemore.servlet.ScServletData.java

public HttpSession _getHttpSession() {
    HttpSession e;
    e = _getRequest().getSession();
    e.setMaxInactiveInterval(getSessionTimeoutSeconds());
    return e;
}

From source file:com.kgmp.mfds.controller.AdminController.java

@RequestMapping(value = "/AdminLoginProc.do")
public ModelAndView adminLogin_proc(@RequestParam("admin_userid") String id,
        @RequestParam("admin_passwd") String pw, HttpSession session) {
    ModelAndView mav = new ModelAndView();
    String msg = null;//from  w  w  w. jav a  2  s .c  om
    String url = null;
    Admin admin = new Admin();
    admin.setId(id);
    admin.setPw(pw);
    try {
        if (admin_service.isLogin(admin)) {
            msg = "? ?.";
            url = "/Basic.do";
            session.setAttribute("id", id);
            session.setAttribute("pw", pw);
            session.setMaxInactiveInterval(60000);
        } else {
            msg = "? ?   ?.";
            url = "/AdminLogin.do";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    mav.addObject("msg", msg);
    mav.addObject("url", url);
    mav.setViewName("/Check_proc");
    return mav;
}

From source file:com.enonic.vertical.adminweb.AdminLogInServlet.java

private void handlerLogin(HttpServletRequest request, HttpServletResponse response, ExtendedMap formItems)
        throws VerticalAdminException {
    String uid = formItems.getString("username", null);
    String passwd = formItems.getString("password", null);
    UserStoreKey userStoreKey;//w  w  w  .ja va  2s. c o m
    String userStoreKeyStr = formItems.getString("userstorekey", null);
    AdminService admin = lookupAdminBean();

    if (userStoreKeyStr != null) {
        userStoreKey = new UserStoreKey(userStoreKeyStr);
    } else {
        userStoreKey = userStoreService.getDefaultUserStore().getKey();
    }

    securityService.logoutAdminUser();
    HttpSession session = request.getSession(true);

    session.setAttribute("selectedloginuserstore", userStoreKey.toString());

    // language
    AdminConsoleTranslationService languageMap = AdminConsoleTranslationService.getInstance();
    String languageCode;
    Cookie cookie = CookieUtil.getCookie(request, "languageCode");
    if (cookie == null) {
        languageCode = languageMap.getDefaultLanguageCode();
    } else {
        languageCode = cookie.getValue();
    }
    session.setAttribute("languageCode", languageCode);

    User user = null;
    String errorCode = null;
    try {
        if (uid == null || passwd == null) {
            String message = "User and/or password not set.";
            VerticalAdminLogger.error(this.getClass(), 0, message, null);
            session.setAttribute("loginerrorcode", EC_401_MISSING_USER_PASSWD);
            session.setAttribute("loginerror", message);
            session.setMaxInactiveInterval(SESSION_TIMEOUT_ERROR);
            errorCode = EC_401_MISSING_USER_PASSWD;
        } else {
            // authenticate user
            QualifiedUsername qualifiedUsername;
            if (UserEntity.isBuiltInUser(uid)) {
                qualifiedUsername = new QualifiedUsername(uid);
            } else {
                qualifiedUsername = new QualifiedUsername(userStoreKey, uid);
            }
            user = securityService.loginAdminUser(qualifiedUsername, passwd);
        }
    } catch (InvalidCredentialsException vse) {
        String message = "Failed to authenticate user (domain key: %0): %1";
        Object[] msgData = { userStoreKey, uid };
        VerticalAdminLogger.warn(this.getClass(), 0, message, msgData, null);
        message = StringUtil.expandString(message, msgData, vse);
        session.setAttribute("loginerrorcode", EC_401_USER_PASSWD_WRONG);
        session.setAttribute("loginerror", message);
        session.setMaxInactiveInterval(SESSION_TIMEOUT_ERROR);
        errorCode = EC_401_USER_PASSWD_WRONG;
        String remoteAdr = request.getRemoteAddr();
        createLogEntry(user, admin, userStoreKey, remoteAdr, LogType.LOGIN_FAILED.asInteger(), uid);
    } catch (AdminConsoleAccessDeniedException e) {
        String message = "User is not authorized to use administration console.";
        VerticalAdminLogger.error(this.getClass(), 0, message, null);
        session.setAttribute("loginerrorcode", EC_401_ACCESS_DENIED);
        session.setAttribute("loginerror", message);
        session.setMaxInactiveInterval(SESSION_TIMEOUT_ERROR);
        errorCode = EC_401_ACCESS_DENIED;
    }

    if (errorCode != null) {
        if (formItems.containsKey("editContent")) {
            ExtendedMap parameters = new ExtendedMap();
            parameters.put("editContent", formItems.getInt("editContent"));
            redirectClientToAdminPath("login", parameters, request, response);
            return;
        }
        redirectClientToAdminPath("login", request, response);
        return;
    }

    // no errors occured during authentication and authorization of user

    String remoteAdr = request.getRemoteAddr();
    user.setSelectedLanguageCode(languageCode);

    try {
        final boolean loggingSuccessful = createLogEntry(user, admin, userStoreKey, remoteAdr,
                LogType.LOGIN.asInteger(), null);
        // Log login (only let the user log in if creation of log entry was successfull):
        if (!loggingSuccessful) {
            String message = "Failed to create log entry of user login";
            VerticalAdminLogger.error(this.getClass(), 0, message, null);
            session.setAttribute("loginerrorcode", EC_500_UNEXPECTED_ERROR);
            session.setAttribute("loginerror", message);
            session.setMaxInactiveInterval(SESSION_TIMEOUT_ERROR);
            return;
        }

        if (userStoreKey != null) {
            logUserStoreLogin(user, admin, request.getRemoteAddr(), request.getRemoteHost(), userStoreKey);
        }

        // Reset some cookie data:
        String deploymentPath = DeploymentPathResolver.getAdminDeploymentPath(request);

        if (userStoreKey != null) {
            CookieUtil.setCookie(response, user.getKey() + "userstorekey", userStoreKey.toString(), -1,
                    deploymentPath);
        }

        CookieUtil.setCookie(response, user.getKey() + "selectedunitkey", "-1", -1, deploymentPath);
        // If the enterpriseadmin user did'nt select a domain,
        // show system tab page, else show domain tab page.
        Cookie tabPageCookie = CookieUtil.getCookie(request, user.getKey() + "mainmenu_selectedTabPage");
        int tabPage = -1;
        if (tabPageCookie != null) {
            tabPage = Integer.parseInt(tabPageCookie.getValue());
        }

        CookieUtil.setCookie(response, user.getKey() + "mainmenu_selectedTabPage", String.valueOf(tabPage), -1,
                deploymentPath);
        session.setAttribute("selectedunitkey", "-1");

        ExtendedMap parameters = new ExtendedMap();
        parameters.put("page", "0");
        if (formItems.containsKey("rightframe")) {
            parameters.put("rightframe", formItems.getString("rightframe"));
        }
        if (formItems.containsKey("referer")) {
            parameters.put("referer", formItems.getString("referer", ""));
        }

        //ren: VS-1970
        if (formItems.containsKey("editContent")) {
            parameters.put("editContent", formItems.getInt("editContent"));
        }
        //end: VS-1970
        session.removeAttribute("loginerrorcode");
        session.removeAttribute("loginerror");
        redirectClientToAdminPath("adminpage", parameters, request, response);

    } catch (VerticalAdminException vae) {
        String message = "Failed to redirect to admin page: %t";
        VerticalAdminLogger.fatalAdmin(this.getClass(), 0, message, vae);
    }

}

From source file:com.mirth.connect.server.api.servlets.UserServlet.java

@Override
@DontCheckAuthorized/*  w ww  .j a v  a 2  s  .  c  o m*/
public LoginStatus login(String username, String password) {
    LoginStatus loginStatus = null;

    try {
        int tryCount = 0;
        int status = configurationController.getStatus();
        while (status != ConfigurationController.STATUS_INITIAL_DEPLOY
                && status != ConfigurationController.STATUS_OK) {
            if (tryCount >= 5) {
                loginStatus = new LoginStatus(Status.FAIL,
                        "Server is still starting or otherwise unavailable. Please try again shortly.");
                break;
            }

            Thread.sleep(1000);
            status = configurationController.getStatus();
            tryCount++;
        }

        if (loginStatus == null) {
            ConfigurationController configurationController = ControllerFactory.getFactory()
                    .createConfigurationController();

            HttpSession session = request.getSession();

            loginStatus = userController.authorizeUser(username, password);
            username = StringUtils.defaultString(loginStatus.getUpdatedUsername(), username);

            User validUser = null;

            if ((loginStatus.getStatus() == LoginStatus.Status.SUCCESS)
                    || (loginStatus.getStatus() == LoginStatus.Status.SUCCESS_GRACE_PERIOD)) {
                validUser = userController.getUser(null, username);

                /*
                 * There must be a user to login with and store in the session, even if an
                 * Authorization Plugin returned a LoginStatus of SUCCESS
                 */
                if (validUser == null) {
                    loginStatus = new LoginStatus(LoginStatus.Status.FAIL,
                            "Could not find a valid user with username: " + username);
                } else {
                    // set the sessions attributes
                    session.setAttribute(SESSION_USER, validUser.getId());
                    session.setAttribute(SESSION_AUTHORIZED, true);

                    // this prevents the session from timing out
                    session.setMaxInactiveInterval(-1);

                    // set the user status to logged in in the database
                    userController.loginUser(validUser);

                    // add the user's session to to session map
                    UserSessionCache.getInstance().registerSessionForUser(session, validUser);
                }
            }

            // Manually audit the Login event with the username since the user ID has not been stored to the session yet
            ServerEvent event = new ServerEvent(configurationController.getServerId(),
                    operation.getDisplayName());
            if (validUser != null) {
                event.setUserId(validUser.getId());
            }
            event.setIpAddress(getRequestIpAddress());
            event.setLevel(Level.INFORMATION);

            // Set the outcome to the result of the login attempt
            event.setOutcome(((loginStatus.getStatus() == LoginStatus.Status.SUCCESS)
                    || (loginStatus.getStatus() == LoginStatus.Status.SUCCESS_GRACE_PERIOD)) ? Outcome.SUCCESS
                            : Outcome.FAILURE);

            Map<String, String> attributes = new HashMap<String, String>();
            attributes.put("username", username);
            event.setAttributes(attributes);

            eventController.dispatchEvent(event);
        }
    } catch (Exception e) {
        throw new MirthApiException(e);
    }

    if (loginStatus.getStatus() != Status.SUCCESS && loginStatus.getStatus() != Status.SUCCESS_GRACE_PERIOD) {
        throw new MirthApiException(Response.status(Response.Status.UNAUTHORIZED).entity(loginStatus).build());
    }

    return loginStatus;
}