Skip to content
Snippets Groups Projects
Commit 364a6ee6 authored by hugcubi's avatar hugcubi
Browse files

Mejora del manejo de errores en users y auth

parent a00f340a
No related branches found
No related tags found
2 merge requests!36Develop,!33Fix/kong review
......@@ -55,14 +55,14 @@ public class UserAPI {
*/
public User registerUser(RegisterRequest registerRequest) {
String url = USER_API_URL;
System.out.println(url + " " + registerRequest);
try {
ResponseEntity<User> userResponse = restTemplate.postForEntity(url, registerRequest, User.class);
if (!userResponse.getStatusCode().is2xxSuccessful()) {
String errorMessage = "Failed to register user: " + userResponse.getStatusCode() + ". " + userResponse.getBody();
throw new HttpClientErrorException(userResponse.getStatusCode(), errorMessage);
}
return userResponse.getBody();
} catch (HttpClientErrorException ex) {
if (ex.getStatusCode() == HttpStatus.BAD_REQUEST)
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Register failed");
throw ex;
}
}
/**
......
......@@ -6,7 +6,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpClientErrorException;
import com.uva.api.auth.models.auth.LoginRequest;
import com.uva.api.auth.models.auth.RegisterRequest;
......@@ -25,26 +24,12 @@ public class AuthController {
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
try {
return authService.login(loginRequest);
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.FORBIDDEN) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.FORBIDDEN);
}
}
return new ResponseEntity<>("Algo no fue bien", HttpStatus.UNAUTHORIZED);
}
@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody RegisterRequest registerRequest) {
try {
return authService.register(registerRequest);
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.CONFLICT)
return new ResponseEntity<>(e.getMessage(), HttpStatus.CONFLICT);
}
return new ResponseEntity<>("Algo no fue bien", HttpStatus.UNAUTHORIZED);
}
@PostMapping("/password")
......
package com.uva.api.auth.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.client.HttpClientErrorException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(HttpClientErrorException.class)
public ResponseEntity<Map<String, Object>> handleHttpClientErrorException(HttpClientErrorException ex) {
Map<String, Object> body = new HashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("message", ex.getMessage());
return new ResponseEntity<>(body, ex.getStatusCode());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleGeneralException(Exception ex) {
Map<String, Object> body = new HashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("message", "An unexpected error occurred: " + ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
......@@ -79,7 +79,7 @@ public class AuthService {
public ResponseEntity<?> changePassword(String token, String actualPass, String newPass) {
JwtData decoded = jwtUtil.decodeToken(token);
if (decoded == null)
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
throw new HttpClientErrorException(HttpStatus.FORBIDDEN);
String email = decoded.getEmail();
User user = getUser(email, actualPass);
......@@ -87,23 +87,22 @@ public class AuthService {
boolean changePasswordAllowed = decoded.isAdmin() || user != null;
if (user != null && !validStrings(actualPass, newPass))
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST);
if (!changePasswordAllowed)
throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Invalid credentials");
if (changePasswordAllowed) {
// Actualizamos la nueva
String hashPass = SecurityUtils.encrypt(newPass);
userAPI.changePassword(user, hashPass);
// Hacemos un login con los nuevos datos
return login(new LoginRequest(email, newPass));
} else {
return new ResponseEntity<>("Invalid credentials", HttpStatus.FORBIDDEN);
}
}
public ResponseEntity<?> deleteUser(String token, int id, String password) {
JwtData decoded = jwtUtil.decodeToken(token);
if (decoded == null)
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
throw new HttpClientErrorException(HttpStatus.FORBIDDEN);
String email = decoded.getEmail();
User user = getUser(email, password);
......@@ -112,13 +111,12 @@ public class AuthService {
|| (user != null && user.getId() == id);
if (user != null && !validStrings(password))
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST);
if (!changePasswordAllowed)
throw new HttpClientErrorException(HttpStatus.FORBIDDEN, "Invalid credentials");
if (changePasswordAllowed) {
userAPI.deleteUser(user);
return new ResponseEntity<>(HttpStatus.OK);
} else {
return new ResponseEntity<>("Invalid credentials", HttpStatus.FORBIDDEN);
}
return ResponseEntity.ok(user);
}
}
......@@ -4,6 +4,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.client.HttpClientErrorException;
import java.time.LocalDateTime;
import java.util.HashMap;
......@@ -21,6 +22,15 @@ public class GlobalExceptionHandler {
return new ResponseEntity<>(body, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(HttpClientErrorException.class)
public ResponseEntity<Map<String, Object>> handleHttpClientErrorException(HttpClientErrorException ex) {
Map<String, Object> body = new HashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("message", ex.getMessage());
return new ResponseEntity<>(body, ex.getStatusCode());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleGeneralException(Exception ex) {
Map<String, Object> body = new HashMap<>();
......
......@@ -8,4 +8,6 @@ import com.uva.api.users.models.User;
public interface UserRepository extends JpaRepository<User, Integer> {
Optional<User> findByEmail(String email);
Boolean existsByEmail(String email);
}
......@@ -5,7 +5,6 @@ import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.uva.api.users.api.HotelApi;
import com.uva.api.users.models.Manager;
import com.uva.api.users.models.User;
......
......@@ -4,8 +4,10 @@ import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import com.uva.api.users.models.AuthDTO;
import com.uva.api.users.models.User;
......@@ -47,6 +49,9 @@ public class UserService {
}
public ResponseEntity<User> registerNewUser(AuthDTO request) {
if (userRepository.existsByEmail(request.getEmail()))
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST);
User user = new User();
BeanUtils.copyProperties(request, user);
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment