Example usage for org.springframework.security.authentication AccountExpiredException AccountExpiredException

List of usage examples for org.springframework.security.authentication AccountExpiredException AccountExpiredException

Introduction

In this page you can find the example usage for org.springframework.security.authentication AccountExpiredException AccountExpiredException.

Prototype

public AccountExpiredException(String msg) 

Source Link

Document

Constructs a AccountExpiredException with the specified message.

Usage

From source file:grails.plugin.springsecurity.userdetails.DefaultPreAuthenticationChecks.java

public void check(UserDetails user) {
    if (!user.isAccountNonLocked()) {
        log.debug("User account is locked");

        throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked",
                "User account is locked"));
    }//from   ww  w .  j a  v a2 s  .co m

    if (!user.isEnabled()) {
        log.debug("User account is disabled");

        throw new DisabledException(
                messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"));
    }

    if (!user.isAccountNonExpired()) {
        log.debug("User account is expired");

        throw new AccountExpiredException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"));
    }
}

From source file:cn.net.withub.demo.bootsec.hello.security.CustomAuthenticationProvider.java

@Transactional
@Override/*w  w w  .  j  a  va  2s  .  c  o m*/
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String username = token.getName(); //???
    //?
    UserDetails userDetails = null;
    if (username != null) {
        userDetails = userDetailsService.loadUserByUsername(username);
    }

    if (userDetails == null) {
        return null;//null??
        //throw new UsernameNotFoundException("??/?");
    } else if (!userDetails.isEnabled()) {
        throw new DisabledException("?");
    } else if (!userDetails.isAccountNonExpired()) {
        throw new AccountExpiredException("?");
    } else if (!userDetails.isAccountNonLocked()) {
        throw new LockedException("??");
    } else if (!userDetails.isCredentialsNonExpired()) {
        throw new LockedException("?");
    }

    //??
    String encPass = userDetails.getPassword();

    //authentication?credentials
    if (!md5PasswordEncoder.isPasswordValid(encPass, token.getCredentials().toString(), null)) {
        throw new BadCredentialsException("Invalid username/password");
    }

    //?
    return new UsernamePasswordAuthenticationToken(userDetails, encPass, userDetails.getAuthorities());
}

From source file:org.xaloon.wicket.security.spring.SpringUserDetailsService.java

private UserDetails createAdaptor(org.xaloon.core.api.security.model.UserDetails userDetails) {
    if (!userDetails.isEnabled()) {
        throw new DisabledException(SecurityFacade.ACCOUNT_DISABLED);
    }/*from  ww w. j a v a  2 s .c o  m*/
    if (!userDetails.isAccountNonExpired()) {
        throw new AccountExpiredException(SecurityFacade.ACCOUNT_EXPIRED);
    }
    if (!userDetails.isAccountNonLocked()) {
        throw new LockedException(SecurityFacade.ACCOUNT_LOCKED);
    }
    if (!userDetails.isCredentialsNonExpired()) {
        throw new CredentialsExpiredException(SecurityFacade.CREDENTIALS_EXPIRED);
    }

    DefaultUserDetails details = new DefaultUserDetails();
    details.setAccountNonExpired(userDetails.isAccountNonExpired());
    details.setAccountNonLocked(userDetails.isAccountNonLocked());
    details.setCredentialsNonExpired(userDetails.isCredentialsNonExpired());
    details.setEnabled(userDetails.isEnabled());
    details.setPassword(userDetails.getPassword());
    details.setUsername(userDetails.getUsername());

    List<Authority> authorities = loginService.getIndirectAuthoritiesForUsername(userDetails.getUsername());
    if (!authorities.isEmpty()) {
        createAdaptorForAuthorities(details, authorities);
    }
    if (!userDetails.getAliases().isEmpty()) {
        details.getAliases().addAll(userDetails.getAliases());
    }
    return details;
}

From source file:md.ibanc.rm.sessions.CustomAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    String username = authentication.getName();
    String password = authentication.getCredentials().toString();

    LoginFormValidator loginFormValidator = new LoginFormValidator();

    if (!loginFormValidator.isLoginValid(username)) {
        throw new BadCredentialsException("Numele de utilizator contine simboluri interzise");
    }// w w  w.j  a v a2s .  c o m

    if (!loginFormValidator.isValidPassword(password)) {
        throw new BadCredentialsException("Parola contine simboluri interzise");
    }

    Users users = usersService.findUserByEmail(username);

    if (users == null) {
        throw new UsernameNotFoundException("Asa utilizator nu exista in baza de date");
    }

    String hashPassword = UtilHashMD5.createMD5Hash(FormatPassword.CreatePassword(users.getId(), password));

    if (!hashPassword.equals(users.getPassword())) {
        throw new BadCredentialsException("Parola este gresita");
    }

    if (!users.getActive()) {
        throw new AccountExpiredException("Nu aveti drept sa accesati acest serviciu");
    }

    Collection<? extends GrantedAuthority> authoritiesRoles = getAuthorities(users);

    return new UsernamePasswordAuthenticationToken(username, hashPassword, authoritiesRoles);

}

From source file:br.com.joaops.smt.security.SmtAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication a) throws AuthenticationException {
    String username = a.getName();
    String password = a.getCredentials().toString();

    UserDetails user = this.userDetails.loadUserByUsername(username);

    if (user == null) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
                "AbstractUserDetailsAuthenticationProvider.badCredentials");
        throw new BadCredentialsException(message);
    }//from  w ww.j  a v a2s  .com

    if (!user.getUsername().equals(username)) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
                "AbstractUserDetailsAuthenticationProvider.badCredentials");
        throw new BadCredentialsException(message);
    }

    if (!passwordEncoder.matches(password, user.getPassword())) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
                "AbstractUserDetailsAuthenticationProvider.badCredentials");
        throw new BadCredentialsException(message);
    }

    if (user.isEnabled() == false) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled",
                "AbstractUserDetailsAuthenticationProvider.disabled");
        throw new DisabledException(message);
    }

    if (user.isAccountNonLocked() == false) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked",
                "AbstractUserDetailsAuthenticationProvider.locked");
        throw new LockedException(message);
    }

    if (user.isAccountNonExpired() == false) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired",
                "AbstractUserDetailsAuthenticationProvider.expired");
        throw new AccountExpiredException(message);
    }

    if (user.isCredentialsNonExpired() == false) {
        String message = this.messages.getMessage(
                "AbstractUserDetailsAuthenticationProvider.credentialsExpired",
                "AbstractUserDetailsAuthenticationProvider.credentialsExpired");
        throw new CredentialsExpiredException(message);
    }

    return new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
}

From source file:org.taverna.server.master.identity.StrippedDownAuthProvider.java

@PerfLogged
@Override//from w  w  w . j a  v  a 2s  .  c  o m
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    if (!(authentication instanceof UsernamePasswordAuthenticationToken))
        throw new IllegalArgumentException("can only authenticate against username+password");
    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;

    // Determine username
    String username = (auth.getPrincipal() == null) ? "NONE_PROVIDED" : auth.getName();

    UserDetails user;

    try {
        user = retrieveUser(username, auth);
        if (user == null)
            throw new IllegalStateException(
                    "retrieveUser returned null - a violation of the interface contract");
    } catch (UsernameNotFoundException notFound) {
        if (logger.isDebugEnabled())
            logger.debug("User '" + username + "' not found", notFound);
        throw new BadCredentialsException("Bad credentials");
    }

    // Pre-auth
    if (!user.isAccountNonLocked())
        throw new LockedException("User account is locked");
    if (!user.isEnabled())
        throw new DisabledException("User account is disabled");
    if (!user.isAccountNonExpired())
        throw new AccountExpiredException("User account has expired");
    Object credentials = auth.getCredentials();
    if (credentials == null) {
        logger.debug("Authentication failed: no credentials provided");

        throw new BadCredentialsException("Bad credentials");
    }

    String providedPassword = credentials.toString();
    boolean matched = false;
    synchronized (authCache) {
        AuthCacheEntry pw = authCache.get(username);
        if (pw != null && providedPassword != null) {
            if (pw.valid(providedPassword))
                matched = true;
            else
                authCache.remove(username);
        }
    }
    // Auth
    if (!matched) {
        if (!passwordEncoder.matches(providedPassword, user.getPassword())) {
            logger.debug("Authentication failed: password does not match stored value");

            throw new BadCredentialsException("Bad credentials");
        }
        if (providedPassword != null)
            synchronized (authCache) {
                authCache.put(username, new AuthCacheEntry(providedPassword));
            }
    }

    // Post-auth
    if (!user.isCredentialsNonExpired())
        throw new CredentialsExpiredException("User credentials have expired");

    return createSuccessAuthentication(user, auth, user);
}

From source file:fr.insalyon.creatis.vip.api.rest.security.apikey.ApikeyAuthenticationProvider.java

private void checkUserInfo(UserDetails user) {
    if (!user.isAccountNonLocked()) {
        logger.info("User account is locked");

        throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked",
                "User account is locked"));
    }//from  w  w  w . ja  v  a2 s . co  m

    if (!user.isEnabled()) {
        logger.info("User account is disabled");

        throw new DisabledException(
                messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"));
    }

    if (!user.isAccountNonExpired()) {
        logger.info("User account is expired");

        throw new AccountExpiredException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"));
    }
    if (!user.isCredentialsNonExpired()) {
        logger.info("User account credentials have expired");

        throw new CredentialsExpiredException(
                messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired",
                        "User credentials have expired"));
    }
}

From source file:org.cloudifysource.security.CloudifyDaoAuthenticationProvider.java

private void runAuthenticationChecks(final CloudifyUserDetails user) {
    if (!user.isAccountNonLocked()) {
        logger.warning("User account is locked");

        throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked",
                "User account is locked"));
    }//from w w  w  .  j  a  v a  2s  .c om

    if (!user.isEnabled()) {
        logger.warning("User account is disabled");

        throw new DisabledException(
                messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"));
    }

    if (!user.isAccountNonExpired()) {
        logger.warning("User account is expired");

        throw new AccountExpiredException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"));
    }

    if (!user.isCredentialsNonExpired()) {
        logger.warning("User account credentials have expired");

        throw new CredentialsExpiredException(
                messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired",
                        "User credentials have expired"));
    }
}

From source file:org.medici.bia.security.BiaDaoAuthenticationProvider.java

@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken)
        throws AuthenticationException {
    try {//w  ww  .j a v  a2s .  c  o  m
        Long startTime = System.currentTimeMillis();
        super.additionalAuthenticationChecks(userDetails, usernamePasswordAuthenticationToken);

        User user = getUserDAO().findUser(userDetails.getUsername());

        if (!user.getActive()) {
            throw new DisabledException("User is not activated");
        }

        if (!user.getApproved()) {
            throw new AccountNotApprovedException(
                    "User has not been approved yet. Wait for an approvation email before logging");
        }

        if (!user.getExpirationDate().after(new Date())) {
            throw new AccountExpiredException("User is expired");
        }

        if (user.getLocked()) {
            throw new LockedException("User is locked");
        }

        user.setLastLoginDate(user.getCurrentLoginDate());
        user.setCurrentLoginDate(new Date());
        user.setBadLogin(0);

        getUserDAO().merge(user);

        AccessLog accessLog = new AccessLog();
        accessLog.setAccount(userDetails.getUsername());
        accessLog.setDateAndTime(new Date(System.currentTimeMillis()));
        accessLog.setIpAddress(((WebAuthenticationDetails) usernamePasswordAuthenticationToken.getDetails())
                .getRemoteAddress());
        accessLog.setAction("/loginProcess");

        List<UserRole> userRoles = getUserRoleDAO().findUserRoles(user.getAccount());
        accessLog.setAuthorities(UserRoleUtils.toString(userRoles));
        accessLog.setExecutionTime(System.currentTimeMillis() - startTime);
        accessLog.setHttpMethod(HttpMethod.POST.toString());

        try {
            getLogService().traceAccessLog(accessLog);

            // Update the online users in "application context variable"
            applicationAccessContainer.addOnlineUser(user);

        } catch (ApplicationThrowable applicationThrowable) {
            logger.error(applicationThrowable);
        }

        logger.info(" Authentication OK");
    } catch (AuthenticationException authenticationException) {
        User user = getUserDAO().findUser(userDetails.getUsername());

        if (user != null) {
            if (!user.getActive()) {
                throw new DisabledException("User is not activated", authenticationException);
            }

            if (!user.getApproved()) {
                throw new AccountNotApprovedException(
                        "User has not been approved yet. Wait for an approvation email before logging");
            }

            if (!user.getExpirationDate().after(new Date())) {
                throw new AccountExpiredException("User is expired", authenticationException);
            }

            if (user.getLocked()) {
                throw new LockedException("User is locked", authenticationException);
            }

            user.setBadLogin(user.getBadLogin() + 1);

            Integer badLogin = NumberUtils
                    .createInteger(ApplicationPropertyManager.getApplicationProperty("user.maxBadLogin"));

            if (user.getBadLogin() > badLogin) {
                user.setLocked(true);
                getUserDAO().merge(user);
                try {
                    getAdminService().addLockedUser(user);

                } catch (ApplicationThrowable ath) {

                }
            }

            getUserDAO().merge(user);
        }

        throw authenticationException;
    }
}

From source file:org.medici.bia.security.BiaLdapUserDetailsMapper.java

/**
 * /*from  www. j av a  2s .co m*/
 * @param ctx
 * @param username
 * @param authorities
 * @return UserDetails 
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
        Collection<GrantedAuthority> authorities) {
    BiaLdapUserDetailsImpl.Essence essence = new BiaLdapUserDetailsImpl.Essence(ctx);
    Object passwordValue = ctx.getObjectAttribute(passwordAttributeName);
    User user = null;

    if (passwordValue != null) {
        essence.setPassword(mapPassword(passwordValue));
    }

    essence.setUsername(username);

    // Map the roles
    for (int i = 0; (roleAttributes != null) && (i < roleAttributes.length); i++) {
        String[] rolesForAttribute = ctx.getStringAttributes(roleAttributes[i]);

        if (rolesForAttribute == null) {
            logger.debug("Couldn't read role attribute '" + roleAttributes[i] + "' for user "
                    + ctx.getNameInNamespace());
            continue;
        }

        for (int j = 0; j < rolesForAttribute.length; j++) {
            GrantedAuthority authority = createAuthority(rolesForAttribute[j]);

            if (authority != null) {
                essence.addAuthority(authority);
            }
        }
    }

    // Add the supplied authorities

    for (GrantedAuthority authority : authorities) {
        essence.addAuthority(authority);
    }

    // Check for PPolicy data
    PasswordPolicyResponseControl ppolicy = (PasswordPolicyResponseControl) ctx
            .getObjectAttribute(PasswordPolicyControl.OID);

    if (ppolicy != null) {
        essence.setTimeBeforeExpiration(ppolicy.getTimeBeforeExpiration());
        essence.setGraceLoginsRemaining(ppolicy.getGraceLoginsRemaining());
    }

    BiaLdapUserDetailsImpl docSourcesLdapUserDetailsImpl = essence.createUserDetails();

    try {
        user = getUserDAO().findUser(docSourcesLdapUserDetailsImpl.getUsername());
        if (user != null) {
            user.setLastLoginDate(user.getCurrentLoginDate());
            user.setCurrentLoginDate(new Date());
            user.setBadLogin(0);

            getUserDAO().merge(user);
        } else {
            // If user is null, we need to create user record...
            user = new User(docSourcesLdapUserDetailsImpl.getUsername());
            Calendar expirationDate = Calendar.getInstance();
            expirationDate.add(Calendar.MONTH, NumberUtils.createInteger(
                    ApplicationPropertyManager.getApplicationProperty("user.expiration.user.months")));
            user.setExpirationDate(expirationDate.getTime());
            Calendar expirationPasswordDate = Calendar.getInstance();
            expirationPasswordDate.add(Calendar.MONTH, NumberUtils.createInteger(
                    ApplicationPropertyManager.getApplicationProperty("user.expiration.password.months")));
            user.setExpirationPasswordDate(expirationPasswordDate.getTime());
            user.setBadLogin(0);
            user.setActive(true);
            user.setLocked(false);
            user.setRegistrationDate(new Date());
            user.setActivationDate(new Date());
            user.setLastLoginDate(user.getCurrentLoginDate());
            user.setCurrentLoginDate(new Date());
            user.setForumNumberOfPost(new Long(0));
            getUserDAO().persist(user);
        }
    } catch (PersistenceException persistenceException) {
        logger.error("Exception during user update", persistenceException);

    }

    if (!user.getActive()) {
        throw new DisabledException("User is not activated");
    }

    //MD: This code isn't implemented
    /*if (!user.getApproved()) 
       throw new AccountNotApprovedException("User is not approved");*/

    if (!user.getExpirationDate().after(new Date())) {
        throw new AccountExpiredException("User is expired");
    }

    if (user.getLocked()) {
        throw new LockedException("User is locked");
    }

    return docSourcesLdapUserDetailsImpl;
}