diff --git a/.gitignore b/.gitignore index 0a816db..2d249f9 100644 --- a/.gitignore +++ b/.gitignore @@ -24,4 +24,4 @@ hs_err_pid* replay_pid* -core/.rsa/ +.idea diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml index 712ab9d..d36e4ce 100644 --- a/.idea/jarRepositories.xml +++ b/.idea/jarRepositories.xml @@ -1,6 +1,11 @@ + + + + \ No newline at end of file diff --git a/backlib/pom.xml b/backlib/pom.xml index 0e6f095..56b9a29 100644 --- a/backlib/pom.xml +++ b/backlib/pom.xml @@ -2,24 +2,55 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - - net.miarma - backend - 1.0.0 - backlib + net.miarma + 1.0.0 + 25 + 4.0.1 25 25 + + + MiarmaGit + https://git.miarma.net/api/packages/Gallardo7761/maven + + + + + MiarmaGit + https://git.miarma.net/api/packages/Gallardo7761/maven + + + MiarmaGit + https://git.miarma.net/api/packages/Gallardo7761/maven + + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring.boot.version} + pom + import + + + + - org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-validation + org.springframework.boot spring-boot-starter-data-jpa @@ -33,22 +64,6 @@ mariadb-java-client runtime - - jakarta.validation - jakarta.validation-api - 3.1.1 - - - org.hibernate.validator - hibernate-validator - 8.0.0.Final - - - org.projectlombok - lombok - 1.18.42 - compile - org.springframework.boot spring-boot-starter-webflux @@ -72,11 +87,5 @@ 0.11.5 runtime - - - net.miarma - backlib - 1.0.0 - \ No newline at end of file diff --git a/backlib/src/main/java/net/miarma/backlib/dto/ApiErrorDto.java b/backlib/src/main/java/net/miarma/backlib/dto/ApiErrorDto.java new file mode 100644 index 0000000..ed05156 --- /dev/null +++ b/backlib/src/main/java/net/miarma/backlib/dto/ApiErrorDto.java @@ -0,0 +1,65 @@ +package net.miarma.backlib.dto; + +import tools.jackson.databind.ObjectMapper; + +import java.time.Instant; + +public class ApiErrorDto { + private int status; + private String error; + private String message; + private String path; + private Instant timestamp; + + public ApiErrorDto(int status, String error, String message, String path) { + this.status = status; + this.error = error; + this.message = message; + this.path = path; + this.timestamp = Instant.now(); + } + + public int getStatus() { + return status; + } + + public void setStatus(int status) { + this.status = status; + } + + public String getError() { + return error; + } + + public void setError(String error) { + this.error = error; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public Instant getTimestamp() { + return timestamp; + } + + public void setTimestamp(Instant timestamp) { + this.timestamp = timestamp; + } + + public String toJson() { + return new ObjectMapper().writeValueAsString(this); + } +} diff --git a/backlib/src/main/java/net/miarma/backlib/exception/BadRequestException.java b/backlib/src/main/java/net/miarma/backlib/exception/BadRequestException.java new file mode 100644 index 0000000..60c0621 --- /dev/null +++ b/backlib/src/main/java/net/miarma/backlib/exception/BadRequestException.java @@ -0,0 +1,7 @@ +package net.miarma.backlib.exception; + +public class BadRequestException extends RuntimeException { + public BadRequestException(String message) { + super(message); + } +} diff --git a/backlib/src/main/java/net/miarma/backlib/exception/ConflictException.java b/backlib/src/main/java/net/miarma/backlib/exception/ConflictException.java new file mode 100644 index 0000000..4cfe49a --- /dev/null +++ b/backlib/src/main/java/net/miarma/backlib/exception/ConflictException.java @@ -0,0 +1,7 @@ +package net.miarma.backlib.exception; + +public class ConflictException extends RuntimeException { + public ConflictException(String message) { + super(message); + } +} diff --git a/backlib/src/main/java/net/miarma/backlib/exception/ForbiddenException.java b/backlib/src/main/java/net/miarma/backlib/exception/ForbiddenException.java new file mode 100644 index 0000000..64e03bf --- /dev/null +++ b/backlib/src/main/java/net/miarma/backlib/exception/ForbiddenException.java @@ -0,0 +1,7 @@ +package net.miarma.backlib.exception; + +public class ForbiddenException extends RuntimeException { + public ForbiddenException(String message) { + super(message); + } +} diff --git a/backlib/src/main/java/net/miarma/backlib/exception/NotFoundException.java b/backlib/src/main/java/net/miarma/backlib/exception/NotFoundException.java new file mode 100644 index 0000000..2f8892c --- /dev/null +++ b/backlib/src/main/java/net/miarma/backlib/exception/NotFoundException.java @@ -0,0 +1,5 @@ +package net.miarma.backlib.exception; + +public class NotFoundException extends RuntimeException { + public NotFoundException(String message) { super(message); } +} diff --git a/backlib/src/main/java/net/miarma/backlib/exception/UnauthorizedException.java b/backlib/src/main/java/net/miarma/backlib/exception/UnauthorizedException.java new file mode 100644 index 0000000..39c35b3 --- /dev/null +++ b/backlib/src/main/java/net/miarma/backlib/exception/UnauthorizedException.java @@ -0,0 +1,7 @@ +package net.miarma.backlib.exception; + +public class UnauthorizedException extends RuntimeException { + public UnauthorizedException(String message) { + super(message); + } +} diff --git a/backlib/src/main/java/net/miarma/backlib/exception/ValidationException.java b/backlib/src/main/java/net/miarma/backlib/exception/ValidationException.java new file mode 100644 index 0000000..941d52d --- /dev/null +++ b/backlib/src/main/java/net/miarma/backlib/exception/ValidationException.java @@ -0,0 +1,7 @@ +package net.miarma.backlib.exception; + +public class ValidationException extends RuntimeException { + public ValidationException(String message) { + super(message); + } +} diff --git a/backlib/src/main/java/net/miarma/backlib/http/GlobalExceptionHandler.java b/backlib/src/main/java/net/miarma/backlib/http/GlobalExceptionHandler.java new file mode 100644 index 0000000..3ac8dc5 --- /dev/null +++ b/backlib/src/main/java/net/miarma/backlib/http/GlobalExceptionHandler.java @@ -0,0 +1,110 @@ +package net.miarma.backlib.http; + +import jakarta.servlet.http.HttpServletRequest; +import net.miarma.backlib.dto.ApiErrorDto; +import net.miarma.backlib.exception.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalExceptionHandler { + @ExceptionHandler(NotFoundException.class) + public ResponseEntity handleNotFound( + NotFoundException ex, HttpServletRequest req) { + + ApiErrorDto error = new ApiErrorDto( + HttpStatus.NOT_FOUND.value(), + HttpStatus.NOT_FOUND.getReasonPhrase(), + ex.getMessage(), + req.getRequestURI() + ); + + return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error); + } + + @ExceptionHandler(BadRequestException.class) + public ResponseEntity handleBadRequest( + BadRequestException ex, HttpServletRequest req) { + + ApiErrorDto error = new ApiErrorDto( + HttpStatus.BAD_REQUEST.value(), + HttpStatus.BAD_REQUEST.getReasonPhrase(), + ex.getMessage(), + req.getRequestURI() + ); + + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error); + } + + @ExceptionHandler(UnauthorizedException.class) + public ResponseEntity handleUnauthorized( + UnauthorizedException ex, HttpServletRequest req) { + + ApiErrorDto error = new ApiErrorDto( + HttpStatus.UNAUTHORIZED.value(), + HttpStatus.UNAUTHORIZED.getReasonPhrase(), + ex.getMessage(), + req.getRequestURI() + ); + + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(error); + } + + @ExceptionHandler(ForbiddenException.class) + public ResponseEntity handleForbidden( + ForbiddenException ex, HttpServletRequest req) { + + ApiErrorDto error = new ApiErrorDto( + HttpStatus.FORBIDDEN.value(), + HttpStatus.FORBIDDEN.getReasonPhrase(), + ex.getMessage(), + req.getRequestURI() + ); + + return ResponseEntity.status(HttpStatus.FORBIDDEN).body(error); + } + + @ExceptionHandler(ConflictException.class) + public ResponseEntity handleConflict( + ConflictException ex, HttpServletRequest req) { + + ApiErrorDto error = new ApiErrorDto( + HttpStatus.CONFLICT.value(), + HttpStatus.CONFLICT.getReasonPhrase(), + ex.getMessage(), + req.getRequestURI() + ); + + return ResponseEntity.status(HttpStatus.CONFLICT).body(error); + } + + @ExceptionHandler(ValidationException.class) + public ResponseEntity handleValidation( + ValidationException ex, HttpServletRequest req) { + + ApiErrorDto error = new ApiErrorDto( + HttpStatus.UNPROCESSABLE_CONTENT.value(), + HttpStatus.UNPROCESSABLE_CONTENT.getReasonPhrase(), + ex.getMessage(), + req.getRequestURI() + ); + + return ResponseEntity.status(HttpStatus.UNPROCESSABLE_CONTENT).body(error); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleAll( + Exception ex, HttpServletRequest req) { + + ApiErrorDto error = new ApiErrorDto( + HttpStatus.INTERNAL_SERVER_ERROR.value(), + HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), + "Internal server error", + req.getRequestURI() + ); + + return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error); + } +} diff --git a/backlib/src/main/java/net/miarma/backlib/http/RestAccessDeniedHandler.java b/backlib/src/main/java/net/miarma/backlib/http/RestAccessDeniedHandler.java new file mode 100644 index 0000000..2a54995 --- /dev/null +++ b/backlib/src/main/java/net/miarma/backlib/http/RestAccessDeniedHandler.java @@ -0,0 +1,31 @@ +package net.miarma.backlib.http; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import net.miarma.backlib.dto.ApiErrorDto; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +@Component +public class RestAccessDeniedHandler implements AccessDeniedHandler { + + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, + AccessDeniedException accessDeniedException) throws IOException { + + ApiErrorDto error = new ApiErrorDto( + HttpStatus.FORBIDDEN.value(), + HttpStatus.FORBIDDEN.getReasonPhrase(), + "Forbidden", + request.getRequestURI() + ); + + response.setStatus(HttpStatus.FORBIDDEN.value()); + response.setContentType("application/json"); + response.getWriter().write(error.toJson()); + } +} \ No newline at end of file diff --git a/backlib/src/main/java/net/miarma/backlib/http/RestAuthEntryPoint.java b/backlib/src/main/java/net/miarma/backlib/http/RestAuthEntryPoint.java new file mode 100644 index 0000000..e2e2f68 --- /dev/null +++ b/backlib/src/main/java/net/miarma/backlib/http/RestAuthEntryPoint.java @@ -0,0 +1,34 @@ +package net.miarma.backlib.http; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import net.miarma.backlib.dto.ApiErrorDto; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +import java.io.IOException; + +@Component +public class RestAuthEntryPoint implements AuthenticationEntryPoint { + + @Override + public void commence(HttpServletRequest request, HttpServletResponse response, + AuthenticationException authException) throws IOException { + + ApiErrorDto error = new ApiErrorDto( + HttpStatus.UNAUTHORIZED.value(), + HttpStatus.UNAUTHORIZED.getReasonPhrase(), + "Unauthorized", + request.getRequestURI() + ); + + response.setStatus(HttpStatus.UNAUTHORIZED.value()); + response.setContentType("application/json"); + response.getWriter().write(error.toJson()); + } +} + diff --git a/backlib/src/main/java/net/miarma/backlib/security/JwtService.java b/backlib/src/main/java/net/miarma/backlib/security/JwtService.java index b9ee2cd..5a0b1f1 100644 --- a/backlib/src/main/java/net/miarma/backlib/security/JwtService.java +++ b/backlib/src/main/java/net/miarma/backlib/security/JwtService.java @@ -34,10 +34,6 @@ public class JwtService { @PostConstruct public void init() throws Exception { - System.out.println("user.name = " + System.getProperty("user.name")); - System.out.println("user.home = " + System.getProperty("user.home")); - System.out.println("privateKeyPath = " + privateKeyPath); - this.privateKey = loadPrivateKey(privateKeyPath); this.publicKey = loadPublicKey(publicKeyPath); } diff --git a/cine/pom.xml b/cine/pom.xml index 5928dbc..e33e655 100644 --- a/cine/pom.xml +++ b/cine/pom.xml @@ -9,6 +9,13 @@ cine + + + gitea + https://git.miarma.net/api/packages/Gallardo7761/maven + + + diff --git a/core/pom.xml b/core/pom.xml index 7c7a7f4..446f550 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -14,6 +14,13 @@ 25 + + + gitea + https://git.miarma.net/api/packages/Gallardo7761/maven + + + @@ -72,7 +79,7 @@ 0.11.5 runtime - + net.miarma backlib @@ -80,4 +87,21 @@ + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + + + repackage + + + + + + + \ No newline at end of file diff --git a/core/src/main/java/net/miarma/backend/core/config/SecurityConfig.java b/core/src/main/java/net/miarma/backend/core/config/SecurityConfig.java index 7149780..80c9e00 100644 --- a/core/src/main/java/net/miarma/backend/core/config/SecurityConfig.java +++ b/core/src/main/java/net/miarma/backend/core/config/SecurityConfig.java @@ -1,6 +1,8 @@ package net.miarma.backend.core.config; import net.miarma.backend.core.security.JwtFilter; +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; @@ -18,10 +20,18 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic @EnableWebSecurity @EnableMethodSecurity(prePostEnabled = true) public class SecurityConfig { - private final JwtFilter jwtFilter; + private final JwtFilter jwtFilter; + private final RestAuthEntryPoint authEntryPoint; + private final RestAccessDeniedHandler accessDeniedHandler; - public SecurityConfig(JwtFilter jwtFilter) { + public SecurityConfig( + JwtFilter jwtFilter, + RestAuthEntryPoint authEntryPoint, + RestAccessDeniedHandler accessDeniedHandler + ) { this.jwtFilter = jwtFilter; + this.authEntryPoint = authEntryPoint; + this.accessDeniedHandler = accessDeniedHandler; } @Bean @@ -29,6 +39,10 @@ public class SecurityConfig { http .csrf(csrf -> csrf.disable()) .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .exceptionHandling(ex -> ex + .authenticationEntryPoint(authEntryPoint) + .accessDeniedHandler(accessDeniedHandler) + ) .authorizeHttpRequests(auth -> auth .requestMatchers("/auth/**", "/screenshot").permitAll() .anyRequest().authenticated() diff --git a/core/src/main/java/net/miarma/backend/core/service/AuthService.java b/core/src/main/java/net/miarma/backend/core/service/AuthService.java index 7b21b45..c2efde8 100644 --- a/core/src/main/java/net/miarma/backend/core/service/AuthService.java +++ b/core/src/main/java/net/miarma/backend/core/service/AuthService.java @@ -2,6 +2,9 @@ package net.miarma.backend.core.service; import java.util.UUID; +import net.miarma.backlib.exception.ConflictException; +import net.miarma.backlib.exception.ForbiddenException; +import net.miarma.backlib.exception.UnauthorizedException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; @@ -34,9 +37,13 @@ public class AuthService { public LoginResponse login(LoginRequest request) { Credential cred = credentialService.getForLogin(request.serviceId(), request.username()); - + if (!passwordEncoder.matches(request.password(), cred.getPassword())) { - throw new RuntimeException("Invalid credentials"); + throw new UnauthorizedException("Invalid credentials"); + } + + if (cred.getStatus() == 0) { + throw new ForbiddenException("This account is inactive"); } String token = jwtService.generateToken(cred.getUserId(), request.serviceId()); @@ -48,13 +55,13 @@ public class AuthService { public LoginResponse register(RegisterRequest request) { if (credentialService.existsByUsernameAndService(request.username(), request.serviceId())) { - throw new RuntimeException("Username already taken"); + throw new ConflictException("Username already taken"); } User user; try { user = credentialService.getByEmail(request.email()); - } catch (RuntimeException e) { + } catch (Exception e) { UserDto dto = new UserDto(); dto.setUserId(UUID.randomUUID()); dto.setDisplayName(request.displayName()); diff --git a/core/src/main/java/net/miarma/backend/core/service/CredentialService.java b/core/src/main/java/net/miarma/backend/core/service/CredentialService.java index 06145c5..9b36308 100644 --- a/core/src/main/java/net/miarma/backend/core/service/CredentialService.java +++ b/core/src/main/java/net/miarma/backend/core/service/CredentialService.java @@ -3,6 +3,10 @@ package net.miarma.backend.core.service; import java.util.List; import java.util.UUID; +import net.miarma.backlib.exception.BadRequestException; +import net.miarma.backlib.exception.ConflictException; +import net.miarma.backlib.exception.NotFoundException; +import net.miarma.backlib.exception.ValidationException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -29,30 +33,30 @@ public class CredentialService { public Credential getById(UUID credentialId) { byte[] idBytes = UuidUtil.uuidToBin(credentialId); return credentialRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Credential not found")); + .orElseThrow(() -> new NotFoundException("Credential not found")); } public Credential create(Credential credential) { if (credential.getUsername() == null || credential.getUsername().isBlank()) { - throw new IllegalArgumentException("Username cannot be blank"); + throw new ValidationException("Username cannot be blank"); } if (credential.getEmail() == null || !credential.getEmail().matches("^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$")) { - throw new IllegalArgumentException("Invalid email format"); + throw new ValidationException("Invalid email format"); } if (credential.getPassword() == null || credential.getPassword().length() < 6) { - throw new IllegalArgumentException("Password must be at least 6 characters"); + throw new ValidationException("Password must be at least 6 characters"); } if (credential.getServiceId() == null || credential.getServiceId() < 0) { - throw new IllegalArgumentException("ServiceId must be positive"); + throw new ValidationException("ServiceId must be positive"); } boolean existsUsername = credentialRepository.existsByUsernameAndServiceId( credential.getUsername(), credential.getServiceId()); - if (existsUsername) throw new IllegalArgumentException("Username already exists for this service"); + if (existsUsername) throw new ConflictException("Username already exists for this service"); boolean existsEmail = credentialRepository.existsByEmailAndServiceId( credential.getEmail(), credential.getServiceId()); - if (existsEmail) throw new IllegalArgumentException("Email already exists for this service"); + if (existsEmail) throw new ConflictException("Email already exists for this service"); credential.setCredentialId(UUID.randomUUID()); credential.setPassword(passwordEncoder.encode(credential.getPassword())); @@ -74,25 +78,25 @@ public class CredentialService { public List getByUserId(UUID userId) { List creds = credentialRepository.findByUserId(UuidUtil.uuidToBin(userId)); if (creds.isEmpty()) { - throw new RuntimeException("User has no credentials"); + throw new NotFoundException("User has no credentials"); } return creds; } public User getByEmail(String email) { return credentialRepository.findByEmail(email) - .orElseThrow(() -> new RuntimeException("No credential found for email")) + .orElseThrow(() -> new NotFoundException("No credential found for email")) .getUser(); } public Credential getByUserIdAndService(UUID userId, Byte serviceId) { return credentialRepository.findByUserIdAndServiceId(userId, serviceId) - .orElseThrow(() -> new RuntimeException("Credential not found in this site")); + .orElseThrow(() -> new NotFoundException("Credential not found in this site")); } public Credential getForLogin(Byte serviceId, String username) { return credentialRepository.findByServiceIdAndUsername(serviceId, username) - .orElseThrow(() -> new RuntimeException("Invalid credentials")); + .orElseThrow(() -> new BadRequestException("Invalid credentials")); } public boolean existsByUsernameAndService(String username, int serviceId) { @@ -102,7 +106,7 @@ public class CredentialService { public boolean isOwner(UUID credentialId, UUID userId) { byte[] idBytes = UuidUtil.uuidToBin(credentialId); Credential c = credentialRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Credential not found")); + .orElseThrow(() -> new NotFoundException("Credential not found")); return c.getUserId().equals(userId); } @@ -110,16 +114,16 @@ public class CredentialService { byte[] idBytes = UuidUtil.uuidToBin(credentialId); Credential cred = credentialRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Credential not found")); + .orElseThrow(() -> new NotFoundException("Credential not found")); if (dto.getUsername() != null && dto.getUsername().isBlank()) { - throw new IllegalArgumentException("Username cannot be blank"); + throw new ValidationException("Username cannot be blank"); } if (dto.getEmail() != null && !dto.getEmail().matches("^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$")) { - throw new IllegalArgumentException("Invalid email format"); + throw new ValidationException("Invalid email format"); } if (dto.getServiceId() != null && dto.getServiceId() < 0) { - throw new IllegalArgumentException("ServiceId must be positive"); + throw new ValidationException("ServiceId must be positive"); } if (dto.getUsername() != null) cred.setUsername(dto.getUsername()); @@ -134,10 +138,10 @@ public class CredentialService { byte[] idBytes = UuidUtil.uuidToBin(credentialId); Credential cred = credentialRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Credential not found")); + .orElseThrow(() -> new NotFoundException("Credential not found")); if (!passwordEncoder.matches(request.oldPassword(), cred.getPassword())) { - throw new IllegalArgumentException("Old password is incorrect"); + throw new ValidationException("Old password is incorrect"); } cred.setPassword(passwordEncoder.encode(request.newPassword())); @@ -147,19 +151,19 @@ public class CredentialService { public void delete(UUID credentialId) { byte[] idBytes = UuidUtil.uuidToBin(credentialId); if(!credentialRepository.existsById(idBytes)) - throw new RuntimeException("Credential not found"); + throw new NotFoundException("Credential not found"); credentialRepository.deleteById(idBytes); } public Byte getStatus(UUID credentialId) { Credential credential = credentialRepository.findById(UuidUtil.uuidToBin(credentialId)) - .orElseThrow(() -> new RuntimeException("User not found"));; + .orElseThrow(() -> new NotFoundException("User not found"));; return credential.getStatus(); } public void updateStatus(UUID credentialId, Byte status) { Credential credential = credentialRepository.findById(UuidUtil.uuidToBin(credentialId)) - .orElseThrow(() -> new RuntimeException("User not found"));; + .orElseThrow(() -> new NotFoundException("User not found"));; credential.setStatus(status); credentialRepository.save(credential); } diff --git a/core/src/main/java/net/miarma/backend/core/service/FileService.java b/core/src/main/java/net/miarma/backend/core/service/FileService.java index 4c3d6ad..442bc0e 100644 --- a/core/src/main/java/net/miarma/backend/core/service/FileService.java +++ b/core/src/main/java/net/miarma/backend/core/service/FileService.java @@ -11,6 +11,7 @@ import java.util.UUID; import net.miarma.backend.core.mapper.FileMapper; import net.miarma.backlib.dto.FileDto; +import net.miarma.backlib.exception.NotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -32,7 +33,7 @@ public class FileService { public File getById(UUID fileId) { byte[] idBytes = UuidUtil.uuidToBin(fileId); return fileRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("File not found")); + .orElseThrow(() -> new NotFoundException("File not found")); } public List getAll() { @@ -62,7 +63,7 @@ public class FileService { public File update(File file) { byte[] idBytes = UuidUtil.uuidToBin(file.getFileId()); if (!fileRepository.existsById(idBytes)) { - throw new RuntimeException("File not found"); + throw new NotFoundException("File not found"); } return fileRepository.save(file); } @@ -70,7 +71,7 @@ public class FileService { public void delete(UUID fileId) { byte[] idBytes = UuidUtil.uuidToBin(fileId); if (!fileRepository.existsById(idBytes)) { - throw new RuntimeException("File not found"); + throw new NotFoundException("File not found"); } fileRepository.deleteById(idBytes); } diff --git a/core/src/main/java/net/miarma/backend/core/service/UserService.java b/core/src/main/java/net/miarma/backend/core/service/UserService.java index c5607fe..5c56aa1 100644 --- a/core/src/main/java/net/miarma/backend/core/service/UserService.java +++ b/core/src/main/java/net/miarma/backend/core/service/UserService.java @@ -5,6 +5,8 @@ import java.util.UUID; import net.miarma.backend.core.mapper.UserMapper; import net.miarma.backlib.dto.ChangeAvatarRequest; +import net.miarma.backlib.exception.NotFoundException; +import net.miarma.backlib.exception.ValidationException; import org.springframework.stereotype.Service; import jakarta.transaction.Transactional; @@ -29,12 +31,12 @@ public class UserService { public User getById(UUID userId) { byte[] idBytes = UuidUtil.uuidToBin(userId); return userRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("User not found")); + .orElseThrow(() -> new NotFoundException("User not found")); } public User create(UserDto dto) { if(dto.getDisplayName() == null || dto.getDisplayName().isBlank()) { - throw new RuntimeException("Display name is required"); + throw new ValidationException("Display name is required"); } User user = new User(); @@ -50,7 +52,7 @@ public class UserService { public User update(UUID userId, UserDto dto) { byte[] idBytes = UuidUtil.uuidToBin(userId); User user = userRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("User not found")); + .orElseThrow(() -> new NotFoundException("User not found")); if (dto.getDisplayName() != null) { String displayName = dto.getDisplayName().trim(); @@ -74,13 +76,13 @@ public class UserService { public void delete(UUID userId) { byte[] idBytes = UuidUtil.uuidToBin(userId); if(!userRepository.existsById(idBytes)) - throw new RuntimeException("User not found"); + throw new NotFoundException("User not found"); userRepository.deleteById(idBytes); } public UserDto updateAvatar(UUID userId, ChangeAvatarRequest req) { User user = userRepository.findById(UuidUtil.uuidToBin(userId)) - .orElseThrow(() -> new RuntimeException("User not found")); + .orElseThrow(() -> new NotFoundException("User not found")); user.setAvatar(req.avatar()); userRepository.save(user); return UserMapper.toDto(user); @@ -88,26 +90,26 @@ public class UserService { public Byte getStatus(UUID userId) { User user = userRepository.findById(UuidUtil.uuidToBin(userId)) - .orElseThrow(() -> new RuntimeException("User not found"));; + .orElseThrow(() -> new NotFoundException("User not found"));; return user.getGlobalStatus(); } public void updateStatus(UUID userId, Byte status) { User user = userRepository.findById(UuidUtil.uuidToBin(userId)) - .orElseThrow(() -> new RuntimeException("User not found"));; + .orElseThrow(() -> new NotFoundException("User not found"));; user.setGlobalStatus(status); userRepository.save(user); } public Byte getRole(UUID userId) { User user = userRepository.findById(UuidUtil.uuidToBin(userId)) - .orElseThrow(() -> new RuntimeException("User not found"));; + .orElseThrow(() -> new NotFoundException("User not found"));; return user.getGlobalRole(); } public void updateRole(UUID userId, Byte role) { User user = userRepository.findById(UuidUtil.uuidToBin(userId)) - .orElseThrow(() -> new RuntimeException("User not found"));; + .orElseThrow(() -> new NotFoundException("User not found"));; user.setGlobalRole(role); userRepository.save(user); } diff --git a/core/src/main/resources/application-dev.yml b/core/src/main/resources/application-dev.yml new file mode 100644 index 0000000..6b02d69 --- /dev/null +++ b/core/src/main/resources/application-dev.yml @@ -0,0 +1,21 @@ +server: + port: 8080 + servlet: + context-path: /v2/core + +spring: + datasource: + url: jdbc:mariadb://localhost:3306/miarma_v2 + username: admin + password: ${DB_PASS} + driver-class-name: org.mariadb.jdbc.Driver + +logging: + level: + org.hibernate.SQL: DEBUG + org.hibernate.orm.jdbc.bind: TRACE + org.springframework.security: DEBUG + +jwt: + private-key-path: /home/jomaa/.config/miarma-backend/private.pem + public-key-path: /home/jomaa/.config/miarma-backend/public.pem diff --git a/core/src/main/resources/application-prod.yml b/core/src/main/resources/application-prod.yml new file mode 100644 index 0000000..d1881bd --- /dev/null +++ b/core/src/main/resources/application-prod.yml @@ -0,0 +1,20 @@ +server: + port: 8080 + servlet: + context-path: /v2/core + +spring: + datasource: + url: jdbc:mariadb://mariadb:3306/miarma_v2 + username: ${DB_USER} + password: ${DB_PASS} + driver-class-name: org.mariadb.jdbc.Driver + +logging: + level: + org.springframework.security: INFO + org.hibernate.SQL: WARN + +jwt: + private-key-path: ${JWT_PRIVATE_KEY} + public-key-path: ${JWT_PUBLIC_KEY} diff --git a/core/src/main/resources/application.yml b/core/src/main/resources/application.yml index 2498ba3..520b00a 100644 --- a/core/src/main/resources/application.yml +++ b/core/src/main/resources/application.yml @@ -1,43 +1,21 @@ -server: - port: 8080 - servlet: - context-path: /v2/core - spring: application: name: core-service - datasource: - url: jdbc:mariadb://localhost:3306/miarma_v2 - username: admin - password: ositovito - driver-class-name: org.mariadb.jdbc.Driver - jpa: open-in-view: false hibernate: ddl-auto: validate properties: hibernate: - format_sql: true jdbc: time_zone: UTC jackson: - serialization: - indent-output: true default-property-inclusion: non_null time-zone: Europe/Madrid -logging: - level: - org.hibernate.SQL: DEBUG - org.hibernate.orm.jdbc.bind: TRACE - org.springframework.security: INFO - jwt: - private-key-path: /home/jomaa/.config/miarma-backend/private.pem - public-key-path: /home/jomaa/.config/miarma-backend/public.pem expiration-ms: 3600000 management: diff --git a/huertos/pom.xml b/huertos/pom.xml index 30de887..2bdaf75 100644 --- a/huertos/pom.xml +++ b/huertos/pom.xml @@ -14,6 +14,13 @@ 25 + + + gitea + https://git.miarma.net/api/packages/Gallardo7761/maven + + + @@ -65,4 +72,22 @@ + + + + org.springframework.boot + spring-boot-maven-plugin + ${spring.boot.version} + + + + repackage + + + + + + + + \ No newline at end of file diff --git a/huertos/src/main/java/net/miarma/backend/huertos/config/SecurityConfig.java b/huertos/src/main/java/net/miarma/backend/huertos/config/SecurityConfig.java index 6e412b2..efb69ef 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/config/SecurityConfig.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/config/SecurityConfig.java @@ -1,6 +1,8 @@ package net.miarma.backend.huertos.config; import net.miarma.backend.huertos.security.HuertosJwtFilter; +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.annotation.method.configuration.EnableMethodSecurity; @@ -16,28 +18,43 @@ import org.springframework.security.web.authentication.UsernamePasswordAuthentic public class SecurityConfig { private final HuertosJwtFilter jwtFilter; + private final RestAuthEntryPoint authEntryPoint; + private final RestAccessDeniedHandler accessDeniedHandler; - public SecurityConfig(HuertosJwtFilter jwtFilter) { + public SecurityConfig( + HuertosJwtFilter jwtFilter, + RestAuthEntryPoint authEntryPoint, + RestAccessDeniedHandler accessDeniedHandler + ) { this.jwtFilter = jwtFilter; + this.authEntryPoint = authEntryPoint; + this.accessDeniedHandler = accessDeniedHandler; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http - .csrf(csrf -> csrf.disable()) - .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) - .authorizeHttpRequests(auth -> auth - // PUBLICAS - .requestMatchers("/login").permitAll() - .requestMatchers("/announces/**").permitAll() - .requestMatchers("/huertos/members/waitlist").permitAll() + .csrf(csrf -> csrf.disable()) + .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .exceptionHandling(ex -> ex + .authenticationEntryPoint(authEntryPoint) + .accessDeniedHandler(accessDeniedHandler) + ) + .authorizeHttpRequests(auth -> auth + // PUBLICAS + .requestMatchers("/login").permitAll() + .requestMatchers("/announces/**").permitAll() + .requestMatchers("/huertos/members/waitlist").permitAll() .requestMatchers("/huertos/members/waitlist/limited").permitAll() - .requestMatchers("/huertos/members/latest-number").permitAll() - // PRIVADAS - .requestMatchers("/**").authenticated() - ); + .requestMatchers("/huertos/members/latest-number").permitAll() + // PRIVADAS + .anyRequest().authenticated() + ); + http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class); + return http.build(); } } + diff --git a/huertos/src/main/java/net/miarma/backend/huertos/service/AnnouncementService.java b/huertos/src/main/java/net/miarma/backend/huertos/service/AnnouncementService.java index fc62917..5e5df58 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/service/AnnouncementService.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/service/AnnouncementService.java @@ -4,6 +4,7 @@ import jakarta.transaction.Transactional; import net.miarma.backend.huertos.dto.AnnouncementDto; import net.miarma.backend.huertos.model.Announcement; import net.miarma.backend.huertos.repository.AnnouncementRepository; +import net.miarma.backlib.exception.NotFoundException; import net.miarma.backlib.util.UuidUtil; import org.springframework.stereotype.Service; @@ -28,7 +29,7 @@ public class AnnouncementService { public Announcement getById(UUID announceId) { byte[] idBytes = UuidUtil.uuidToBin(announceId); return announcementRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Announcement not found")); + .orElseThrow(() -> new NotFoundException("Announcement not found")); } public Announcement create(Announcement announcement) { @@ -42,7 +43,7 @@ public class AnnouncementService { public Announcement update(UUID announceId, AnnouncementDto.Request dto) { byte[] idBytes = UuidUtil.uuidToBin(announceId); Announcement announcement = announcementRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Announcement not found")); + .orElseThrow(() -> new NotFoundException("Announcement not found")); if (dto.getBody() != null) announcement.setBody(dto.getBody()); if (dto.getPriority() != null) announcement.setPriority(dto.getPriority()); @@ -54,7 +55,7 @@ public class AnnouncementService { public void delete(UUID announceId) { byte[] idBytes = UuidUtil.uuidToBin(announceId); if (!announcementRepository.existsById(idBytes)) - throw new RuntimeException("Announcement not found"); + throw new NotFoundException("Announcement not found"); announcementRepository.deleteById(idBytes); } } diff --git a/huertos/src/main/java/net/miarma/backend/huertos/service/BalanceService.java b/huertos/src/main/java/net/miarma/backend/huertos/service/BalanceService.java index 7e9a1d7..8de4526 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/service/BalanceService.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/service/BalanceService.java @@ -3,6 +3,8 @@ package net.miarma.backend.huertos.service; import java.time.Instant; import java.util.Optional; +import net.miarma.backlib.exception.ConflictException; +import net.miarma.backlib.exception.NotFoundException; import org.springframework.stereotype.Service; import jakarta.transaction.Transactional; @@ -21,12 +23,12 @@ public class BalanceService { public Balance get() { return repo.findById((byte) 1) - .orElseThrow(() -> new RuntimeException("Balance not found")); + .orElseThrow(() -> new NotFoundException("Balance not found")); } public Balance create(Balance balance) { if (repo.existsById((byte) 1)) { - throw new RuntimeException("Balance already exists"); + throw new ConflictException("Balance already exists"); } balance.setId((byte) 1); balance.setCreatedAt(Instant.now()); @@ -35,7 +37,7 @@ public class BalanceService { public Balance update(Balance dto) { Balance balance = repo.findById((byte) 1) - .orElseThrow(() -> new RuntimeException("Balance not found")); + .orElseThrow(() -> new NotFoundException("Balance not found")); if (dto.getInitialBank() != null) balance.setInitialBank(dto.getInitialBank()); if (dto.getInitialCash() != null) balance.setInitialCash(dto.getInitialCash()); @@ -45,7 +47,7 @@ public class BalanceService { public void delete() { if (!repo.existsById((byte) 1)) { - throw new RuntimeException("Balance not found"); + throw new NotFoundException("Balance not found"); } repo.deleteById((byte) 1); } diff --git a/huertos/src/main/java/net/miarma/backend/huertos/service/ExpenseService.java b/huertos/src/main/java/net/miarma/backend/huertos/service/ExpenseService.java index da0a71d..6d9b9fa 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/service/ExpenseService.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/service/ExpenseService.java @@ -4,6 +4,8 @@ import jakarta.transaction.Transactional; import net.miarma.backend.huertos.dto.ExpenseDto; import net.miarma.backend.huertos.model.Expense; import net.miarma.backend.huertos.repository.ExpenseRepository; +import net.miarma.backlib.exception.NotFoundException; +import net.miarma.backlib.exception.ValidationException; import net.miarma.backlib.util.UuidUtil; import org.springframework.stereotype.Service; @@ -28,21 +30,21 @@ public class ExpenseService { public Expense getById(UUID expenseId) { byte[] idBytes = UuidUtil.uuidToBin(expenseId); return expenseRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Expense not found")); + .orElseThrow(() -> new NotFoundException("Expense not found")); } public Expense create(Expense expense) { if (expense.getConcept() == null || expense.getConcept().isBlank()) { - throw new RuntimeException("Concept is required"); + throw new ValidationException("Concept is required"); } if (expense.getAmount() == null) { - throw new RuntimeException("Amount is required"); + throw new ValidationException("Amount is required"); } if (expense.getSupplier() == null || expense.getSupplier().isBlank()) { - throw new RuntimeException("Supplier is required"); + throw new ValidationException("Supplier is required"); } if (expense.getInvoice() == null || expense.getInvoice().isBlank()) { - throw new RuntimeException("Invoice is required"); + throw new ValidationException("Invoice is required"); } expense.setExpenseId(UUID.randomUUID()); @@ -54,7 +56,7 @@ public class ExpenseService { public Expense update(UUID expenseId, ExpenseDto.Request dto) { byte[] idBytes = UuidUtil.uuidToBin(expenseId); Expense expense = expenseRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Expense not found")); + .orElseThrow(() -> new NotFoundException("Expense not found")); if (dto.getConcept() != null) expense.setConcept(dto.getConcept()); if (dto.getAmount() != null) expense.setAmount(dto.getAmount()); @@ -68,7 +70,7 @@ public class ExpenseService { public void delete(UUID expenseId) { byte[] idBytes = UuidUtil.uuidToBin(expenseId); if (!expenseRepository.existsById(idBytes)) { - throw new RuntimeException("Expense not found"); + throw new NotFoundException("Expense not found"); } expenseRepository.deleteById(idBytes); } diff --git a/huertos/src/main/java/net/miarma/backend/huertos/service/HuertosUserMetadataService.java b/huertos/src/main/java/net/miarma/backend/huertos/service/HuertosUserMetadataService.java index 0f46775..c8387cf 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/service/HuertosUserMetadataService.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/service/HuertosUserMetadataService.java @@ -5,6 +5,9 @@ import java.util.List; import java.util.UUID; import java.util.stream.Collectors; +import net.miarma.backlib.exception.BadRequestException; +import net.miarma.backlib.exception.ConflictException; +import net.miarma.backlib.exception.NotFoundException; import org.springframework.stereotype.Service; import jakarta.transaction.Transactional; @@ -31,12 +34,12 @@ public class HuertosUserMetadataService { public HuertosUserMetadata getById(UUID userId) { byte[] idBytes = UuidUtil.uuidToBin(userId); return repository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("User metadata not found")); + .orElseThrow(() -> new NotFoundException("User metadata not found")); } public HuertosUserMetadata getByMemberNumber(Integer memberNumber) { return repository.findByMemberNumber(memberNumber) - .orElseThrow(() -> new RuntimeException("User metadata not found")); + .orElseThrow(() -> new NotFoundException("User metadata not found")); } public boolean existsById(UUID userId) { @@ -46,16 +49,16 @@ public class HuertosUserMetadataService { public HuertosUserMetadata create(HuertosUserMetadata meta) { if (meta.getUserId() == null) { - throw new RuntimeException("userId is required"); + throw new BadRequestException("userId is required"); } if (repository.existsById(UuidUtil.uuidToBin(meta.getUserId()))) { - throw new RuntimeException("Metadata already exists for this user"); + throw new ConflictException("Metadata already exists for this user"); } - if (meta.getMemberNumber() == null) throw new RuntimeException("memberNumber required"); - if (meta.getPlotNumber() == null) throw new RuntimeException("plotNumber required"); - if (meta.getDni() == null || meta.getDni().isBlank()) throw new RuntimeException("dni required"); - if (meta.getPhone() == null || meta.getPhone().isBlank()) throw new RuntimeException("phone required"); + if (meta.getMemberNumber() == null) throw new BadRequestException("memberNumber required"); + if (meta.getPlotNumber() == null) throw new BadRequestException("plotNumber required"); + if (meta.getDni() == null || meta.getDni().isBlank()) throw new BadRequestException("dni required"); + if (meta.getPhone() == null || meta.getPhone().isBlank()) throw new BadRequestException("phone required"); if (meta.getType() == null) meta.setType((byte) 0); if (meta.getRole() == null) meta.setRole((byte) 0); @@ -70,7 +73,7 @@ public class HuertosUserMetadataService { byte[] idBytes = UuidUtil.uuidToBin(userId); HuertosUserMetadata meta = repository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("User metadata not found")); + .orElseThrow(() -> new NotFoundException("User metadata not found")); if (dto.getMemberNumber() != null) meta.setMemberNumber(dto.getMemberNumber()); if (dto.getPlotNumber() != null) meta.setPlotNumber(dto.getPlotNumber()); @@ -88,7 +91,7 @@ public class HuertosUserMetadataService { public void delete(UUID userId) { byte[] idBytes = UuidUtil.uuidToBin(userId); if (!repository.existsById(idBytes)) { - throw new RuntimeException("User metadata not found"); + throw new NotFoundException("User metadata not found"); } repository.deleteById(idBytes); } diff --git a/huertos/src/main/java/net/miarma/backend/huertos/service/IncomeService.java b/huertos/src/main/java/net/miarma/backend/huertos/service/IncomeService.java index 502b580..42e26fa 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/service/IncomeService.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/service/IncomeService.java @@ -7,6 +7,9 @@ import java.util.UUID; import net.miarma.backend.huertos.dto.IncomeDto; import net.miarma.backend.huertos.model.HuertosUserMetadata; import net.miarma.backend.huertos.repository.HuertosUserMetadataRepository; +import net.miarma.backlib.exception.BadRequestException; +import net.miarma.backlib.exception.NotFoundException; +import net.miarma.backlib.exception.ValidationException; import org.springframework.stereotype.Service; import jakarta.transaction.Transactional; @@ -34,7 +37,7 @@ public class IncomeService { public Income getById(UUID incomeId) { byte[] idBytes = UuidUtil.uuidToBin(incomeId); return incomeRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Income not found")); + .orElseThrow(() -> new NotFoundException("Income not found")); } public List getByUserId(UUID userId) { @@ -45,13 +48,13 @@ public class IncomeService { public Income create(Income income) { if (income.getUserId() == null) { - throw new RuntimeException("userId is required"); + throw new BadRequestException("userId is required"); } if (income.getConcept() == null || income.getConcept().isBlank()) { - throw new RuntimeException("concept is required"); + throw new BadRequestException("concept is required"); } if (income.getAmount() == null || income.getAmount().signum() <= 0) { - throw new RuntimeException("amount must be positive"); + throw new ValidationException("amount must be positive"); } income.setIncomeId(UUID.randomUUID()); @@ -64,12 +67,12 @@ public class IncomeService { byte[] idBytes = UuidUtil.uuidToBin(incomeId); Income income = incomeRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Income not found")); + .orElseThrow(() -> new NotFoundException("Income not found")); if (dto.getConcept() != null) income.setConcept(dto.getConcept()); if (dto.getAmount() != null) { if (dto.getAmount().signum() <= 0) { - throw new RuntimeException("amount must be positive"); + throw new ValidationException("amount must be positive"); } income.setAmount(dto.getAmount()); } @@ -83,7 +86,7 @@ public class IncomeService { byte[] idBytes = UuidUtil.uuidToBin(incomeId); if (!incomeRepository.existsById(idBytes)) { - throw new RuntimeException("Income not found"); + throw new NotFoundException("Income not found"); } incomeRepository.deleteById(idBytes); @@ -93,7 +96,7 @@ public class IncomeService { try { UUID userId = metadataService.getByMemberNumber(memberNumber).getUserId(); return !getByUserId(userId).isEmpty(); - } catch (RuntimeException e) { + } catch (Exception e) { return false; } } diff --git a/huertos/src/main/java/net/miarma/backend/huertos/service/MemberService.java b/huertos/src/main/java/net/miarma/backend/huertos/service/MemberService.java index d19efd0..1b6d1f5 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/service/MemberService.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/service/MemberService.java @@ -6,6 +6,7 @@ import net.miarma.backend.huertos.dto.WaitlistCensoredDto; import net.miarma.backend.huertos.mapper.HuertosUserMetadataMapper; import net.miarma.backend.huertos.security.NameCensorer; import net.miarma.backlib.dto.UserWithCredentialDto; +import net.miarma.backlib.exception.NotFoundException; import org.springframework.stereotype.Service; import java.util.Comparator; @@ -88,21 +89,21 @@ public class MemberService { return getAll((byte)1).stream() .filter(dto -> dto.metadata().getMemberNumber().equals(memberNumber)) .findFirst() - .orElseThrow(() -> new RuntimeException("Member not found")); + .orElseThrow(() -> new NotFoundException("Member not found")); } public MemberDto getByPlotNumber(Integer plotNumber) { return getAll((byte)1).stream() .filter(dto -> dto.metadata().getPlotNumber().equals(plotNumber)) .findFirst() - .orElseThrow(() -> new RuntimeException("Member not found")); + .orElseThrow(() -> new NotFoundException("Member not found")); } public MemberDto getByDni(String dni) { return getAll((byte)1).stream() .filter(dto -> dni.equals(dto.metadata().getDni())) .findFirst() - .orElseThrow(() -> new RuntimeException("Member not found")); + .orElseThrow(() -> new NotFoundException("Member not found")); } public Boolean hasIncomes(Integer memberNumber) { diff --git a/huertos/src/main/java/net/miarma/backend/huertos/service/PreUserService.java b/huertos/src/main/java/net/miarma/backend/huertos/service/PreUserService.java index 3ae0c75..74cc6e9 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/service/PreUserService.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/service/PreUserService.java @@ -5,6 +5,8 @@ import java.util.List; import java.util.UUID; import net.miarma.backend.huertos.dto.PreUserDto; +import net.miarma.backlib.exception.BadRequestException; +import net.miarma.backlib.exception.NotFoundException; import org.springframework.stereotype.Service; import jakarta.transaction.Transactional; @@ -29,7 +31,7 @@ public class PreUserService { public PreUser getById(UUID preUserId) { byte[] idBytes = UuidUtil.uuidToBin(preUserId); return repository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("PreUser not found")); + .orElseThrow(() -> new NotFoundException("PreUser not found")); } public List getByRequestId(UUID requestId) { @@ -42,22 +44,22 @@ public class PreUserService { public PreUser create(PreUser preUser) { if (preUser.getRequestId() == null) { - throw new RuntimeException("requestId is required"); + throw new BadRequestException("requestId is required"); } if (preUser.getUserName() == null || preUser.getUserName().isBlank()) { - throw new RuntimeException("userName is required"); + throw new BadRequestException("userName is required"); } if (preUser.getDisplayName() == null || preUser.getDisplayName().isBlank()) { - throw new RuntimeException("displayName is required"); + throw new BadRequestException("displayName is required"); } if (preUser.getDni() == null || preUser.getDni().isBlank()) { - throw new RuntimeException("dni is required"); + throw new BadRequestException("dni is required"); } if (preUser.getPhone() == null || preUser.getPhone().isBlank()) { - throw new RuntimeException("phone is required"); + throw new BadRequestException("phone is required"); } if (preUser.getEmail() == null || preUser.getEmail().isBlank()) { - throw new RuntimeException("email is required"); + throw new BadRequestException("email is required"); } preUser.setPreUserId(UUID.randomUUID()); @@ -70,7 +72,7 @@ public class PreUserService { byte[] idBytes = UuidUtil.uuidToBin(preUserId); PreUser preUser = repository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("PreUser not found")); + .orElseThrow(() -> new NotFoundException("PreUser not found")); if (dto.getUserName() != null) preUser.setUserName(dto.getUserName()); if (dto.getDisplayName() != null) preUser.setDisplayName(dto.getDisplayName()); @@ -93,7 +95,7 @@ public class PreUserService { byte[] idBytes = UuidUtil.uuidToBin(preUserId); if (!repository.existsById(idBytes)) { - throw new RuntimeException("PreUser not found"); + throw new NotFoundException("PreUser not found"); } repository.deleteById(idBytes); diff --git a/huertos/src/main/java/net/miarma/backend/huertos/service/RequestService.java b/huertos/src/main/java/net/miarma/backend/huertos/service/RequestService.java index 9ffaf0e..f5830d7 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/service/RequestService.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/service/RequestService.java @@ -6,6 +6,8 @@ import java.util.UUID; import net.miarma.backend.huertos.dto.RequestDto; import net.miarma.backend.huertos.model.HuertosUserMetadata; +import net.miarma.backlib.exception.BadRequestException; +import net.miarma.backlib.exception.NotFoundException; import org.springframework.stereotype.Service; import jakarta.transaction.Transactional; @@ -33,7 +35,7 @@ public class RequestService { public Request getById(UUID requestId) { byte[] idBytes = UuidUtil.uuidToBin(requestId); return requestRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Request not found")); + .orElseThrow(() -> new NotFoundException("Request not found")); } public List getByUserId(UUID userId) { @@ -56,13 +58,13 @@ public class RequestService { public Request create(Request request) { if (request.getType() == null) { - throw new RuntimeException("type is required"); + throw new BadRequestException("type is required"); } if (request.getStatus() == null) { - throw new RuntimeException("status is required"); + throw new BadRequestException("status is required"); } if (request.getRequestedBy() == null) { - throw new RuntimeException("requestedBy is required"); + throw new BadRequestException("requestedBy is required"); } request.setRequestId(UUID.randomUUID()); @@ -75,7 +77,7 @@ public class RequestService { byte[] idBytes = UuidUtil.uuidToBin(requestId); Request request = requestRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Request not found")); + .orElseThrow(() -> new NotFoundException("Request not found")); if (dto.getType() != null) request.setType(dto.getType()); if (dto.getStatus() != null) request.setStatus(dto.getStatus()); @@ -88,7 +90,7 @@ public class RequestService { public Request acceptRequest(UUID requestId) { byte[] idBytes = UuidUtil.uuidToBin(requestId); Request request = requestRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Request not found")); + .orElseThrow(() -> new NotFoundException("Request not found")); request.setStatus((byte)1); return requestRepository.save(request); } @@ -96,7 +98,7 @@ public class RequestService { public Request rejectRequest(UUID requestId) { byte[] idBytes = UuidUtil.uuidToBin(requestId); Request request = requestRepository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Request not found")); + .orElseThrow(() -> new NotFoundException("Request not found")); request.setStatus((byte)2); return requestRepository.save(request); } @@ -105,7 +107,7 @@ public class RequestService { byte[] idBytes = UuidUtil.uuidToBin(requestId); if (!requestRepository.existsById(idBytes)) { - throw new RuntimeException("Request not found"); + throw new NotFoundException("Request not found"); } requestRepository.deleteById(idBytes); diff --git a/huertos/src/main/java/net/miarma/backend/huertos/service/view/VHuertosMembersService.java b/huertos/src/main/java/net/miarma/backend/huertos/service/view/VHuertosMembersService.java index 4d7ef17..69df4a0 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/service/view/VHuertosMembersService.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/service/view/VHuertosMembersService.java @@ -3,6 +3,7 @@ package net.miarma.backend.huertos.service.view; import java.util.List; import java.util.UUID; +import net.miarma.backlib.exception.NotFoundException; import org.springframework.stereotype.Service; import jakarta.transaction.Transactional; @@ -27,6 +28,6 @@ public class VHuertosMembersService { public VHuertosMembers getById(UUID userId) { byte[] idBytes = UuidUtil.uuidToBin(userId); return repository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Member not found")); + .orElseThrow(() -> new NotFoundException("Member not found")); } } diff --git a/huertos/src/main/java/net/miarma/backend/huertos/service/view/VIncomesWithFullNamesService.java b/huertos/src/main/java/net/miarma/backend/huertos/service/view/VIncomesWithFullNamesService.java index 9ed2f28..3c50cd2 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/service/view/VIncomesWithFullNamesService.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/service/view/VIncomesWithFullNamesService.java @@ -3,6 +3,7 @@ package net.miarma.backend.huertos.service.view; import java.util.List; import java.util.UUID; +import net.miarma.backlib.exception.NotFoundException; import org.springframework.stereotype.Service; import jakarta.transaction.Transactional; @@ -27,7 +28,7 @@ public class VIncomesWithFullNamesService { public VIncomesWithFullNames getById(UUID incomeId) { byte[] idBytes = UuidUtil.uuidToBin(incomeId); return repository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Income not found")); + .orElseThrow(() -> new NotFoundException("Income not found")); } public List getByUserId(UUID userId) { diff --git a/huertos/src/main/java/net/miarma/backend/huertos/service/view/VRequestsWithPreUsersService.java b/huertos/src/main/java/net/miarma/backend/huertos/service/view/VRequestsWithPreUsersService.java index 6e3fe01..3fddd6e 100644 --- a/huertos/src/main/java/net/miarma/backend/huertos/service/view/VRequestsWithPreUsersService.java +++ b/huertos/src/main/java/net/miarma/backend/huertos/service/view/VRequestsWithPreUsersService.java @@ -3,6 +3,7 @@ package net.miarma.backend.huertos.service.view; import java.util.List; import java.util.UUID; +import net.miarma.backlib.exception.NotFoundException; import org.springframework.stereotype.Service; import jakarta.transaction.Transactional; @@ -27,7 +28,7 @@ public class VRequestsWithPreUsersService { public VRequestsWithPreUsers getById(UUID requestId) { byte[] idBytes = UuidUtil.uuidToBin(requestId); return repository.findById(idBytes) - .orElseThrow(() -> new RuntimeException("Request not found")); + .orElseThrow(() -> new NotFoundException("Request not found")); } public List getByRequestType(Byte type) { diff --git a/huertos/src/main/resources/application-dev.yml b/huertos/src/main/resources/application-dev.yml new file mode 100644 index 0000000..d35311b --- /dev/null +++ b/huertos/src/main/resources/application-dev.yml @@ -0,0 +1,28 @@ +server: + port: 8081 + servlet: + context-path: /v2/huertos + +spring: + datasource: + url: jdbc:mariadb://localhost:3306/miarma_v2 + username: admin + password: ${DB_PASS} + driver-class-name: org.mariadb.jdbc.Driver + +logging: + level: + org.hibernate.SQL: DEBUG + org.hibernate.orm.jdbc.bind: TRACE + +core: + url: http://localhost:8080/v2/core + +huertos: + user: SYSTEM + password: ${HUERTOS_SYSTEM_PASSWORD} + +mail: + smtp: + server: smtp.dondominio.com + port: 587 \ No newline at end of file diff --git a/huertos/src/main/resources/application-prod.yml b/huertos/src/main/resources/application-prod.yml new file mode 100644 index 0000000..75868ce --- /dev/null +++ b/huertos/src/main/resources/application-prod.yml @@ -0,0 +1,27 @@ +server: + port: 8081 + servlet: + context-path: /v2/huertos + +spring: + datasource: + url: jdbc:mariadb://mariadb:3306/miarma_v2 + username: ${DB_USER} + password: ${DB_PASS} + driver-class-name: org.mariadb.jdbc.Driver + +logging: + level: + org.hibernate.SQL: WARN + +core: + url: http://core:8080/v2/core + +huertos: + user: SYSTEM + password: ${HUERTOS_SYSTEM_PASSWORD} + +mail: + smtp: + server: smtp.dondominio.com + port: 587 \ No newline at end of file diff --git a/huertos/src/main/resources/application.yml b/huertos/src/main/resources/application.yml index 8d8b4af..87de0a8 100644 --- a/huertos/src/main/resources/application.yml +++ b/huertos/src/main/resources/application.yml @@ -1,66 +1,23 @@ -server: - port: 8081 - servlet: - context-path: /v2/huertos - spring: application: name: huertos-service - datasource: - url: jdbc:mariadb://localhost:3306/miarma_v2 - username: admin - password: ositovito - driver-class-name: org.mariadb.jdbc.Driver - jpa: open-in-view: false hibernate: ddl-auto: validate properties: hibernate: - format_sql: true jdbc: time_zone: UTC jackson: - serialization: - indent-output: true default-property-inclusion: non_null time-zone: Europe/Madrid -logging: - level: - org.hibernate.SQL: DEBUG - org.hibernate.orm.jdbc.bind: TRACE - org.springframework.security: INFO - jwt: - private-key-path: /home/jomaa/.config/miarma-backend/private.pem - public-key-path: /home/jomaa/.config/miarma-backend/public.pem expiration-ms: 3600000 -core: - url: "http://localhost:8080/v2/core" - -huertos: - user: "SYSTEM" - password: "mR193*8ztxgskTrt" - -mail: - smtp: - server: smtp.dondominio.com - port: 587 - password: - presidente: Huertos$Presidenzia2025 - secretaria: Huertos$Secretarya2025 - tesoreria: Huertos$Tesorerya2025 - admin: Mi.Primer.Aire.Mundo.Clima;99 - noreply: hpeeuRqn2-2MN_ - imap: - server: imap.dondominio.com - port: 993 - management: endpoints: web: diff --git a/minecraft/pom.xml b/minecraft/pom.xml index 56cd265..2531777 100644 --- a/minecraft/pom.xml +++ b/minecraft/pom.xml @@ -14,6 +14,13 @@ 25 + + + gitea + https://git.miarma.net/api/packages/Gallardo7761/maven + + + diff --git a/mpaste/pom.xml b/mpaste/pom.xml index c4fe027..fbff362 100644 --- a/mpaste/pom.xml +++ b/mpaste/pom.xml @@ -14,6 +14,13 @@ 25 + + + gitea + https://git.miarma.net/api/packages/Gallardo7761/maven + + +