Example usage for org.apache.shiro.authc.credential HashingPasswordService passwordsMatch

List of usage examples for org.apache.shiro.authc.credential HashingPasswordService passwordsMatch

Introduction

In this page you can find the example usage for org.apache.shiro.authc.credential HashingPasswordService passwordsMatch.

Prototype

boolean passwordsMatch(Object plaintext, Hash savedPasswordHash);

Source Link

Document

Returns true if the submittedPlaintext password matches the existing savedPasswordHash , false otherwise.

Usage

From source file:br.com.criativasoft.opendevice.wsrest.resource.AuthRest.java

License:Open Source License

private Response doLogin(Subject currentUser, String username, String password, boolean isApiKey) {

    LOG.debug("Using ApiKey (" + isApiKey + "), username : " + username);

    Account account = null;//from   w w w.  java  2 s .  c om
    String authtoken = null;
    boolean logged = false;

    // Login using: ApiKey
    if (isApiKey) {

        account = accountDao.getAccountByApiKey(username);

        // Generate and cache the 'AuthToken', this will be used in AuthenticationFilter
        // This token will be used in BearerTokenRealm
        // TODO: Need configure expire using EhCache
        if (account != null) {

            // NOTE(RR): To simplify the development of clients, AuthToken and API Key will be the AccountUUID.
            // This can be changed in the future (issues #57)
            // authtoken = UUID.randomUUID().toString();
            authtoken = account.getUuid();

            // Add token to cache (thid will be used in BearerTokenRealm)
            DefaultSecurityManager securityManager = (DefaultSecurityManager) SecurityUtils
                    .getSecurityManager();
            Cache<Object, Object> cache = securityManager.getCacheManager().getCache(TOKEN_CACHE);
            cache.put(authtoken, username); // username (is Api_Key in this case)
            logged = true;
        }

        // login using: Form
    } else if (!currentUser.isAuthenticated()) {

        try {

            User user = userDao.getUser(username);

            if (user == null)
                throw new AuthenticationException("Incorrect username");

            // ckeck plain version (loaded from database)
            boolean passwordsMatch = password.equals(user.getPassword());

            // Check encryption version (provided by user)
            if (!passwordsMatch) {
                HashingPasswordService service = new DefaultPasswordService();
                passwordsMatch = service.passwordsMatch(password, user.getPassword());
            }

            if (!passwordsMatch)
                throw new AuthenticationException("Incorrect password");

            Set<UserAccount> uaccounts = user.getAccounts();

            // Filter normal accounts
            uaccounts = uaccounts.stream().filter(accountx -> accountx.getType() != AccountType.DEVICE)
                    .collect(Collectors.toSet());

            if (uaccounts.isEmpty())
                throw new AuthenticationException("No accounts for user");

            if (uaccounts.size() > 1) {
                // TODO: Need return list and redirect to annother page...
                return ErrorResponse.status(Status.FORBIDDEN,
                        "Multiple Accounts not supported for now !! (open ticket !)");
            }

            AccountAuth token = new AccountAuth(uaccounts.iterator().next().getId(), user.getId());
            //token.setRememberMe(false); // to be remembered across sessions

            currentUser.login(token);

            // currentUser.getSession(true).setTimeout(xxxxx);

            if (currentUser.isAuthenticated()) {
                AccountPrincipal principal = (AccountPrincipal) currentUser.getPrincipal();
                logged = true;
                authtoken = principal.getAccountUUID();
                user.setLastLogin(new Date());
            }

        } catch (UnknownAccountException e) {
            return ErrorResponse.UNAUTHORIZED("Unknown Account");
        } catch (IncorrectCredentialsException e) {
            return ErrorResponse.status(Status.FORBIDDEN, "Incorrect Credentials");
        } catch (AuthenticationException e) {
            return ErrorResponse.UNAUTHORIZED(e.getMessage());
        }
    }

    if (logged) {
        return noCache(Response.status(Status.OK).entity("{\"token\":\"" + authtoken + "\"}"));
    } else {
        return ErrorResponse.UNAUTHORIZED("Authentication Fail");
    }

}