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

Repaso al servicio, creo que ya esta

parent cd64edc8
No related branches found
No related tags found
2 merge requests!36Develop,!31Dev/refactor hotels booking
Showing
with 435 additions and 301 deletions
......@@ -52,11 +52,6 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
......
......
......@@ -16,21 +16,19 @@ public class BookingAPI {
@Autowired
private RestTemplate restTemplate;
@Value("${external.services.bookings.url}")
@Value("${services.external.bookings.url}")
private String BOOKING_API_URL;
public List<Booking> getAllBookingsByUserId(int id) {
public void deleteAllByUserId(int id) {
String url = BOOKING_API_URL + "?userId={id}";
Booking[] bookingsArray = restTemplate
.getForObject(url, Booking[].class, id);
return Arrays.asList(bookingsArray);
restTemplate.delete(url, id);
}
public void deleteAllByUserId(int id) {
public List<Booking> getAllByUserId(int id) {
String url = BOOKING_API_URL + "?userId={id}";
restTemplate.delete(url, id);
Booking[] bookings = restTemplate.getForObject(url, Booking[].class, id);
return Arrays.asList(bookings);
}
}
......@@ -11,12 +11,11 @@ public class HotelApi {
@Autowired
private RestTemplate restTemplate;
@Value("${external.services.hotels.url}")
@Value("${services.external.hotels.url}")
private String HOTELS_API;
public void deleteAllByManagerId(Integer id) {
String url = HOTELS_API + "?managerId={id}";
restTemplate.delete(url, id);
}
}
package com.uva.api.apis;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.JsonNode;
import com.uva.api.models.remote.JwtData;
@Component
public class TokenAPI {
@Autowired
private RestTemplate restTemplate;
@Value("${spring.application.name}")
private String service;
@Value("${services.internal.token.url}")
private String TOKEN_API_URL;
public JwtData getServiceToken() {
String url = TOKEN_API_URL + "/service";
Map<String, String> body = new HashMap<>();
body.put("service", service);
String token = restTemplate.postForObject(url, body, JsonNode.class)
.get("token").asText();
return decodeToken(token);
}
public JwtData decodeToken(String token) {
String url = TOKEN_API_URL + "/info";
Map<String, String> body = new HashMap<>();
body.put("token", token);
JwtData response = restTemplate.postForObject(url, body, JwtData.class);
response.setToken(token);
return response;
}
}
package com.uva.api.interceptor;
package com.uva.api.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
......@@ -7,40 +7,25 @@ import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.stereotype.Component;
import com.uva.api.models.UserRol;
import com.uva.api.utils.JwtUtil;
import com.uva.api.services.TokenService;
import java.io.IOException;
@Component
public class AuthHttpInterceptor implements ClientHttpRequestInterceptor {
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {
@Autowired
private JwtUtil jwtUtil;
private String token;
private String getAccessToken() {
if (token == null || token.isEmpty()) {
// TODO cambiar también si el token ha caducado
token = jwtUtil.generateToken("auth", "auth@dev.com", UserRol.ADMIN);
}
return token;
}
private TokenService service;
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
// Generar o cargar el JWT token desde el bean JwtUtil
String jwtToken = getAccessToken();
// System.out.println("Using token " + jwtToken);
String jwtToken = service.getServiceToken();
System.out.println("Using token " + jwtToken);
// Agregar el token al encabezado Authorization
request.getHeaders().add("Authorization", "Bearer " + jwtToken);
// Continuar con la ejecución de la solicitud
return execution.execute(request, body);
}
}
......@@ -23,7 +23,7 @@ public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable());
http.csrf(csrf -> csrf.disable())
// .authorizeHttpRequests(authorize -> authorize
// // Permitir OPTIONS sin autenticación
// .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
......@@ -47,8 +47,8 @@ public class SecurityConfig {
// // Rechazar el resto
// .anyRequest().denyAll())
// // Registra el filtro antes del filtro estándar de autenticación
// .addFilterBefore(jwtAuthenticationFilter,
// UsernamePasswordAuthenticationFilter.class);
.addFilterBefore(jwtAuthenticationFilter,
UsernamePasswordAuthenticationFilter.class);
return http.build();
}
......
......
package com.uva.api.controllers;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import com.uva.api.models.ClientStatus;
import com.uva.api.services.ClientService;
@RestController
@RequestMapping("users/clients")
@CrossOrigin(origins = "*")
public class ClientController {
@Autowired
private ClientService clientService;
// Clients
@GetMapping
public ResponseEntity<?> getAllClients() {
return clientService.findAll();
}
@GetMapping("/{id}")
public ResponseEntity<?> getClientById(@PathVariable int id) {
return clientService.findById(id);
}
@PatchMapping("/{id}")
public ResponseEntity<?> updateClientState(@PathVariable int id, @RequestBody Map<String, String> json) {
String strStatus = json.get("status");
if (strStatus == null) {
return new ResponseEntity<String>("Missing required fields", HttpStatus.BAD_REQUEST);
}
try {
ClientStatus clientStatus = ClientStatus.valueOf(strStatus);
return ResponseEntity.ok(clientService.updateClientStatus(id, clientStatus));
} catch (IllegalArgumentException e) {
return new ResponseEntity<String>("Unknown Client state", HttpStatus.BAD_REQUEST);
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND)
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
throw e;
}
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteClient(@PathVariable Integer id) {
try {
return ResponseEntity.ok(clientService.deleteById(id));
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND)
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
throw e;
}
}
}
package com.uva.api.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import com.uva.api.models.Manager;
import com.uva.api.services.ManagerService;
@RestController
@RequestMapping("users/managers")
@CrossOrigin(origins = "*")
public class ManagerController {
@Autowired
private ManagerService managerService;
@GetMapping
public ResponseEntity<List<Manager>> getAllHotelManagers() {
List<Manager> users = managerService.findAll();
return ResponseEntity.ok(users);
}
@GetMapping("/{id}")
public ResponseEntity<Manager> getHotelManagerById(@PathVariable Integer id) {
return ResponseEntity.ok(managerService.findById(id));
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteHotelManager(@PathVariable Integer id) {
try {
return ResponseEntity.ok(managerService.deleteById(id));
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND)
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
throw e;
}
}
}
package com.uva.api.controllers;
import java.util.List;
import java.util.Map;
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.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
......@@ -18,16 +15,8 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import com.fasterxml.jackson.databind.JsonNode;
import com.uva.api.models.AuthResponse;
import com.uva.api.models.Client;
import com.uva.api.models.Manager;
import com.uva.api.models.User;
import com.uva.api.models.ClientStatus;
import com.uva.api.services.ClientService;
import com.uva.api.services.ManagerService;
import com.uva.api.models.AuthDTO;
import com.uva.api.services.UserService;
import com.uva.api.utils.Utils;
......@@ -39,19 +28,9 @@ public class UserController {
@Autowired
private UserService userService;
@Autowired
private ClientService clientService;
@Autowired
private ManagerService managerService;
// Common
@PostMapping
public ResponseEntity<?> addUser(@RequestBody AuthResponse body) {
User user = new User();
BeanUtils.copyProperties(body, user);
userService.registerNewUser(user);
return new ResponseEntity<User>(user, HttpStatus.ACCEPTED);
public ResponseEntity<?> addUser(@RequestBody AuthDTO body) {
return userService.registerNewUser(body);
}
@PutMapping("/{id}")
......@@ -63,14 +42,8 @@ public class UserController {
if (!Utils.notEmptyStrings(name, email)) {
return new ResponseEntity<String>("Missing required fields", HttpStatus.BAD_REQUEST);
}
try {
User user = userService.updateUserData(id, name, email);
return new ResponseEntity<User>(user, HttpStatus.OK);
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND)
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
throw e;
}
return userService.updateUserData(id, name, email);
}
@PutMapping("/{id}/password")
......@@ -81,122 +54,67 @@ public class UserController {
return new ResponseEntity<String>("Missing required fields", HttpStatus.BAD_REQUEST);
}
try {
User user = userService.changePassword(id, password);
return new ResponseEntity<User>(user, HttpStatus.OK);
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND)
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
throw e;
}
}
return userService.changePassword(id, password);
}
// TODO aplicarr verificación
// @Autowired
// private TokenService ser;
// private String validate(String token) {
// JWTData decoded = ser.decodeToken(token);
// if (decoded == null) {
// return "Invalid token format";
// }
// UserRol rol = decoded.getRol();
// String audience = decoded.getAudience();
// boolean a = (rol == null || rol != UserRol.ADMIN);
// boolean b = (audience == null || !audience.equals("INTERNAL"));
// if (a && b) {
// return "Invalid " + a + " " + b;
// }
// return null;
// }
// @GetMapping(params = { "email" })
// public ResponseEntity<?> getUserByEmail(@RequestParam String email,
// @RequestHeader(value = "Authorization", required = true) String
// authorization) {
// try {
// if (authorization == null) {
// return new ResponseEntity<String>("Missing required fields",
// HttpStatus.BAD_REQUEST);
// }
// String m = validate(authorization.substring(7));
// if (m != null) {
// return new ResponseEntity<String>(m, HttpStatus.BAD_REQUEST);
// }
// return ResponseEntity.ok(userService.getUserByEmail(email));
// } catch (HttpClientErrorException e) {
// if (e.getStatusCode() == HttpStatus.NOT_FOUND)
// return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
// throw e;
// }
// }
@GetMapping(params = { "email" })
public ResponseEntity<?> getUserByEmail(@RequestParam String email) {
try {
return ResponseEntity.ok(userService.getUserByEmail(email));
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND)
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
throw e;
}
return userService.getUserByEmail(email);
}
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
List<User> users = userService.getAllUsers();
return ResponseEntity.ok(users);
public ResponseEntity<?> getAllUsers() {
return userService.getAllUsers();
}
@GetMapping("/{id}")
public ResponseEntity<?> getUserById(@PathVariable int id) {
return ResponseEntity.ok(userService.getUserById(id));
return userService.getUserById(id);
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteUser(@PathVariable Integer id) {
try {
User user = userService.getUserById(id);
switch (user.getRol()) {
case CLIENT:
clientService.deleteById(id);
break;
case HOTEL_ADMIN:
managerService.deleteById(id);
default:
break;
}
return ResponseEntity.ok(user);
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND)
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
throw e;
}
}
// Clients
@GetMapping("/clients")
public ResponseEntity<List<Client>> getAllClients() {
List<Client> users = clientService.findAll();
return ResponseEntity.ok(users);
}
@GetMapping("/clients/{id}")
public ResponseEntity<Client> getClientById(@PathVariable int id) {
return ResponseEntity.ok(clientService.findById(id));
public ResponseEntity<?> deleteUser(@PathVariable int id) {
return userService.deleteUserById(id);
}
@PatchMapping("/clients/{id}")
public ResponseEntity<?> updateClientState(@PathVariable int id, @RequestBody Map<String, String> json) {
String strStatus = json.get("status");
if (strStatus == null) {
return new ResponseEntity<String>("Missing required fields", HttpStatus.BAD_REQUEST);
}
try {
ClientStatus clientStatus = ClientStatus.valueOf(strStatus);
return ResponseEntity.ok(clientService.updateClientStatus(id, clientStatus));
} catch (IllegalArgumentException e) {
return new ResponseEntity<String>("Unknown Client state", HttpStatus.BAD_REQUEST);
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND)
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
throw e;
}
}
@DeleteMapping("/clients/{id}")
public ResponseEntity<?> deleteClient(@PathVariable Integer id) {
try {
return ResponseEntity.ok(clientService.deleteById(id));
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND)
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
throw e;
}
}
// HotelManagers
@GetMapping("/managers")
public ResponseEntity<List<Manager>> getAllHotelManagers() {
List<Manager> users = managerService.findAll();
return ResponseEntity.ok(users);
}
@GetMapping("/managers/{id}")
public ResponseEntity<Manager> getHotelManagerById(@PathVariable int id) {
return ResponseEntity.ok(managerService.findById(id));
}
@DeleteMapping("/managers/{id}")
public ResponseEntity<?> deleteHotelManager(@PathVariable Integer id) {
try {
return ResponseEntity.ok(managerService.deleteById(id));
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == HttpStatus.NOT_FOUND)
return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
throw e;
}
}
}
......@@ -12,8 +12,8 @@ import java.util.Map;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(HotelNotFoundException.class)
public ResponseEntity<Map<String, Object>> handleHotelNotFound(HotelNotFoundException ex) {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<Map<String, Object>> handleUserNotFound(UserNotFoundException ex) {
Map<String, Object> body = new HashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("message", ex.getMessage());
......@@ -21,24 +21,6 @@ public class GlobalExceptionHandler {
return new ResponseEntity<>(body, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(InvalidRequestException.class)
public ResponseEntity<Map<String, Object>> handleInvalidRequest(InvalidRequestException ex) {
Map<String, Object> body = new HashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("message", ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(InvalidDateRangeException.class)
public ResponseEntity<Map<String, Object>> handleInvalidDateRange(InvalidDateRangeException ex) {
Map<String, Object> body = new HashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("message", ex.getMessage());
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleGeneralException(Exception ex) {
Map<String, Object> body = new HashMap<>();
......
......
package com.uva.api.exceptions;
public class InvalidDateRangeException extends RuntimeException {
public InvalidDateRangeException(String message) {
super(message);
}
}
package com.uva.api.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class InvalidRequestException extends RuntimeException {
public InvalidRequestException(String message) {
super(message);
}
}
......@@ -4,8 +4,8 @@ import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND) // Devuelve un 404 cuando se lanza la excepción
public class HotelNotFoundException extends RuntimeException {
public HotelNotFoundException(int id) {
super("Hotel not found with id: " + id);
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(int id) {
super("User not found with id: " + id);
}
}
package com.uva.api.filter;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.uva.api.models.UserRol;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.uva.api.models.remote.JwtData;
import com.uva.api.services.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
......@@ -19,21 +17,19 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.Filter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Map;
@Component
public class JwtAuthenticationFilter implements Filter {
@Value("${security.jwt.secret-key}")
private String secretKey;
private Algorithm getSigningAlgorithm() {
return Algorithm.HMAC256(secretKey); // Usar HMAC256 con la clave secreta
}
@Autowired
private TokenService service;
private String getTokenFromRequest(HttpServletRequest request) {
String authHeader = request.getHeader("Authorization");
......@@ -43,26 +39,17 @@ public class JwtAuthenticationFilter implements Filter {
return authHeader.substring(7);
}
private DecodedJWT validateAndDecodeToken(String token) {
private JwtData validateAndDecodeToken(String token) {
try {
JWTVerifier verifier = JWT.require(getSigningAlgorithm()).build();
return verifier.verify(token); // Verifica y decodifica el token
} catch (JWTVerificationException ex) {
System.out.println(
"[" + LocalDateTime.now().toString() + "] Error de verificación del token: " + ex.getMessage());
return service.decodeToken(token);
} catch (Exception ex) {
System.err.println(
"[" + LocalDateTime.now().toString() + "] Error de verificación del token");
ex.printStackTrace(System.err);
return null;
}
}
private String getEmailFromToken(DecodedJWT jwt) {
return jwt.getClaim("email").asString();
}
private UserRol getRoleFromToken(DecodedJWT jwt) {
String role = jwt.getClaim("rol").asString();
return UserRol.valueOf(role);
}
private String formatRole(UserRol rol) {
return String.format("ROLE_%s", rol.toString());
}
......@@ -70,34 +57,42 @@ public class JwtAuthenticationFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String token = getTokenFromRequest(httpRequest);
System.out.print("[" + LocalDateTime.now().toString() + "] TOKEN: " + token);
System.out.println("[" + LocalDateTime.now().toString() + "] TOKEN: " + token);
if (token != null) {
DecodedJWT jwt = validateAndDecodeToken(token);
System.out.print(" " + jwt.toString() + " ");
JwtData jwt = validateAndDecodeToken(token);
if (jwt != null) {
String email = getEmailFromToken(jwt);
UserRol role = getRoleFromToken(jwt);
System.out.print(" email=" + email + " role=" + role + " ");
if (email != null && role != null && SecurityContextHolder.getContext().getAuthentication() == null) {
// Crear la autoridad con el rol del token
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(formatRole(role));
// Crear autenticación
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(email,
null, Collections.singletonList(authority));
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
// Establecer autenticación en el contexto de seguridad
SecurityContextHolder.getContext().setAuthentication(authentication);
}
System.out.println("-->" + jwt + "<--");
}
}
// String email = getEmailFromToken(jwt);
// UserRol role = getRoleFromToken(jwt);
// System.out.print(" email=" + email + " role=" + role + " ");
// if (email != null && role != null &&
// SecurityContextHolder.getContext().getAuthentication() == null) {
// // Crear la autoridad con el rol del token
// SimpleGrantedAuthority authority = new
// SimpleGrantedAuthority(formatRole(role));
// // Crear autenticación
// UsernamePasswordAuthenticationToken authentication = new
// UsernamePasswordAuthenticationToken(email,
// null, Collections.singletonList(authority));
// authentication.setDetails(new
// WebAuthenticationDetailsSource().buildDetails(httpRequest));
// // Establecer autenticación en el contexto de seguridad
// SecurityContextHolder.getContext().setAuthentication(authentication);
// }
// }
// }
// Continuar con el resto de filtros
chain.doFilter(request, response);
}
......
......
......@@ -9,11 +9,11 @@ import lombok.Setter;
@AllArgsConstructor
@Getter
@Setter
public class AuthResponse {
public class AuthDTO {
private int id;
private String name;
private String email;
private String password;
private UserRol rol;
private UserRol rol = UserRol.CLIENT;
}
package com.uva.api.models;
import java.time.LocalDate;
import java.util.List;
import com.uva.api.models.remote.Booking;
import jakarta.persistence.Basic;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.Table;
import jakarta.persistence.Transient;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
......@@ -29,29 +26,23 @@ import lombok.ToString;
@EqualsAndHashCode(callSuper = true)
public class Client extends User {
@Basic(optional = false)
@Column(nullable = false)
@Enumerated(EnumType.STRING)
private ClientStatus status = ClientStatus.NO_BOOKINGS;
@Transient
private List<Booking> bookings;
public Client(int id, String name, String email, String password, ClientStatus status,
List<Booking> bookings) {
super(id, name, email, password, UserRol.CLIENT);
setStatus(status);
setBookings(bookings);
}
public ClientStatus getStatus() {
if (getBookings() == null || getBookings().isEmpty())
return ClientStatus.NO_BOOKINGS;
boolean activeBookings = getBookings().stream()
.anyMatch(booking -> !booking.getEndDate().isBefore(LocalDate.now())); // reserva >= ahora
return activeBookings ? ClientStatus.WITH_ACTIVE_BOOKINGS : ClientStatus.WITH_INACTIVE_BOOKINGS;
}
public void setStatus(ClientStatus status) {
this.status = status;
}
// public ClientStatus getStatus() {
// if (getBookings() == null || getBookings().isEmpty())
// return ClientStatus.NO_BOOKINGS;
// boolean activeBookings = getBookings().stream()
// .anyMatch(booking -> !booking.getEndDate().isBefore(LocalDate.now())); //
// reserva >= ahora
// return activeBookings ? ClientStatus.WITH_ACTIVE_BOOKINGS :
// ClientStatus.WITH_INACTIVE_BOOKINGS;
// }
}
package com.uva.api.models;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.persistence.Entity;
......@@ -23,6 +24,7 @@ import lombok.ToString;
public class Manager extends User {
@Transient
@JsonIgnore
private JsonNode hotels;
public Manager(int id, String name, String email, String password, JsonNode hotels) {
......
......
package com.uva.api.models.remote;
import java.util.Date;
import com.uva.api.models.UserRol;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@Data
@ToString
public class JwtData {
private String token;
private Integer id;
private String name;
private String email;
private UserRol rol;
private String service;
private String subject;
private String audience;
private Long ttl;
private Date issuedAt;
private Date expiresAt;
public boolean isAdmin() {
return rol != null && rol == UserRol.ADMIN;
}
}
\ No newline at end of file
package com.uva.api.services;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.uva.api.apis.BookingAPI;
import com.uva.api.models.Client;
import com.uva.api.models.User;
import com.uva.api.models.UserRol;
import com.uva.api.models.ClientStatus;
import com.uva.api.models.remote.Booking;
import com.uva.api.models.ClientStatus;
import com.uva.api.repositories.ClientRepository;
import com.uva.api.utils.Utils;
......@@ -26,20 +26,13 @@ public class ClientService {
@Autowired
private BookingAPI bookingAPI;
public List<Client> findAll() {
return clientRepository.findAll();
public ResponseEntity<?> findAll() {
return ResponseEntity.ok(clientRepository.findAll());
}
public Client findById(int id) {
public ResponseEntity<?> findById(int id) {
Client client = Utils.assertUser(clientRepository.findById(id));
List<Booking> bookings;
try {
bookings = bookingAPI.getAllBookingsByUserId(client.getId());
} catch (Exception e) {
bookings = new ArrayList<>();
}
client.setBookings(bookings);
return client;
return ResponseEntity.ok(client);
}
public Client deleteById(int id) {
......@@ -57,27 +50,30 @@ public class ClientService {
return clientRepository.save(client);
}
// TODO No entiendo donde debería ir esto
public User updateClientStatus(int id, ClientStatus status) {
Client user = Utils.assertUser(clientRepository.findById(id));
boolean activeBookings = user.getBookings().stream()
List<Booking> bookings = bookingAPI.getAllByUserId(id);
boolean activeBookings = bookings.stream()
.anyMatch(booking -> !booking.getEndDate().isBefore(LocalDate.now())); // reserva >= ahora
boolean inactiveBookings = user.getBookings().stream()
boolean inactiveBookings = bookings.stream()
.anyMatch(booking -> booking.getEndDate().isBefore(LocalDate.now())); // reserva < ahora
switch (status) {
case NO_BOOKINGS:
if (!user.getBookings().isEmpty())
if (!bookings.isEmpty())
throw new IllegalArgumentException("Invalid State: The user has at least one booking");
break;
case WITH_ACTIVE_BOOKINGS:
if (user.getBookings().isEmpty())
if (bookings.isEmpty())
throw new IllegalArgumentException("Invalid State: The user don't has bookings");
if (!activeBookings)
throw new IllegalArgumentException("Invalid State: The user don't has active bookings");
break;
case WITH_INACTIVE_BOOKINGS:
if (user.getBookings().isEmpty())
if (bookings.isEmpty())
throw new IllegalArgumentException("Invalid State: The user don't has bookings");
if (!inactiveBookings)
throw new IllegalArgumentException("Invalid State: The user don't has inactive bookings");
......
......
package com.uva.api.services;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.uva.api.apis.TokenAPI;
import com.uva.api.models.remote.JwtData;
@Service
public class TokenService {
@Autowired
private TokenAPI api;
private JwtData ownToken;
private Map<String, JwtData> cache = new HashMap<>();
private boolean expireSoon(JwtData decoded) {
return (decoded.getExpiresAt().getTime() - System.currentTimeMillis()) / 1000 <= 10;
}
public String getServiceToken() {
if (ownToken == null || expireSoon(ownToken)) {
System.out.println("Generando token");
long s = System.currentTimeMillis();
ownToken = api.getServiceToken();
long t = System.currentTimeMillis() - s;
System.out.println("Token Generando en " + t + " ms");
}
return ownToken.getToken();
}
public JwtData decodeToken(String token) {
if (cache.containsKey(token))
return cache.get(token);
System.out.println("Actualizando token");
long s = System.currentTimeMillis();
JwtData decoded = api.decodeToken(token);
long t = System.currentTimeMillis() - s;
System.out.println("Actualizando token en " + t + " ms");
cache.put(token, decoded);
return decoded;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment