feat(user/controller): implementados login y register

parent 4ad663bf
package com.example.apprecetas.user.infrastructure.controller;
import com.example.apprecetas.exception.UnprocessableEntityException;
import com.example.apprecetas.security.jwt.JwtTokenProvider;
import com.example.apprecetas.user.application.CreateUserUseCase;
import com.example.apprecetas.user.application.ReadUserUseCase;
import com.example.apprecetas.user.infrastructure.controller.dto.AuthResponse;
import com.example.apprecetas.user.infrastructure.controller.dto.LoginRequest;
import com.example.apprecetas.user.infrastructure.controller.dto.UserInputDto;
import com.example.apprecetas.user.infrastructure.controller.dto.UserOutputDto;
import com.example.apprecetas.user.infrastructure.mapper.UserMapper;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.mapstruct.factory.Mappers;
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.userdetails.UsernameNotFoundException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.net.URI;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {
private final AuthenticationManager authenticationManager;
private final JwtTokenProvider jwtTokenProvider;
private final ReadUserUseCase readUserService;
private final CreateUserUseCase createUserService;
private final UserMapper mapper = Mappers.getMapper(UserMapper.class);
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
try {
UserOutputDto userOutputDto = mapper.map(readUserService.readByUsername(loginRequest.getUsername()));
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
loginRequest.getUsername(),
loginRequest.getPassword()
)
);
String token = jwtTokenProvider.generateToken(authentication.getName());
return ResponseEntity.ok(new AuthResponse(token));
} catch (UsernameNotFoundException e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Usuario no encontrado");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Credenciales no válidas");
}
}
@PostMapping("/register")
public ResponseEntity<AuthResponse> register(@RequestBody @Valid UserInputDto userInputDto,
BindingResult result) {
if (result.hasErrors()) {
String errorMsg = result.getFieldErrors().stream()
.map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
.collect(Collectors.joining("; "));
throw new UnprocessableEntityException(errorMsg);
}
try {
URI location = URI.create("/user");
UserOutputDto userOutputDto = mapper.map(createUserService.create(mapper.map(userInputDto)));
String token = jwtTokenProvider.generateToken(userOutputDto.getUsername());
return ResponseEntity.created(location).body(new AuthResponse(token));
} catch (Exception e) {
throw new UnprocessableEntityException("Usuario ya registrado. Cambie sus credenciales.");
}
}
}
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