Fix: CORS.
This commit is contained in:
@@ -76,7 +76,7 @@
|
||||
<dependency>
|
||||
<groupId>net.miarma</groupId>
|
||||
<artifactId>backlib</artifactId>
|
||||
<version>1.0.1</version>
|
||||
<version>1.1.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
package net.miarma.backend.huertos.client;
|
||||
|
||||
import net.miarma.backlib.dto.ApiErrorDto;
|
||||
import net.miarma.backlib.dto.LoginRequest;
|
||||
import net.miarma.backlib.dto.LoginResponse;
|
||||
import net.miarma.backlib.exception.*;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.client.HttpServerErrorException;
|
||||
@@ -25,10 +28,46 @@ public class CoreAuthClient {
|
||||
|
||||
|
||||
public LoginResponse login(LoginRequest req) {
|
||||
return restTemplate.postForObject(
|
||||
coreUrl + "/auth/login",
|
||||
req,
|
||||
LoginResponse.class
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
|
||||
HttpEntity<LoginRequest> requestEntity = new HttpEntity<>(req, headers);
|
||||
|
||||
ResponseEntity<LoginResponse> response = restTemplate.exchange(
|
||||
coreUrl + "/auth/login",
|
||||
HttpMethod.POST,
|
||||
requestEntity,
|
||||
LoginResponse.class
|
||||
);
|
||||
|
||||
if (!response.getStatusCode().is2xxSuccessful()) {
|
||||
handleError(response);
|
||||
}
|
||||
|
||||
return response.getBody();
|
||||
}
|
||||
|
||||
private void handleError(ResponseEntity<?> response) {
|
||||
HttpStatusCode statusCode = response.getStatusCode();
|
||||
|
||||
if (statusCode.equals(HttpStatus.UNAUTHORIZED)) {
|
||||
throw new UnauthorizedException("Credenciales no válidas");
|
||||
} else if (statusCode.equals(HttpStatus.FORBIDDEN)) {
|
||||
throw new ForbiddenException("Esa cuenta está desactivada");
|
||||
} else if (statusCode.equals(HttpStatus.NOT_FOUND)) {
|
||||
throw new NotFoundException("No encontrado");
|
||||
} else if (statusCode.equals(HttpStatus.BAD_REQUEST)) {
|
||||
throw new BadRequestException("Datos de solicitud faltantes");
|
||||
} else if (statusCode.equals(HttpStatus.CONFLICT)) {
|
||||
throw new ConflictException("Ya existe");
|
||||
} else if (statusCode.equals(HttpStatus.UNPROCESSABLE_CONTENT)) {
|
||||
throw new ValidationException("general", "Los datos no tienen formato válido");
|
||||
} else {
|
||||
if (statusCode.is4xxClientError()) {
|
||||
throw new BadRequestException(response.getBody().toString());
|
||||
} else {
|
||||
throw new RuntimeException("Error desconocido");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,11 +4,14 @@ import net.miarma.backend.huertos.dto.RequestMetadataDto;
|
||||
import net.miarma.backend.huertos.model.RequestMetadata;
|
||||
import net.miarma.backend.huertos.util.UsernameGenerator;
|
||||
import net.miarma.backlib.dto.*;
|
||||
import net.miarma.backlib.exception.*;
|
||||
import net.miarma.backlib.security.PasswordGenerator;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
@@ -19,85 +22,170 @@ public class HuertosWebClient {
|
||||
|
||||
private final RestTemplate restTemplate;
|
||||
private final String coreUrl;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public HuertosWebClient(@Qualifier("secureRestTemplate") RestTemplate restTemplate,
|
||||
@Value("${core.url}") String coreUrl) {
|
||||
@Value("${core.url}") String coreUrl,
|
||||
ObjectMapper objectMapper) {
|
||||
this.restTemplate = restTemplate;
|
||||
this.coreUrl = coreUrl;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public UserWithCredentialDto getUserWithCredential(UUID userId, Byte serviceId) {
|
||||
return restTemplate.getForObject(
|
||||
ResponseEntity<UserWithCredentialDto> response = restTemplate.exchange(
|
||||
coreUrl + "/users/{user_id}/service/{service_id}",
|
||||
HttpMethod.GET,
|
||||
null,
|
||||
UserWithCredentialDto.class,
|
||||
userId, serviceId
|
||||
);
|
||||
|
||||
if (!response.getStatusCode().is2xxSuccessful()) {
|
||||
handleError(response);
|
||||
}
|
||||
|
||||
return response.getBody();
|
||||
}
|
||||
|
||||
public List<UserWithCredentialDto> getAllUsersWithCredentials(Byte serviceId) {
|
||||
UserWithCredentialDto[] arr = restTemplate.getForObject(
|
||||
coreUrl + "/users/service/{service_id}",
|
||||
UserWithCredentialDto[].class,
|
||||
serviceId
|
||||
ResponseEntity<UserWithCredentialDto[]> response = restTemplate.exchange(
|
||||
coreUrl + "/users/service/{service_id}",
|
||||
HttpMethod.GET,
|
||||
null,
|
||||
UserWithCredentialDto[].class,
|
||||
serviceId
|
||||
);
|
||||
|
||||
if (!response.getStatusCode().is2xxSuccessful()) {
|
||||
handleError(response);
|
||||
}
|
||||
|
||||
UserWithCredentialDto[] arr = response.getBody();
|
||||
return arr == null ? List.of() : Arrays.asList(arr);
|
||||
}
|
||||
|
||||
public UserWithCredentialDto createUser(
|
||||
RequestMetadataDto metadataDto
|
||||
) {
|
||||
|
||||
public UserWithCredentialDto createUser(RequestMetadataDto metadataDto) {
|
||||
// 1. Crear el usuario
|
||||
CreateUserDto userDto = new CreateUserDto(metadataDto.displayName(), null);
|
||||
UserDto createdUser = restTemplate.postForObject(
|
||||
coreUrl + "/users",
|
||||
userDto,
|
||||
UserDto.class
|
||||
HttpEntity<CreateUserDto> userRequestEntity = new HttpEntity<>(userDto);
|
||||
|
||||
ResponseEntity<UserDto> userResponse = restTemplate.exchange(
|
||||
coreUrl + "/users",
|
||||
HttpMethod.POST,
|
||||
userRequestEntity,
|
||||
UserDto.class
|
||||
);
|
||||
|
||||
if (createdUser == null)
|
||||
if (!userResponse.getStatusCode().is2xxSuccessful()) {
|
||||
handleError(userResponse);
|
||||
}
|
||||
|
||||
UserDto createdUser = userResponse.getBody();
|
||||
if (createdUser == null) {
|
||||
throw new RuntimeException("No se pudo crear al usuario");
|
||||
}
|
||||
|
||||
CreateCredentialDto credDto = new CreateCredentialDto(
|
||||
createdUser.getUserId(),
|
||||
(byte)1,
|
||||
UsernameGenerator.generate(metadataDto.displayName(), metadataDto.memberNumber()),
|
||||
metadataDto.email(),
|
||||
PasswordGenerator.generate(8),
|
||||
(byte)1
|
||||
);
|
||||
CredentialDto createdCred = restTemplate.postForObject(
|
||||
coreUrl + "/credentials",
|
||||
credDto,
|
||||
CredentialDto.class
|
||||
createdUser.getUserId(),
|
||||
(byte) 1,
|
||||
UsernameGenerator.generate(metadataDto.displayName(), metadataDto.memberNumber()),
|
||||
metadataDto.email(),
|
||||
PasswordGenerator.generate(8),
|
||||
(byte) 1
|
||||
);
|
||||
|
||||
if (createdCred == null)
|
||||
HttpEntity<CreateCredentialDto> credRequestEntity = new HttpEntity<>(credDto);
|
||||
|
||||
ResponseEntity<CredentialDto> credResponse = restTemplate.exchange(
|
||||
coreUrl + "/credentials",
|
||||
HttpMethod.POST,
|
||||
credRequestEntity,
|
||||
CredentialDto.class
|
||||
);
|
||||
|
||||
if (!credResponse.getStatusCode().is2xxSuccessful()) {
|
||||
handleError(credResponse);
|
||||
}
|
||||
|
||||
CredentialDto createdCred = credResponse.getBody();
|
||||
if (createdCred == null) {
|
||||
throw new RuntimeException("No se pudo crear la cuenta del usuario");
|
||||
}
|
||||
|
||||
return new UserWithCredentialDto(createdUser, createdCred);
|
||||
}
|
||||
|
||||
public void deleteUser(UUID userId) {
|
||||
try {
|
||||
restTemplate.delete(coreUrl + "/users/{user_id}", userId);
|
||||
} catch (Exception e) { }
|
||||
ResponseEntity<Void> response = restTemplate.exchange(
|
||||
coreUrl + "/users/{user_id}",
|
||||
HttpMethod.DELETE,
|
||||
null,
|
||||
Void.class,
|
||||
userId
|
||||
);
|
||||
|
||||
if (!response.getStatusCode().is2xxSuccessful()) {
|
||||
if (response.getStatusCode() != HttpStatus.NOT_FOUND) {
|
||||
handleError(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Byte getCredentialStatus(UUID userId, Byte serviceId) {
|
||||
return restTemplate.getForObject(
|
||||
ResponseEntity<Byte> response = restTemplate.exchange(
|
||||
coreUrl + "/credentials/{service_id}/{user_id}/status",
|
||||
HttpMethod.GET,
|
||||
null,
|
||||
Byte.class,
|
||||
serviceId, userId
|
||||
);
|
||||
|
||||
if (!response.getStatusCode().is2xxSuccessful()) {
|
||||
handleError(response);
|
||||
}
|
||||
|
||||
return response.getBody();
|
||||
}
|
||||
|
||||
public void updateCredentialStatus(UUID userId, Byte serviceId, Byte newStatus) {
|
||||
ChangeStatusRequest req = new ChangeStatusRequest(newStatus);
|
||||
restTemplate.put(
|
||||
HttpEntity<ChangeStatusRequest> requestEntity = new HttpEntity<>(req);
|
||||
|
||||
ResponseEntity<Void> response = restTemplate.exchange(
|
||||
coreUrl + "/credentials/{service_id}/{user_id}/status",
|
||||
req,
|
||||
HttpMethod.PUT,
|
||||
requestEntity,
|
||||
Void.class,
|
||||
serviceId, userId
|
||||
);
|
||||
|
||||
if (!response.getStatusCode().is2xxSuccessful()) {
|
||||
handleError(response);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleError(ResponseEntity<?> response) {
|
||||
HttpStatusCode statusCode = response.getStatusCode();
|
||||
|
||||
if (statusCode.equals(HttpStatus.UNAUTHORIZED)) {
|
||||
throw new UnauthorizedException("Credenciales no válidas");
|
||||
} else if (statusCode.equals(HttpStatus.FORBIDDEN)) {
|
||||
throw new ForbiddenException("Esa cuenta está desactivada");
|
||||
} else if (statusCode.equals(HttpStatus.NOT_FOUND)) {
|
||||
throw new NotFoundException("No encontrado");
|
||||
} else if (statusCode.equals(HttpStatus.BAD_REQUEST)) {
|
||||
throw new BadRequestException("Datos de solicitud faltantes");
|
||||
} else if (statusCode.equals(HttpStatus.CONFLICT)) {
|
||||
throw new ConflictException("Ya existe");
|
||||
} else if (statusCode.equals(HttpStatus.UNPROCESSABLE_CONTENT)) {
|
||||
throw new ValidationException("general", "Los datos no tienen formato válido");
|
||||
} else {
|
||||
if (statusCode.is4xxClientError()) {
|
||||
throw new BadRequestException(response.getBody().toString());
|
||||
} else {
|
||||
throw new RuntimeException("Error desconocido");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
package net.miarma.backend.huertos.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class CorsConfig {
|
||||
|
||||
@Bean
|
||||
public WebMvcConfigurer corsConfigurer() {
|
||||
return new WebMvcConfigurer() {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedOrigins(
|
||||
"http://localhost:3000"
|
||||
)
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
|
||||
.allowedHeaders("*")
|
||||
.allowCredentials(true);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
package net.miarma.backend.huertos.config;
|
||||
|
||||
import io.jsonwebtoken.io.IOException;
|
||||
import net.miarma.backend.huertos.service.CoreAuthService;
|
||||
import net.miarma.backlib.security.CoreAuthTokenHolder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.client.ClientHttpRequestInterceptor;
|
||||
import org.springframework.http.client.ClientHttpResponse;
|
||||
import org.springframework.web.client.ResponseErrorHandler;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -15,20 +18,31 @@ public class RestTemplateConfig {
|
||||
|
||||
@Bean
|
||||
public RestTemplate authRestTemplate() {
|
||||
return new RestTemplate();
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
restTemplate.setErrorHandler(new NoOpResponseErrorHandler());
|
||||
return restTemplate;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RestTemplate secureRestTemplate(CoreAuthService coreAuthService) {
|
||||
RestTemplate rt = new RestTemplate();
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
rt.getInterceptors().add((request, body, execution) -> {
|
||||
restTemplate.getInterceptors().add((request, body, execution) -> {
|
||||
String token = coreAuthService.getToken();
|
||||
request.getHeaders().setBearerAuth(token);
|
||||
return execution.execute(request, body);
|
||||
});
|
||||
|
||||
return rt;
|
||||
restTemplate.setErrorHandler(new NoOpResponseErrorHandler());
|
||||
|
||||
return restTemplate;
|
||||
}
|
||||
|
||||
public static class NoOpResponseErrorHandler implements ResponseErrorHandler {
|
||||
@Override
|
||||
public boolean hasError(ClientHttpResponse response) throws IOException {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,18 +5,12 @@ import net.miarma.backlib.http.RestAccessDeniedHandler;
|
||||
import net.miarma.backlib.http.RestAuthEntryPoint;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@@ -37,23 +31,9 @@ public class SecurityConfig {
|
||||
this.accessDeniedHandler = accessDeniedHandler;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
config.setAllowedOrigins(List.of("http://localhost:3000"));
|
||||
config.setAllowedMethods(List.of("GET","POST","PUT","DELETE","OPTIONS"));
|
||||
config.setAllowedHeaders(List.of("*"));
|
||||
config.setAllowCredentials(true);
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", config);
|
||||
return source;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.cors(Customizer.withDefaults())
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.exceptionHandling(ex -> ex
|
||||
|
||||
Reference in New Issue
Block a user