package de.rwth.idsg.bikeman.service;
import de.rwth.idsg.bikeman.domain.PersistentToken;
import de.rwth.idsg.bikeman.domain.User;
import de.rwth.idsg.bikeman.repository.PersistentTokenRepository;
import de.rwth.idsg.bikeman.repository.UserRepository;
import de.rwth.idsg.bikeman.security.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.List;
/**
* Service class for managing users.
*/
@Service
@Transactional
@Slf4j
public class UserService {
@Inject
private PasswordEncoder passwordEncoder;
@Inject
private UserRepository userRepository;
@Inject
private PersistentTokenRepository persistentTokenRepository;
public void updateUserInformation(String login) {
User currentUser = userRepository.findByLoginIgnoreCase(SecurityUtils.getCurrentLogin());
currentUser.setLogin(login);
userRepository.save(currentUser);
log.debug("Changed Information for User: {}", currentUser);
}
public void changePassword(String password) {
User currentUser = userRepository.findByLoginIgnoreCase(SecurityUtils.getCurrentLogin());
String encryptedPassword = passwordEncoder.encode(password);
currentUser.setPassword(encryptedPassword);
userRepository.save(currentUser);
log.debug("Changed password for User: {}", currentUser);
}
@Transactional(readOnly = true)
public User getUserWithAuthorities() {
User currentUser = userRepository.findByLoginIgnoreCase(SecurityUtils.getCurrentLogin());
currentUser.getAuthorities().size(); // eagerly load the association
return currentUser;
}
/**
* Persistent Token are used for providing automatic authentication, they should be automatically deleted after
* 30 days.
* <p/>
* <p>
* This is scheduled to get fired everyday, at midnight.
* </p>
*/
@Scheduled(cron = "0 0 0 * * ?")
public void removeOldPersistentTokens() {
LocalDate now = new LocalDate();
List<PersistentToken> tokens = persistentTokenRepository.findByTokenDateBefore(now.minusMonths(1));
for (PersistentToken token : tokens) {
log.debug("Deleting token {}", token.getSeries());
User user = token.getUser();
user.getPersistentTokens().remove(token);
persistentTokenRepository.delete(token);
}
}
}