Search in sources :

Example 21 with MotechUser

use of org.motechproject.security.domain.MotechUser in project motech by motech.

the class MotechLoginSuccessHandler method onAuthenticationSuccess.

@Override
@Transactional
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
    super.onAuthenticationSuccess(request, response, authentication);
    LOGGER.info("User {} logged in", authentication.getName());
    LOGGER.debug("Authorities for {}: {}", authentication.getName(), authentication.getAuthorities());
    MotechUser motechUser = motechUsersDao.findByUserName(authentication.getName());
    motechUser.setFailureLoginCounter(0);
    motechUsersDao.update(motechUser);
    HttpSession session = request.getSession();
    // set session timeout
    session.setMaxInactiveInterval(settingService.getSessionTimeout());
    // this is a fallback for sessions started before web-security started, i.e. on the Bootstrap screen
    sessionHandler.addSession(session);
}
Also used : MotechUser(org.motechproject.security.domain.MotechUser) HttpSession(javax.servlet.http.HttpSession) Transactional(org.springframework.transaction.annotation.Transactional)

Example 22 with MotechUser

use of org.motechproject.security.domain.MotechUser in project motech by motech.

the class PasswordRecoveryServiceImpl method oneTimeTokenOpenId.

@Override
@Transactional
public String oneTimeTokenOpenId(String email, DateTime expiration, boolean notify) throws UserNotFoundException, NonAdminUserException {
    MotechUser user = motechUsersDao.findUserByEmail(email);
    DateTime expirationDate = expiration;
    if (expirationDate == null) {
        expirationDate = DateTime.now().plusHours(DEFAULT_EXPIRATION_HOURS);
    } else if (expirationDate.isBefore(DateTime.now())) {
        throw new IllegalArgumentException("The expiration date shouldn't be a past date!");
    }
    if (user == null) {
        throw new UserNotFoundException("User with email not found: " + email);
    }
    List<String> roles = user.getRoles();
    boolean isAdminUser = false;
    for (String role : roles) {
        if (role.toLowerCase().contains("admin")) {
            isAdminUser = true;
        }
    }
    if (!isAdminUser) {
        throw new NonAdminUserException("You are not admin User: " + user.getUserName());
    }
    String token = RandomStringUtils.randomAlphanumeric(TOKEN_LENGTH);
    PasswordRecovery recovery = createRecovery(user.getUserName(), user.getEmail(), token, expirationDate, user.getLocale());
    if (notify) {
        emailSender.sendOneTimeToken(recovery);
    }
    LOGGER.info("Created a one time token for user " + user.getUserName());
    return token;
}
Also used : UserNotFoundException(org.motechproject.security.exception.UserNotFoundException) MotechUser(org.motechproject.security.domain.MotechUser) NonAdminUserException(org.motechproject.security.exception.NonAdminUserException) PasswordRecovery(org.motechproject.security.domain.PasswordRecovery) DateTime(org.joda.time.DateTime) Transactional(org.springframework.transaction.annotation.Transactional)

Example 23 with MotechUser

use of org.motechproject.security.domain.MotechUser in project motech by motech.

the class PasswordRecoveryServiceImpl method validateTokenAndLoginUser.

@Override
@Transactional
public void validateTokenAndLoginUser(String token, HttpServletRequest request, HttpServletResponse response) throws IOException {
    PasswordRecovery recovery = findForToken(token);
    if (validateRecovery(recovery)) {
        MotechUser user = motechUsersDao.findUserByEmail(recovery.getEmail());
        OpenIDAuthenticationToken openIDToken = new OpenIDAuthenticationToken(OpenIDAuthenticationStatus.SUCCESS, user.getOpenId(), "one time login ", new ArrayList<>());
        Authentication authentication = authenticationManager.authenticate(openIDToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        request.getSession(true).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
        passwordRecoveriesDataService.delete(recovery);
        redirectStrategy.sendRedirect(request, response, "/server/home");
    } else {
        redirectStrategy.sendRedirect(request, response, "/server/login");
    }
}
Also used : MotechUser(org.motechproject.security.domain.MotechUser) Authentication(org.springframework.security.core.Authentication) OpenIDAuthenticationToken(org.springframework.security.openid.OpenIDAuthenticationToken) PasswordRecovery(org.motechproject.security.domain.PasswordRecovery) Transactional(org.springframework.transaction.annotation.Transactional)

Example 24 with MotechUser

use of org.motechproject.security.domain.MotechUser in project motech by motech.

the class PasswordRecoveryServiceImpl method resetPassword.

@Override
@Transactional
public void resetPassword(String token, String password, String passwordConfirmation) throws InvalidTokenException {
    if (!password.equals(passwordConfirmation)) {
        throw new IllegalArgumentException("Password and confirmation do not match");
    }
    PasswordRecovery recovery = findForToken(token);
    if (!validateRecovery(recovery)) {
        throw new InvalidTokenException();
    }
    MotechUser user = motechUsersDao.findByUserName(recovery.getUsername());
    if (user == null) {
        throw new InvalidTokenException("This user has been deleted");
    }
    String encodedPassword = passwordEncoder.encodePassword(password);
    user.setPassword(encodedPassword);
    motechUsersDao.update(user);
    passwordRecoveriesDataService.delete(recovery);
}
Also used : InvalidTokenException(org.motechproject.security.exception.InvalidTokenException) MotechUser(org.motechproject.security.domain.MotechUser) PasswordRecovery(org.motechproject.security.domain.PasswordRecovery) Transactional(org.springframework.transaction.annotation.Transactional)

Example 25 with MotechUser

use of org.motechproject.security.domain.MotechUser in project motech by motech.

the class MotechLoginSuccessHandlerTest method shouldResetFailureLoginCounter.

@Test
public void shouldResetFailureLoginCounter() throws ServletException, IOException {
    MotechUser user = new MotechUser();
    user.setUserName("testUser");
    user.setFailureLoginCounter(3);
    when(authentication.getName()).thenReturn("testUser");
    when(motechUsersDao.findByUserName("testUser")).thenReturn(user);
    when(request.getSession()).thenReturn(session);
    when(settingService.getSessionTimeout()).thenReturn(500);
    motechLoginSuccessHandler.onAuthenticationSuccess(request, response, authentication);
    verify(motechUsersDao).update(userCaptor.capture());
    assertEquals((Integer) 0, userCaptor.getValue().getFailureLoginCounter());
}
Also used : MotechUser(org.motechproject.security.domain.MotechUser) Test(org.junit.Test)

Aggregations

MotechUser (org.motechproject.security.domain.MotechUser)61 Test (org.junit.Test)27 Transactional (org.springframework.transaction.annotation.Transactional)24 MotechUserProfile (org.motechproject.security.domain.MotechUserProfile)8 ArrayList (java.util.ArrayList)6 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)6 DateTime (org.joda.time.DateTime)4 PasswordRecovery (org.motechproject.security.domain.PasswordRecovery)4 Authentication (org.springframework.security.core.Authentication)4 User (org.springframework.security.core.userdetails.User)4 HttpSession (javax.servlet.http.HttpSession)3 MotechRole (org.motechproject.security.domain.MotechRole)3 RoleDto (org.motechproject.security.model.RoleDto)3 ConfigAttribute (org.springframework.security.access.ConfigAttribute)3 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)3 AuthenticationException (org.springframework.security.core.AuthenticationException)3 UserNotFoundException (org.motechproject.security.exception.UserNotFoundException)2 UserDto (org.motechproject.security.model.UserDto)2 SecurityConfig (org.springframework.security.access.SecurityConfig)2 AbstractAuthenticationToken (org.springframework.security.authentication.AbstractAuthenticationToken)2