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

Ajustes de acceso

parent 9ff18f3b
Branches
No related tags found
2 merge requests!26Revert "Funciona register",!21Dev/auth backend
......@@ -3,3 +3,7 @@ taller
*.pdf
**/target/
**/.vscode
*.ln
*.tmp
**/tmp
*.log
\ No newline at end of file
......@@ -2,7 +2,6 @@ package com.uva.monolith.services.auth;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
......@@ -24,23 +23,19 @@ public class SecurityConfig {
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/users").access((authentication, context) -> {
String method = context.getRequest().getMethod();
String email = context.getRequest().getParameter("email");
// Permitir POST a /users solo al rol ADMIN
boolean register = method.equals("POST") && authentication.get().getAuthorities().stream()
.anyMatch(auth -> auth.getAuthority().equals("ROLE_ADMIN"));
// Permitir GET a /users con parámetro email solo al rol ADMIN
boolean access = method.equals("GET") && email != null && !email.isEmpty() &&
authentication.get().getAuthorities().stream()
.anyMatch(auth -> auth.getAuthority().equals("ROLE_ADMIN"));
return new AuthorizationDecision(register || access);
})
.requestMatchers("/users/**").hasRole(UserRol.CLIENT.toString())
.requestMatchers("/hotels/**", "/booking/**").permitAll() //
// .requestMatchers("/users/**", "/hotels/**", "/booking/**").authenticated() //
// Protegidas
)
// Permitir todas las conexiones
.requestMatchers("").permitAll()
// Acceso restringido a usuarios y administradores
.requestMatchers("users", "users/**")
.hasAnyRole(UserRol.ADMIN.toString(), UserRol.CLIENT.toString())
// Acceso restringido a gestores de hoteles y administradores
.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);
......
......
......@@ -29,7 +29,6 @@ public class UserService {
return passwordEncoder.encode(password);
}
@GetMapping("/users")
public User findByEmail(@RequestParam String email) {
return userRepository.findByEmail(email)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Usuario no encontrado"));
......
......
// TODO eliminar si realmente no necesitamos comunicar un servicio con otro
package com.uva.authentication.api;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -47,8 +48,8 @@ public class UserAPI {
String url = USER_API_URL + "?email={" + email + "}";
try {
ResponseEntity<User> userResponse = // restTemplate.getForEntity(url, User.class, email, headers);
restTemplate.exchange(url, HttpMethod.GET, entity, User.class);
ResponseEntity<User> userResponse = restTemplate.getForEntity(url, User.class, email);
// restTemplate.exchange(url, HttpMethod.GET, entity, User.class);
return userResponse.getBody();
} catch (HttpClientErrorException e) {
if (e.getStatusCode() != HttpStatus.NOT_FOUND)
......
......
......@@ -9,6 +9,7 @@ import com.uva.authentication.models.*;
import com.uva.authentication.services.AuthService;
@RestController
@CrossOrigin(origins = "*")
public class AuthController {
@Autowired
......
......
......@@ -27,9 +27,6 @@ public class AuthService {
@Autowired
private JwtUtil jwtUtil;
@Autowired
private UserAPI userAPI;
@Autowired
private HotelManagerRepository hotelManagerRepository;
......@@ -37,30 +34,22 @@ public class AuthService {
private ClientRepository clientRepository;
@Autowired
private UserRepository userRepository;
private UserAPI userAPI;
private String hashPass(String password) {
// return String.valueOf(Objects.hashCode(password));
String hash = SecurityUtils.encrypt(password);
System.out.println(password + " --> " + hash);
return hash;
}
@Autowired
private UserRepository userRepository;
private boolean authenticateUser(LoginRequest request, User user) {
System.err.println(user);
if (user == null)
return false;
String hashPass = hashPass(request.getPassword());
System.err.println("PASSWORD: " + request.getPassword() + "\n" + hashPass + "\n" +
user.getPassword());
// return hashPass.equals(user.getPassword());
return SecurityUtils.checkPassword(request.getPassword(), user.getPassword());
}
public String login(LoginRequest loginRequest) {
// User user = userAPI.getUserByEmail(loginRequest.getEmail());
User user = userRepository.findByEmail(loginRequest.getEmail())
.orElseThrow(() -> new HttpClientErrorException(HttpStatus.FORBIDDEN, "Invalid credentials"));
.orElseThrow(() -> new HttpClientErrorException(HttpStatus.FORBIDDEN,
"Invalid credentials"));
boolean isAuthenticated = authenticateUser(loginRequest, user);
if (!isAuthenticated) {
......@@ -75,29 +64,30 @@ public class AuthService {
public User register(RegisterRequest registerRequest) {
// User user = userAPI.getUserByEmail(registerRequest.getEmail());
Optional<User> user = userRepository.findByEmail(null);
Optional<User> user = userRepository.findByEmail(registerRequest.getEmail());
if (user.isPresent())
throw new HttpClientErrorException(HttpStatus.CONFLICT, "Email already in use");
String hashPass = hashPass(registerRequest.getPassword());
String hashPass = SecurityUtils.encrypt(registerRequest.getPassword());
// return userAPI.registerUser(registerRequest);
User newUser;
if (registerRequest.getRol() == UserRol.HOTEL_ADMIN) {
HotelManager hm = new HotelManager();
hm.setName(registerRequest.getName());
hm.setEmail(registerRequest.getEmail());
hm.setRol(registerRequest.getRol());
// hm.setName(registerRequest.getName());
// hm.setEmail(registerRequest.getEmail());
// hm.setRol(registerRequest.getRol());
BeanUtils.copyProperties(registerRequest, hm);
hm.setPassword(hashPass);
newUser = hotelManagerRepository.save(hm);
} else {
Client client = new Client();
client.setName(registerRequest.getName());
client.setEmail(registerRequest.getEmail());
// client.setName(registerRequest.getName());
// client.setEmail(registerRequest.getEmail());
BeanUtils.copyProperties(registerRequest, client);
client.setRol(UserRol.CLIENT);
client.setPassword(hashPass);
newUser = clientRepository.save(client);
}
System.out.println("<--\n" + hashPass + "\n" + newUser.getPassword() + "\n-->");
return newUser;
}
......
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please to comment