Skip to content
Snippets Groups Projects
Commit 9d629449 authored by migudel's avatar migudel :speech_balloon:
Browse files

Avance con las conexiones

parent 56e2c695
No related branches found
No related tags found
1 merge request!36Develop
Showing
with 136 additions and 192 deletions
......@@ -20,7 +20,7 @@ lint:
disabled:
- git-diff-check
enabled:
- checkov@3.2.334
- checkov@3.2.336
- dotenv-linter@3.3.0
- hadolint@2.12.1-beta
- markdownlint@0.43.0
......
......
......@@ -53,6 +53,7 @@ public class UserAPI {
*/
public User registerUser(RegisterRequest registerRequest) {
String url = USER_API_URL;
System.out.println(registerRequest + " " + registerRequest.getPassword());
ResponseEntity<User> userResponse = restTemplate.postForEntity(url, registerRequest, User.class);
if (!userResponse.getStatusCode().is2xxSuccessful()) {
String errorMessage = "Failed to register user: " + userResponse.getStatusCode() + ". " + userResponse.getBody();
......
......
......@@ -42,7 +42,7 @@ public class AuthController {
if (e.getStatusCode() == HttpStatus.CONFLICT) {
return new ResponseEntity<String>(e.getMessage(), HttpStatus.CONFLICT);
}
e.fillInStackTrace();
e.printStackTrace(System.err);
}
return new ResponseEntity<String>("Algo no fue bien", HttpStatus.UNAUTHORIZED);
......@@ -63,7 +63,7 @@ public class AuthController {
String actualPassword = json.get("actual");
String newPassword = json.get("new");
if (validStrings(email, actualPassword, newPassword))
if (!validStrings(email, actualPassword, newPassword))
return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
try {
......
......
......@@ -2,52 +2,19 @@ package com.uva.authentication.models;
import com.uva.authentication.models.remote.UserRol;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
public class AuthResponse {
private int id;
private String username;
private String name;
private String email;
private String password;
private UserRol rol;
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRol getRol() {
return this.rol;
}
public void setRol(UserRol rol) {
this.rol = rol;
}
}
......@@ -8,7 +8,7 @@ import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@ToString
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
public class RegisterRequest extends LoginRequest {
......
......
package com.uva.authentication.models.remote;
public enum UserRol {
ADMIN, AUTH
ADMIN, AUTH, HOTEL_ADMIN, CLIENT
}
......@@ -46,14 +46,17 @@ public class AuthService {
}
public String register(RegisterRequest registerRequest) {
String plainTextPassword = registerRequest.getPassword();
// Ciframos la contraseña
String hashPass = SecurityUtils.encrypt(registerRequest.getPassword());
String hashPass = SecurityUtils.encrypt(plainTextPassword);
registerRequest.setPassword(hashPass);
// Registramos el usuario
User user = userAPI.registerUser(registerRequest);
LoginRequest logReq = new LoginRequest();
BeanUtils.copyProperties(user, logReq);
// Recuperamos la contraseña y lo loggeamos
logReq.setPassword(plainTextPassword);
System.err.println(logReq);
return login(logReq);
}
......
......
......@@ -22,32 +22,33 @@ public class SecurityConfig {
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(authorize -> authorize
// Permitir OPTIONS sin autenticación
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// Acceso restringido a usuarios y administradores
.requestMatchers("users", "users/**").hasAnyRole(
UserRol.CLIENT.toString(),
UserRol.HOTEL_ADMIN.toString(),
UserRol.ADMIN.toString())
// Acceso restringido a gestores de hoteles y administradores
.requestMatchers(HttpMethod.GET, "hotels", "hotels/*").hasAnyRole(
UserRol.CLIENT.toString(),
UserRol.HOTEL_ADMIN.toString(),
UserRol.ADMIN.toString())
.requestMatchers("hotels", "hotels/**")
.hasAnyRole(UserRol.ADMIN.toString(), UserRol.HOTEL_ADMIN.toString())
// Acceso restringido a cualquier usuario del sistema
.requestMatchers("bookings", "bookings/**")
.hasAnyRole(UserRol.ADMIN.toString(), UserRol.HOTEL_ADMIN.toString(),
UserRol.CLIENT.toString())
// Rechazar el resto
.anyRequest().denyAll())
// Registra el filtro antes del filtro estándar de autenticación
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable());
// .authorizeHttpRequests(authorize -> authorize
// // Permitir OPTIONS sin autenticación
// .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// // Acceso restringido a usuarios y administradores
// .requestMatchers("users", "users/**").hasAnyRole(
// UserRol.CLIENT.toString(),
// UserRol.HOTEL_ADMIN.toString(),
// UserRol.ADMIN.toString())
// // Acceso restringido a gestores de hoteles y administradores
// .requestMatchers(HttpMethod.GET, "hotels", "hotels/*").hasAnyRole(
// UserRol.CLIENT.toString(),
// UserRol.HOTEL_ADMIN.toString(),
// UserRol.ADMIN.toString())
// .requestMatchers("hotels", "hotels/**")
// .hasAnyRole(UserRol.ADMIN.toString(), UserRol.HOTEL_ADMIN.toString())
// // Acceso restringido a cualquier usuario del sistema
// .requestMatchers("bookings", "bookings/**")
// .hasAnyRole(UserRol.ADMIN.toString(), UserRol.HOTEL_ADMIN.toString(),
// UserRol.CLIENT.toString())
// // Rechazar el resto
// .anyRequest().denyAll())
// // Registra el filtro antes del filtro estándar de autenticación
// .addFilterBefore(jwtAuthenticationFilter,
// UsernamePasswordAuthenticationFilter.class);
return http.build();
}
......
......
......@@ -7,6 +7,8 @@ spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.security.user.enabled=false
security.jwt.secret-key=MiClaveDeSeguridadMuyLargaParaQueNoFalleSpringBoot
# 1h in millisecond
security.jwt.expiration-time=3600000
......
......
......@@ -21,7 +21,7 @@ public class HotelManagerAPI {
public Boolean existsHotelManagerById(int id) {
try {
String url = MANAGERS_API_URL + "/{id}";
return restTemplate.getForEntity(url, Map.class, id).getBody().containsKey("id");
return restTemplate.getForObject(url, Map.class, id).containsKey("id");
} catch (HttpClientErrorException e) {
if (e.getStatusCode() != HttpStatus.NOT_FOUND)
throw e;
......
......
......@@ -22,27 +22,31 @@ public class SecurityConfig {
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(authorize -> authorize
// Permitir OPTIONS sin autenticación
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// Acceso restringido a usuarios y administradores
.requestMatchers("users", "users/**").hasAnyRole(
UserRol.CLIENT.toString(), UserRol.HOTEL_ADMIN.toString(), UserRol.ADMIN.toString())
// Acceso restringido a gestores de hoteles y administradores
.requestMatchers(HttpMethod.GET, "hotels", "hotels/*").hasAnyRole(
UserRol.CLIENT.toString(), UserRol.HOTEL_ADMIN.toString(), UserRol.ADMIN.toString())
.requestMatchers("hotels", "hotels/**")
.hasAnyRole(UserRol.ADMIN.toString(), UserRol.HOTEL_ADMIN.toString())
// Acceso restringido a cualquier usuario del sistema
.requestMatchers("bookings", "bookings/**")
.hasAnyRole(UserRol.ADMIN.toString(), UserRol.HOTEL_ADMIN.toString(), UserRol.CLIENT.toString())
// Rechazar el resto
.anyRequest().denyAll())
// Registra el filtro antes del filtro estándar de autenticación
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable());
// .authorizeHttpRequests(authorize -> authorize
// // Permitir OPTIONS sin autenticación
// .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// // Acceso restringido a usuarios y administradores
// .requestMatchers("users", "users/**").hasAnyRole(
// UserRol.CLIENT.toString(), UserRol.HOTEL_ADMIN.toString(),
// UserRol.ADMIN.toString())
// // Acceso restringido a gestores de hoteles y administradores
// .requestMatchers(HttpMethod.GET, "hotels", "hotels/*").hasAnyRole(
// UserRol.CLIENT.toString(), UserRol.HOTEL_ADMIN.toString(),
// UserRol.ADMIN.toString())
// .requestMatchers("hotels", "hotels/**")
// .hasAnyRole(UserRol.ADMIN.toString(), UserRol.HOTEL_ADMIN.toString())
// // Acceso restringido a cualquier usuario del sistema
// .requestMatchers("bookings", "bookings/**")
// .hasAnyRole(UserRol.ADMIN.toString(), UserRol.HOTEL_ADMIN.toString(),
// UserRol.CLIENT.toString())
// // Rechazar el resto
// .anyRequest().denyAll())
// // Registra el filtro antes del filtro estándar de autenticación
// .addFilterBefore(jwtAuthenticationFilter,
// UsernamePasswordAuthenticationFilter.class);
return http.build();
}
......
......
......@@ -61,10 +61,11 @@ public class HotelController {
// Añadir un hotel con sus habitaciones
@PostMapping
public ResponseEntity<Hotel> addHotel(@RequestBody Hotel hotel) {
public ResponseEntity<?> addHotel(@RequestBody Hotel hotel) {
boolean exist = hotelManagerAPI.existsHotelManagerById(hotel.getManagerId());
if (exist) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
if (!exist) {
return new ResponseEntity<>(
"No existe el manager con id " + String.valueOf(hotel.getManagerId()), HttpStatus.BAD_REQUEST);
}
Hotel savedHotel = hotelRepository.save(hotel);
return new ResponseEntity<>(savedHotel, HttpStatus.CREATED);
......
......
......@@ -46,4 +46,9 @@ public class Hotel {
@Column(name = "manager_id")
private int managerId;
public void setRooms(List<Room> rooms) {
this.rooms = rooms;
rooms.forEach(r -> r.setHotel(this));
}
}
......@@ -32,10 +32,13 @@ public class Room {
@JoinColumn(name = "hotel_id", referencedColumnName = "id")
@JsonIgnore
private Hotel hotel;
@Column(name = "room_number", nullable = false)
private String roomNumber;
@Column(name = "type", nullable = false)
private RoomType type;
@Column(name = "available", nullable = false)
private boolean available;
}
......@@ -15,22 +15,4 @@ public interface RoomRepository extends JpaRepository<Room, Integer> {
// Encontrar todas las habitaciones de un hotel
List<Room> findAllByHotelId(int hotelId);
// Encontrar habitaciones disponibles de un hotel en un rango de fechas
@Query("""
SELECT r FROM Room r
WHERE r.hotel.id = ?1
AND r.available = true
AND NOT EXISTS (
SELECT b FROM Booking b
WHERE b.roomId.id = r.id
AND (
b.endDate >= ?2
OR
?3 >= b.startDate
)
)
""")
List<Room> findAvailableRoomsByHotelAndDates_(
int hotelId, LocalDate startDate, LocalDate endDate);
}
......@@ -7,10 +7,12 @@ spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.security.user.enabled=false
security.jwt.secret-key=MiClaveDeSeguridadMuyLargaParaQueNoFalleSpringBoot
# 1h in millisecond
security.jwt.expiration-time=3600000
security.jwt.kid=cYz3kNRLAirxVhHXQ5rh5xKrOwHwZVui
external.services.managers.url="http://localhost:8201/users/managers"
external.services.bookings.url="http://localhost:8401/bookings"
\ No newline at end of file
external.services.managers.url=http://localhost:8201/users/managers
external.services.bookings.url=http://localhost:8401/bookings
\ No newline at end of file
......@@ -16,7 +16,7 @@ public class BookingAPI {
@Autowired
private RestTemplate restTemplate;
@Value("${external.services.booking.url}")
@Value("${external.services.bookings.url}")
private String BOOKING_API_URL;
public List<Booking> getAllBookingsByUserId(int id) {
......
......
......@@ -22,32 +22,33 @@ public class SecurityConfig {
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(authorize -> authorize
// Permitir OPTIONS sin autenticación
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// Acceso restringido a usuarios y administradores
.requestMatchers("users", "users/**").hasAnyRole(
UserRol.CLIENT.toString(),
UserRol.HOTEL_ADMIN.toString(),
UserRol.ADMIN.toString())
// Acceso restringido a gestores de hoteles y administradores
.requestMatchers(HttpMethod.GET, "hotels", "hotels/*").hasAnyRole(
UserRol.CLIENT.toString(),
UserRol.HOTEL_ADMIN.toString(),
UserRol.ADMIN.toString())
.requestMatchers("hotels", "hotels/**")
.hasAnyRole(UserRol.ADMIN.toString(), UserRol.HOTEL_ADMIN.toString())
// Acceso restringido a cualquier usuario del sistema
.requestMatchers("bookings", "bookings/**")
.hasAnyRole(UserRol.ADMIN.toString(), UserRol.HOTEL_ADMIN.toString(),
UserRol.CLIENT.toString())
// Rechazar el resto
.anyRequest().denyAll())
// Registra el filtro antes del filtro estándar de autenticación
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable());
// .authorizeHttpRequests(authorize -> authorize
// // Permitir OPTIONS sin autenticación
// .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// // Acceso restringido a usuarios y administradores
// .requestMatchers("users", "users/**").hasAnyRole(
// UserRol.CLIENT.toString(),
// UserRol.HOTEL_ADMIN.toString(),
// UserRol.ADMIN.toString())
// // Acceso restringido a gestores de hoteles y administradores
// .requestMatchers(HttpMethod.GET, "hotels", "hotels/*").hasAnyRole(
// UserRol.CLIENT.toString(),
// UserRol.HOTEL_ADMIN.toString(),
// UserRol.ADMIN.toString())
// .requestMatchers("hotels", "hotels/**")
// .hasAnyRole(UserRol.ADMIN.toString(), UserRol.HOTEL_ADMIN.toString())
// // Acceso restringido a cualquier usuario del sistema
// .requestMatchers("bookings", "bookings/**")
// .hasAnyRole(UserRol.ADMIN.toString(), UserRol.HOTEL_ADMIN.toString(),
// UserRol.CLIENT.toString())
// // Rechazar el resto
// .anyRequest().denyAll())
// // Registra el filtro antes del filtro estándar de autenticación
// .addFilterBefore(jwtAuthenticationFilter,
// UsernamePasswordAuthenticationFilter.class);
return http.build();
}
......
......
......@@ -3,6 +3,7 @@ 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;
......@@ -20,6 +21,7 @@ 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;
......@@ -45,9 +47,11 @@ public class UserController {
// Common
@PostMapping
public ResponseEntity<?> addUser(@RequestBody User user) {
public ResponseEntity<?> addUser(@RequestBody AuthResponse body) {
User user = new User();
BeanUtils.copyProperties(body, user);
userService.registerNewUser(user);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
return new ResponseEntity<User>(user, HttpStatus.ACCEPTED);
}
@PutMapping("/{id}")
......
......
package com.uva.api.models;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class AuthResponse {
private int id;
private String username;
private String name;
private String email;
private String password;
private UserRol rol;
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRol getRol() {
return this.rol;
}
public void setRol(UserRol rol) {
this.rol = rol;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment