bugfix(user): cambio de username a email para el token

parent b6a3670e
...@@ -23,10 +23,10 @@ public class JwtTokenProvider { ...@@ -23,10 +23,10 @@ public class JwtTokenProvider {
private final SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256); private final SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
public String generateToken(String username) { public String generateToken(String email) {
long jwtExpirationMs = 3600000; // 1 hora en milisegundos long jwtExpirationMs = 3600000; // 1 hora en milisegundos
return Jwts.builder() return Jwts.builder()
.subject(username) .subject(email)
.issuedAt(new Date()) .issuedAt(new Date())
.expiration(Date.from(Instant.now().plus(jwtExpirationMs, ChronoUnit.MILLIS))) .expiration(Date.from(Instant.now().plus(jwtExpirationMs, ChronoUnit.MILLIS)))
.signWith(secretKey) .signWith(secretKey)
...@@ -52,8 +52,8 @@ public class JwtTokenProvider { ...@@ -52,8 +52,8 @@ public class JwtTokenProvider {
} }
public Authentication getAuthentication(String token) { public Authentication getAuthentication(String token) {
String username = getUsernameFromToken(token); String email = getUsernameFromToken(token);
UserDetails userDetails = userDetailsService.loadUserByUsername(username); UserDetails userDetails = userDetailsService.loadUserByUsername(email);
return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
} }
......
...@@ -15,12 +15,12 @@ public class CustomUserDetailsServiceImpl implements UserDetailsService { ...@@ -15,12 +15,12 @@ public class CustomUserDetailsServiceImpl implements UserDetailsService {
private final ReadUserRepository userRepository; private final ReadUserRepository userRepository;
@Override @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return userRepository.readByUsername(username) return userRepository.readByEmail(email)
.map(user -> User.withUsername(user.getUsername()) .map(user -> User.withUsername(user.getEmail())
.password(user.getPassword()) .password(user.getPassword())
.roles(user.getRole().name()) .roles(user.getRole().name())
.build()) .build())
.orElseThrow(() -> new UsernameNotFoundException("User con username " + username + " no encontrado")); .orElseThrow(() -> new UsernameNotFoundException("Usuario con email " + email + " no encontrado"));
} }
} }
package com.example.apprecetas.user.infrastructure.controller; package com.example.apprecetas.user.infrastructure.controller;
import com.example.apprecetas.exception.EntityNotFoundException;
import com.example.apprecetas.exception.UnprocessableEntityException; import com.example.apprecetas.exception.UnprocessableEntityException;
import com.example.apprecetas.security.jwt.JwtTokenProvider; import com.example.apprecetas.security.jwt.JwtTokenProvider;
import com.example.apprecetas.user.application.CreateUserUseCase; import com.example.apprecetas.user.application.CreateUserUseCase;
...@@ -17,7 +18,6 @@ import org.springframework.http.ResponseEntity; ...@@ -17,7 +18,6 @@ import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.validation.BindingResult; import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
...@@ -40,23 +40,30 @@ public class AuthController { ...@@ -40,23 +40,30 @@ public class AuthController {
private final UserMapper mapper = Mappers.getMapper(UserMapper.class); private final UserMapper mapper = Mappers.getMapper(UserMapper.class);
@PostMapping("/login") @PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) { public ResponseEntity<?> login(@RequestBody @Valid LoginRequest loginRequest,
BindingResult result) {
if (result.hasErrors()) {
String errorMsg = result.getFieldErrors().stream()
.map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
.collect(Collectors.joining("; "));
throw new UnprocessableEntityException(errorMsg);
}
try { try {
UserOutputDto userOutputDto = mapper.map(readUserService.readByUsername(loginRequest.getUsername())); readUserService.readByEmail(loginRequest.getEmail());
Authentication authentication = authenticationManager.authenticate( Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken( new UsernamePasswordAuthenticationToken(
loginRequest.getUsername(), loginRequest.getEmail(),
loginRequest.getPassword() loginRequest.getPassword()
) )
); );
String token = jwtTokenProvider.generateToken(authentication.getName()); String token = jwtTokenProvider.generateToken(authentication.getName());
return ResponseEntity.ok(new AuthResponse(token)); return ResponseEntity.ok(new AuthResponse(token));
} catch (UsernameNotFoundException e) { } catch (EntityNotFoundException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Usuario no encontrado"); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Usuario no encontrado");
} catch (Exception e) { } catch (Exception e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Credenciales no válidas"); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Contraseña incorrecta");
} }
} }
...@@ -73,7 +80,7 @@ public class AuthController { ...@@ -73,7 +80,7 @@ public class AuthController {
URI location = URI.create("/user"); URI location = URI.create("/user");
UserOutputDto userOutputDto = mapper.map(createUserService.create(mapper.map(userInputDto))); UserOutputDto userOutputDto = mapper.map(createUserService.create(mapper.map(userInputDto)));
String token = jwtTokenProvider.generateToken(userOutputDto.getUsername()); String token = jwtTokenProvider.generateToken(userOutputDto.getEmail());
return ResponseEntity.created(location).body(new AuthResponse(token)); return ResponseEntity.created(location).body(new AuthResponse(token));
} catch (Exception e) { } catch (Exception e) {
......
...@@ -5,8 +5,8 @@ import lombok.Data; ...@@ -5,8 +5,8 @@ import lombok.Data;
@Data @Data
public class LoginRequest { public class LoginRequest {
@NotEmpty(message = "Nombre de usuario obligatorio") @NotEmpty(message = "Email obligatorio")
private String username; private String email;
@NotEmpty(message = "Contraseña obligatoria") @NotEmpty(message = "Contraseña obligatoria")
private String password; private String password;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment