Example usage for javax.servlet.http Cookie setPath

List of usage examples for javax.servlet.http Cookie setPath

Introduction

In this page you can find the example usage for javax.servlet.http Cookie setPath.

Prototype

public void setPath(String uri) 

Source Link

Document

Specifies a path for the cookie to which the client should return the cookie.

Usage

From source file:org.jboss.web.loadbalancer.Loadbalancer.java

protected HttpClient prepareServerRequest(HttpServletRequest request, HttpServletResponse response,
        HttpMethod method) {/*from   ww w.ja  v a 2s  .c  o m*/
    // clear state
    HttpClient client = new HttpClient(connectionManager);
    client.setStrictMode(false);
    client.setTimeout(connectionTimeout);
    method.setFollowRedirects(false);
    method.setDoAuthentication(false);
    client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY);

    Enumeration reqHeaders = request.getHeaderNames();

    while (reqHeaders.hasMoreElements()) {
        String headerName = (String) reqHeaders.nextElement();
        String headerValue = request.getHeader(headerName);

        if (!ignorableHeader.contains(headerName.toLowerCase())) {
            method.setRequestHeader(headerName, headerValue);
        }
    }

    //Cookies
    Cookie[] cookies = request.getCookies();
    HttpState state = client.getState();

    for (int i = 0; cookies != null && i < cookies.length; ++i) {
        Cookie cookie = cookies[i];

        org.apache.commons.httpclient.Cookie reqCookie = new org.apache.commons.httpclient.Cookie();

        reqCookie.setName(cookie.getName());
        reqCookie.setValue(cookie.getValue());

        if (cookie.getPath() != null) {
            reqCookie.setPath(cookie.getPath());
        } else {
            reqCookie.setPath("/");
        }

        reqCookie.setSecure(cookie.getSecure());

        reqCookie.setDomain(method.getHostConfiguration().getHost());
        state.addCookie(reqCookie);
    }
    return client;
}

From source file:csns.web.filter.DepartmentFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    String contextPath = request.getContextPath();
    String path = request.getRequestURI().substring(contextPath.length());
    Cookie cookie = WebUtils.getCookie(request, "default-dept");

    if (path.startsWith("/department/")) {
        int beginIndex = "/department/".length();
        int endIndex = path.indexOf("/", beginIndex);
        if (endIndex < 0)
            endIndex = path.length();//from   ww  w .  j  av a  2s.c o  m
        String dept = path.substring(beginIndex, endIndex);
        request.setAttribute("dept", dept);

        logger.debug(path + " -> " + dept);

        if (cookie == null) {
            cookie = new Cookie("default-dept", dept);
            cookie.setPath("/");
            cookie.setMaxAge(100000000);
            response.addCookie(cookie);
        }
    } else {
        if (cookie != null)
            request.setAttribute("dept", cookie.getValue());
    }

    filterChain.doFilter(request, response);
}

From source file:org.nuxeo.ecm.platform.ui.web.auth.cas2.Cas2Authenticator.java

protected void removeCookie(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Cookie cookie) {
    log.debug(String.format("Removing cookie %s.", cookie.getName()));
    cookie.setMaxAge(0);/*from w w  w . ja v a2 s . c om*/
    cookie.setValue("");
    cookie.setPath(httpRequest.getContextPath());
    httpResponse.addCookie(cookie);
}

From source file:org.loklak.api.cms.LoginService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JSONObjectWithDefault permissions) throws APIException {

    // login check for app
    if (post.get("checkLogin", false)) {
        JSONObject result = new JSONObject();
        if (authorization.getIdentity().isEmail()) {
            result.put("loggedIn", true);
            result.put("message", "You are logged in as " + authorization.getIdentity().getName());
        } else {//from w  w w  . jav a  2  s . c o m
            result.put("loggedIn", false);
            result.put("message", "Not logged in");
        }
        return result;
    }

    // do logout if requested
    if (post.get("logout", false)) { // logout if requested

        // invalidate session
        post.getRequest().getSession().invalidate();

        // delete cookie if set
        deleteLoginCookie(response);

        JSONObject result = new JSONObject();
        result.put("message", "Logout successful");
        return result;
    }

    // check login type by checking which parameters are set
    boolean passwordLogin = false;
    boolean pubkeyHello = false;
    boolean pubkeyLogin = false;

    if (post.get("login", null) != null && post.get("password", null) != null
            && post.get("type", null) != null) {
        passwordLogin = true;
    } else if (post.get("login", null) != null && post.get("keyhash", null) != null) {
        pubkeyHello = true;
    } else if (post.get("sessionID", null) != null && post.get("response", null) != null) {
        pubkeyLogin = true;
    } else {
        throw new APIException(400, "Bad login parameters.");
    }

    // check if user is blocked because of too many invalid login attempts
    checkInvalidLogins(post, authorization, permissions);

    if (passwordLogin) { // do login via password

        String login = post.get("login", null);
        String password = post.get("password", null);
        String type = post.get("type", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.passwd_login, login));
        ClientIdentity identity = authentication.getIdentity();

        // check if the password is valid
        String passwordHash;
        String salt;
        try {
            passwordHash = authentication.getString("passwordHash");
            salt = authentication.getString("salt");
        } catch (Throwable e) {
            Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: "
                    + post.getClientHost() + " : password or salt missing in database");
            throw new APIException(422, "Invalid credentials");
        }

        if (!passwordHash.equals(getHash(password, salt))) {

            // save invalid login in accounting object
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");

            Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: "
                    + post.getClientHost());
            throw new APIException(422, "Invalid credentials");
        }

        JSONObject result = new JSONObject();

        switch (type) {
        case "session": // create a browser session
            post.getRequest().getSession().setAttribute("identity", identity);
            break;
        case "cookie": // set a long living cookie
            // create random string as token
            String loginToken = createRandomString(30);

            // create cookie
            Cookie loginCookie = new Cookie("login", loginToken);
            loginCookie.setPath("/");
            loginCookie.setMaxAge(defaultCookieTime.intValue());

            // write cookie to database
            ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken);
            JSONObject user_obj = new JSONObject();
            user_obj.put("id", identity.toString());
            user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime);
            DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent());

            response.addCookie(loginCookie);
            break;
        case "access-token": // create and display an access token

            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);

            break;
        default:
            throw new APIException(400, "Invalid type");
        }

        Log.getLog().info(
                "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost());

        result.put("message", "You are logged in as " + identity.getName());
        return result;
    } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge

        String login = post.get("login", null);
        String keyHash = post.get("keyhash", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.passwd_login, login));
        ClientIdentity identity = authentication.getIdentity();

        if (!DAO.login_keys.has(identity.toString())
                || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash))
            throw new APIException(400, "Unknown key");

        String challengeString = createRandomString(30);
        String newSessionID = createRandomString(30);

        ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange,
                newSessionID);
        Authentication challenge_auth = new Authentication(credential, DAO.authentication);
        challenge_auth.setIdentity(identity);
        challenge_auth.put("activated", true);

        challenge_auth.put("challenge", challengeString);
        challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash));
        challenge_auth.setExpireTime(60 * 10);

        JSONObject result = new JSONObject();
        result.put("challenge", challengeString);
        result.put("sessionID", newSessionID);
        result.put("message",
                "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID");
        return result;
    } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid

        String sessionID = post.get("sessionID", null);
        String challangeResponse = post.get("response", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID));
        ClientIdentity identity = authentication.getIdentity();

        String challenge = authentication.getString("challenge");
        PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA");

        Signature sig;
        boolean verified;
        try {
            sig = Signature.getInstance("SHA256withRSA");
            sig.initVerify(key);
            sig.update(challenge.getBytes());
            verified = sig.verify(Base64.getDecoder().decode(challangeResponse));
        } catch (NoSuchAlgorithmException e) {
            throw new APIException(400, "No such algorithm");
        } catch (InvalidKeyException e) {
            throw new APIException(400, "Invalid key");
        } catch (Throwable e) {
            throw new APIException(400, "Bad signature");
        }

        if (verified) {
            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            JSONObject result = new JSONObject();

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);
            return result;
        } else {
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");
            throw new APIException(400, "Bad Signature");
        }
    }
    throw new APIException(500, "Server error");
}

From source file:com.xwiki.authentication.ntlm.NTLMAuthServiceImpl.java

public XWikiUser checkAuth(XWikiContext context) throws XWikiException {
    Cookie cookie;//from   w  w  w.j av a  2s  . com

    LOG.debug("checkAuth");

    LOG.debug("Action: " + context.getAction());
    if (context.getAction().startsWith("logout")) {
        cookie = getCookie("XWIKINTLMAUTHINFO", context);
        if (cookie != null) {
            cookie.setMaxAge(0);
            context.getResponse().addCookie(cookie);
        }

        return null;
    }

    Principal principal = null;

    Cookie[] cookies = context.getRequest().getCookies();
    if (cookies != null) {
        for (Cookie c : cookies) {
            LOG.debug("CookieList: " + c.getName() + " => " + c.getValue());
        }
    }

    cookie = getCookie("XWIKINTLMAUTHINFO", context);
    if (cookie != null) {
        LOG.debug("Found Cookie");
        String uname = decryptText(cookie.getValue(), context);
        if (uname != null) {
            principal = new SimplePrincipal(uname);
        }
    }

    String msg = context.getRequest().getHeader("Authorization");
    if (msg != null) {
        LOG.debug("Found NTLM Auth Cookie, this could be an IE6 bug (#831167)");
        if (msg.startsWith("NTLM ")) {
            LOG.debug("Removing principal because of NTLM header");
            principal = null;
        }
    }

    XWikiUser user;

    // Authenticate
    if (principal == null) {
        principal = authenticate(null, null, context);
        if (principal == null) {
            LOG.debug("Can't get principal");
            return null;
        }

        LOG.debug("Saving auth cookie");
        String encuname = encryptText(principal.getName().contains(":") ? principal.getName()
                : context.getDatabase() + ":" + principal.getName(), context);
        Cookie usernameCookie = new Cookie("XWIKINTLMAUTHINFO", encuname);
        usernameCookie.setMaxAge(-1);
        usernameCookie.setPath("/");
        context.getResponse().addCookie(usernameCookie);

        user = new XWikiUser(principal.getName());
    } else {
        user = new XWikiUser(principal.getName().startsWith(context.getDatabase())
                ? principal.getName().substring(context.getDatabase().length() + 1)
                : principal.getName());
    }

    LOG.debug("XWikiUser=" + user);

    return user;
}

From source file:fr.paris.lutece.plugins.mylutece.modules.openam.service.OpenamService.java

/**
 * set a paris connect cokkie in the HttpServletResponse
 *
 * @param strPCUID//from  ww w .  j av a2s.co m
 *            the user PCUID
 * @param response
 *            The HTTP response
 */
public void setConnectionCookie(String strPCUID, HttpServletResponse response) {
    // set a connexion cookie to let the user access other PC Services
    // without sign in
    Cookie openamCookie = new Cookie(COOKIE_OPENAM_NAME, strPCUID);
    openamCookie.setDomain(COOKIE_OPENAM_DOMAIN);
    openamCookie.setSecure(COOKIE_OPENAM_SECURE);
    openamCookie.setMaxAge(COOKIE_OPENAM_MAX_AGE);
    openamCookie.setPath(COOKIE_OPENAM_PATH);

    response.addCookie(openamCookie);
}

From source file:org.kuali.mobility.shared.interceptors.NativeCookieInterceptor.java

/**
 * Attempts tp check if the device is running natively and sets the native cookie
 *
 * @param request//from w ww .j  a v a2 s .co m
 * @param phonegap
 * @return
 */
private boolean checkNative(HttpServletRequest request, HttpServletResponse response, String phonegap) {
    String nativeParam = request.getParameter("native");
    String nativeCookie = findCookie(request.getCookies(), COOKIE_NATIVE);
    boolean isNative = false;
    if (!StringUtils.isEmpty(nativeParam)) {
        isNative = "yes".equalsIgnoreCase(nativeParam);
    }
    // If there is a phonegap version, it must be native
    else if (!StringUtils.isEmpty(phonegap)) {
        isNative = true;
    }
    // Use the previous cookie value
    else if (!StringUtils.isEmpty(nativeCookie)) {
        isNative = "yes".equalsIgnoreCase(nativeCookie);
    }

    /*
     *  If detected a native setting, but there was no phonegap version, we have to 
     *  assume something is wrong and not enable nativeness
     */
    if (isNative && StringUtils.isEmpty(phonegap)) {
        LOG.info(
                "We detected a native user, but has no reference to a phonegap version - disabling nativeness");
        isNative = false;
    }

    // If there is a cordova version, it must be native
    boolean useSecureCookies = Boolean
            .parseBoolean(getKmeProperties().getProperty("kme.secure.cookie", "false"));
    Cookie cookie = new Cookie(COOKIE_NATIVE, (isNative ? "yes" : "no"));
    int cookieMaxAge = Integer.parseInt(getKmeProperties().getProperty("cookie.max.age", "3600"));
    cookie.setMaxAge(cookieMaxAge); // default one hour, should implement in kme.config properties.
    cookie.setPath(request.getContextPath());
    cookie.setSecure(useSecureCookies);
    response.addCookie(cookie);
    LOG.debug("Setting native cookie : " + isNative);

    request.getSession().setAttribute(SESSION_NATIVE, isNative);
    return isNative;
}

From source file:com.google.gsa.valve.modules.ldap.LDAPUniqueCreds.java

/**
 * Sets the LDAP authentication cookie//from ww w  . j  a  v  a 2  s. com
 * 
 * @return the LDAP authentication cookie
 */
public Cookie settingCookie() {
    // Instantiate a new cookie
    Cookie extAuthCookie = new Cookie("gsa_ad_auth", "true");
    String authCookieDomain = null;
    String authCookiePath = null;

    // Cache cookie properties
    authCookieDomain = valveConf.getAuthCookieDomain();
    authCookiePath = valveConf.getAuthCookiePath();

    // Set extra cookie parameters
    extAuthCookie.setDomain(authCookieDomain);
    extAuthCookie.setPath(authCookiePath);
    extAuthCookie.setMaxAge(authMaxAge);

    // Log info
    logger.debug("Adding cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":"
            + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure());

    return extAuthCookie;
}

From source file:org.loklak.api.aaa.LoginService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JSONObjectWithDefault permissions) throws APIException {

    // login check for app
    if (post.get("checkLogin", false)) {
        JSONObject result = new JSONObject();
        if (authorization.getIdentity().isEmail()) {
            result.put("loggedIn", true);
            result.put("message", "You are logged in as " + authorization.getIdentity().getName());
        } else {//w  w w  .  jav a  2  s .  c  om
            result.put("loggedIn", false);
            result.put("message", "Not logged in");
        }
        return result;
    }

    // do logout if requested
    boolean logout = post.get("logout", false);
    boolean delete = post.get("delete", false);
    if (logout || delete) { // logout if requested

        // invalidate session
        post.getRequest().getSession().invalidate();

        // delete cookie if set
        deleteLoginCookie(response);

        if (delete) {
            ClientCredential pwcredential = new ClientCredential(authorization.getIdentity());
            delete = DAO.authentication.has(pwcredential.toString());
            if (delete)
                DAO.authentication.remove(pwcredential.toString());
        }

        JSONObject result = new JSONObject();
        result.put("message", delete ? "Account deletion successful" : "Logout successful");
        return result;
    }

    // check login type by checking which parameters are set
    boolean passwordLogin = false;
    boolean pubkeyHello = false;
    boolean pubkeyLogin = false;

    if (post.get("login", null) != null && post.get("password", null) != null
            && post.get("type", null) != null) {
        passwordLogin = true;
    } else if (post.get("login", null) != null && post.get("keyhash", null) != null) {
        pubkeyHello = true;
    } else if (post.get("sessionID", null) != null && post.get("response", null) != null) {
        pubkeyLogin = true;
    } else {
        throw new APIException(400, "Bad login parameters.");
    }

    // check if user is blocked because of too many invalid login attempts
    checkInvalidLogins(post, authorization, permissions);

    if (passwordLogin) { // do login via password

        String login = post.get("login", null);
        String password = post.get("password", null);
        String type = post.get("type", null);
        ClientCredential pwcredential = new ClientCredential(ClientCredential.Type.passwd_login, login);
        Authentication authentication = getAuthentication(post, authorization, pwcredential);
        ClientIdentity identity = authentication.getIdentity();

        // check if the password is valid
        String passwordHash;
        String salt;
        try {
            passwordHash = authentication.getString("passwordHash");
            salt = authentication.getString("salt");
        } catch (Throwable e) {
            Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: "
                    + post.getClientHost() + " : password or salt missing in database");
            throw new APIException(422, "Invalid credentials");
        }

        if (!passwordHash.equals(getHash(password, salt))) {

            // save invalid login in accounting object
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");

            Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: "
                    + post.getClientHost());
            throw new APIException(422, "Invalid credentials");
        }

        JSONObject result = new JSONObject();

        switch (type) {
        case "session": // create a browser session
            post.getRequest().getSession().setAttribute("identity", identity);
            break;
        case "cookie": // set a long living cookie
            // create random string as token
            String loginToken = createRandomString(30);

            // create cookie
            Cookie loginCookie = new Cookie("login", loginToken);
            loginCookie.setPath("/");
            loginCookie.setMaxAge(defaultCookieTime.intValue());

            // write cookie to database
            ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken);
            JSONObject user_obj = new JSONObject();
            user_obj.put("id", identity.toString());
            user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime);
            DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent());

            response.addCookie(loginCookie);
            break;
        case "access-token": // create and display an access token

            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);

            break;
        default:
            throw new APIException(400, "Invalid type");
        }

        Log.getLog().info(
                "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost());

        result.put("message", "You are logged in as " + identity.getName());
        return result;
    } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge

        String login = post.get("login", null);
        String keyHash = post.get("keyhash", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.passwd_login, login));
        ClientIdentity identity = authentication.getIdentity();

        if (!DAO.login_keys.has(identity.toString())
                || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash))
            throw new APIException(400, "Unknown key");

        String challengeString = createRandomString(30);
        String newSessionID = createRandomString(30);

        ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange,
                newSessionID);
        Authentication challenge_auth = new Authentication(credential, DAO.authentication);
        challenge_auth.setIdentity(identity);
        challenge_auth.put("activated", true);

        challenge_auth.put("challenge", challengeString);
        challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash));
        challenge_auth.setExpireTime(60 * 10);

        JSONObject result = new JSONObject();
        result.put("challenge", challengeString);
        result.put("sessionID", newSessionID);
        result.put("message",
                "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID");
        return result;
    } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid

        String sessionID = post.get("sessionID", null);
        String challangeResponse = post.get("response", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID));
        ClientIdentity identity = authentication.getIdentity();

        String challenge = authentication.getString("challenge");
        PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA");

        Signature sig;
        boolean verified;
        try {
            sig = Signature.getInstance("SHA256withRSA");
            sig.initVerify(key);
            sig.update(challenge.getBytes());
            verified = sig.verify(Base64.getDecoder().decode(challangeResponse));
        } catch (NoSuchAlgorithmException e) {
            throw new APIException(400, "No such algorithm");
        } catch (InvalidKeyException e) {
            throw new APIException(400, "Invalid key");
        } catch (Throwable e) {
            throw new APIException(400, "Bad signature");
        }

        if (verified) {
            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            JSONObject result = new JSONObject();

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);
            return result;
        } else {
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");
            throw new APIException(400, "Bad Signature");
        }
    }
    throw new APIException(500, "Server error");
}

From source file:ai.susi.server.api.aaa.LoginService.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization,
        final JsonObjectWithDefault permissions) throws APIException {

    // login check for app
    if (post.get("checkLogin", false)) {
        JSONObject result = new JSONObject();
        if (authorization.getIdentity().isEmail()) {
            result.put("loggedIn", true);
            result.put("message", "You are logged in as " + authorization.getIdentity().getName());
        } else {// w ww  . j av  a  2s . c o  m
            result.put("loggedIn", false);
            result.put("message", "Not logged in");
        }
        return result;
    }

    // do logout if requested
    boolean logout = post.get("logout", false);
    boolean delete = post.get("delete", false);
    if (logout || delete) { // logout if requested

        // invalidate session
        post.getRequest().getSession().invalidate();

        // delete cookie if set
        deleteLoginCookie(response);

        if (delete) {
            ClientCredential pwcredential = new ClientCredential(authorization.getIdentity());
            delete = DAO.authentication.has(pwcredential.toString());
            if (delete)
                DAO.authentication.remove(pwcredential.toString());
        }

        JSONObject result = new JSONObject();
        result.put("message", delete ? "Account deletion successful" : "Logout successful");
        return result;
    }

    // check login type by checking which parameters are set
    boolean passwordLogin = false;
    boolean pubkeyHello = false;
    boolean pubkeyLogin = false;

    if (post.get("login", null) != null && post.get("password", null) != null
            && post.get("type", null) != null) {
        passwordLogin = true;
    } else if (post.get("login", null) != null && post.get("keyhash", null) != null) {
        pubkeyHello = true;
    } else if (post.get("sessionID", null) != null && post.get("response", null) != null) {
        pubkeyLogin = true;
    } else {
        throw new APIException(400, "Bad login parameters.");
    }

    // check if user is blocked because of too many invalid login attempts
    checkInvalidLogins(post, authorization, permissions);

    if (passwordLogin) { // do login via password

        String login = post.get("login", null);
        String password = post.get("password", null);
        String type = post.get("type", null);
        ClientCredential pwcredential = new ClientCredential(ClientCredential.Type.passwd_login, login);
        Authentication authentication = getAuthentication(post, authorization, pwcredential);
        ClientIdentity identity = authentication.getIdentity();

        // check if the password is valid
        String passwordHash;
        String salt;
        try {
            passwordHash = authentication.getString("passwordHash");
            salt = authentication.getString("salt");
        } catch (Throwable e) {
            Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: "
                    + post.getClientHost() + " : password or salt missing in database");
            throw new APIException(422, "Invalid credentials");
        }

        if (!passwordHash.equals(getHash(password, salt))) {

            // save invalid login in accounting object
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");

            Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: "
                    + post.getClientHost());
            throw new APIException(422, "Invalid credentials");
        }

        JSONObject result = new JSONObject();

        switch (type) {
        case "session": // create a browser session
            post.getRequest().getSession().setAttribute("identity", identity);
            break;
        case "cookie": // set a long living cookie
            // create random string as token
            String loginToken = createRandomString(30);

            // create cookie
            Cookie loginCookie = new Cookie("login", loginToken);
            loginCookie.setPath("/");
            loginCookie.setMaxAge(defaultCookieTime.intValue());

            // write cookie to database
            ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken);
            JSONObject user_obj = new JSONObject();
            user_obj.put("id", identity.toString());
            user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime);
            DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent());

            response.addCookie(loginCookie);
            break;
        case "access-token": // create and display an access token

            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);

            break;
        default:
            throw new APIException(400, "Invalid type");
        }

        Log.getLog().info(
                "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost());

        result.put("message", "You are logged in as " + identity.getName());
        return result;
    } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge

        String login = post.get("login", null);
        String keyHash = post.get("keyhash", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.passwd_login, login));
        ClientIdentity identity = authentication.getIdentity();

        if (!DAO.login_keys.has(identity.toString())
                || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash))
            throw new APIException(400, "Unknown key");

        String challengeString = createRandomString(30);
        String newSessionID = createRandomString(30);

        ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange,
                newSessionID);
        Authentication challenge_auth = new Authentication(credential, DAO.authentication);
        challenge_auth.setIdentity(identity);
        challenge_auth.put("activated", true);

        challenge_auth.put("challenge", challengeString);
        challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash));
        challenge_auth.setExpireTime(60 * 10);

        JSONObject result = new JSONObject();
        result.put("challenge", challengeString);
        result.put("sessionID", newSessionID);
        result.put("message",
                "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID");
        return result;
    } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid

        String sessionID = post.get("sessionID", null);
        String challangeResponse = post.get("response", null);

        Authentication authentication = getAuthentication(post, authorization,
                new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID));
        ClientIdentity identity = authentication.getIdentity();

        String challenge = authentication.getString("challenge");
        PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA");

        Signature sig;
        boolean verified;
        try {
            sig = Signature.getInstance("SHA256withRSA");
            sig.initVerify(key);
            sig.update(challenge.getBytes());
            verified = sig.verify(Base64.getDecoder().decode(challangeResponse));
        } catch (NoSuchAlgorithmException e) {
            throw new APIException(400, "No such algorithm");
        } catch (InvalidKeyException e) {
            throw new APIException(400, "Invalid key");
        } catch (Throwable e) {
            throw new APIException(400, "Bad signature");
        }

        if (verified) {
            long valid_seconds;
            try {
                valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime);
            } catch (Throwable e) {
                throw new APIException(400, "Invalid value for 'valid_seconds'");
            }

            String token = createAccessToken(identity, valid_seconds);

            JSONObject result = new JSONObject();

            if (valid_seconds == -1)
                result.put("valid_seconds", "forever");
            else
                result.put("valid_seconds", valid_seconds);

            result.put("access_token", token);
            return result;
        } else {
            authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login");
            throw new APIException(400, "Bad Signature");
        }
    }
    throw new APIException(500, "Server error");
}