Compare commits
5 Commits
33b3a460ca
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dead14b1bd | ||
|
|
6a5a4b6871 | ||
|
|
d3c19a6186 | ||
|
|
681b6a3ba2 | ||
|
|
4303caaf74 |
11
TODO
11
TODO
@@ -1,8 +1,6 @@
|
||||
POR HACER --------------------------------
|
||||
- sistema comun de errores en back & front
|
||||
- cambiar contraseña (?)
|
||||
- documentación
|
||||
- implementar urlParams para filtros
|
||||
- documentación
|
||||
- mail wrapper
|
||||
|
||||
RESUELTO ---------------------------------
|
||||
@@ -11,3 +9,10 @@ RESUELTO ---------------------------------
|
||||
- aceptar solicitudes LE/Colab (sobre todo por crear preusers)
|
||||
- mejorar queries para no filtrar en memoria -> IMPOSIBLE CON ENDPOINTS INTERNOS DE CORE: RESUELTO CON CACHING
|
||||
- normalizar el uso de services y repositories desde otros services y repositories
|
||||
- sistema comun de errores en back & front
|
||||
- nombre del requester
|
||||
- cambiar contraseña (?)
|
||||
- todos los socios en dropdown ingresos
|
||||
- validacion LE/COlab
|
||||
- createdAt custom en ing,gastos
|
||||
- editar createdAt
|
||||
@@ -4,7 +4,7 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>backlib</artifactId>
|
||||
<groupId>net.miarma</groupId>
|
||||
<version>1.0.1</version>
|
||||
<version>1.1.0</version>
|
||||
|
||||
<properties>
|
||||
<java.version>25</java.version>
|
||||
|
||||
@@ -7,11 +7,15 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class ApiValidationErrorDto {
|
||||
private int status;
|
||||
private Map<String,String> errors;
|
||||
private String path;
|
||||
private Instant timestamp;
|
||||
|
||||
public ApiValidationErrorDto(Map<String,String> errors) {
|
||||
public ApiValidationErrorDto(Map<String,String> errors, String path) {
|
||||
this.status = 422;
|
||||
this.errors = errors;
|
||||
this.path = path;
|
||||
this.timestamp = Instant.now();
|
||||
}
|
||||
|
||||
@@ -19,6 +23,22 @@ public class ApiValidationErrorDto {
|
||||
return errors;
|
||||
}
|
||||
|
||||
public int getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(int status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getPath() {
|
||||
return path;
|
||||
}
|
||||
|
||||
public void setPath(String path) {
|
||||
this.path = path;
|
||||
}
|
||||
|
||||
public void setErrors(Map<String,String> errors) {
|
||||
this.errors = errors;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package net.miarma.backlib.filter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
public class RequestLoggingFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(RequestLoggingFilter.class);
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain
|
||||
) throws ServletException, IOException {
|
||||
|
||||
long start = System.currentTimeMillis();
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
|
||||
long duration = System.currentTimeMillis() - start;
|
||||
|
||||
log.info("({}) {} {} -> {} ({} ms)",
|
||||
request.getRemoteAddr(),
|
||||
request.getMethod(),
|
||||
request.getRequestURI(),
|
||||
response.getStatus(),
|
||||
duration
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
package net.miarma.backend.huertos.config;
|
||||
package net.miarma.backlib.http;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class CorsConfig {
|
||||
@Profile("dev") // esto asegura que solo se cargue en dev
|
||||
public class DevCorsConfig {
|
||||
|
||||
@Bean
|
||||
public WebMvcConfigurer corsConfigurer() {
|
||||
@@ -14,12 +16,10 @@ public class CorsConfig {
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedOrigins(
|
||||
"http://localhost:3000"
|
||||
)
|
||||
.allowedOrigins("http://localhost:3000") // tu frontend React
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
|
||||
.allowedHeaders("*")
|
||||
.allowCredentials(true);
|
||||
.allowCredentials(true)
|
||||
.allowedHeaders("*");
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -84,9 +84,10 @@ public class GlobalExceptionHandler {
|
||||
}
|
||||
|
||||
@ExceptionHandler(ValidationException.class)
|
||||
public ResponseEntity<ApiValidationErrorDto> handleValidation(ValidationException ex) {
|
||||
public ResponseEntity<ApiValidationErrorDto> handleValidation(
|
||||
ValidationException ex, HttpServletRequest req) {
|
||||
Map<String, String> errors = Map.of(ex.getField(), ex.getMessage());
|
||||
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_CONTENT).body(new ApiValidationErrorDto(errors));
|
||||
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_CONTENT).body(new ApiValidationErrorDto(errors, req.getRequestURI()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
artifactId=backlib
|
||||
groupId=net.miarma
|
||||
version=1.0.1
|
||||
version=1.1.0
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/config/SecurityCommonConfig.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/ApiErrorDto.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/ApiValidationErrorDto.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/ChangeAvatarRequest.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/ChangePasswordRequest.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/ChangeRoleRequest.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/ChangeStatusRequest.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/CreateCredentialDto.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/CreateUserDto.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/CredentialDto.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/FileDto.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/dto/LoginRequest.java
|
||||
@@ -19,10 +21,13 @@
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/exception/NotFoundException.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/exception/UnauthorizedException.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/exception/ValidationException.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/filter/RequestLoggingFilter.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/http/DevCorsConfig.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/http/GlobalExceptionHandler.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/http/RestAccessDeniedHandler.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/http/RestAuthEntryPoint.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/security/CoreAuthTokenHolder.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/security/JwtService.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/security/PasswordGenerator.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/security/ServiceAuthFilter.java
|
||||
/home/jomaa/git/miarma-backend/backlib/src/main/java/net/miarma/backlib/util/UuidUtil.java
|
||||
|
||||
10
build-upload.sh
Executable file
10
build-upload.sh
Executable file
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
|
||||
cd core/
|
||||
mvn clean package
|
||||
cd ..
|
||||
cd huertos/
|
||||
mvn clean package
|
||||
cd ..
|
||||
scp core/target/core-1.0.0.jar jomaa@10.0.0.254:/home/jomaa/transfer
|
||||
scp huertos/target/huertos-1.0.0.jar jomaa@10.0.0.254:/home/jomaa/transfer
|
||||
@@ -83,7 +83,7 @@
|
||||
<dependency>
|
||||
<groupId>net.miarma</groupId>
|
||||
<artifactId>backlib</artifactId>
|
||||
<version>1.0.1</version>
|
||||
<version>1.1.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
package net.miarma.backend.core.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",
|
||||
"http://localhost:8081",
|
||||
"http://huertos:8081"
|
||||
)
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
|
||||
.allowedHeaders("*")
|
||||
.allowCredentials(true);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -5,22 +5,16 @@ 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.authentication.AuthenticationManager;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||
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.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
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;
|
||||
import java.util.Optional;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@@ -29,34 +23,27 @@ public class SecurityConfig {
|
||||
private final JwtFilter jwtFilter;
|
||||
private final RestAuthEntryPoint authEntryPoint;
|
||||
private final RestAccessDeniedHandler accessDeniedHandler;
|
||||
private final CorsConfigurationSource corsConfigurationSource;
|
||||
|
||||
public SecurityConfig(
|
||||
JwtFilter jwtFilter,
|
||||
RestAuthEntryPoint authEntryPoint,
|
||||
RestAccessDeniedHandler accessDeniedHandler
|
||||
RestAccessDeniedHandler accessDeniedHandler,
|
||||
Optional<CorsConfigurationSource> corsConfigurationSource
|
||||
) {
|
||||
this.jwtFilter = jwtFilter;
|
||||
this.authEntryPoint = authEntryPoint;
|
||||
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;
|
||||
this.corsConfigurationSource = corsConfigurationSource.orElse(null);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
if (corsConfigurationSource != null) {
|
||||
http.cors(Customizer.withDefaults());
|
||||
}
|
||||
|
||||
http
|
||||
.cors(Customizer.withDefaults())
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.exceptionHandling(ex -> ex
|
||||
@@ -64,7 +51,10 @@ public class SecurityConfig {
|
||||
.accessDeniedHandler(accessDeniedHandler)
|
||||
)
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/auth/**", "/screenshot").permitAll()
|
||||
.requestMatchers("/auth/login").permitAll()
|
||||
.requestMatchers("/auth/refresh").permitAll()
|
||||
.requestMatchers("/auth/change-password").permitAll()
|
||||
.requestMatchers("/screenshot").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import net.miarma.backlib.dto.*;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
@@ -14,25 +15,16 @@ import net.miarma.backend.core.model.Credential;
|
||||
import net.miarma.backend.core.service.AuthService;
|
||||
import net.miarma.backend.core.service.CredentialService;
|
||||
import net.miarma.backlib.security.JwtService;
|
||||
import net.miarma.backlib.dto.ChangePasswordRequest;
|
||||
import net.miarma.backlib.dto.LoginRequest;
|
||||
import net.miarma.backlib.dto.LoginResponse;
|
||||
import net.miarma.backlib.dto.RegisterRequest;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/auth")
|
||||
public class AuthController {
|
||||
|
||||
private final CredentialService credentialService;
|
||||
private final JwtService jwtService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final AuthService authService;
|
||||
|
||||
public AuthController(CredentialService credentialService, JwtService jwtService,
|
||||
PasswordEncoder passwordEncoder, AuthService authService) {
|
||||
this.credentialService = credentialService;
|
||||
public AuthController(JwtService jwtService, AuthService authService) {
|
||||
this.jwtService = jwtService;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.authService = authService;
|
||||
}
|
||||
|
||||
@@ -49,15 +41,29 @@ public class AuthController {
|
||||
return ResponseEntity.ok(authService.register(request));
|
||||
}
|
||||
|
||||
@PostMapping("/refresh")
|
||||
@GetMapping("/refresh")
|
||||
public ResponseEntity<?> refreshToken(@RequestHeader("Authorization") String authHeader) {
|
||||
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
||||
return ResponseEntity.status(401).body("Token missing");
|
||||
return ResponseEntity.status(401).body(
|
||||
new ApiErrorDto(
|
||||
401,
|
||||
"Unauthorized",
|
||||
"No hay token",
|
||||
"/v2/core/auth/change-password"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
String token = authHeader.substring(7);
|
||||
if (!jwtService.validateToken(token)) {
|
||||
return ResponseEntity.status(401).body("Invalid token");
|
||||
return ResponseEntity.status(401).body(
|
||||
new ApiErrorDto(
|
||||
401,
|
||||
"Unauthorized",
|
||||
"Invalid token",
|
||||
"/v2/core/auth/change-password"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
UUID userId = jwtService.getUserId(token);
|
||||
@@ -75,35 +81,37 @@ public class AuthController {
|
||||
@PostMapping("/change-password")
|
||||
public ResponseEntity<?> changePassword(
|
||||
@RequestHeader("Authorization") String authHeader,
|
||||
@Valid @RequestBody ChangePasswordRequest request
|
||||
@RequestBody ChangePasswordRequest request
|
||||
) {
|
||||
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
||||
return ResponseEntity.status(401).body("Token missing");
|
||||
return ResponseEntity.status(401).body(
|
||||
new ApiErrorDto(
|
||||
401,
|
||||
"Unauthorized",
|
||||
"No hay token",
|
||||
"/v2/core/auth/change-password"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
String token = authHeader.substring(7);
|
||||
if (!jwtService.validateToken(token)) {
|
||||
return ResponseEntity.status(401).body("Invalid token");
|
||||
return ResponseEntity.status(401).body(
|
||||
new ApiErrorDto(
|
||||
401,
|
||||
"Unauthorized",
|
||||
"Invalid token",
|
||||
"/v2/core/auth/change-password"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
UUID userId = jwtService.getUserId(token);
|
||||
|
||||
Credential cred = credentialService.getByUserId(userId)
|
||||
.stream()
|
||||
.filter(c -> c.getServiceId().equals(request.serviceId()))
|
||||
.findFirst().get();
|
||||
if (cred == null) {
|
||||
return ResponseEntity.status(404).body("Credential not found");
|
||||
authService.changePassword(userId, request);
|
||||
return ResponseEntity.ok(Map.of("message", "Contraseña cambiada correctamente"));
|
||||
}
|
||||
|
||||
if (!passwordEncoder.matches(request.oldPassword(), cred.getPassword())) {
|
||||
return ResponseEntity.status(400).body("Old password is incorrect");
|
||||
}
|
||||
|
||||
credentialService.updatePassword(cred.getCredentialId(), request);
|
||||
|
||||
return ResponseEntity.ok(Map.of("message", "Password changed successfully"));
|
||||
}
|
||||
|
||||
@GetMapping("/validate")
|
||||
public ResponseEntity<Boolean> validate(@RequestHeader("Authorization") String authHeader) {
|
||||
|
||||
@@ -44,33 +44,44 @@ public class FileController {
|
||||
return ResponseEntity.ok(files);
|
||||
}
|
||||
|
||||
@GetMapping("/{fileId}")
|
||||
@PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#fileId, authentication.principal.userId)")
|
||||
@GetMapping("/{file_id}")
|
||||
@PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#file_id, authentication.principal.userId)")
|
||||
public ResponseEntity<File> getById(@PathVariable("file_id") UUID fileId) {
|
||||
File file = fileService.getById(fileId);
|
||||
return ResponseEntity.ok(file);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@PostMapping(consumes = "multipart/form-data")
|
||||
@PreAuthorize("hasRole('ADMIN') or #uploadedBy == authentication.principal.userId")
|
||||
public ResponseEntity<FileDto.Response> create(
|
||||
@RequestBody FileDto.Request dto,
|
||||
@RequestPart("file") MultipartFile file
|
||||
@RequestPart("file") MultipartFile file,
|
||||
@RequestPart("fileName") String fileName,
|
||||
@RequestPart("mimeType") String mimeType,
|
||||
@RequestPart("uploadedBy") UUID uploadedBy,
|
||||
@RequestPart("context") Integer context
|
||||
) throws IOException {
|
||||
File created = fileService.create(FileMapper.toEntity(dto), file.getBytes());
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(FileMapper.toResponse(created));
|
||||
|
||||
File entity = new File();
|
||||
entity.setFileName(fileName);
|
||||
entity.setMimeType(mimeType);
|
||||
entity.setUploadedBy(uploadedBy);
|
||||
entity.setContext(context.byteValue());
|
||||
|
||||
File created = fileService.create(entity, file.getBytes());
|
||||
return ResponseEntity.status(HttpStatus.CREATED)
|
||||
.body(FileMapper.toResponse(created));
|
||||
}
|
||||
|
||||
@PutMapping("/{fileId}")
|
||||
@PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#fileId, authentication.principal.userId)")
|
||||
public ResponseEntity<File> update(@PathVariable("fileId") UUID fileId, @RequestBody FileDto.Request request) {
|
||||
@PutMapping("/{file_id}")
|
||||
@PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#file_id, authentication.principal.userId)")
|
||||
public ResponseEntity<File> update(@PathVariable("file_id") UUID fileId, @RequestBody FileDto.Request request) {
|
||||
File updated = fileService.update(fileId, FileMapper.toEntity(request));
|
||||
return ResponseEntity.ok(updated);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{fileId}")
|
||||
@PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#fileId, authentication.principal.userId)")
|
||||
public ResponseEntity<Void> delete(@PathVariable("fileId") UUID fileId, @RequestBody Map<String,String> body) throws IOException {
|
||||
@DeleteMapping("/{file_id}")
|
||||
@PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#file_id, authentication.principal.userId)")
|
||||
public ResponseEntity<Void> delete(@PathVariable("file_id") UUID fileId, @RequestBody Map<String,String> body) throws IOException {
|
||||
String filePath = body.get("file_path");
|
||||
Files.deleteIfExists(Paths.get(filePath));
|
||||
fileService.delete(fileId);
|
||||
|
||||
@@ -3,9 +3,7 @@ package net.miarma.backend.core.service;
|
||||
import java.util.UUID;
|
||||
|
||||
import net.miarma.backlib.dto.*;
|
||||
import net.miarma.backlib.exception.ConflictException;
|
||||
import net.miarma.backlib.exception.ForbiddenException;
|
||||
import net.miarma.backlib.exception.UnauthorizedException;
|
||||
import net.miarma.backlib.exception.*;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -75,4 +73,22 @@ public class AuthService {
|
||||
|
||||
return new LoginResponse(token, UserMapper.toDto(user), CredentialMapper.toDto(cred));
|
||||
}
|
||||
|
||||
public void changePassword(UUID userId, ChangePasswordRequest request) {
|
||||
Credential cred = credentialService.getByUserId(userId)
|
||||
.stream()
|
||||
.filter(c -> c.getServiceId().equals(request.serviceId()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new NotFoundException("Cuenta no encontrada"));
|
||||
|
||||
if (!passwordEncoder.matches(request.oldPassword(), cred.getPassword())) {
|
||||
throw new ValidationException("oldPassword", "La contraseña actual es incorrecta");
|
||||
}
|
||||
|
||||
if (request.newPassword().length() < 8) {
|
||||
throw new ValidationException("newPassword", "La nueva contraseña debe tener al menos 8 caracteres");
|
||||
}
|
||||
|
||||
credentialService.updatePassword(cred.getCredentialId(), request);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
|
||||
HttpEntity<LoginRequest> requestEntity = new HttpEntity<>(req, headers);
|
||||
|
||||
ResponseEntity<LoginResponse> response = restTemplate.exchange(
|
||||
coreUrl + "/auth/login",
|
||||
req,
|
||||
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(
|
||||
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(
|
||||
HttpEntity<CreateUserDto> userRequestEntity = new HttpEntity<>(userDto);
|
||||
|
||||
ResponseEntity<UserDto> userResponse = restTemplate.exchange(
|
||||
coreUrl + "/users",
|
||||
userDto,
|
||||
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,
|
||||
(byte) 1,
|
||||
UsernameGenerator.generate(metadataDto.displayName(), metadataDto.memberNumber()),
|
||||
metadataDto.email(),
|
||||
PasswordGenerator.generate(8),
|
||||
(byte)1
|
||||
(byte) 1
|
||||
);
|
||||
CredentialDto createdCred = restTemplate.postForObject(
|
||||
|
||||
HttpEntity<CreateCredentialDto> credRequestEntity = new HttpEntity<>(credDto);
|
||||
|
||||
ResponseEntity<CredentialDto> credResponse = restTemplate.exchange(
|
||||
coreUrl + "/credentials",
|
||||
credDto,
|
||||
HttpMethod.POST,
|
||||
credRequestEntity,
|
||||
CredentialDto.class
|
||||
);
|
||||
|
||||
if (createdCred == null)
|
||||
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,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,11 +12,9 @@ import org.springframework.security.config.annotation.web.configuration.EnableWe
|
||||
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;
|
||||
import java.util.Optional;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@@ -26,34 +24,27 @@ public class SecurityConfig {
|
||||
private final HuertosJwtFilter jwtFilter;
|
||||
private final RestAuthEntryPoint authEntryPoint;
|
||||
private final RestAccessDeniedHandler accessDeniedHandler;
|
||||
private final CorsConfigurationSource corsConfigurationSource;
|
||||
|
||||
public SecurityConfig(
|
||||
HuertosJwtFilter jwtFilter,
|
||||
RestAuthEntryPoint authEntryPoint,
|
||||
RestAccessDeniedHandler accessDeniedHandler
|
||||
RestAccessDeniedHandler accessDeniedHandler,
|
||||
Optional<CorsConfigurationSource> corsConfigurationSource
|
||||
) {
|
||||
this.jwtFilter = jwtFilter;
|
||||
this.authEntryPoint = authEntryPoint;
|
||||
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;
|
||||
this.corsConfigurationSource = corsConfigurationSource.orElse(null);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
if (corsConfigurationSource != null) {
|
||||
http.cors(Customizer.withDefaults());
|
||||
}
|
||||
|
||||
http
|
||||
.cors(Customizer.withDefaults())
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.exceptionHandling(ex -> ex
|
||||
|
||||
@@ -98,6 +98,7 @@ public class IncomeController {
|
||||
@PathVariable("income_id") UUID incomeId,
|
||||
@RequestBody IncomeDto.Request dto
|
||||
) {
|
||||
IO.println(dto.getCreatedAt());
|
||||
return ResponseEntity.ok(
|
||||
IncomeMapper.toResponse(
|
||||
incomeService.update(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package net.miarma.backend.huertos.controller;
|
||||
|
||||
import net.miarma.backend.huertos.dto.*;
|
||||
import net.miarma.backend.huertos.dto.view.VIncomesWithInfoDto;
|
||||
import net.miarma.backend.huertos.mapper.IncomeMapper;
|
||||
import net.miarma.backend.huertos.mapper.RequestMapper;
|
||||
import net.miarma.backend.huertos.security.HuertosPrincipal;
|
||||
@@ -31,7 +32,7 @@ public class MemberController {
|
||||
@GetMapping
|
||||
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||
public ResponseEntity<List<MemberDto>> getAll() {
|
||||
return ResponseEntity.ok(memberService.getAll((byte)1));
|
||||
return ResponseEntity.ok(memberService.getAll());
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
@@ -45,6 +46,12 @@ public class MemberController {
|
||||
);
|
||||
}
|
||||
|
||||
@GetMapping("/dropdown")
|
||||
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||
public ResponseEntity<List<DropdownDto>> getDropdown() {
|
||||
return ResponseEntity.ok(memberService.getDropdown());
|
||||
}
|
||||
|
||||
@GetMapping("/{user_id:[0-9a-fA-F\\-]{36}}")
|
||||
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||
public ResponseEntity<MemberDto> getById(@PathVariable("user_id") UUID userId) {
|
||||
@@ -75,7 +82,7 @@ public class MemberController {
|
||||
|
||||
@GetMapping("/number/{member_number}/incomes")
|
||||
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||
public ResponseEntity<List<IncomeDto.Response>> getMemberIncomes(@PathVariable("member_number") Integer memberNumber) {
|
||||
public ResponseEntity<List<VIncomesWithInfoDto>> getMemberIncomes(@PathVariable("member_number") Integer memberNumber) {
|
||||
return ResponseEntity.ok(memberService.getIncomes(memberNumber));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
package net.miarma.backend.huertos.dto;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record DropdownDto(UUID userId, Integer memberNumber, String displayName) {
|
||||
}
|
||||
@@ -11,6 +11,7 @@ public class ExpenseDto {
|
||||
private String supplier;
|
||||
private String invoice;
|
||||
private Byte type;
|
||||
private Instant createdAt;
|
||||
|
||||
public String getConcept() {
|
||||
return concept;
|
||||
@@ -51,6 +52,14 @@ public class ExpenseDto {
|
||||
public void setType(Byte type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Response {
|
||||
@@ -59,6 +68,8 @@ public class ExpenseDto {
|
||||
private BigDecimal amount;
|
||||
private String supplier;
|
||||
private String invoice;
|
||||
private Byte type;
|
||||
private Instant createdAt;
|
||||
|
||||
public UUID getExpenseId() {
|
||||
return expenseId;
|
||||
@@ -115,8 +126,5 @@ public class ExpenseDto {
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
private Byte type;
|
||||
private Instant createdAt;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ public class IncomeDto {
|
||||
private BigDecimal amount;
|
||||
private Byte type;
|
||||
private Byte frequency;
|
||||
private Instant createdAt;
|
||||
|
||||
public Integer getMemberNumber() {
|
||||
return memberNumber;
|
||||
@@ -60,6 +61,14 @@ public class IncomeDto {
|
||||
public void setFrequency(Byte frequency) {
|
||||
this.frequency = frequency;
|
||||
}
|
||||
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Response {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package net.miarma.backend.huertos.dto;
|
||||
|
||||
import net.miarma.backend.huertos.dto.view.VIncomesWithInfoDto;
|
||||
import net.miarma.backlib.dto.CredentialDto;
|
||||
import net.miarma.backlib.dto.UserDto;
|
||||
|
||||
@@ -10,7 +11,7 @@ public record MemberProfileDto(
|
||||
CredentialDto account,
|
||||
UserMetadataDto metadata,
|
||||
List<RequestDto.Response> requests,
|
||||
List<IncomeDto.Response> payments,
|
||||
List<VIncomesWithInfoDto> payments,
|
||||
boolean hasCollaborator,
|
||||
boolean hasGreenhouse,
|
||||
boolean hasCollaboratorRequest,
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package net.miarma.backend.huertos.mapper;
|
||||
|
||||
import net.miarma.backend.huertos.dto.DropdownDto;
|
||||
import net.miarma.backend.huertos.dto.MemberDto;
|
||||
|
||||
public class DropdownDtoMapper {
|
||||
public static DropdownDto toDto(MemberDto dto) {
|
||||
return new DropdownDto(dto.user().getUserId(), dto.metadata().getMemberNumber(), dto.user().getDisplayName());
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ public class ExpenseMapper {
|
||||
entity.setSupplier(dto.getSupplier());
|
||||
entity.setInvoice(dto.getInvoice());
|
||||
entity.setType(dto.getType());
|
||||
entity.setCreatedAt(dto.getCreatedAt());
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ public class IncomeMapper {
|
||||
entity.setAmount(dto.getAmount());
|
||||
entity.setType(dto.getType());
|
||||
entity.setFrequency(dto.getFrequency());
|
||||
entity.setCreatedAt(dto.getCreatedAt());
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ public class RequestMapper {
|
||||
Request entity = new Request();
|
||||
entity.setType(dto.getType());
|
||||
entity.setUserId(dto.getUserId());
|
||||
entity.setName(dto.getName());
|
||||
entity.setStatus((byte) 0);
|
||||
|
||||
if (dto.getMetadata() != null) {
|
||||
|
||||
@@ -38,7 +38,7 @@ public class Income {
|
||||
@Column(name = "frequency")
|
||||
private Byte frequency;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
@Column(name = "created_at", nullable = false, updatable = true)
|
||||
private Instant createdAt;
|
||||
|
||||
@PrePersist
|
||||
|
||||
@@ -3,12 +3,14 @@ package net.miarma.backend.huertos.service;
|
||||
import jakarta.transaction.Transactional;
|
||||
import net.miarma.backend.huertos.dto.AnnouncementDto;
|
||||
import net.miarma.backend.huertos.model.Announcement;
|
||||
import net.miarma.backend.huertos.model.Income;
|
||||
import net.miarma.backend.huertos.repository.AnnouncementRepository;
|
||||
import net.miarma.backlib.exception.NotFoundException;
|
||||
import net.miarma.backlib.util.UuidUtil;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -25,7 +27,9 @@ public class AnnouncementService {
|
||||
}
|
||||
|
||||
public List<Announcement> getAll() {
|
||||
return announcementRepository.findAll();
|
||||
return announcementRepository.findAll().stream()
|
||||
.sorted(Comparator.comparing(Announcement::getCreatedAt).reversed())
|
||||
.toList();
|
||||
}
|
||||
|
||||
public Announcement getById(UUID announceId) {
|
||||
|
||||
@@ -3,6 +3,7 @@ package net.miarma.backend.huertos.service;
|
||||
import jakarta.transaction.Transactional;
|
||||
import net.miarma.backend.huertos.dto.ExpenseDto;
|
||||
import net.miarma.backend.huertos.model.Expense;
|
||||
import net.miarma.backend.huertos.model.Income;
|
||||
import net.miarma.backend.huertos.repository.ExpenseRepository;
|
||||
import net.miarma.backlib.exception.NotFoundException;
|
||||
import net.miarma.backlib.exception.ValidationException;
|
||||
@@ -10,6 +11,7 @@ import net.miarma.backlib.util.UuidUtil;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -24,7 +26,9 @@ public class ExpenseService {
|
||||
}
|
||||
|
||||
public List<Expense> getAll() {
|
||||
return expenseRepository.findAll();
|
||||
return expenseRepository.findAll().stream()
|
||||
.sorted(Comparator.comparing(Expense::getCreatedAt).reversed())
|
||||
.toList();
|
||||
}
|
||||
|
||||
public Expense getById(UUID expenseId) {
|
||||
@@ -46,9 +50,11 @@ public class ExpenseService {
|
||||
if (expense.getInvoice() == null || expense.getInvoice().isBlank()) {
|
||||
throw new ValidationException("invoice", "La factura es obligatoria");
|
||||
}
|
||||
if (expense.getCreatedAt() == null) {
|
||||
expense.setCreatedAt(Instant.now());
|
||||
}
|
||||
|
||||
expense.setExpenseId(UUID.randomUUID());
|
||||
expense.setCreatedAt(Instant.now());
|
||||
|
||||
return expenseRepository.save(expense);
|
||||
}
|
||||
@@ -74,6 +80,9 @@ public class ExpenseService {
|
||||
if (changes.getType() != null)
|
||||
expense.setType(changes.getType());
|
||||
|
||||
if (changes.getCreatedAt() != null)
|
||||
expense.setCreatedAt(changes.getCreatedAt());
|
||||
|
||||
return expenseRepository.save(expense);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
package net.miarma.backend.huertos.service;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.TemporalAmount;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import net.miarma.backend.huertos.model.view.VIncomesWithInfo;
|
||||
import net.miarma.backend.huertos.service.view.VIncomesWithInfoService;
|
||||
import net.miarma.backlib.exception.BadRequestException;
|
||||
import net.miarma.backlib.exception.NotFoundException;
|
||||
import net.miarma.backlib.exception.ValidationException;
|
||||
@@ -19,16 +23,21 @@ import net.miarma.backlib.util.UuidUtil;
|
||||
public class IncomeService {
|
||||
|
||||
private final IncomeRepository incomeRepository;
|
||||
private final VIncomesWithInfoService incomesWithInfoService;
|
||||
private final UserMetadataService metadataService;
|
||||
|
||||
public IncomeService(IncomeRepository incomeRepository,
|
||||
VIncomesWithInfoService incomesWithInfoService,
|
||||
UserMetadataService metadataService) {
|
||||
this.incomeRepository = incomeRepository;
|
||||
this.incomesWithInfoService = incomesWithInfoService;
|
||||
this.metadataService = metadataService;
|
||||
}
|
||||
|
||||
public List<Income> getAll() {
|
||||
return incomeRepository.findAll();
|
||||
return incomeRepository.findAll().stream()
|
||||
.sorted(Comparator.comparing(Income::getCreatedAt).reversed())
|
||||
.toList();
|
||||
}
|
||||
|
||||
public Income getById(UUID incomeId) {
|
||||
@@ -47,15 +56,20 @@ public class IncomeService {
|
||||
if (income.getUserId() == null) {
|
||||
throw new BadRequestException("El identificador de usuario es obligatorio");
|
||||
}
|
||||
if (income.getConcept() == null || income.getConcept().isBlank()) {
|
||||
if (income.getConcept() == null) {
|
||||
throw new BadRequestException("El concepto es obligatorio");
|
||||
}
|
||||
if (income.getConcept().isBlank() || income.getConcept().isEmpty()) {
|
||||
throw new ValidationException("concept", "El concepto no puede ir vacío");
|
||||
}
|
||||
if (income.getAmount() == null || income.getAmount().signum() <= 0) {
|
||||
throw new ValidationException("amount", "La cantidad debe ser positiva");
|
||||
}
|
||||
if (income.getCreatedAt() == null) {
|
||||
income.setCreatedAt(Instant.now());
|
||||
}
|
||||
|
||||
income.setIncomeId(UUID.randomUUID());
|
||||
income.setCreatedAt(Instant.now());
|
||||
|
||||
return incomeRepository.save(income);
|
||||
}
|
||||
@@ -75,6 +89,9 @@ public class IncomeService {
|
||||
}
|
||||
if (changes.getType() != null) income.setType(changes.getType());
|
||||
if (changes.getFrequency() != null) income.setFrequency(changes.getFrequency());
|
||||
if (changes.getCreatedAt() != null && !changes.getCreatedAt().equals(income.getCreatedAt())) {
|
||||
income.setCreatedAt(changes.getCreatedAt());
|
||||
}
|
||||
|
||||
return incomeRepository.save(income);
|
||||
}
|
||||
@@ -104,8 +121,8 @@ public class IncomeService {
|
||||
return !incomes.isEmpty() && incomes.stream().allMatch(Income::isPaid);
|
||||
}
|
||||
|
||||
public List<Income> getByMemberNumber(Integer memberNumber) {
|
||||
public List<VIncomesWithInfo> getByMemberNumber(Integer memberNumber) {
|
||||
UUID userId = metadataService.getByMemberNumber(memberNumber).getUserId();
|
||||
return getByUserId(userId);
|
||||
return incomesWithInfoService.getByUserId(userId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,12 @@
|
||||
|
||||
import net.miarma.backend.huertos.client.HuertosWebClient;
|
||||
import net.miarma.backend.huertos.dto.*;
|
||||
import net.miarma.backend.huertos.dto.view.VIncomesWithInfoDto;
|
||||
import net.miarma.backend.huertos.mapper.DropdownDtoMapper;
|
||||
import net.miarma.backend.huertos.mapper.RequestMapper;
|
||||
import net.miarma.backend.huertos.mapper.UserMetadataMapper;
|
||||
import net.miarma.backend.huertos.mapper.IncomeMapper;
|
||||
import net.miarma.backend.huertos.mapper.view.VIncomesWithInfoMapper;
|
||||
import net.miarma.backend.huertos.security.NameCensorer;
|
||||
import net.miarma.backlib.dto.UserWithCredentialDto;
|
||||
import net.miarma.backlib.exception.NotFoundException;
|
||||
@@ -52,8 +55,8 @@
|
||||
}
|
||||
|
||||
@Cacheable("members")
|
||||
public List<MemberDto> getAll(Byte serviceId) {
|
||||
List<UserWithCredentialDto> all = huertosWebClient.getAllUsersWithCredentials(serviceId);
|
||||
public List<MemberDto> getAll() {
|
||||
List<UserWithCredentialDto> all = huertosWebClient.getAllUsersWithCredentials((byte)1);
|
||||
|
||||
return all.stream()
|
||||
.filter(uwc -> metadataService.existsById(uwc.user().getUserId()))
|
||||
@@ -65,6 +68,7 @@
|
||||
UserMetadataMapper.toDto(meta)
|
||||
);
|
||||
})
|
||||
.sorted(Comparator.comparing(dto -> dto.metadata().getMemberNumber()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@@ -76,8 +80,8 @@
|
||||
.map(RequestMapper::toResponse)
|
||||
.toList();
|
||||
|
||||
List<IncomeDto.Response> payments = incomeService.getByMemberNumber(memberNumber).stream()
|
||||
.map(IncomeMapper::toResponse)
|
||||
List<VIncomesWithInfoDto> payments = incomeService.getByMemberNumber(memberNumber).stream()
|
||||
.map(VIncomesWithInfoMapper::toResponse)
|
||||
.toList();
|
||||
|
||||
return new MemberProfileDto(
|
||||
@@ -125,29 +129,29 @@
|
||||
}
|
||||
|
||||
public MemberDto getByMemberNumber(Integer memberNumber) {
|
||||
return getAll((byte)1).stream()
|
||||
return getAll().stream()
|
||||
.filter(dto -> dto.metadata().getMemberNumber().equals(memberNumber))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new NotFoundException("No hay socio con ese número"));
|
||||
}
|
||||
|
||||
public MemberDto getByPlotNumber(Integer plotNumber) {
|
||||
return getAll((byte)1).stream()
|
||||
return getAll().stream()
|
||||
.filter(dto -> dto.metadata().getPlotNumber().equals(plotNumber))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new NotFoundException("No hay socio con ese huerto"));
|
||||
}
|
||||
|
||||
public MemberDto getByDni(String dni) {
|
||||
return getAll((byte)1).stream()
|
||||
return getAll().stream()
|
||||
.filter(dto -> dni.equals(dto.metadata().getDni()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new NotFoundException("No hay socio con ese DNI"));
|
||||
}
|
||||
|
||||
public List<IncomeDto.Response> getIncomes(Integer memberNumber) {
|
||||
public List<VIncomesWithInfoDto> getIncomes(Integer memberNumber) {
|
||||
return incomeService.getByMemberNumber(memberNumber).stream()
|
||||
.map(IncomeMapper::toResponse)
|
||||
.map(VIncomesWithInfoMapper::toResponse)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@@ -156,7 +160,7 @@
|
||||
}
|
||||
|
||||
public Boolean hasCollaborator(Integer memberNumber) {
|
||||
List<MemberDto> all = getAll((byte)1);
|
||||
List<MemberDto> all = getAll();
|
||||
|
||||
var member = all.stream()
|
||||
.filter(dto -> dto.metadata().getMemberNumber().equals(memberNumber))
|
||||
@@ -189,4 +193,10 @@
|
||||
UUID userId = metadataService.getByMemberNumber(memberNumber).getUserId();
|
||||
return requestService.hasGreenhouseRequest(userId);
|
||||
}
|
||||
|
||||
public List<DropdownDto> getDropdown() {
|
||||
return getAll().stream()
|
||||
.map(DropdownDtoMapper::toDto)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,11 +60,17 @@ public class RequestService {
|
||||
throw new BadRequestException("El tipo de solicitud es obligatorio");
|
||||
}
|
||||
|
||||
if (request.getType() == 2 && hasCollaboratorRequest(request.getUserId())) { // tiene soli de collab
|
||||
if (request.getType() == 1 && hasUnregisterRequest(request.getUserId())) {
|
||||
throw new ConflictException("Ya tienes una solicitud, espera que se acepte o se elimine al ser rechazada");
|
||||
}
|
||||
|
||||
if (request.getType() == 1 && hasGreenhouseRequest(request.getUserId())) { // tiene soli de invernadero
|
||||
if ((request.getType() == 2 || request.getType() == 3) &&
|
||||
hasCollaboratorRequest(request.getUserId())) { // tiene soli de collab
|
||||
throw new ConflictException("Ya tienes una solicitud, espera que se acepte o se elimine al ser rechazada");
|
||||
}
|
||||
|
||||
if ((request.getType() == 4 || request.getType() == 5) &&
|
||||
hasGreenhouseRequest(request.getUserId())) { // tiene soli de invernadero
|
||||
throw new ConflictException("Ya tienes una solicitud, espera que se acepte o se elimine al ser rechazada");
|
||||
}
|
||||
|
||||
@@ -119,11 +125,16 @@ public class RequestService {
|
||||
|
||||
public boolean hasGreenhouseRequest(UUID userId) {
|
||||
return getByUserId(userId).stream()
|
||||
.anyMatch(r -> r.getType() == 1);
|
||||
.anyMatch(r -> r.getType() == 4 || r.getType() == 5);
|
||||
}
|
||||
|
||||
public boolean hasCollaboratorRequest(UUID userId) {
|
||||
return getByUserId(userId).stream()
|
||||
.anyMatch(r -> r.getType() == 2);
|
||||
.anyMatch(r -> r.getType() == 2 || r.getType() == 3);
|
||||
}
|
||||
|
||||
public boolean hasUnregisterRequest(UUID userId) {
|
||||
return getByUserId(userId).stream()
|
||||
.anyMatch(r -> r.getType() == 1);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package net.miarma.backend.huertos.service.view;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import net.miarma.backend.huertos.model.Income;
|
||||
import net.miarma.backlib.exception.NotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -22,7 +24,9 @@ public class VIncomesWithInfoService {
|
||||
}
|
||||
|
||||
public List<VIncomesWithInfo> getAll() {
|
||||
return repository.findAll();
|
||||
return repository.findAll().stream()
|
||||
.sorted(Comparator.comparing(VIncomesWithInfo::getCreatedAt).reversed())
|
||||
.toList();
|
||||
}
|
||||
|
||||
public VIncomesWithInfo getById(UUID incomeId) {
|
||||
|
||||
@@ -2,27 +2,45 @@ package net.miarma.backend.huertos.validation;
|
||||
|
||||
import net.miarma.backend.huertos.model.RequestMetadata;
|
||||
import net.miarma.backlib.exception.BadRequestException;
|
||||
import net.miarma.backlib.exception.ValidationException;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class RequestValidator {
|
||||
|
||||
private static final Pattern DNI_PATTERN = Pattern.compile("\\d{8}[A-Za-z]");
|
||||
private static final Pattern EMAIL_PATTERN = Pattern.compile("^[\\w.%+-]+@[\\w.-]+\\.[a-zA-Z]{2,6}$");
|
||||
private static final Pattern PHONE_PATTERN = Pattern.compile("^\\+?\\d{9,15}$");
|
||||
|
||||
public static void validate(RequestMetadata metadata, Byte requestType) {
|
||||
if (metadata.getRequestId() == null) {
|
||||
throw new BadRequestException("Estos metadatos deben pertenecer a una solicitud (falta ID)");
|
||||
}
|
||||
|
||||
if (isBlank(metadata.getDisplayName())) {
|
||||
throw new BadRequestException("El nombre es obligatorio");
|
||||
throw new BadRequestException("El nombre a mostrar es obligatorio");
|
||||
} else if (metadata.getDisplayName().length() < 3) {
|
||||
throw new ValidationException("displayName", "El nombre a mostrar debe tener al menos 3 caracteres");
|
||||
}
|
||||
|
||||
if (isBlank(metadata.getDni())) {
|
||||
throw new BadRequestException("El DNI es obligatorio");
|
||||
} else if (!DNI_PATTERN.matcher(metadata.getDni()).matches()) {
|
||||
throw new ValidationException("dni", "Formato de DNI inválido (ej: 12345678A)");
|
||||
} else if (!DniValidator.isValid(metadata.getDni())) {
|
||||
throw new ValidationException("dni", "Este DNI no es un DNI real");
|
||||
}
|
||||
|
||||
if (isBlank(metadata.getEmail())) {
|
||||
throw new BadRequestException("El email es obligatorio");
|
||||
} else if (!EMAIL_PATTERN.matcher(metadata.getEmail()).matches()) {
|
||||
throw new ValidationException("email", "Email inválido");
|
||||
}
|
||||
|
||||
if (isBlank(metadata.getUsername())) {
|
||||
throw new BadRequestException("El username es obligatorio");
|
||||
throw new BadRequestException("El usuario es obligatorio");
|
||||
} else if (metadata.getUsername().length() < 3) {
|
||||
throw new ValidationException("username", "El usuario debe tener al menos 3 caracteres");
|
||||
}
|
||||
|
||||
if (metadata.getType() == null) {
|
||||
@@ -31,7 +49,7 @@ public class RequestValidator {
|
||||
|
||||
if (requestType == 2) {
|
||||
if (metadata.getPlotNumber() == null) {
|
||||
throw new BadRequestException("El colaborador debe tener parcela");
|
||||
throw new BadRequestException("El colaborador debe tener huerto");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +64,24 @@ public class RequestValidator {
|
||||
throw new BadRequestException("La dirección, código postal y ciudad son obligatorios");
|
||||
}
|
||||
}
|
||||
|
||||
if (requestType == 0) {
|
||||
if (isBlank(metadata.getAddress())) {
|
||||
throw new ValidationException("address", "La dirección es obligatoria");
|
||||
}
|
||||
if (isBlank(metadata.getZipCode())) {
|
||||
throw new ValidationException("zipCode", "El código postal es obligatorio");
|
||||
} else if(metadata.getZipCode().length() < 5) {
|
||||
throw new ValidationException("zipCode", "El código postal debe tener 5 dígitos");
|
||||
}
|
||||
if (isBlank(metadata.getCity())) {
|
||||
throw new ValidationException("city", "La ciudad es obligatoria");
|
||||
}
|
||||
}
|
||||
|
||||
if (metadata.getPhone() != null && !PHONE_PATTERN.matcher(metadata.getPhone()).matches()) {
|
||||
throw new ValidationException("phone", "Teléfono inválido (debe tener 9 dígitos)");
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isBlank(String s) {
|
||||
|
||||
Reference in New Issue
Block a user