Example usage for javax.servlet.http HttpServletRequest getRemoteHost

List of usage examples for javax.servlet.http HttpServletRequest getRemoteHost

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRemoteHost.

Prototype

public String getRemoteHost();

Source Link

Document

Returns the fully qualified name of the client or the last proxy that sent the request.

Usage

From source file:org.apache.roller.weblogger.ui.rendering.servlets.CommentServlet.java

/**
 * Service incoming POST requests./*w  ww.  ja v a 2 s  .  c om*/
 *
 * Here we handle incoming comment postings.
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    String error = null;
    String dispatch_url = null;

    Weblog weblog = null;
    WeblogEntry entry = null;

    String message = null;
    RollerMessages messages = new RollerMessages();

    // are we doing a preview?  or a post?
    String method = request.getParameter("method");
    final boolean preview;
    if (method != null && method.equals("preview")) {
        preview = true;
        messages.addMessage("commentServlet.previewCommentOnly");
        log.debug("Handling comment preview post");
    } else {
        preview = false;
        log.debug("Handling regular comment post");
    }

    // throttling protection against spammers
    if (commentThrottle != null && commentThrottle.processHit(request.getRemoteAddr())) {

        log.debug("ABUSIVE " + request.getRemoteAddr());
        IPBanList.getInstance().addBannedIp(request.getRemoteAddr());
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    WeblogCommentRequest commentRequest = null;
    try {
        commentRequest = new WeblogCommentRequest(request);

        // lookup weblog specified by comment request
        weblog = WebloggerFactory.getWeblogger().getWeblogManager()
                .getWeblogByHandle(commentRequest.getWeblogHandle());

        if (weblog == null) {
            throw new WebloggerException("unable to lookup weblog: " + commentRequest.getWeblogHandle());
        }

        // lookup entry specified by comment request
        entry = commentRequest.getWeblogEntry();
        if (entry == null) {
            throw new WebloggerException("unable to lookup entry: " + commentRequest.getWeblogAnchor());
        }

        // we know what the weblog entry is, so setup our urls
        dispatch_url = "/roller-ui/rendering/page/" + weblog.getHandle();
        if (commentRequest.getLocale() != null) {
            dispatch_url += "/" + commentRequest.getLocale();
        }
        dispatch_url += "/entry/" + URLUtilities.encode(commentRequest.getWeblogAnchor());

    } catch (Exception e) {
        // some kind of error parsing the request or looking up weblog
        log.debug("error creating page request", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    log.debug("Doing comment posting for entry = " + entry.getPermalink());

    // collect input from request params and construct new comment object
    // fields: name, email, url, content, notify
    // TODO: data validation on collected comment data
    WeblogEntryComment comment = new WeblogEntryComment();
    comment.setName(commentRequest.getName());
    comment.setEmail(commentRequest.getEmail());
    comment.setUrl(commentRequest.getUrl());
    comment.setContent(commentRequest.getContent());
    comment.setNotify(Boolean.valueOf(commentRequest.isNotify()));
    comment.setWeblogEntry(entry);
    comment.setRemoteHost(request.getRemoteHost());
    comment.setPostTime(new Timestamp(System.currentTimeMillis()));

    // set comment content-type depending on if html is allowed
    if (WebloggerRuntimeConfig.getBooleanProperty("users.comments.htmlenabled")) {
        comment.setContentType("text/html");
    } else {
        comment.setContentType("text/plain");
    }

    // set whatever comment plugins are configured
    comment.setPlugins(WebloggerRuntimeConfig.getProperty("users.comments.plugins"));

    WeblogEntryCommentForm cf = new WeblogEntryCommentForm();
    cf.setData(comment);
    if (preview) {
        cf.setPreview(comment);
    }

    I18nMessages messageUtils = I18nMessages.getMessages(commentRequest.getLocaleInstance());

    // check if comments are allowed for this entry
    // this checks site-wide settings, weblog settings, and entry settings
    if (!entry.getCommentsStillAllowed() || !entry.isPublished()) {
        error = messageUtils.getString("comments.disabled");

        // if this is a real comment post then authenticate request
    } else if (!preview && !this.authenticator.authenticate(request)) {
        error = messageUtils.getString("error.commentAuthFailed");
        log.debug("Comment failed authentication");
    }

    // bail now if we have already found an error
    if (error != null) {
        cf.setError(error);
        request.setAttribute("commentForm", cf);
        RequestDispatcher dispatcher = request.getRequestDispatcher(dispatch_url);
        dispatcher.forward(request, response);
        return;
    }

    int validationScore = commentValidationManager.validateComment(comment, messages);
    log.debug("Comment Validation score: " + validationScore);

    if (!preview) {

        if (validationScore == 100 && weblog.getCommentModerationRequired()) {
            // Valid comments go into moderation if required
            comment.setStatus(WeblogEntryComment.PENDING);
            message = messageUtils.getString("commentServlet.submittedToModerator");
        } else if (validationScore == 100) {
            // else they're approved
            comment.setStatus(WeblogEntryComment.APPROVED);
            message = messageUtils.getString("commentServlet.commentAccepted");
        } else {
            // Invalid comments are marked as spam
            log.debug("Comment marked as spam");
            comment.setStatus(WeblogEntryComment.SPAM);
            error = messageUtils.getString("commentServlet.commentMarkedAsSpam");

            // add specific error messages if they exist
            if (messages.getErrorCount() > 0) {
                Iterator errors = messages.getErrors();
                RollerMessage errorKey = null;

                StringBuilder buf = new StringBuilder();
                buf.append("<ul>");
                while (errors.hasNext()) {
                    errorKey = (RollerMessage) errors.next();

                    buf.append("<li>");
                    if (errorKey.getArgs() != null) {
                        buf.append(messageUtils.getString(errorKey.getKey(), errorKey.getArgs()));
                    } else {
                        buf.append(messageUtils.getString(errorKey.getKey()));
                    }
                    buf.append("</li>");
                }
                buf.append("</ul>");

                error += buf.toString();
            }

        }

        try {
            if (!WeblogEntryComment.SPAM.equals(comment.getStatus())
                    || !WebloggerRuntimeConfig.getBooleanProperty("comments.ignoreSpam.enabled")) {

                WeblogEntryManager mgr = WebloggerFactory.getWeblogger().getWeblogEntryManager();
                mgr.saveComment(comment);
                WebloggerFactory.getWeblogger().flush();

                // Send email notifications only to subscribers if comment is 100% valid
                boolean notifySubscribers = (validationScore == 100);
                MailUtil.sendEmailNotification(comment, messages, messageUtils, notifySubscribers);

                // only re-index/invalidate the cache if comment isn't moderated
                if (!weblog.getCommentModerationRequired()) {
                    IndexManager manager = WebloggerFactory.getWeblogger().getIndexManager();

                    // remove entry before (re)adding it, or in case it isn't Published
                    manager.removeEntryIndexOperation(entry);

                    // if published, index the entry
                    if (entry.isPublished()) {
                        manager.addEntryIndexOperation(entry);
                    }

                    // Clear all caches associated with comment
                    CacheManager.invalidate(comment);
                }

                // comment was successful, clear the comment form
                cf = new WeblogEntryCommentForm();
            }

        } catch (WebloggerException re) {
            log.error("Error saving comment", re);
            error = re.getMessage();
        }
    }

    // the work has been done, now send the user back to the entry page
    if (error != null) {
        cf.setError(error);
    }
    if (message != null) {
        cf.setMessage(message);
    }
    request.setAttribute("commentForm", cf);

    log.debug("comment processed, forwarding to " + dispatch_url);
    RequestDispatcher dispatcher = request.getRequestDispatcher(dispatch_url);
    dispatcher.forward(request, response);
}

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Show HTTP header information./* w w w.  j ava 2  s . com*/
 *
 * @param req Description of the Parameter
 */
protected void showRequestInfo(HttpServletRequest req) {

    System.out.println();
    System.out.println("SlideDAV Request Info");
    System.out.println();

    // Show generic info
    System.out.println("Encoding : " + req.getCharacterEncoding());
    System.out.println("Length : " + req.getContentLength());
    System.out.println("Type : " + req.getContentType());

    System.out.println();
    System.out.println("Parameters");

    Enumeration parameters = req.getParameterNames();

    while (parameters.hasMoreElements()) {
        String paramName = (String) parameters.nextElement();
        String[] values = req.getParameterValues(paramName);
        System.out.print(paramName + " : ");
        for (int i = 0; i < values.length; i++) {
            System.out.print(values[i] + ", ");
        }
        System.out.println();
    }

    System.out.println();

    System.out.println("Protocol : " + req.getProtocol());
    System.out.println("Address : " + req.getRemoteAddr());
    System.out.println("Host : " + req.getRemoteHost());
    System.out.println("Scheme : " + req.getScheme());
    System.out.println("Server Name : " + req.getServerName());
    System.out.println("Server Port : " + req.getServerPort());

    System.out.println();
    System.out.println("Attributes");

    Enumeration attributes = req.getAttributeNames();

    while (attributes.hasMoreElements()) {
        String attributeName = (String) attributes.nextElement();
        System.out.print(attributeName + " : ");
        System.out.println(req.getAttribute(attributeName).toString());
    }

    System.out.println();

    // Show HTTP info
    System.out.println();
    System.out.println("HTTP Header Info");
    System.out.println();

    System.out.println("Authentication Type : " + req.getAuthType());
    System.out.println("HTTP Method : " + req.getMethod());
    System.out.println("Path Info : " + req.getPathInfo());
    System.out.println("Path translated : " + req.getPathTranslated());
    System.out.println("Query string : " + req.getQueryString());
    System.out.println("Remote user : " + req.getRemoteUser());
    System.out.println("Requested session id : " + req.getRequestedSessionId());
    System.out.println("Request URI : " + req.getRequestURI());
    System.out.println("Context path : " + req.getContextPath());
    System.out.println("Servlet path : " + req.getServletPath());
    System.out.println("User principal : " + req.getUserPrincipal());

    System.out.println();
    System.out.println("Headers : ");

    Enumeration headers = req.getHeaderNames();

    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        System.out.print(headerName + " : ");
        System.out.println(req.getHeader(headerName));
    }

    System.out.println();
    System.out.println();

}

From source file:com.liferay.portal.action.LoginAction.java

public static void setLoginCookies(HttpServletRequest req, HttpServletResponse res, HttpSession ses,
        long userId, boolean rememberMe) throws PortalException, SystemException, EncryptorException {
    if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.SESSION_ENABLE_PHISHING_PROTECTION))) {

        // Invalidate the previous session to prevent phishing

        LastPath lastPath = (LastPath) ses.getAttribute(WebKeys.LAST_PATH);

        // GNOMON Gi9: KEEP ANY USER_CARRY ATTRIBUTES (for example shopping cart)
        HashMap userCarryAttributes = getUserCarryAttributes(ses);

        try {//from  w  ww  .j ava  2 s.  co  m
            ses.invalidate();
        } catch (Exception e) {
            _log.info("Session has already invalidated");
        }

        ses = req.getSession(true);

        addSessionAttributes(ses, userCarryAttributes);

        if (lastPath != null) {
            ses.setAttribute(WebKeys.LAST_PATH, lastPath);
        }
    }

    // Set cookies

    String domain = PropsUtil.get(PropsUtil.SESSION_COOKIE_DOMAIN);

    User user = UserLocalServiceUtil.getUserById(userId);
    Company company = CompanyLocalServiceUtil.getCompanyById(user.getCompanyId());
    String userIdString = String.valueOf(userId);

    ses.setAttribute("j_username", userIdString);
    ses.setAttribute("j_password", user.getPassword());
    ses.setAttribute("j_remoteuser", userIdString);

    ses.setAttribute(WebKeys.USER_PASSWORD, user.getPassword());

    Cookie idCookie = new Cookie(CookieKeys.ID, UserLocalServiceUtil.encryptUserId(userIdString));

    if (Validator.isNotNull(domain)) {
        idCookie.setDomain(domain);
    }

    idCookie.setPath(StringPool.SLASH);

    Cookie passwordCookie = new Cookie(CookieKeys.PASSWORD,
            Encryptor.encrypt(company.getKeyObj(), user.getPassword()));

    if (Validator.isNotNull(domain)) {
        passwordCookie.setDomain(domain);
    }

    passwordCookie.setPath(StringPool.SLASH);

    int loginMaxAge = GetterUtil.getInteger(PropsUtil.get(PropsUtil.COMPANY_SECURITY_AUTO_LOGIN_MAX_AGE),
            CookieKeys.MAX_AGE);

    if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.SESSION_DISABLED))) {

        rememberMe = true;
    }

    if (rememberMe) {
        idCookie.setMaxAge(loginMaxAge);
        passwordCookie.setMaxAge(loginMaxAge);
    } else {
        idCookie.setMaxAge(0);
        passwordCookie.setMaxAge(0);
    }

    Cookie loginCookie = new Cookie(CookieKeys.LOGIN, user.getLogin());

    if (Validator.isNotNull(domain)) {
        loginCookie.setDomain(domain);
    }

    loginCookie.setPath(StringPool.SLASH);
    loginCookie.setMaxAge(loginMaxAge);

    Cookie screenNameCookie = new Cookie(CookieKeys.SCREEN_NAME,
            Encryptor.encrypt(company.getKeyObj(), user.getScreenName()));

    if (Validator.isNotNull(domain)) {
        screenNameCookie.setDomain(domain);
    }

    screenNameCookie.setPath(StringPool.SLASH);
    screenNameCookie.setMaxAge(loginMaxAge);

    CookieKeys.addCookie(res, idCookie);
    CookieKeys.addCookie(res, passwordCookie);
    CookieKeys.addCookie(res, loginCookie);
    CookieKeys.addCookie(res, screenNameCookie);

    //add entry to user tracking if needed
    boolean trackUser = GetterUtil.getBoolean(PropsUtil.get(user.getCompanyId(), "gn.user.tracking.enabled"),
            false);
    if (trackUser) {
        GnUserTracking track = new GnUserTracking();
        track.setCompanyId(user.getCompanyId());
        track.setUserId(user.getUserId());
        track.setLoginDate(new Date());
        String fromIp = req.getHeader("X-Forwarded-For");
        if (Validator.isNull(fromIp))
            fromIp = req.getRemoteAddr() + (Validator.isNotNull(req.getRemoteHost())
                    && !req.getRemoteAddr().equals(req.getRemoteHost()) ? "( " + req.getRemoteHost() + " )"
                            : "");

        track.setFromIp(fromIp);
        GnPersistenceService.getInstance(null).createObject(track);
    }
    EventsService.getInstance().createEvent(user, "PortalAuth",
            "User " + user.getScreenName() + " has logged in " + req.getServerName(), "loginaction", null);
}

From source file:org.alfresco.repo.webdav.auth.BaseKerberosAuthenticationFilter.java

public boolean authenticateRequest(ServletContext context, HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {
    // Check if there is an authorization header with an SPNEGO security blob

    String authHdr = req.getHeader("Authorization");
    boolean reqAuth = false;

    if (authHdr != null) {
        // Check for a Kerberos/SPNEGO authorization header

        if (authHdr.startsWith("Negotiate"))
            reqAuth = true;// w w  w. j a v a 2  s.  co  m
        else if (authHdr.startsWith("NTLM")) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Received NTLM logon from client");

            // Restart the authentication

            restartLoginChallenge(context, req, resp);
            return false;
        } else if (isFallbackEnabled()) {
            return performFallbackAuthentication(context, req, resp);
        }
    }

    // Check if the user is already authenticated        
    SessionUser user = getSessionUser(context, req, resp, true);
    HttpSession httpSess = req.getSession(true);
    if (user == null) {
        user = (SessionUser) httpSess.getAttribute("_alfAuthTicket");
        // MNT-13191 Opening /alfresco/webdav from a Kerberos-authenticated IE11 browser causes HTTP error 500
        if (user != null) {
            String userName = user.getUserName();
            AuthenticationUtil.setFullyAuthenticatedUser(userName);
        }
    }

    // If the user has been validated and we do not require re-authentication then continue to
    // the next filter
    if (user != null && reqAuth == false) {
        // Filter validate hook
        onValidate(context, req, resp, new TicketCredentials(user.getTicket()));

        // Debug

        if (getLogger().isDebugEnabled())
            getLogger().debug("Authentication not required (user), chaining ...");

        // Chain to the next filter

        return true;
    }

    // Check if the login page is being accessed, do not intercept the login page
    if (checkLoginPage(req, resp)) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Login page requested, chaining ...");

        // Chain to the next filter

        return true;
    }

    // Check the authorization header

    if (authHdr == null) {

        // If ticket based logons are allowed, check for a ticket parameter

        if (allowsTicketLogons()) {
            // Check if a ticket parameter has been specified in the reuqest

            if (checkForTicketParameter(context, req, resp)) {
                // Filter validate hook
                if (getLogger().isDebugEnabled())
                    getLogger().debug("Authenticated with a ticket parameter.");

                if (user == null) {
                    user = (SessionUser) httpSess.getAttribute(getUserAttributeName());
                }
                onValidate(context, req, resp, new TicketCredentials(user.getTicket()));

                // Chain to the next filter

                return true;
            }
        }

        // Debug

        if (getLogger().isDebugEnabled())
            getLogger().debug("New Kerberos auth request from " + req.getRemoteHost() + " ("
                    + req.getRemoteAddr() + ":" + req.getRemotePort() + ")");

        // Send back a request for SPNEGO authentication
        logonStartAgain(context, req, resp, true);
        return false;
    } else {
        // Decode the received SPNEGO blob and validate

        final byte[] spnegoByts = Base64.decodeBase64(authHdr.substring(10).getBytes());

        // Check if the client sent an NTLMSSP blob

        if (isNTLMSSPBlob(spnegoByts, 0)) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Client sent an NTLMSSP security blob");

            // Restart the authentication

            restartLoginChallenge(context, req, resp);
            return false;
        }

        //  Check the received SPNEGO token type

        int tokType = -1;

        try {
            tokType = SPNEGO.checkTokenType(spnegoByts, 0, spnegoByts.length);
        } catch (IOException ex) {
        }

        // Check for a NegTokenInit blob

        if (tokType == SPNEGO.NegTokenInit) {
            //  Parse the SPNEGO security blob to get the Kerberos ticket

            NegTokenInit negToken = new NegTokenInit();

            try {
                // Decode the security blob

                negToken.decode(spnegoByts, 0, spnegoByts.length);

                //  Determine the authentication mechanism the client is using and logon

                String oidStr = null;
                if (negToken.numberOfOids() > 0)
                    oidStr = negToken.getOidAt(0).toString();

                if (oidStr != null && (oidStr.equals(OID.ID_MSKERBEROS5) || oidStr.equals(OID.ID_KERBEROS5))) {
                    //  Kerberos logon

                    try {
                        NegTokenTarg negTokenTarg = doKerberosLogon(negToken, req, resp, httpSess);
                        if (negTokenTarg != null) {
                            // Allow the user to access the requested page
                            onValidate(context, req, resp, new KerberosCredentials(negToken, negTokenTarg));
                            if (getLogger().isDebugEnabled())
                                getLogger().debug("Authenticated through Kerberos.");
                            return true;
                        } else {
                            // Send back a request for SPNEGO authentication
                            if (getLogger().isDebugEnabled())
                                getLogger().debug("Failed SPNEGO authentication.");
                            restartLoginChallenge(context, req, resp);
                            return false;
                        }
                    } catch (AuthenticationException ex) {
                        // Even though the user successfully authenticated, the ticket may not be granted, e.g. to
                        // max user limit
                        if (getLogger().isDebugEnabled())
                            getLogger().debug("Validate failed.", ex);
                        onValidateFailed(context, req, resp, httpSess, new TicketCredentials(user.getTicket()));
                        return false;
                    }
                } else {
                    //  Unsupported mechanism, e.g. NegoEx

                    if (getLogger().isDebugEnabled())
                        getLogger().debug("Unsupported SPNEGO mechanism " + oidStr);

                    // Try again!

                    restartLoginChallenge(context, req, resp);
                }
            } catch (IOException ex) {
                // Log the error

                if (getLogger().isDebugEnabled())
                    getLogger().debug(ex);
            }
        } else {
            //  Unknown SPNEGO token type

            if (getLogger().isDebugEnabled())
                getLogger().debug("Unknown SPNEGO token type");

            // Send back a request for SPNEGO authentication

            restartLoginChallenge(context, req, resp);
        }
    }
    return false;
}

From source file:aaf.vhr.idp.http.VhrRemoteUserAuthServlet.java

/** {@inheritDoc} */
@Override//from  w  w  w .j a  v a  2 s  . c om
protected void service(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    try {
        // key to ExternalAuthentication session
        String key = null;
        boolean isVhrReturn = false;
        boolean isForceAuthn = false;
        DateTime authnStart = null; // when this authentication started at the IdP
        // array to use as return parameter when calling VhrSessionValidator
        DateTime authnInstantArr[] = new DateTime[1];

        if (httpRequest.getParameter(REDIRECT_REQ_PARAM_NAME) != null) {
            // we have come back from the VHR
            isVhrReturn = true;
            key = httpRequest.getParameter(REDIRECT_REQ_PARAM_NAME);
            HttpSession hs = httpRequest.getSession();

            if (hs != null && hs.getAttribute(AUTHN_INIT_INSTANT_ATTR_NAME + key) != null) {
                authnStart = (DateTime) hs.getAttribute(AUTHN_INIT_INSTANT_ATTR_NAME + key);
                // remove the attribute from the session so that we do not attempt to reuse it...
                hs.removeAttribute(AUTHN_INIT_INSTANT_ATTR_NAME);
            }
            ;

            if (hs != null && hs.getAttribute(IS_FORCE_AUTHN_ATTR_NAME + key) != null) {
                isForceAuthn = ((Boolean) hs.getAttribute(IS_FORCE_AUTHN_ATTR_NAME + key)).booleanValue();
                // remove the attribute from the session so that we do not attempt to reuse it...
                hs.removeAttribute(AUTHN_INIT_INSTANT_ATTR_NAME);
            }
            ;

        } else {
            // starting a new SSO request
            key = ExternalAuthentication.startExternalAuthentication(httpRequest);

            // check if forceAuthn is set
            Object forceAuthnAttr = httpRequest.getAttribute(ExternalAuthentication.FORCE_AUTHN_PARAM);
            if (forceAuthnAttr != null && forceAuthnAttr instanceof java.lang.Boolean) {
                log.debug("Loading foceAuthn value");
                isForceAuthn = ((Boolean) forceAuthnAttr).booleanValue();
            }

            // check if we can see when authentication was initiated
            final AuthenticationContext authCtx = ExternalAuthentication
                    .getProfileRequestContext(key, httpRequest)
                    .getSubcontext(AuthenticationContext.class, false);
            if (authCtx != null) {
                log.debug("Authentication initiation is {}", authCtx.getInitiationInstant());
                authnStart = new DateTime(authCtx.getInitiationInstant(), DateTimeZone.UTC);
                log.debug("AuthnStart is {}", authnStart);
            }
            ;

        }
        ;
        log.debug("forceAuthn is {}, authnStart is {}", isForceAuthn, authnStart);

        if (key == null) {
            log.error("No ExternalAuthentication sesssion key found");
            throw new ServletException("No ExternalAuthentication sesssion key found");
        }
        ;
        // we now have a key - either:
        // * we started new authentication
        // * or we have returned from VHR and loaded the key from the HttpSession

        String username = null;

        // We may have a cookie - either as part of return or from previous session
        // Attempt to locate VHR SessionID
        String vhrSessionID = null;
        Cookie[] cookies = httpRequest.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(SSO_COOKIE_NAME)) {
                vhrSessionID = cookie.getValue();
                break;
            }
        }

        if (vhrSessionID != null) {
            log.info("Found vhrSessionID from {}. Establishing validity.", httpRequest.getRemoteHost());
            username = vhrSessionValidator.validateSession(vhrSessionID, (isForceAuthn ? authnStart : null),
                    authnInstantArr);
        }
        ;

        // If we do not have a username yet (no Vhr session cookie or did not validate),
        // we redirect to VHR - but only if we are not returning from the VHR
        // Reason: (i) we do not want to loop and (ii) we do not have the full context otherwise initialized by
        // ExternalAuthentication.startExternalAuthentication()
        if (username == null && !isVhrReturn) {

            URLCodec codec = new URLCodec();
            String relyingParty = (String) httpRequest.getAttribute("relyingParty");
            String serviceName = "";

            log.info("No vhrSessionID found from {}. Directing to VHR authentication process.",
                    httpRequest.getRemoteHost());
            log.debug("Relying party which initiated the SSO request was: {}", relyingParty);

            // try getting a RelyingPartyUIContext
            // we should pass on the request for consent revocation
            final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(key, httpRequest);
            final RelyingPartyUIContext rpuiCtx = prc.getSubcontext(AuthenticationContext.class, true)
                    .getSubcontext(RelyingPartyUIContext.class, false);
            if (rpuiCtx != null) {
                serviceName = rpuiCtx.getServiceName();
                log.debug("RelyingPartyUIContext received, ServiceName is {}", serviceName);
            }
            ;

            // save session *key*
            HttpSession hs = httpRequest.getSession(true);
            hs.setAttribute(IS_FORCE_AUTHN_ATTR_NAME + key, new Boolean(isForceAuthn));
            hs.setAttribute(AUTHN_INIT_INSTANT_ATTR_NAME + key, authnStart);

            try {
                httpResponse.sendRedirect(String.format(vhrLoginEndpoint,
                        codec.encode(httpRequest.getRequestURL().toString() + "?" + REDIRECT_REQ_PARAM_NAME
                                + "=" + codec.encode(key)),
                        codec.encode(relyingParty), codec.encode(serviceName)));
            } catch (EncoderException e) {
                log.error("Could not encode VHR redirect params");
                throw new IOException(e);
            }
            return; // we issued a redirect - return now
        }
        ;

        if (username == null) {
            log.warn("VirtualHome authentication failed: no username received");
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                    "VirtualHome authentication failed: no username received");
            ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
            return;
        }

        // check if consent revocation was requested
        String consentRevocationParam = httpRequest.getParameter(consentRevocationParamName);
        if (consentRevocationParam != null) {
            // we should pass on the request for consent revocation
            final ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(key, httpRequest);
            final ConsentManagementContext consentCtx = prc.getSubcontext(ConsentManagementContext.class, true);
            log.debug("Consent revocation request received, setting revokeConsent in consentCtx");
            consentCtx.setRevokeConsent(consentRevocationParam.equalsIgnoreCase("true"));
        }
        ;

        // Set authnInstant to timestamp returned by VHR
        if (authnInstantArr[0] != null) {
            log.debug("Response from VHR includes authenticationInstant time {}, passing this back to IdP",
                    authnInstantArr[0]);
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_INSTANT_KEY, authnInstantArr[0]);
        }
        ;

        httpRequest.setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, username);

        ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);

    } catch (final ExternalAuthenticationException e) {
        throw new ServletException("Error processing external authentication request", e);
    }
}

From source file:org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter.java

public boolean authenticateRequest(ServletContext context, HttpServletRequest sreq, HttpServletResponse sresp)
        throws IOException, ServletException {
    // Check if there is an authorization header with an NTLM security blob
    String authHdr = sreq.getHeader(AUTHORIZATION);
    boolean reqAuth = false;

    // Check if an NTLM authorization header was received

    if (authHdr != null) {
        // Check for an NTLM authorization header

        if (authHdr.startsWith(AUTH_NTLM))
            reqAuth = true;//w  ww.ja  va 2  s.co m
        else if (authHdr.startsWith("Negotiate")) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Received 'Negotiate' from client, may be SPNEGO/Kerberos logon");

            // Restart the authentication

            restartLoginChallenge(context, sreq, sresp);
            return false;
        } else if (isFallbackEnabled()) {
            return performFallbackAuthentication(context, sreq, sresp);
        }
    }

    // Check if the user is already authenticated
    SessionUser user = getSessionUser(context, sreq, sresp, true);

    // If the user has been validated and we do not require re-authentication then continue to
    // the next filter
    if (user != null && reqAuth == false) {
        // Filter validate hook
        onValidate(context, sreq, sresp, new TicketCredentials(user.getTicket()));

        if (getLogger().isDebugEnabled())
            getLogger().debug("Authentication not required (user), chaining ...");

        // Chain to the next filter
        return true;
    }

    // Check if the login page is being accessed, do not intercept the login page
    if (hasLoginPage() && sreq.getRequestURI().endsWith(getLoginPage()) == true) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Login page requested, chaining ...");

        // Chain to the next filter
        return true;
    }

    // Check if the browser is Opera, if so then display the login page as Opera does not
    // support NTLM and displays an error page if a request to use NTLM is sent to it
    String userAgent = sreq.getHeader("user-agent");
    if (userAgent != null && userAgent.indexOf("Opera ") != -1) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("Opera detected, redirecting to login page");

        // If there is no login page configured (WebDAV) then just keep requesting the user details from the client

        if (hasLoginPage())
            redirectToLoginPage(sreq, sresp);
        else
            restartLoginChallenge(context, sreq, sresp);
        return false;
    }

    // Check the authorization header
    if (authHdr == null) {
        // Check for a ticket based logon, if enabled

        if (allowsTicketLogons()) {
            // Check if the request includes an authentication ticket

            if (checkForTicketParameter(context, sreq, sresp)) {

                // Authentication was bypassed using a ticket parameter
                return true;
            }
        }

        // DEBUG

        if (getLogger().isDebugEnabled())
            getLogger().debug("New NTLM auth request from " + sreq.getRemoteHost() + " (" + sreq.getRemoteAddr()
                    + ":" + sreq.getRemotePort() + ") SID:" + sreq.getSession().getId());

        // Send back a request for NTLM authentication
        restartLoginChallenge(context, sreq, sresp);
        return false;
    } else {
        HttpSession session = sreq.getSession();
        Object sessionMutex = WebUtils.getSessionMutex(session);
        // Decode the received NTLM blob and validate
        final byte[] ntlmByts = Base64.decodeBase64(authHdr.substring(5).getBytes());
        int ntlmTyp = NTLMMessage.isNTLMType(ntlmByts);
        if (ntlmTyp == NTLM.Type1) {
            // Process the type 1 NTLM message
            Type1NTLMMessage type1Msg = new Type1NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                processType1(type1Msg, sreq, sresp);
            }
            return false;
        } else if (ntlmTyp == NTLM.Type3) {
            // Process the type 3 NTLM message
            Type3NTLMMessage type3Msg = new Type3NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                return processType3(type3Msg, context, sreq, sresp);
            }
        } else {
            if (getLogger().isDebugEnabled())
                getLogger().debug("NTLM blob not handled, redirecting to login page.");

            if (hasLoginPage())
                redirectToLoginPage(sreq, sresp);
            else
                restartLoginChallenge(context, sreq, sresp);
            return false;
        }
    }
}

From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java

public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) {
    HttpServletRequest initialRequest = (HttpServletRequest) request;
    this.session = session;
    this.authorization = authorization;
    //Copy common data
    authType = initialRequest.getAuthType();
    contextPath = initialRequest.getContextPath();
    remoteUser = initialRequest.getRemoteUser();
    userPrincipal = initialRequest.getUserPrincipal();
    requestedSessionId = initialRequest.getRequestedSessionId();
    requestedSessionIdValid = initialRequest.isRequestedSessionIdValid();

    attributes = new HashMap();
    Enumeration attributeNames = initialRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = (String) attributeNames.nextElement();
        Object attribute = initialRequest.getAttribute(name);
        if ((null != name) && (null != attribute)) {
            attributes.put(name, attribute);
        }/*from ww  w .  j ava  2 s.  c o  m*/
    }

    // Warning:  For some reason, the various javax.include.* attributes are
    // not available via the getAttributeNames() call.  This may be limited
    // to a Liferay issue but when the MainPortlet dispatches the call to
    // the MainServlet, all of the javax.include.* attributes can be
    // retrieved using this.request.getAttribute() but they do NOT appear in
    // the Enumeration of names returned by getAttributeNames().  So here
    // we manually add them to our map to ensure we can find them later.
    String[] incAttrKeys = Constants.INC_CONSTANTS;
    for (int index = 0; index < incAttrKeys.length; index++) {
        String incAttrKey = incAttrKeys[index];
        Object incAttrVal = initialRequest.getAttribute(incAttrKey);
        if (incAttrVal != null) {
            attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey));
        }
    }

    headers = new HashMap();
    Enumeration headerNames = initialRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration values = initialRequest.getHeaders(name);
        headers.put(name, Collections.list(values));
    }

    parameters = new HashMap();
    Enumeration parameterNames = initialRequest.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String name = (String) parameterNames.nextElement();
        parameters.put(name, initialRequest.getParameterValues(name));
    }

    scheme = initialRequest.getScheme();
    serverName = initialRequest.getServerName();
    serverPort = initialRequest.getServerPort();
    secure = initialRequest.isSecure();

    //Copy servlet specific data
    cookies = initialRequest.getCookies();
    method = initialRequest.getMethod();
    pathInfo = initialRequest.getPathInfo();
    pathTranslated = initialRequest.getPathTranslated();
    queryString = initialRequest.getQueryString();
    requestURI = initialRequest.getRequestURI();
    try {
        requestURL = initialRequest.getRequestURL();
    } catch (NullPointerException e) {
        //TODO remove this catch block when GlassFish bug is addressed
        if (log.isErrorEnabled()) {
            log.error("Null Protocol Scheme in request", e);
        }
        HttpServletRequest req = initialRequest;
        requestURL = new StringBuffer(
                "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI());
    }
    servletPath = initialRequest.getServletPath();
    servletSession = initialRequest.getSession();
    isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie();
    isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL();
    characterEncoding = initialRequest.getCharacterEncoding();
    contentLength = initialRequest.getContentLength();
    contentType = initialRequest.getContentType();
    protocol = initialRequest.getProtocol();
    remoteAddr = initialRequest.getRemoteAddr();
    remoteHost = initialRequest.getRemoteHost();
    initializeServlet2point4Properties(initialRequest);
}

From source file:com.adito.security.DefaultLogonController.java

/**
 * @param request//from  w  w w .  j  av  a2s . com
 * @param response
 * @param scheme
 */
public void logon(HttpServletRequest request, HttpServletResponse response, AuthenticationScheme scheme)
        throws Exception {
    User user = scheme.getUser();

    // Check logon is currently allowed
    String logonNotAllowedReason = LogonControllerFactory.getInstance().checkLogonAllowed(user);

    if (logonNotAllowedReason != null) {
        log.warn("Logon not allowed because '" + logonNotAllowedReason + "'");
        throw new Exception(logonNotAllowedReason);
    }

    if (log.isInfoEnabled()) {
        log.info("Session logon ticket is "
                + (String) request.getSession().getAttribute(Constants.LOGON_TICKET));
        log.info("Logging on " + scheme.getUsername() + " for scheme " + scheme.getSchemeName());
    }
    // Sucessful login, remove any locks
    unlockUser(scheme.getUsername());

    String host = (request.isSecure()
            || SystemProperties.get("jetty.force.HTTPSRedirect", "false").equals("true") ? "https" : "http")
            + "://" + request.getHeader(HttpConstants.HDR_HOST);

    request.getSession().setAttribute(Constants.HOST, host);
    SessionInfo info = null;
    boolean fireEvent = false;
    if (request.getSession().getAttribute(Constants.SESSION_LOCKED) == null) {
        InetAddress address = InetAddress.getByName(request.getRemoteAddr());
        int sessionType = SessionInfo.getSessionTypeForUserAgent(request.getHeader("User-Agent"));
        checkForMultipleSessions(user, address, sessionType);
        info = addLogonTicket(request, response, user, address, sessionType);
        try {
            info.getHttpSession().setAttribute(Constants.VPN_AUTOSTART,
                    CoreUtil.getUsersProfileProperty(info.getHttpSession(), "client.autoStart", user));
        } catch (Exception e) {
            throw new SecurityErrorException(SecurityErrorException.INTERNAL_ERROR, e.getMessage());
        }
        fireEvent = true;
    }
    // Initialise the session
    initialiseSession(request.getSession(), user);
    // Build the menus
    CoreUtil.resetMainNavigation(request.getSession());

    char[] pw = getPasswordFromCredentials(scheme);
    String mode = Property.getProperty(new SystemConfigKey("security.privateKeyMode"));
    if (!mode.equals("disabled")) {

        try {
            PublicKeyStore.getInstance().verifyPrivateKey(user.getPrincipalName(), pw);
        } catch (PromptForPasswordException e) {
            CoreUtil.addPageInterceptListener(request.getSession(),
                    new PromptForPrivateKeyPassphraseInterceptListener());
        } catch (UpdatePrivateKeyPassphraseException e) {
            if (mode.equals("prompt")) {
                CoreUtil.addPageInterceptListener(request.getSession(),
                        new PromptForPrivateKeyPassphraseInterceptListener());
            } else {
                CoreUtil.addPageInterceptListener(request.getSession(),
                        new UpdatePrivateKeyPassphraseInterceptListener());
            }
        }
    }

    /*
     * Make sure the logon event gets fired after the private key has
     * been initialised. This is repeated in the actions the page
     * intercept listeners redirect to
     */
    if (fireEvent) {
        CoreServlet.getServlet()
                .fireCoreEvent(new CoreEvent(this, CoreEventConstants.LOGON, scheme, info)
                        .addAttribute(CoreAttributeConstants.EVENT_ATTR_IP_ADDRESS, request.getRemoteAddr())
                        .addAttribute(CoreAttributeConstants.EVENT_ATTR_HOST, request.getRemoteHost())
                        .addAttribute(CoreAttributeConstants.EVENT_ATTR_SCHEME, scheme.getSchemeName()));
    }
}

From source file:org.alfresco.web.site.servlet.SSOAuthenticationFilter.java

/**
 * Run the filter/*w  w  w .j av  a 2  s .com*/
 * 
 * @param sreq ServletRequest
 * @param sresp ServletResponse
 * @param chain FilterChain
 * 
 * @exception IOException
 * @exception ServletException
 */
public void doFilter(ServletRequest sreq, ServletResponse sresp, FilterChain chain)
        throws IOException, ServletException {
    NDC.remove();
    NDC.push(Thread.currentThread().getName());
    final boolean debug = logger.isDebugEnabled();

    // Wrap externally authenticated requests that provide the user in an HTTP header
    // with one that returns the correct name from getRemoteUser(). For use in our own
    // calls to this method and any chained filters.
    sreq = wrapHeaderAuthenticatedRequest(sreq);

    // Bypass the filter if we don't have an endpoint with external auth enabled
    if (this.endpoint == null) {
        if (debug)
            logger.debug("There is no endpoint with external auth enabled.");
        chain.doFilter(sreq, sresp);
        return;
    }

    // Get the HTTP request/response/session
    HttpServletRequest req = (HttpServletRequest) sreq;
    HttpServletResponse res = (HttpServletResponse) sresp;
    HttpSession session = req.getSession();

    if (req.getServletPath() != null && req.getServletPath().startsWith(UNAUTHENTICATED_ACCESS_PROXY)) {
        if (debug)
            logger.debug("SSO is by-passed for unauthenticated access endpoint.");
        chain.doFilter(sreq, sresp);
        return;
    }

    // external invitation link should not trigger any SSO
    if (PAGE_SERVLET_PATH.equals(req.getServletPath()) && IGNORE_LINK.equals(req.getPathInfo())) {
        if (debug)
            logger.debug("SSO is by-passed for external invitation link.");
        chain.doFilter(sreq, sresp);
        return;
    }

    if (debug)
        logger.debug("Processing request " + req.getRequestURI() + " SID:" + session.getId());

    // Login page or login submission
    String pathInfo;
    if (PAGE_SERVLET_PATH.equals(req.getServletPath())
            && (LOGIN_PATH_INFORMATION.equals(pathInfo = req.getPathInfo())
                    || pathInfo == null && LOGIN_PARAMETER.equals(req.getParameter("pt")))) {
        if (debug)
            logger.debug("Login page requested, chaining ...");

        // Chain to the next filter
        chain.doFilter(sreq, sresp);
        return;
    }

    // initialize a new request context
    RequestContext context = null;
    try {
        // perform a "silent" init - i.e. no user creation or remote connections
        context = RequestContextUtil.initRequestContext(getApplicationContext(), req, true);
    } catch (Exception ex) {
        logger.error("Error calling initRequestContext", ex);
        throw new ServletException(ex);
    }

    // get the page from the model if any - it may not require authentication
    Page page = context.getPage();
    if (page != null && page.getAuthentication() == RequiredAuthentication.none) {
        if (logger.isDebugEnabled())
            logger.debug("Unauthenticated page requested - skipping auth filter...");
        chain.doFilter(sreq, sresp);
        return;
    }

    // If userHeader (X-Alfresco-Remote-User or similar) external auth - does not require a challenge/response
    if (this.userHeader != null) {
        String userId = AuthenticationUtil.getUserId(req);
        if (userId != null && req.getRemoteUser() != null) {
            if (logger.isDebugEnabled())
                logger.debug("userHeader external auth - skipping auth filter...");
            setExternalAuthSession(session);
            onSuccess(req, res, session, req.getRemoteUser());
            chain.doFilter(sreq, sresp);
            return;
        } else {
            // initial external user login requires a ping check to authenticate remote Session
            challengeOrPassThrough(chain, req, res, session);
            return;
        }
    }

    // Check if there is an authorization header with a challenge response
    String authHdr = req.getHeader(HEADER_AUTHORIZATION);

    // We are not passing on a challenge response and we have sufficient client session information
    if (authHdr == null && AuthenticationUtil.isAuthenticated(req)) {
        if (debug)
            logger.debug("Touching the repo to ensure we still have an authenticated session.");
        challengeOrPassThrough(chain, req, res, session);
        return;
    }

    // Check the authorization header
    if (authHdr == null) {
        if (debug)
            logger.debug("New auth request from " + req.getRemoteHost() + " (" + req.getRemoteAddr() + ":"
                    + req.getRemotePort() + ")");
        challengeOrPassThrough(chain, req, res, session);
        return;
    }
    // SPNEGO / Kerberos authentication
    else if (authHdr.startsWith(AUTH_SPNEGO) && this.krbRealm != null) {
        if (debug)
            logger.debug("Processing SPNEGO / Kerberos authentication.");
        // Decode the received SPNEGO blob and validate

        final byte[] spnegoByts = Base64.decode(authHdr.substring(10).getBytes());

        // Check if the client sent an NTLMSSP blob

        if (isNTLMSSPBlob(spnegoByts, 0)) {
            if (logger.isDebugEnabled())
                logger.debug("Client sent an NTLMSSP security blob");

            // Restart the authentication

            restartAuthProcess(session, req, res, AUTH_SPNEGO);
            return;
        }

        //  Check the received SPNEGO token type

        int tokType = -1;

        try {
            tokType = SPNEGO.checkTokenType(spnegoByts, 0, spnegoByts.length);
        } catch (IOException ex) {
        }

        // Check for a NegTokenInit blob

        if (tokType == SPNEGO.NegTokenInit) {
            if (debug)
                logger.debug("Parsing the SPNEGO security blob to get the Kerberos ticket.");

            NegTokenInit negToken = new NegTokenInit();

            try {
                // Decode the security blob

                negToken.decode(spnegoByts, 0, spnegoByts.length);

                //  Determine the authentication mechanism the client is using and logon

                String oidStr = null;
                if (negToken.numberOfOids() > 0)
                    oidStr = negToken.getOidAt(0).toString();

                if (oidStr != null && (oidStr.equals(OID.ID_MSKERBEROS5) || oidStr.equals(OID.ID_KERBEROS5))) {
                    if (debug)
                        logger.debug("Kerberos logon.");
                    //  Kerberos logon

                    if (doKerberosLogon(negToken, req, res, session) != null) {
                        // Allow the user to access the requested page

                        chain.doFilter(req, res);
                        if (logger.isDebugEnabled())
                            logger.debug("Request processing ended");
                    } else {
                        // Send back a request for SPNEGO authentication

                        restartAuthProcess(session, req, res, AUTH_SPNEGO);
                    }
                } else {
                    //  Unsupported mechanism, e.g. NegoEx

                    if (logger.isDebugEnabled())
                        logger.debug("Unsupported SPNEGO mechanism " + oidStr);

                    // Try again!

                    restartAuthProcess(session, req, res, AUTH_SPNEGO);
                }
            } catch (IOException ex) {
                // Log the error

                if (logger.isDebugEnabled())
                    logger.debug(ex);
            }
        } else {
            //  Unknown SPNEGO token type

            if (logger.isDebugEnabled())
                logger.debug("Unknown SPNEGO token type");

            // Send back a request for SPNEGO authentication

            restartAuthProcess(session, req, res, AUTH_SPNEGO);
        }
    }
    // NTLM authentication
    else if (authHdr.startsWith(AUTH_NTLM)) {
        if (debug)
            logger.debug("Processing NTLM authentication.");
        // Decode the received NTLM blob and validate
        final byte[] authHdrByts = authHdr.substring(5).getBytes();
        final byte[] ntlmByts = Base64.decode(authHdrByts);
        int ntlmTyp = NTLMMessage.isNTLMType(ntlmByts);
        Object sessionMutex = WebUtils.getSessionMutex(session);

        if (ntlmTyp == NTLM.Type1) {
            if (debug)
                logger.debug("Process the type 1 NTLM message.");
            Type1NTLMMessage type1Msg = new Type1NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                processType1(type1Msg, req, res, session);
            }
        } else if (ntlmTyp == NTLM.Type3) {
            if (debug)
                logger.debug("Process the type 3 NTLM message.");
            Type3NTLMMessage type3Msg = new Type3NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                processType3(type3Msg, req, res, session, chain);
            }
        } else {
            if (debug)
                logger.debug("NTLM not handled, redirecting to login page");

            redirectToLoginPage(req, res);
        }
    }
    // Possibly basic auth - allow through
    else {
        if (debug)
            logger.debug("Processing Basic Authentication.");
        // ACE-3257 fix, it looks like basic auth header was sent.
        // However lets check for presence of remote_user CGI variable in AJP.
        // If remote user is not null then it most likely that apache proxy with mod_auth_basic module is used
        if (AuthenticationUtil.isAuthenticated(req) || req.getRemoteUser() != null) {
            if (debug)
                logger.debug("Ensuring the session is still valid.");
            challengeOrPassThrough(chain, req, res, session);
        } else {
            if (debug)
                logger.debug("Establish a new session or bring up the login page.");
            chain.doFilter(req, res);
        }
    }
}

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;/*from  w  ww .jav  a 2 s. c  om*/
    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);
    }

}