-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoginUser.java
More file actions
98 lines (85 loc) · 4.21 KB
/
LoginUser.java
File metadata and controls
98 lines (85 loc) · 4.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com.outfitlab.project.domain.useCases.user;
import com.outfitlab.project.domain.exceptions.NullFieldsException;
import com.outfitlab.project.domain.exceptions.UserNotFoundException;
import com.outfitlab.project.domain.interfaces.repositories.UserRepository;
import com.outfitlab.project.domain.model.dto.LoginDTO;
import com.outfitlab.project.infrastructure.config.security.AuthResponse;
import com.outfitlab.project.infrastructure.config.security.jwt.JwtService;
import com.outfitlab.project.infrastructure.config.security.jwt.Token;
import com.outfitlab.project.infrastructure.model.UserEntity;
import com.outfitlab.project.infrastructure.repositories.interfaces.TokenRepository;
import com.outfitlab.project.infrastructure.repositories.interfaces.UserJpaRepository;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
public class LoginUser {
private final UserRepository userRepository;
private final UserJpaRepository userJpaRepository;
private final TokenRepository tokenRepository;
private final JwtService jwtService;
private final PasswordEncoder passwordEncoder;
private final AuthenticationManager authManager;
public LoginUser(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthenticationManager authManager,
TokenRepository tokenRepository, JwtService jwtService, UserJpaRepository userJpaRepository) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.authManager = authManager;
this.tokenRepository = tokenRepository;
this.jwtService = jwtService;
this.userJpaRepository = userJpaRepository;
}
public ResponseEntity<AuthResponse> execute(LoginDTO loginDTO) {
if (loginDTO.getEmail().isBlank() || loginDTO.getPassword().isBlank()) {
throw new NullFieldsException("Debe completar la totalidad de los campos para autenticarse.");
}
try {
Authentication auth = authManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginDTO.getEmail(),
loginDTO.getPassword()));
} catch (AuthenticationException ex) {
throw new UserNotFoundException("Email o contraseña incorrecta, vuelva a intentarlo.");
}
UserEntity userEntity = userJpaRepository.findByEmail(loginDTO.getEmail());
if (!userEntity.isVerified()) {
throw new UserNotFoundException("La cuenta aún no ha sido verificada. Puedes consultar el estado de la gesión en soporte@outfitlab.com.");
}
var user = userJpaRepository.getByEmail(loginDTO.getEmail())
.orElseThrow();
var accessToken = jwtService.generateToken(user);
var refreshToken = jwtService.generateRefreshToken(user);
revokeAllUserTokens(user);
saveUserToken(user, accessToken);
return new ResponseEntity<>(
AuthResponse.builder()
.access_token(accessToken)
.refresh_token(refreshToken)
.user(UserEntity.convertEntityToModel(user))
.build(),
HttpStatus.OK);
}
private void saveUserToken(UserEntity user, String token) {
var saveToken = Token.builder()
.token(token)
.user(user)
.revoked(false)
.expired(false)
.build();
tokenRepository.save(saveToken);
}
private void revokeAllUserTokens(UserEntity user) {
var validTokens = tokenRepository.allValidTokensByUser(user.getId());
if (validTokens.isEmpty()) {
return;
}
validTokens.forEach(token -> {
token.setRevoked(true);
token.setExpired(true);
});
tokenRepository.saveAll(validTokens);
}
}