Updated Sync Service

This commit is contained in:
Giancarlo Panichi 2022-10-17 18:52:32 +02:00
parent 4b6cd01797
commit 2ab230a3ba
6 changed files with 258 additions and 250 deletions

View File

@ -34,7 +34,7 @@ import java.util.stream.Collectors;
@Transactional("epasMedTransactionManager")
public class UserService {
private final Logger log = LoggerFactory.getLogger(UserService.class);
private final Logger logger = LoggerFactory.getLogger(UserService.class);
private final UserRepository userRepository;
@ -44,7 +44,8 @@ public class UserService {
private final AuthorityRepository authorityRepository;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, PersistentTokenRepository persistentTokenRepository, AuthorityRepository authorityRepository) {
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder,
PersistentTokenRepository persistentTokenRepository, AuthorityRepository authorityRepository) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.persistentTokenRepository = persistentTokenRepository;
@ -52,22 +53,20 @@ public class UserService {
}
public Optional<User> activateRegistration(String key) {
log.debug("Activating user for activation key {}", key);
return userRepository.findOneByActivationKey(key)
.map(user -> {
logger.debug("Activating user for activation key {}", key);
return userRepository.findOneByActivationKey(key).map(user -> {
// activate given user for the registration key.
user.setActivated(true);
user.setActivationKey(null);
log.debug("Activated user: {}", user);
logger.debug("Activated user: {}", user);
return user;
});
}
public Optional<User> completePasswordReset(String newPassword, String key) {
log.debug("Reset user password for reset key {}", key);
logger.debug("Reset user password for reset key {}", key);
return userRepository.findOneByResetKey(key)
.filter(user -> user.getResetDate().isAfter(Instant.now().minusSeconds(86400)))
.map(user -> {
.filter(user -> user.getResetDate().isAfter(Instant.now().minusSeconds(86400))).map(user -> {
user.setPassword(passwordEncoder.encode(newPassword));
user.setResetKey(null);
user.setResetDate(null);
@ -76,9 +75,7 @@ public class UserService {
}
public Optional<User> requestPasswordReset(String mail) {
return userRepository.findOneByEmailIgnoreCase(mail)
.filter(User::getActivated)
.map(user -> {
return userRepository.findOneByEmailIgnoreCase(mail).filter(User::getActivated).map(user -> {
user.setResetKey(RandomUtil.generateResetKey());
user.setResetDate(Instant.now());
return user;
@ -118,7 +115,7 @@ public class UserService {
authorityRepository.findById(AuthoritiesConstants.USER).ifPresent(authorities::add);
newUser.setAuthorities(authorities);
userRepository.save(newUser);
log.debug("Created Information for User: {}", newUser);
logger.debug("Created Information for User: {}", newUser);
return newUser;
}
@ -151,15 +148,12 @@ public class UserService {
user.setResetDate(Instant.now());
user.setActivated(true);
if (userDTO.getAuthorities() != null) {
Set<Authority> authorities = userDTO.getAuthorities().stream()
.map(authorityRepository::findById)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
Set<Authority> authorities = userDTO.getAuthorities().stream().map(authorityRepository::findById)
.filter(Optional::isPresent).map(Optional::get).collect(Collectors.toSet());
user.setAuthorities(authorities);
}
userRepository.save(user);
log.debug("Created Information for User: {}", user);
logger.debug("Created Information for User: {}", user);
return user;
}
@ -170,10 +164,7 @@ public class UserService {
* @return updated user.
*/
public Optional<UserDTO> updateUser(UserDTO userDTO) {
return Optional.of(userRepository
.findById(userDTO.getId()))
.filter(Optional::isPresent)
.map(Optional::get)
return Optional.of(userRepository.findById(userDTO.getId())).filter(Optional::isPresent).map(Optional::get)
.map(user -> {
user.setLogin(userDTO.getLogin().toLowerCase());
user.setFirstName(userDTO.getFirstName());
@ -186,26 +177,23 @@ public class UserService {
user.setLangKey(userDTO.getLangKey());
Set<Authority> managedAuthorities = user.getAuthorities();
managedAuthorities.clear();
userDTO.getAuthorities().stream()
.map(authorityRepository::findById)
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(managedAuthorities::add);
log.debug("Changed Information for User: {}", user);
userDTO.getAuthorities().stream().map(authorityRepository::findById).filter(Optional::isPresent)
.map(Optional::get).forEach(managedAuthorities::add);
logger.debug("Changed Information for User: {}", user);
return user;
})
.map(UserDTO::new);
}).map(UserDTO::new);
}
public void deleteUser(String login) {
userRepository.findOneByLogin(login).ifPresent(user -> {
userRepository.delete(user);
log.debug("Deleted User: {}", user);
logger.debug("Deleted User: {}", user);
});
}
/**
* Update basic information (first name, last name, email, language) for the current user.
* Update basic information (first name, last name, email, language) for the
* current user.
*
* @param firstName first name of user.
* @param lastName last name of user.
@ -214,9 +202,7 @@ public class UserService {
* @param imageUrl image URL of user.
*/
public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) {
SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.ifPresent(user -> {
SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneByLogin).ifPresent(user -> {
user.setFirstName(firstName);
user.setLastName(lastName);
if (email != null) {
@ -224,23 +210,22 @@ public class UserService {
}
user.setLangKey(langKey);
user.setImageUrl(imageUrl);
log.debug("Changed Information for User: {}", user);
logger.debug("Changed Information for User: {}", user);
});
}
@Transactional(value = "epasMedTransactionManager")
public void changePassword(String currentClearTextPassword, String newPassword) {
SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.ifPresent(user -> {
//logger.debug("CurrenClearTextPassword: {}", currentClearTextPassword);
SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneByLogin).ifPresent(user -> {
String currentEncryptedPassword = user.getPassword();
//logger.debug("CurrentEncryptedPassword: {}", currentEncryptedPassword);
if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) {
throw new InvalidPasswordException();
}
String encryptedPassword = passwordEncoder.encode(newPassword);
user.setPassword(encryptedPassword);
log.debug("Changed password for User: {}", user);
logger.debug("Changed password for User: {}", user);
});
}
@ -260,8 +245,8 @@ public class UserService {
}
/**
* Persistent Token are used for providing automatic authentication, they should be automatically deleted after
* 30 days.
* Persistent Token are used for providing automatic authentication, they should
* be automatically deleted after 30 days.
* <p>
* This is scheduled to get fired everyday, at midnight.
*/
@ -269,7 +254,7 @@ public class UserService {
public void removeOldPersistentTokens() {
LocalDate now = LocalDate.now();
persistentTokenRepository.findByTokenDateBefore(now.minusMonths(1)).forEach(token -> {
log.debug("Deleting token {}", token.getSeries());
logger.debug("Deleting token {}", token.getSeries());
User user = token.getUser();
user.getPersistentTokens().remove(token);
persistentTokenRepository.delete(token);
@ -283,16 +268,16 @@ public class UserService {
*/
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
userRepository
.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS))
.forEach(user -> {
log.debug("Deleting not activated user {}", user.getLogin());
userRepository.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(
Instant.now().minus(3, ChronoUnit.DAYS)).forEach(user -> {
logger.debug("Deleting not activated user {}", user.getLogin());
userRepository.delete(user);
});
}
/**
* Gets a list of all the authorities.
*
* @return a list of all the authorities.
*/
@Transactional(value = "epasMedTransactionManager", readOnly = true)

View File

@ -1074,7 +1074,8 @@ public class SyncService {
if (eWTT.getUpdatedAt() != null && !eWTT.getUpdatedAt().isEmpty()) {
LocalDateTime updatedAt = LocalDateTime.parse(eWTT.getUpdatedAt(), formatter);
if (lastUpdate.compareTo(updatedAt) < 0) {
Timestamp dataMod = Timestamp.valueOf(updatedAt);
LocalDateTime dMod=updatedAt.truncatedTo(ChronoUnit.SECONDS);
Timestamp dataMod = Timestamp.valueOf(dMod);
SIOrario siOrario = new SIOrario(Long.valueOf(eWTT.getId()), eWTT.getDescription(),
Boolean.valueOf(eWTT.getHorizontal()), Boolean.valueOf(eWTT.getDisabled()), dataMod,
SI_FLAG_DEL_FALSE, fluxId);
@ -1178,6 +1179,7 @@ public class SyncService {
Timestamp dataMod;
try {
LocalDateTime dMod = LocalDateTime.parse(epasStamping.getDate(), formatter);
dMod=dMod.truncatedTo(ChronoUnit.SECONDS);
dataMod = Timestamp.valueOf(dMod);
} catch (IllegalArgumentException | DateTimeParseException e) {
logger.error("Invalid stamping data format: {}", e.getLocalizedMessage(), e);
@ -1334,7 +1336,9 @@ public class SyncService {
}
}
Timestamp dataMod = Timestamp.valueOf(now);
LocalDateTime dMod=now.truncatedTo(ChronoUnit.SECONDS);
Timestamp dataMod = Timestamp.valueOf(dMod);
Integer durata = 0;
if (startDate != null && endDate != null) {
LocalDate startD = LocalDate.parse(leave.getStart());
@ -1447,7 +1451,8 @@ public class SyncService {
}
}
Timestamp dataMod = Timestamp.valueOf(now);
LocalDateTime dMod=now.truncatedTo(ChronoUnit.SECONDS);
Timestamp dataMod = Timestamp.valueOf(dMod);
SIPersOrario siPersOrario = new SIPersOrario(id, idPersona, pwtDTO.getCf(), startDate, endDate,
pwtDTO.getDescrizione(), pwtDTO.getLun(), pwtDTO.getMar(), pwtDTO.getMer(), pwtDTO.getGio(),
@ -1482,7 +1487,8 @@ public class SyncService {
// }
// Set Update DateTime
Timestamp dataMod = Timestamp.valueOf(now);
LocalDateTime dMod=now.truncatedTo(ChronoUnit.SECONDS);
Timestamp dataMod = Timestamp.valueOf(dMod);
logger.info("Persons Validated: {}", epasValidates.getValidatedPersons().length);
checkFiscalCode(epasValidates.getValidatedPersons());
@ -1554,7 +1560,8 @@ public class SyncService {
logger.info("Reference: {}-{}", year, month);
// Set Update DateTime
Timestamp dataMod = Timestamp.valueOf(now);
LocalDateTime dMod=now.truncatedTo(ChronoUnit.SECONDS);
Timestamp dataMod = Timestamp.valueOf(dMod);
// logger.info("Persons Validated: {}",
// epasValidates.getValidatedPersons().length);

View File

@ -36,6 +36,9 @@ export class PasswordComponent implements OnInit {
if (newPassword !== this.passwordForm.get(['confirmPassword'])!.value) {
this.doNotMatch = true;
} else {
// const cpwd=this.passwordForm.get(['currentPassword'])!.value;
// eslint-disable-next-line no-console
// console.log(cpwd)
this.passwordService.save(newPassword, this.passwordForm.get(['currentPassword'])!.value).subscribe(
() => (this.success = true),
() => (this.error = true)

View File

@ -58,6 +58,10 @@
(click)="sync('writesTimeCards')">Scrivi Cartellini</button>
<button class="btn btn-primary" type="button"
(click)="sync('writesOffSiteWorks')">Scrivi Lavoro Fuori Sede</button>
<button class="btn btn-primary" type="button"
(click)="sync('writesLeaves')">Scrivi Aspettative</button>
<button class="btn btn-primary" type="button"
(click)="sync('writesPersonWorkingTime')">Scrivi Pers Orario</button>
</form>
</div>

View File

@ -1 +1,8 @@
export type SyncType = 'test' | 'reads' | 'writesOrario' | 'writesTimeCards' | 'writesOffSiteWorks';
export type SyncType =
| 'test'
| 'reads'
| 'writesOrario'
| 'writesTimeCards'
| 'writesOffSiteWorks'
| 'writesLeaves'
| 'writesPersonWorkingTime';

View File

@ -121,6 +121,8 @@ public class SyncResourceIT {
//dataMod = Timestamp.valueOf(dMod.format(formatterDataMod));
dataMod = Timestamp.valueOf(dMod);
} catch (IllegalArgumentException | DateTimeParseException e) {
logger.error("Invalid stamping data format: {}", e.getLocalizedMessage(), e);
return;