@Override
  protected void onLoginSuccess(
      HttpServletRequest request,
      HttpServletResponse response,
      Authentication successfulAuthentication) {

    String login = successfulAuthentication.getName();

    log.debug("Creating new persistent login for user {}", login);
    PersistentToken token =
        userRepository
            .findOneByLogin(login)
            .map(
                u -> {
                  PersistentToken t = new PersistentToken();
                  t.setSeries(generateSeriesData());
                  t.setUser(u);
                  t.setTokenValue(generateTokenData());
                  t.setTokenDate(LocalDate.now());
                  t.setIpAddress(request.getRemoteAddr());
                  t.setUserAgent(request.getHeader("User-Agent"));
                  return t;
                })
            .orElseThrow(
                () ->
                    new UsernameNotFoundException(
                        "User " + login + " was not found in the database"));
    try {
      persistentTokenRepository.saveAndFlush(token);
      addCookie(token, request, response);
    } catch (DataAccessException e) {
      log.error("Failed to save persistent token ", e);
    }
  }
  @Override
  @Transactional
  protected UserDetails processAutoLoginCookie(
      String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) {

    PersistentToken token = getPersistentToken(cookieTokens);
    String login = token.getUser().getLogin();

    // Token also matches, so login is valid. Update the token value, keeping the *same* series
    // number.
    log.debug(
        "Refreshing persistent login token for user '{}', series '{}'", login, token.getSeries());
    token.setTokenDate(LocalDate.now());
    token.setTokenValue(generateTokenData());
    token.setIpAddress(request.getRemoteAddr());
    token.setUserAgent(request.getHeader("User-Agent"));
    try {
      persistentTokenRepository.saveAndFlush(token);
      addCookie(token, request, response);
    } catch (DataAccessException e) {
      log.error("Failed to update token: ", e);
      throw new RememberMeAuthenticationException("Autologin failed due to data access problem", e);
    }
    return getUserDetailsService().loadUserByUsername(login);
  }
Ejemplo n.º 3
0
 private void generateUserToken(User user, String tokenSeries, LocalDate localDate) {
   PersistentToken token = new PersistentToken();
   token.setSeries(tokenSeries);
   token.setUser(user);
   token.setTokenValue(tokenSeries + "-data");
   token.setTokenDate(localDate);
   token.setIpAddress("127.0.0.1");
   token.setUserAgent("Test agent");
   persistentTokenRepository.saveAndFlush(token);
 }