@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);
    }
  }
  private User createUserIfNotExist(UserProfile userProfile, String langKey, String providerId) {
    String email = userProfile.getEmail();
    String userName = userProfile.getUsername();
    if (StringUtils.isBlank(email) && StringUtils.isBlank(userName)) {
      log.error("Cannot create social user because email and login are null");
      throw new IllegalArgumentException("Email and login cannot be null");
    }
    if (StringUtils.isBlank(email) && userRepository.findOneByLogin(userName).isPresent()) {
      log.error(
          "Cannot create social user because email is null and login already exist, login -> {}",
          userName);
      throw new IllegalArgumentException("Email cannot be null with an existing login");
    }
    Optional<User> user = userRepository.findOneByEmail(email);
    if (user.isPresent()) {
      log.info("User already exist associate the connection to this account");
      return user.get();
    }

    String login = getLoginDependingOnProviderId(userProfile, providerId);
    String encryptedPassword = passwordEncoder.encode(RandomStringUtils.random(10));
    Set<Authority> authorities = new HashSet<>(1);
    authorities.add(authorityRepository.findOne("ROLE_USER"));

    User newUser = new User();
    newUser.setLogin(login);
    newUser.setPassword(encryptedPassword);
    newUser.setFirstName(userProfile.getFirstName());
    newUser.setLastName(userProfile.getLastName());
    newUser.setEmail(email);
    newUser.setActivated(true);
    newUser.setAuthorities(authorities);
    newUser.setLangKey(langKey);

    return userRepository.save(newUser);
  }