Add: full basic Huertos functionality
This commit is contained in:
@@ -1,5 +1,6 @@
|
|||||||
package net.miarma.backlib.config;
|
package net.miarma.backlib.config;
|
||||||
|
|
||||||
|
import net.miarma.backlib.security.JwtService;
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.security.authentication.AuthenticationManager;
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
@@ -20,4 +21,9 @@ public class SecurityCommonConfig {
|
|||||||
public PasswordEncoder passwordEncoder() {
|
public PasswordEncoder passwordEncoder() {
|
||||||
return new BCryptPasswordEncoder(12);
|
return new BCryptPasswordEncoder(12);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public JwtService jwtService() {
|
||||||
|
return new JwtService();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package net.miarma.backlib.dto;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public class CreateCredentialDto {
|
||||||
|
private UUID userId;
|
||||||
|
private Byte serviceId;
|
||||||
|
private String username;
|
||||||
|
private String email;
|
||||||
|
private String password;
|
||||||
|
private Byte status;
|
||||||
|
|
||||||
|
public CreateCredentialDto() {}
|
||||||
|
|
||||||
|
public CreateCredentialDto(UUID userId, Byte serviceId, String username, String email,
|
||||||
|
String password, Byte status) {
|
||||||
|
this.userId = userId;
|
||||||
|
this.serviceId = serviceId;
|
||||||
|
this.username = username;
|
||||||
|
this.email = email;
|
||||||
|
this.password = password;
|
||||||
|
this.status = status;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Getters y setters
|
||||||
|
public UUID getUserId() {
|
||||||
|
return userId;
|
||||||
|
}
|
||||||
|
public void setUserId(UUID userId) {
|
||||||
|
this.userId = userId;
|
||||||
|
}
|
||||||
|
public Byte getServiceId() {
|
||||||
|
return serviceId;
|
||||||
|
}
|
||||||
|
public void setServiceId(Byte serviceId) {
|
||||||
|
this.serviceId = serviceId;
|
||||||
|
}
|
||||||
|
public String getUsername() {
|
||||||
|
return username;
|
||||||
|
}
|
||||||
|
public void setUsername(String username) {
|
||||||
|
this.username = username;
|
||||||
|
}
|
||||||
|
public String getEmail() {
|
||||||
|
return email;
|
||||||
|
}
|
||||||
|
public String getPassword() { return password; }
|
||||||
|
public void setPassword(String password) { this.password = password; }
|
||||||
|
public Byte getStatus() {
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
public void setStatus(Byte status) {
|
||||||
|
this.status = status;
|
||||||
|
}
|
||||||
|
}
|
||||||
123
backlib/src/main/java/net/miarma/backlib/dto/FileDto.java
Normal file
123
backlib/src/main/java/net/miarma/backlib/dto/FileDto.java
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
package net.miarma.backlib.dto;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public class FileDto {
|
||||||
|
|
||||||
|
private FileDto() {}
|
||||||
|
|
||||||
|
public static class Request {
|
||||||
|
private String fileName;
|
||||||
|
private String filePath;
|
||||||
|
private String mimeType;
|
||||||
|
private Byte context;
|
||||||
|
private UUID uploadedBy;
|
||||||
|
|
||||||
|
public String getFileName() {
|
||||||
|
return fileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFileName(String fileName) {
|
||||||
|
this.fileName = fileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFilePath() {
|
||||||
|
return filePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFilePath(String filePath) {
|
||||||
|
this.filePath = filePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMimeType() {
|
||||||
|
return mimeType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMimeType(String mimeType) {
|
||||||
|
this.mimeType = mimeType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Byte getContext() {
|
||||||
|
return context;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setContext(Byte context) {
|
||||||
|
this.context = context;
|
||||||
|
}
|
||||||
|
|
||||||
|
public UUID getUploadedBy() {
|
||||||
|
return uploadedBy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUploadedBy(UUID uploadedBy) {
|
||||||
|
this.uploadedBy = uploadedBy;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class Response {
|
||||||
|
private UUID fileId;
|
||||||
|
private String fileName;
|
||||||
|
private String filePath;
|
||||||
|
private String mimeType;
|
||||||
|
private UUID uploadedBy;
|
||||||
|
private Instant uploadedAt;
|
||||||
|
private Byte context;
|
||||||
|
|
||||||
|
public UUID getFileId() {
|
||||||
|
return fileId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFileId(UUID fileId) {
|
||||||
|
this.fileId = fileId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFileName() {
|
||||||
|
return fileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFileName(String fileName) {
|
||||||
|
this.fileName = fileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFilePath() {
|
||||||
|
return filePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setFilePath(String filePath) {
|
||||||
|
this.filePath = filePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMimeType() {
|
||||||
|
return mimeType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMimeType(String mimeType) {
|
||||||
|
this.mimeType = mimeType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public UUID getUploadedBy() {
|
||||||
|
return uploadedBy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUploadedBy(UUID uploadedBy) {
|
||||||
|
this.uploadedBy = uploadedBy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Instant getUploadedAt() {
|
||||||
|
return uploadedAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUploadedAt(Instant uploadedAt) {
|
||||||
|
this.uploadedAt = uploadedAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Byte getContext() {
|
||||||
|
return context;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setContext(Byte context) {
|
||||||
|
this.context = context;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package net.miarma.backlib.dto;
|
package net.miarma.backlib.dto;
|
||||||
|
|
||||||
import jakarta.validation.constraints.NotBlank;
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import tools.jackson.databind.JsonNode;
|
||||||
|
|
||||||
public record LoginRequest(@NotBlank String username,
|
public record LoginRequest(@NotBlank String username,
|
||||||
@NotBlank String password,
|
@NotBlank String password,
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
package net.miarma.backlib.dto;
|
package net.miarma.backlib.dto;
|
||||||
|
|
||||||
public record LoginResponse(String token,
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
|
||||||
|
public record LoginResponse(@JsonProperty("token") String token,
|
||||||
UserDto user,
|
UserDto user,
|
||||||
CredentialDto account) {}
|
CredentialDto account) {}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
package net.miarma.backlib.dto;
|
||||||
|
|
||||||
|
public record UserWithCredentialDto(UserDto user, CredentialDto account) {}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package net.miarma.backlib.security;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class CoreAuthTokenHolder {
|
||||||
|
private volatile String token;
|
||||||
|
|
||||||
|
public String getToken() {
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setToken(String token) {
|
||||||
|
this.token = token;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ import java.security.spec.PKCS8EncodedKeySpec;
|
|||||||
import java.security.spec.X509EncodedKeySpec;
|
import java.security.spec.X509EncodedKeySpec;
|
||||||
import java.util.Base64;
|
import java.util.Base64;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package net.miarma.backlib.security;
|
||||||
|
|
||||||
|
import jakarta.servlet.FilterChain;
|
||||||
|
import jakarta.servlet.ServletException;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class ServiceAuthFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
|
private final JwtService jwtService;
|
||||||
|
|
||||||
|
public ServiceAuthFilter(JwtService jwtService) {
|
||||||
|
this.jwtService = jwtService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void doFilterInternal(HttpServletRequest request,
|
||||||
|
HttpServletResponse response,
|
||||||
|
FilterChain filterChain)
|
||||||
|
throws ServletException, IOException {
|
||||||
|
|
||||||
|
String path = request.getRequestURI();
|
||||||
|
|
||||||
|
if (path.startsWith("/users/service")) {
|
||||||
|
String authHeader = request.getHeader("Authorization");
|
||||||
|
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
||||||
|
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String token = authHeader.substring(7);
|
||||||
|
if (!jwtService.validateToken(token)) {
|
||||||
|
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
filterChain.doFilter(request, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,14 @@
|
|||||||
package net.miarma.backend.core;
|
package net.miarma.backend.core;
|
||||||
|
|
||||||
|
import net.miarma.backlib.config.SecurityCommonConfig;
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
import org.springframework.context.annotation.Import;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication(scanBasePackages = {
|
||||||
|
"net.miarma.backend.core",
|
||||||
|
"net.miarma.backlib"
|
||||||
|
})
|
||||||
public class CoreApplication {
|
public class CoreApplication {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
SpringApplication.run(CoreApplication.class, args);
|
SpringApplication.run(CoreApplication.class, args);
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ public class SecurityConfig {
|
|||||||
.csrf(csrf -> csrf.disable())
|
.csrf(csrf -> csrf.disable())
|
||||||
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||||
.authorizeHttpRequests(auth -> auth
|
.authorizeHttpRequests(auth -> auth
|
||||||
.requestMatchers("/auth/**").permitAll()
|
.requestMatchers("/auth/**", "/screenshot").permitAll()
|
||||||
.anyRequest().authenticated()
|
.anyRequest().authenticated()
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package net.miarma.backend.core.config;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class WebClientConfig {
|
||||||
|
@Bean
|
||||||
|
public WebClient.Builder webClientBuilder() {
|
||||||
|
return WebClient.builder();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -41,7 +41,9 @@ public class AuthController {
|
|||||||
@PostMapping("/login")
|
@PostMapping("/login")
|
||||||
public ResponseEntity<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
|
public ResponseEntity<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
|
||||||
LoginResponse response = authService.login(request);
|
LoginResponse response = authService.login(request);
|
||||||
return ResponseEntity.ok(response);
|
return ResponseEntity.ok(
|
||||||
|
new LoginResponse(response.token(), response.user(), response.account())
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/register")
|
@PostMapping("/register")
|
||||||
@@ -90,13 +92,13 @@ public class AuthController {
|
|||||||
|
|
||||||
Credential cred = credentialService.getByUserId(userId)
|
Credential cred = credentialService.getByUserId(userId)
|
||||||
.stream()
|
.stream()
|
||||||
.filter(c -> c.getServiceId().equals(request.getServiceId()))
|
.filter(c -> c.getServiceId().equals(request.serviceId()))
|
||||||
.findFirst().get();
|
.findFirst().get();
|
||||||
if (cred == null) {
|
if (cred == null) {
|
||||||
return ResponseEntity.status(404).body("Credential not found");
|
return ResponseEntity.status(404).body("Credential not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!passwordEncoder.matches(request.getOldPassword(), cred.getPassword())) {
|
if (!passwordEncoder.matches(request.oldPassword(), cred.getPassword())) {
|
||||||
return ResponseEntity.status(400).body("Old password is incorrect");
|
return ResponseEntity.status(400).body("Old password is incorrect");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,21 +3,15 @@ package net.miarma.backend.core.controller;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import net.miarma.backlib.dto.ChangeRoleRequest;
|
import net.miarma.backend.core.mapper.CredentialMapper;
|
||||||
import net.miarma.backlib.dto.ChangeStatusRequest;
|
import net.miarma.backend.core.mapper.UserMapper;
|
||||||
|
import net.miarma.backlib.dto.*;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
|
||||||
import org.springframework.web.bind.annotation.PutMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
import net.miarma.backend.core.model.Credential;
|
import net.miarma.backend.core.model.Credential;
|
||||||
import net.miarma.backend.core.service.CredentialService;
|
import net.miarma.backend.core.service.CredentialService;
|
||||||
import net.miarma.backlib.dto.CredentialDto;
|
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/credentials")
|
@RequestMapping("/credentials")
|
||||||
@@ -35,6 +29,16 @@ public class CredentialController {
|
|||||||
return ResponseEntity.ok(credentialService.getAll());
|
return ResponseEntity.ok(credentialService.getAll());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
@PreAuthorize("hasRole('ADMIN')")
|
||||||
|
public ResponseEntity<CredentialDto> create(@RequestBody CreateCredentialDto dto) {
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
CredentialMapper.toDto(
|
||||||
|
credentialService.create(
|
||||||
|
CredentialMapper.toEntity(dto)))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/user/{userId}")
|
@GetMapping("/user/{userId}")
|
||||||
@PreAuthorize("hasRole('ADMIN') or #userId == authentication.principal.userId")
|
@PreAuthorize("hasRole('ADMIN') or #userId == authentication.principal.userId")
|
||||||
public ResponseEntity<List<Credential>> getByUserId(@PathVariable("userId") UUID userId) {
|
public ResponseEntity<List<Credential>> getByUserId(@PathVariable("userId") UUID userId) {
|
||||||
@@ -77,18 +81,4 @@ public class CredentialController {
|
|||||||
credentialService.updateStatus(credentialId, req.status());
|
credentialService.updateStatus(credentialId, req.status());
|
||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.noContent().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{credential_id}/role")
|
|
||||||
public ResponseEntity<Byte> getRole(@PathVariable("credential_id") UUID credentialId) {
|
|
||||||
return ResponseEntity.ok(credentialService.getRole(credentialId));
|
|
||||||
}
|
|
||||||
|
|
||||||
@PutMapping("/{credential_id}/role")
|
|
||||||
public ResponseEntity<Void> updateRole(
|
|
||||||
@PathVariable("credential_id") UUID credentialId,
|
|
||||||
@RequestBody ChangeRoleRequest req
|
|
||||||
) {
|
|
||||||
credentialService.updateRole(credentialId, req.role());
|
|
||||||
return ResponseEntity.noContent().build();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import net.miarma.backend.core.mapper.FileMapper;
|
||||||
|
import net.miarma.backlib.dto.FileDto;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
@@ -37,40 +39,40 @@ public class FileController {
|
|||||||
|
|
||||||
@GetMapping
|
@GetMapping
|
||||||
@PreAuthorize("hasRole('ADMIN')")
|
@PreAuthorize("hasRole('ADMIN')")
|
||||||
public ResponseEntity<List<File>> getAll(@RequestParam Map<String,String> params) {
|
public ResponseEntity<List<File>> getAll() {
|
||||||
List<File> files = fileService.getAll(params);
|
List<File> files = fileService.getAll();
|
||||||
return ResponseEntity.ok(files);
|
return ResponseEntity.ok(files);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/{fileId}")
|
@GetMapping("/{fileId}")
|
||||||
@PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#fileId, authentication.principal.userId)")
|
@PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#fileId, authentication.principal.userId)")
|
||||||
public ResponseEntity<File> getById(@PathVariable UUID fileId) {
|
public ResponseEntity<File> getById(@PathVariable("file_id") UUID fileId) {
|
||||||
File file = fileService.getById(fileId);
|
File file = fileService.getById(fileId);
|
||||||
return ResponseEntity.ok(file);
|
return ResponseEntity.ok(file);
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
@PreAuthorize("hasRole('ADMIN') or #uploadedBy == authentication.principal.userId")
|
@PreAuthorize("hasRole('ADMIN') or #uploadedBy == authentication.principal.userId")
|
||||||
public ResponseEntity<File> create(
|
public ResponseEntity<FileDto.Response> create(
|
||||||
@RequestParam String fileName,
|
@RequestParam String fileName,
|
||||||
@RequestParam String mimeType,
|
@RequestParam String mimeType,
|
||||||
@RequestParam UUID uploadedBy,
|
@RequestParam UUID uploadedBy,
|
||||||
@RequestParam Byte context,
|
@RequestParam Byte context,
|
||||||
@RequestPart("file") MultipartFile file
|
@RequestPart("file") MultipartFile file
|
||||||
) throws IOException {
|
) throws IOException {
|
||||||
File entity = new File();
|
FileDto.Request dto = new FileDto.Request();
|
||||||
entity.setFileName(fileName);
|
dto.setFileName(fileName);
|
||||||
entity.setMimeType(mimeType);
|
dto.setMimeType(mimeType);
|
||||||
entity.setUploadedBy(uploadedBy);
|
dto.setUploadedBy(uploadedBy);
|
||||||
entity.setContext(context);
|
dto.setContext(context);
|
||||||
|
|
||||||
File created = fileService.create(entity, file.getBytes());
|
File created = fileService.create(dto, file.getBytes());
|
||||||
return ResponseEntity.status(HttpStatus.CREATED).body(created);
|
return ResponseEntity.status(HttpStatus.CREATED).body(FileMapper.toResponse(created));
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/{fileId}")
|
@PutMapping("/{fileId}")
|
||||||
@PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#fileId, authentication.principal.userId)")
|
@PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#fileId, authentication.principal.userId)")
|
||||||
public ResponseEntity<File> update(@PathVariable UUID fileId, @RequestBody File file) {
|
public ResponseEntity<File> update(@PathVariable("file_id") UUID fileId, @RequestBody File file) {
|
||||||
file.setFileId(fileId);
|
file.setFileId(fileId);
|
||||||
File updated = fileService.update(file);
|
File updated = fileService.update(file);
|
||||||
return ResponseEntity.ok(updated);
|
return ResponseEntity.ok(updated);
|
||||||
@@ -78,10 +80,10 @@ public class FileController {
|
|||||||
|
|
||||||
@DeleteMapping("/{fileId}")
|
@DeleteMapping("/{fileId}")
|
||||||
@PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#fileId, authentication.principal.userId)")
|
@PreAuthorize("hasRole('ADMIN') or @fileService.isOwner(#fileId, authentication.principal.userId)")
|
||||||
public ResponseEntity<Void> delete(@PathVariable UUID fileId, @RequestBody Map<String,String> body) throws IOException {
|
public ResponseEntity<Void> delete(@PathVariable("file_id") UUID fileId, @RequestBody Map<String,String> body) throws IOException {
|
||||||
String filePath = body.get("file_path");
|
String filePath = body.get("file_path");
|
||||||
Files.deleteIfExists(Paths.get(filePath));
|
Files.deleteIfExists(Paths.get(filePath));
|
||||||
fileService.delete(fileId);
|
fileService.delete(fileId);
|
||||||
return ResponseEntity.noContent().build();
|
return ResponseEntity.ok().build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,35 +3,31 @@ package net.miarma.backend.core.controller;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import net.miarma.backlib.dto.ChangeRoleRequest;
|
import net.miarma.backend.core.mapper.CredentialMapper;
|
||||||
import net.miarma.backlib.dto.ChangeAvatarRequest;
|
import net.miarma.backend.core.model.Credential;
|
||||||
import net.miarma.backlib.dto.ChangeStatusRequest;
|
import net.miarma.backend.core.service.CredentialService;
|
||||||
import net.miarma.backlib.dto.UserExistsResponse;
|
import net.miarma.backlib.dto.*;
|
||||||
|
import org.apache.coyote.Response;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.security.access.prepost.PreAuthorize;
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
|
||||||
import org.springframework.web.bind.annotation.PutMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
|
||||||
import org.springframework.web.bind.annotation.RequestHeader;
|
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
import net.miarma.backend.core.mapper.UserMapper;
|
import net.miarma.backend.core.mapper.UserMapper;
|
||||||
import net.miarma.backend.core.model.User;
|
import net.miarma.backend.core.model.User;
|
||||||
import net.miarma.backlib.security.JwtService;
|
import net.miarma.backlib.security.JwtService;
|
||||||
import net.miarma.backend.core.service.UserService;
|
import net.miarma.backend.core.service.UserService;
|
||||||
import net.miarma.backlib.dto.UserDto;
|
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/users")
|
@RequestMapping("/users")
|
||||||
public class UserController {
|
public class UserController {
|
||||||
private UserService userService;
|
private UserService userService;
|
||||||
|
private CredentialService credentialService;
|
||||||
private JwtService jwtService;
|
private JwtService jwtService;
|
||||||
|
|
||||||
public UserController(UserService userService, JwtService jwtService) {
|
public UserController(UserService userService, CredentialService credentialService, JwtService jwtService) {
|
||||||
this.userService = userService;
|
this.userService = userService;
|
||||||
|
this.credentialService = credentialService;
|
||||||
this.jwtService = jwtService;
|
this.jwtService = jwtService;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,6 +42,14 @@ public class UserController {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping
|
||||||
|
@PreAuthorize("hasRole('ADMIN')")
|
||||||
|
public ResponseEntity<UserDto> create(@RequestBody UserDto dto) {
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
UserMapper.toDto(userService.create(dto))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/{user_id}")
|
@GetMapping("/{user_id}")
|
||||||
@PreAuthorize("hasRole('ADMIN')")
|
@PreAuthorize("hasRole('ADMIN')")
|
||||||
public ResponseEntity<UserDto> getById(@PathVariable("user_id") UUID userId) {
|
public ResponseEntity<UserDto> getById(@PathVariable("user_id") UUID userId) {
|
||||||
@@ -53,6 +57,39 @@ public class UserController {
|
|||||||
return ResponseEntity.ok(UserMapper.toDto(user));
|
return ResponseEntity.ok(UserMapper.toDto(user));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@GetMapping("/service/{service_id}")
|
||||||
|
@PreAuthorize("hasRole('ADMIN')")
|
||||||
|
public ResponseEntity<List<UserWithCredentialDto>> getAllWithCredentials(
|
||||||
|
@PathVariable("service_id") Byte serviceId
|
||||||
|
) {
|
||||||
|
List<Credential> credentials = credentialService.getByServiceIdFetchUser(serviceId);
|
||||||
|
|
||||||
|
List<UserWithCredentialDto> result = credentials.stream()
|
||||||
|
.map(cred -> new UserWithCredentialDto(
|
||||||
|
UserMapper.toDto(cred.getUser()),
|
||||||
|
CredentialMapper.toDto(cred)
|
||||||
|
))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
return ResponseEntity.ok(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{user_id}/service/{service_id}")
|
||||||
|
@PreAuthorize("hasRole('ADMIN')")
|
||||||
|
public ResponseEntity<UserWithCredentialDto> getByIdWithCredentials(
|
||||||
|
@PathVariable("user_id") UUID userId,
|
||||||
|
@PathVariable("service_id") Byte serviceId
|
||||||
|
) {
|
||||||
|
User user = userService.getById(userId);
|
||||||
|
Credential credential = credentialService.getByUserIdAndService(userId, serviceId);
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
UserMapper.toDtoWithCredentials(
|
||||||
|
UserMapper.toDto(user),
|
||||||
|
CredentialMapper.toDto(credential)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@PutMapping("/{user_id}")
|
@PutMapping("/{user_id}")
|
||||||
@PreAuthorize("hasRole('ADMIN') or #userId == principal.userId")
|
@PreAuthorize("hasRole('ADMIN') or #userId == principal.userId")
|
||||||
public ResponseEntity<UserDto> update(@PathVariable("user_id") UUID userId, @RequestBody UserDto dto) {
|
public ResponseEntity<UserDto> update(@PathVariable("user_id") UUID userId, @RequestBody UserDto dto) {
|
||||||
@@ -121,4 +158,11 @@ public class UserController {
|
|||||||
User user = userService.getById(userId);
|
User user = userService.getById(userId);
|
||||||
return ResponseEntity.ok(UserMapper.toDto(user));
|
return ResponseEntity.ok(UserMapper.toDto(user));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{user_id}")
|
||||||
|
@PreAuthorize("hasRole('ADMIN')")
|
||||||
|
public ResponseEntity<Void> delete(@PathVariable("user_id") UUID userId) {
|
||||||
|
userService.delete(userId);
|
||||||
|
return ResponseEntity.ok().build();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
package net.miarma.backend.core.mapper;
|
package net.miarma.backend.core.mapper;
|
||||||
|
|
||||||
import net.miarma.backend.core.model.Credential;
|
import net.miarma.backend.core.model.Credential;
|
||||||
|
import net.miarma.backlib.dto.CreateCredentialDto;
|
||||||
import net.miarma.backlib.dto.CredentialDto;
|
import net.miarma.backlib.dto.CredentialDto;
|
||||||
|
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
public class CredentialMapper {
|
public class CredentialMapper {
|
||||||
|
|
||||||
public static CredentialDto toDto(Credential c) {
|
public static CredentialDto toDto(Credential c) {
|
||||||
@@ -19,4 +22,47 @@ public class CredentialMapper {
|
|||||||
c.getUpdatedAt()
|
c.getUpdatedAt()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static CreateCredentialDto toCreateDto(Credential c) {
|
||||||
|
if (c == null) return null;
|
||||||
|
|
||||||
|
return new CreateCredentialDto(
|
||||||
|
c.getUserId(),
|
||||||
|
c.getServiceId(),
|
||||||
|
c.getUsername(),
|
||||||
|
c.getEmail(),
|
||||||
|
c.getPassword(),
|
||||||
|
c.getStatus()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Credential toEntity(CredentialDto dto) {
|
||||||
|
if (dto == null) return null;
|
||||||
|
|
||||||
|
Credential c = new Credential();
|
||||||
|
c.setCredentialId(dto.getCredentialId());
|
||||||
|
c.setUserId(dto.getUserId());
|
||||||
|
c.setServiceId(dto.getServiceId());
|
||||||
|
c.setUsername(dto.getUsername());
|
||||||
|
c.setEmail(dto.getEmail());
|
||||||
|
c.setStatus(dto.getStatus());
|
||||||
|
c.setCreatedAt(dto.getCreatedAt());
|
||||||
|
c.setUpdatedAt(dto.getUpdatedAt());
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Credential toEntity(CreateCredentialDto dto) {
|
||||||
|
if (dto == null) return null;
|
||||||
|
|
||||||
|
Credential c = new Credential();
|
||||||
|
c.setUserId(dto.getUserId());
|
||||||
|
c.setServiceId(dto.getServiceId());
|
||||||
|
c.setUsername(dto.getUsername());
|
||||||
|
c.setEmail(dto.getEmail());
|
||||||
|
c.setPassword(dto.getPassword());
|
||||||
|
c.setStatus(dto.getStatus());
|
||||||
|
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package net.miarma.backend.core.mapper;
|
||||||
|
|
||||||
|
import net.miarma.backend.core.model.File;
|
||||||
|
import net.miarma.backlib.dto.FileDto;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public class FileMapper {
|
||||||
|
|
||||||
|
private FileMapper() {}
|
||||||
|
|
||||||
|
public static FileDto.Response toResponse(File file) {
|
||||||
|
FileDto.Response res = new FileDto.Response();
|
||||||
|
|
||||||
|
res.setFileId(file.getFileId());
|
||||||
|
res.setFileName(file.getFileName());
|
||||||
|
res.setFilePath(file.getFilePath());
|
||||||
|
res.setMimeType(file.getMimeType());
|
||||||
|
res.setUploadedBy(file.getUploadedBy());
|
||||||
|
res.setUploadedAt(file.getUploadedAt());
|
||||||
|
res.setContext(file.getContext());
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static File toEntity(FileDto.Request req) {
|
||||||
|
File file = new File();
|
||||||
|
|
||||||
|
file.setFileId(UUID.randomUUID());
|
||||||
|
file.setFileName(req.getFileName());
|
||||||
|
file.setFilePath(req.getFilePath());
|
||||||
|
file.setMimeType(req.getMimeType());
|
||||||
|
file.setUploadedBy(req.getUploadedBy());
|
||||||
|
file.setContext(req.getContext());
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
package net.miarma.backend.core.mapper;
|
package net.miarma.backend.core.mapper;
|
||||||
|
|
||||||
import net.miarma.backend.core.model.User;
|
import net.miarma.backend.core.model.User;
|
||||||
|
import net.miarma.backlib.dto.CredentialDto;
|
||||||
import net.miarma.backlib.dto.UserDto;
|
import net.miarma.backlib.dto.UserDto;
|
||||||
|
import net.miarma.backlib.dto.UserWithCredentialDto;
|
||||||
|
|
||||||
public class UserMapper {
|
public class UserMapper {
|
||||||
public static UserDto toDto(User u) {
|
public static UserDto toDto(User u) {
|
||||||
@@ -17,4 +19,10 @@ public class UserMapper {
|
|||||||
u.getUpdatedAt()
|
u.getUpdatedAt()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static UserWithCredentialDto toDtoWithCredentials(UserDto user, CredentialDto account){
|
||||||
|
if (user == null || account == null) return null;
|
||||||
|
|
||||||
|
return new UserWithCredentialDto(user, account);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,7 +50,6 @@ public class Credential {
|
|||||||
private String email;
|
private String email;
|
||||||
private String password;
|
private String password;
|
||||||
private Byte status;
|
private Byte status;
|
||||||
private Byte role;
|
|
||||||
|
|
||||||
@CreationTimestamp
|
@CreationTimestamp
|
||||||
private Instant createdAt;
|
private Instant createdAt;
|
||||||
@@ -84,10 +83,6 @@ public class Credential {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public UUID getCredentialId() {
|
public UUID getCredentialId() {
|
||||||
if (credentialId == null && credentialIdBin != null) {
|
|
||||||
ByteBuffer bb = ByteBuffer.wrap(credentialIdBin);
|
|
||||||
credentialId = new UUID(bb.getLong(), bb.getLong());
|
|
||||||
}
|
|
||||||
return credentialId;
|
return credentialId;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,10 +138,6 @@ public class Credential {
|
|||||||
this.status = status;
|
this.status = status;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Byte getRole() { return role; }
|
|
||||||
|
|
||||||
public void setRole(Byte role) { this.role = role; }
|
|
||||||
|
|
||||||
public Instant getCreatedAt() {
|
public Instant getCreatedAt() {
|
||||||
return createdAt;
|
return createdAt;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,11 @@ public interface CredentialRepository extends JpaRepository<Credential, byte[]>
|
|||||||
Optional<Credential> findByServiceIdAndUsername(@Param("serviceId") Byte serviceId,
|
Optional<Credential> findByServiceIdAndUsername(@Param("serviceId") Byte serviceId,
|
||||||
@Param("username") String username);
|
@Param("username") String username);
|
||||||
|
|
||||||
|
List<Credential> findAllByServiceId(Byte serviceId);
|
||||||
|
|
||||||
|
@Query("SELECT c FROM Credential c JOIN FETCH c.user WHERE c.serviceId = :serviceId")
|
||||||
|
List<Credential> getByServiceIdFetchUser(@Param("serviceId") Byte serviceId);
|
||||||
|
|
||||||
Optional<Credential> findByServiceIdAndEmail(Byte serviceId, String email);
|
Optional<Credential> findByServiceIdAndEmail(Byte serviceId, String email);
|
||||||
|
|
||||||
Optional<Credential> findByUserIdAndServiceId(UUID userId, Byte serviceId);
|
Optional<Credential> findByUserIdAndServiceId(UUID userId, Byte serviceId);
|
||||||
|
|||||||
@@ -35,9 +35,6 @@ public class JwtFilter extends OncePerRequestFilter {
|
|||||||
protected void doFilterInternal(HttpServletRequest request,
|
protected void doFilterInternal(HttpServletRequest request,
|
||||||
HttpServletResponse response,
|
HttpServletResponse response,
|
||||||
FilterChain filterChain) throws ServletException, IOException {
|
FilterChain filterChain) throws ServletException, IOException {
|
||||||
|
|
||||||
System.out.println("JwtFilter ejecutándose para " + request.getRequestURI());
|
|
||||||
|
|
||||||
String authHeader = request.getHeader("Authorization");
|
String authHeader = request.getHeader("Authorization");
|
||||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||||
String token = authHeader.substring(7);
|
String token = authHeader.substring(7);
|
||||||
@@ -63,9 +60,6 @@ public class JwtFilter extends OncePerRequestFilter {
|
|||||||
new UsernamePasswordAuthenticationToken(user, null, authorities);
|
new UsernamePasswordAuthenticationToken(user, null, authorities);
|
||||||
SecurityContextHolder.getContext().setAuthentication(auth);
|
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||||
|
|
||||||
System.out.println("Granted Authorities: " +
|
|
||||||
SecurityContextHolder.getContext().getAuthentication().getAuthorities());
|
|
||||||
|
|
||||||
long timeLeft = jwtService.getExpiration(token).getTime() - System.currentTimeMillis();
|
long timeLeft = jwtService.getExpiration(token).getTime() - System.currentTimeMillis();
|
||||||
if (timeLeft < refreshThreshold) {
|
if (timeLeft < refreshThreshold) {
|
||||||
String newToken = jwtService.generateToken(userId, serviceId);
|
String newToken = jwtService.generateToken(userId, serviceId);
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import net.miarma.backlib.dto.LoginRequest;
|
|||||||
import net.miarma.backlib.dto.LoginResponse;
|
import net.miarma.backlib.dto.LoginResponse;
|
||||||
import net.miarma.backlib.dto.RegisterRequest;
|
import net.miarma.backlib.dto.RegisterRequest;
|
||||||
import net.miarma.backlib.dto.UserDto;
|
import net.miarma.backlib.dto.UserDto;
|
||||||
|
import tools.jackson.databind.JsonNode;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
public class AuthService {
|
public class AuthService {
|
||||||
@@ -32,46 +33,44 @@ public class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public LoginResponse login(LoginRequest request) {
|
public LoginResponse login(LoginRequest request) {
|
||||||
Credential cred = credentialService.getByUserIdAndService(request.getServiceId(), request.getUsername());
|
Credential cred = credentialService.getForLogin(request.serviceId(), request.username());
|
||||||
|
|
||||||
if (!passwordEncoder.matches(request.getPassword(), cred.getPassword())) {
|
if (!passwordEncoder.matches(request.password(), cred.getPassword())) {
|
||||||
throw new RuntimeException("Invalid credentials");
|
throw new RuntimeException("Invalid credentials");
|
||||||
}
|
}
|
||||||
|
|
||||||
String token = jwtService.generateToken(cred.getUserId(), request.getServiceId());
|
String token = jwtService.generateToken(cred.getUserId(), request.serviceId());
|
||||||
|
|
||||||
UserDto userDto = UserMapper.toDto(cred.getUser());
|
UserDto userDto = UserMapper.toDto(cred.getUser());
|
||||||
|
|
||||||
CredentialDto credentialDto = CredentialMapper.toDto(cred);
|
CredentialDto credentialDto = CredentialMapper.toDto(cred);
|
||||||
|
|
||||||
return new LoginResponse(token, userDto, credentialDto);
|
return new LoginResponse(token, userDto, credentialDto);
|
||||||
}
|
}
|
||||||
|
|
||||||
public LoginResponse register(RegisterRequest request) {
|
public LoginResponse register(RegisterRequest request) {
|
||||||
if (credentialService.existsByUsernameAndService(request.getUsername(), request.getServiceId())) {
|
if (credentialService.existsByUsernameAndService(request.username(), request.serviceId())) {
|
||||||
throw new RuntimeException("Username already taken");
|
throw new RuntimeException("Username already taken");
|
||||||
}
|
}
|
||||||
|
|
||||||
User user;
|
User user;
|
||||||
try {
|
try {
|
||||||
user = credentialService.getByEmail(request.getEmail());
|
user = credentialService.getByEmail(request.email());
|
||||||
} catch (RuntimeException e) {
|
} catch (RuntimeException e) {
|
||||||
UserDto dto = new UserDto();
|
UserDto dto = new UserDto();
|
||||||
dto.userId(UUID.randomUUID());
|
dto.setUserId(UUID.randomUUID());
|
||||||
dto.setDisplayName(request.getDisplayName());
|
dto.setDisplayName(request.displayName());
|
||||||
user = userService.create(dto);
|
user = userService.create(dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
Credential cred = new Credential();
|
Credential cred = new Credential();
|
||||||
cred.setCredentialId(UUID.randomUUID());
|
cred.setCredentialId(UUID.randomUUID());
|
||||||
cred.setUser(user);
|
cred.setUser(user);
|
||||||
cred.setServiceId((byte) request.getServiceId());
|
cred.setServiceId(request.serviceId());
|
||||||
cred.setUsername(request.getUsername());
|
cred.setUsername(request.username());
|
||||||
cred.setEmail(request.getEmail());
|
cred.setEmail(request.email());
|
||||||
cred.setPassword(passwordEncoder.encode(request.getPassword()));
|
cred.setPassword(passwordEncoder.encode(request.password()));
|
||||||
credentialService.create(cred);
|
credentialService.create(cred);
|
||||||
|
|
||||||
String token = jwtService.generateToken(user.getUserId(), request.getServiceId());
|
String token = jwtService.generateToken(user.getUserId(), request.serviceId());
|
||||||
|
|
||||||
return new LoginResponse(token, UserMapper.toDto(user), CredentialMapper.toDto(cred));
|
return new LoginResponse(token, UserMapper.toDto(user), CredentialMapper.toDto(cred));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ public class CredentialService {
|
|||||||
credential.getEmail(), credential.getServiceId());
|
credential.getEmail(), credential.getServiceId());
|
||||||
if (existsEmail) throw new IllegalArgumentException("Email already exists for this service");
|
if (existsEmail) throw new IllegalArgumentException("Email already exists for this service");
|
||||||
|
|
||||||
|
credential.setCredentialId(UUID.randomUUID());
|
||||||
credential.setPassword(passwordEncoder.encode(credential.getPassword()));
|
credential.setPassword(passwordEncoder.encode(credential.getPassword()));
|
||||||
return credentialRepository.save(credential);
|
return credentialRepository.save(credential);
|
||||||
}
|
}
|
||||||
@@ -62,6 +63,14 @@ public class CredentialService {
|
|||||||
return credentialRepository.findAll();
|
return credentialRepository.findAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<Credential> getByServiceId(Byte serviceId) {
|
||||||
|
return credentialRepository.findAllByServiceId(serviceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Credential> getByServiceIdFetchUser(Byte serviceId) {
|
||||||
|
return credentialRepository.getByServiceIdFetchUser(serviceId);
|
||||||
|
}
|
||||||
|
|
||||||
public List<Credential> getByUserId(UUID userId) {
|
public List<Credential> getByUserId(UUID userId) {
|
||||||
List<Credential> creds = credentialRepository.findByUserId(UuidUtil.uuidToBin(userId));
|
List<Credential> creds = credentialRepository.findByUserId(UuidUtil.uuidToBin(userId));
|
||||||
if (creds.isEmpty()) {
|
if (creds.isEmpty()) {
|
||||||
@@ -76,8 +85,8 @@ public class CredentialService {
|
|||||||
.getUser();
|
.getUser();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Credential getByUserIdAndService(Byte serviceId, String username) {
|
public Credential getByUserIdAndService(UUID userId, Byte serviceId) {
|
||||||
return credentialRepository.findByServiceIdAndUsername(serviceId, username)
|
return credentialRepository.findByUserIdAndServiceId(userId, serviceId)
|
||||||
.orElseThrow(() -> new RuntimeException("Credential not found in this site"));
|
.orElseThrow(() -> new RuntimeException("Credential not found in this site"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,18 +163,4 @@ public class CredentialService {
|
|||||||
credential.setStatus(status);
|
credential.setStatus(status);
|
||||||
credentialRepository.save(credential);
|
credentialRepository.save(credential);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Byte getRole(UUID credentialId) {
|
|
||||||
Credential credential = credentialRepository.findById(UuidUtil.uuidToBin(credentialId))
|
|
||||||
.orElseThrow(() -> new RuntimeException("User not found"));;
|
|
||||||
return credential.getRole();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void updateRole(UUID credentialId, Byte role) {
|
|
||||||
Credential credential = credentialRepository.findById(UuidUtil.uuidToBin(credentialId))
|
|
||||||
.orElseThrow(() -> new RuntimeException("User not found"));;
|
|
||||||
credential.setRole(role);
|
|
||||||
credentialRepository.save(credential);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ import java.util.List;
|
|||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import net.miarma.backend.core.mapper.FileMapper;
|
||||||
|
import net.miarma.backlib.dto.FileDto;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
@@ -33,15 +35,7 @@ public class FileService {
|
|||||||
.orElseThrow(() -> new RuntimeException("File not found"));
|
.orElseThrow(() -> new RuntimeException("File not found"));
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<File> getAll(Map<String,String> params) {
|
public List<File> getAll() {
|
||||||
if (params.containsKey("userId")) {
|
|
||||||
UUID userId = UUID.fromString(params.get("userId"));
|
|
||||||
return fileRepository.findByUploadedBy(userId);
|
|
||||||
}
|
|
||||||
if (params.containsKey("context")) {
|
|
||||||
Byte context = Byte.parseByte(params.get("context"));
|
|
||||||
return fileRepository.findByContext(context);
|
|
||||||
}
|
|
||||||
return fileRepository.findAll();
|
return fileRepository.findAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,20 +43,20 @@ public class FileService {
|
|||||||
return fileRepository.findByUploadedBy(userId);
|
return fileRepository.findByUploadedBy(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public File create(File file, byte[] fileBinary) throws IOException {
|
public File create(FileDto.Request dto, byte[] fileBinary) throws IOException {
|
||||||
Path dirPath = Paths.get(basePath, String.valueOf(file.getContext()));
|
Path dirPath = Paths.get(basePath, String.valueOf(dto.getContext()));
|
||||||
if (!Files.exists(dirPath)) {
|
if (!Files.exists(dirPath)) {
|
||||||
Files.createDirectories(dirPath);
|
Files.createDirectories(dirPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
Path filePath = dirPath.resolve(file.getFileName());
|
Path filePath = dirPath.resolve(dto.getFileName());
|
||||||
try (FileOutputStream fos = new FileOutputStream(filePath.toFile())) {
|
try (FileOutputStream fos = new FileOutputStream(filePath.toFile())) {
|
||||||
fos.write(fileBinary);
|
fos.write(fileBinary);
|
||||||
}
|
}
|
||||||
|
|
||||||
file.setFilePath(filePath.toString());
|
dto.setFilePath(filePath.toString());
|
||||||
|
|
||||||
return fileRepository.save(file);
|
return fileRepository.save(FileMapper.toEntity(dto));
|
||||||
}
|
}
|
||||||
|
|
||||||
public File update(File file) {
|
public File update(File file) {
|
||||||
|
|||||||
@@ -33,6 +33,12 @@
|
|||||||
<artifactId>mariadb-java-client</artifactId>
|
<artifactId>mariadb-java-client</artifactId>
|
||||||
<scope>runtime</scope>
|
<scope>runtime</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-http-client</artifactId>
|
||||||
|
<version>4.0.1</version>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
<!-- JWT -->
|
<!-- JWT -->
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>io.jsonwebtoken</groupId>
|
<groupId>io.jsonwebtoken</groupId>
|
||||||
|
|||||||
@@ -3,7 +3,10 @@ package net.miarma.backend.huertos;
|
|||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
@SpringBootApplication
|
@SpringBootApplication(scanBasePackages = {
|
||||||
|
"net.miarma.backend.huertos",
|
||||||
|
"net.miarma.backlib"
|
||||||
|
})
|
||||||
public class HuertosApplication {
|
public class HuertosApplication {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
SpringApplication.run(HuertosApplication.class, args);
|
SpringApplication.run(HuertosApplication.class, args);
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package net.miarma.backend.huertos.client;
|
||||||
|
|
||||||
|
import net.miarma.backlib.dto.LoginRequest;
|
||||||
|
import net.miarma.backlib.dto.LoginResponse;
|
||||||
|
import net.miarma.backlib.dto.UserWithCredentialDto;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class HuertosWebClient {
|
||||||
|
|
||||||
|
private final RestTemplate restTemplate;
|
||||||
|
private final String coreUrl;
|
||||||
|
|
||||||
|
public HuertosWebClient(RestTemplate restTemplate,
|
||||||
|
@Value("${core.url}") String coreUrl) {
|
||||||
|
this.restTemplate = restTemplate;
|
||||||
|
this.coreUrl = coreUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String login(String username, String password) {
|
||||||
|
LoginRequest req = new LoginRequest(username, password, (byte) 1);
|
||||||
|
LoginResponse resp = restTemplate.postForObject(
|
||||||
|
coreUrl + "/auth/login",
|
||||||
|
req,
|
||||||
|
LoginResponse.class
|
||||||
|
);
|
||||||
|
return resp.token();
|
||||||
|
}
|
||||||
|
|
||||||
|
public UserWithCredentialDto getUserWithCredential(UUID userId, Byte serviceId) {
|
||||||
|
return restTemplate.getForObject(
|
||||||
|
coreUrl + "/users/{user_id}/service/{service_id}",
|
||||||
|
UserWithCredentialDto.class,
|
||||||
|
userId, serviceId
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<UserWithCredentialDto> getAllUsersWithCredentials(Byte serviceId) {
|
||||||
|
UserWithCredentialDto[] arr = restTemplate.getForObject(
|
||||||
|
coreUrl + "/users/service/{service_id}",
|
||||||
|
UserWithCredentialDto[].class,
|
||||||
|
serviceId
|
||||||
|
);
|
||||||
|
|
||||||
|
return arr == null ? List.of() : Arrays.asList(arr);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package net.miarma.backend.huertos.config;
|
||||||
|
|
||||||
|
import net.miarma.backend.huertos.client.HuertosWebClient;
|
||||||
|
import net.miarma.backlib.security.CoreAuthTokenHolder;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.ApplicationArguments;
|
||||||
|
import org.springframework.boot.ApplicationRunner;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class HuertosStartup implements ApplicationRunner {
|
||||||
|
|
||||||
|
private final HuertosWebClient client;
|
||||||
|
private final CoreAuthTokenHolder tokenHolder;
|
||||||
|
private final String user;
|
||||||
|
private final String pass;
|
||||||
|
|
||||||
|
public HuertosStartup(
|
||||||
|
HuertosWebClient client,
|
||||||
|
CoreAuthTokenHolder tokenHolder,
|
||||||
|
@Value("${huertos.user}") String user,
|
||||||
|
@Value("${huertos.password}") String pass
|
||||||
|
) {
|
||||||
|
this.client = client;
|
||||||
|
this.tokenHolder = tokenHolder;
|
||||||
|
this.user = user;
|
||||||
|
this.pass = pass;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run(ApplicationArguments args) {
|
||||||
|
String token = client.login(user, pass);
|
||||||
|
tokenHolder.setToken(token);
|
||||||
|
System.out.println("TOKEN recibido: " + token);
|
||||||
|
System.out.println("HUERTOS CLIENT has been authenticated in CORE");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package net.miarma.backend.huertos.config;
|
||||||
|
|
||||||
|
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.web.client.RestTemplate;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class RestTemplateConfig {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
public RestTemplate restTemplate(CoreAuthTokenHolder tokenHolder) {
|
||||||
|
RestTemplate restTemplate = new RestTemplate();
|
||||||
|
|
||||||
|
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
|
||||||
|
interceptors.add(authInterceptor(tokenHolder));
|
||||||
|
|
||||||
|
restTemplate.setInterceptors(interceptors);
|
||||||
|
return restTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ClientHttpRequestInterceptor authInterceptor(CoreAuthTokenHolder tokenHolder) {
|
||||||
|
return (request, body, execution) -> {
|
||||||
|
String token = tokenHolder.getToken();
|
||||||
|
if (token != null) {
|
||||||
|
request.getHeaders().add("Authorization", "Bearer " + token);
|
||||||
|
}
|
||||||
|
return execution.execute(request, body);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,6 +31,7 @@ public class SecurityConfig {
|
|||||||
.requestMatchers("/login").permitAll()
|
.requestMatchers("/login").permitAll()
|
||||||
.requestMatchers("/announces/**").permitAll()
|
.requestMatchers("/announces/**").permitAll()
|
||||||
.requestMatchers("/huertos/members/waitlist").permitAll()
|
.requestMatchers("/huertos/members/waitlist").permitAll()
|
||||||
|
.requestMatchers("/huertos/members/waitlist/limited").permitAll()
|
||||||
.requestMatchers("/huertos/members/latest-number").permitAll()
|
.requestMatchers("/huertos/members/latest-number").permitAll()
|
||||||
// PRIVADAS
|
// PRIVADAS
|
||||||
.requestMatchers("/**").authenticated()
|
.requestMatchers("/**").authenticated()
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package net.miarma.backend.huertos.controller;
|
||||||
|
|
||||||
|
import net.miarma.backend.huertos.dto.AnnouncementDto;
|
||||||
|
import net.miarma.backend.huertos.mapper.AnnouncementMapper;
|
||||||
|
import net.miarma.backend.huertos.model.Announcement;
|
||||||
|
import net.miarma.backend.huertos.service.AnnouncementService;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/announcements")
|
||||||
|
public class AnnouncementController {
|
||||||
|
|
||||||
|
private final AnnouncementService announcementService;
|
||||||
|
|
||||||
|
public AnnouncementController(AnnouncementService announcementService) {
|
||||||
|
this.announcementService = announcementService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<List<AnnouncementDto.Response>> getAll() {
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
announcementService.getAll()
|
||||||
|
.stream()
|
||||||
|
.map(AnnouncementMapper::toResponse)
|
||||||
|
.toList()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{announce_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<AnnouncementDto.Response> getById(@PathVariable("announce_id") UUID announcementId) {
|
||||||
|
Announcement announcement = announcementService.getById(announcementId);
|
||||||
|
return ResponseEntity.ok(AnnouncementMapper.toResponse(announcement));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{announce_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<AnnouncementDto.Response> update(
|
||||||
|
@PathVariable("announce_id") UUID announcementId,
|
||||||
|
@RequestBody AnnouncementDto.Request dto
|
||||||
|
) {
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
AnnouncementMapper.toResponse(announcementService.update(announcementId, dto))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{announce_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<Map<String, String>> delete(@PathVariable("announce_id") UUID announcementId) {
|
||||||
|
announcementService.delete(announcementId);
|
||||||
|
return ResponseEntity.ok(Map.of("message", "Deleted announcement: " + announcementId));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package net.miarma.backend.huertos.controller;
|
||||||
|
|
||||||
|
import net.miarma.backend.huertos.dto.BalanceDto;
|
||||||
|
import net.miarma.backend.huertos.mapper.BalanceMapper;
|
||||||
|
import net.miarma.backend.huertos.model.Balance;
|
||||||
|
import net.miarma.backend.huertos.service.BalanceService;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/balance")
|
||||||
|
public class BalanceController {
|
||||||
|
private final BalanceService balanceService;
|
||||||
|
|
||||||
|
public BalanceController(BalanceService balanceService) {
|
||||||
|
this.balanceService = balanceService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<BalanceDto> getBalance() {
|
||||||
|
Balance balance = balanceService.get();
|
||||||
|
return ResponseEntity.ok(BalanceMapper.toDto(balance));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package net.miarma.backend.huertos.controller;
|
||||||
|
|
||||||
|
import net.miarma.backend.huertos.dto.ExpenseDto;
|
||||||
|
import net.miarma.backend.huertos.mapper.ExpenseMapper;
|
||||||
|
import net.miarma.backend.huertos.model.Expense;
|
||||||
|
import net.miarma.backend.huertos.service.ExpenseService;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/expenses")
|
||||||
|
public class ExpenseController {
|
||||||
|
private ExpenseService expenseService;
|
||||||
|
|
||||||
|
public ExpenseController(ExpenseService expenseService) {
|
||||||
|
this.expenseService = expenseService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<List<ExpenseDto.Response>> getAll() {
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
expenseService.getAll()
|
||||||
|
.stream()
|
||||||
|
.map(ExpenseMapper::toResponse)
|
||||||
|
.toList()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{expense_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<ExpenseDto.Response> getById(@PathVariable("expense_id") UUID expenseId) {
|
||||||
|
Expense expense = expenseService.getById(expenseId);
|
||||||
|
return ResponseEntity.ok(ExpenseMapper.toResponse(expense));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{expense_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<ExpenseDto.Response> update(@PathVariable("expense_id") UUID expenseId, @RequestBody ExpenseDto.Request dto) {
|
||||||
|
return ResponseEntity.ok(ExpenseMapper.toResponse(expenseService.update(expenseId, dto)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{expense_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<Map<String,String>> delete(@PathVariable("expense_id") UUID expenseId) {
|
||||||
|
expenseService.delete(expenseId);
|
||||||
|
return ResponseEntity.ok(Map.of("message", "Deleted expense: " + expenseId));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
package net.miarma.backend.huertos.controller;
|
||||||
|
|
||||||
|
import net.miarma.backend.huertos.dto.IncomeDto;
|
||||||
|
import net.miarma.backend.huertos.dto.view.VIncomesWithFullNamesDto;
|
||||||
|
import net.miarma.backend.huertos.mapper.IncomeMapper;
|
||||||
|
import net.miarma.backend.huertos.mapper.view.VIncomesWithFullNamesMapper;
|
||||||
|
import net.miarma.backend.huertos.model.Income;
|
||||||
|
import net.miarma.backend.huertos.service.IncomeService;
|
||||||
|
import net.miarma.backend.huertos.service.view.VIncomesWithFullNamesService;
|
||||||
|
import net.miarma.backlib.security.JwtService;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/incomes")
|
||||||
|
public class IncomeController {
|
||||||
|
private IncomeService incomeService;
|
||||||
|
private VIncomesWithFullNamesService vIncomesWithFullNamesService;
|
||||||
|
private JwtService jwtService;
|
||||||
|
|
||||||
|
public IncomeController(IncomeService incomeService, VIncomesWithFullNamesService vIncomesWithFullNamesService, JwtService jwtService) {
|
||||||
|
this.incomeService = incomeService;
|
||||||
|
this.vIncomesWithFullNamesService = vIncomesWithFullNamesService;
|
||||||
|
this.jwtService = jwtService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<List<IncomeDto.Response>> getAll() {
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
incomeService.getAll()
|
||||||
|
.stream()
|
||||||
|
.map(IncomeMapper::toResponse)
|
||||||
|
.toList()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/with-names")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<List<VIncomesWithFullNamesDto>> getAllWithNames() {
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
vIncomesWithFullNamesService.getAll()
|
||||||
|
.stream()
|
||||||
|
.map(VIncomesWithFullNamesMapper::toResponse)
|
||||||
|
.toList()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/mine")
|
||||||
|
public ResponseEntity<List<IncomeDto.Response>> getMine(@RequestHeader("Authorization") String authHeader) {
|
||||||
|
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
||||||
|
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
String token = authHeader.substring(7);
|
||||||
|
|
||||||
|
UUID userId;
|
||||||
|
try {
|
||||||
|
userId = jwtService.getUserId(token);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
incomeService.getByUserId(userId)
|
||||||
|
.stream()
|
||||||
|
.map(IncomeMapper::toResponse)
|
||||||
|
.toList()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{income_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<IncomeDto.Response> getById(@PathVariable("income_id") UUID incomeId) {
|
||||||
|
Income income = incomeService.getById(incomeId);
|
||||||
|
return ResponseEntity.ok(IncomeMapper.toResponse(income));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{income_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<IncomeDto.Response> update(@PathVariable("income_id") UUID incomeId, @RequestBody IncomeDto.Request dto) {
|
||||||
|
return ResponseEntity.ok(IncomeMapper.toResponse(incomeService.update(incomeId, dto)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{income_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<Map<String,String>> delete(@PathVariable("income_id") UUID incomeId) {
|
||||||
|
incomeService.delete(incomeId);
|
||||||
|
return ResponseEntity.ok(Map.of("message", "Deleted income: " + incomeId));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package net.miarma.backend.huertos.controller;
|
||||||
|
|
||||||
|
import net.miarma.backend.huertos.dto.MemberDto;
|
||||||
|
import net.miarma.backend.huertos.dto.WaitlistCensoredDto;
|
||||||
|
import net.miarma.backend.huertos.security.HuertosPrincipal;
|
||||||
|
import net.miarma.backend.huertos.service.MemberService;
|
||||||
|
import net.miarma.backlib.security.JwtService;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/users")
|
||||||
|
public class MemberController {
|
||||||
|
|
||||||
|
private final MemberService memberService;
|
||||||
|
|
||||||
|
public MemberController(MemberService memberService) {
|
||||||
|
this.memberService = memberService;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Byte getServiceIdFromToken() {
|
||||||
|
var auth = SecurityContextHolder.getContext().getAuthentication();
|
||||||
|
|
||||||
|
if (auth == null || !(auth.getPrincipal() instanceof HuertosPrincipal principal)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return principal.getServiceId();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public List<MemberDto> getAll() {
|
||||||
|
return memberService.getAll(getServiceIdFromToken());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{user_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public MemberDto getById(@PathVariable("user_id") UUID userId) {
|
||||||
|
return memberService.getById(userId, getServiceIdFromToken());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/me")
|
||||||
|
public MemberDto getMe() {
|
||||||
|
HuertosPrincipal principal =
|
||||||
|
(HuertosPrincipal) SecurityContextHolder
|
||||||
|
.getContext()
|
||||||
|
.getAuthentication()
|
||||||
|
.getPrincipal();
|
||||||
|
|
||||||
|
return memberService.getById(principal.getUserId(), getServiceIdFromToken());
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/latest-number")
|
||||||
|
public Integer getLatestNumber() {
|
||||||
|
return memberService.getLatestMemberNumber();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/waitlist")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public List<MemberDto> getWaitlist() {
|
||||||
|
return memberService.getWaitlist();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/waitlist/limited")
|
||||||
|
public List<WaitlistCensoredDto> getWaitlistLimited() {
|
||||||
|
return memberService.getWaitlistLimited();
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/number/{member_number}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public MemberDto getByMemberNumber(@PathVariable("member_number") Integer memberNumber) {
|
||||||
|
return memberService.getByMemberNumber(memberNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/number/{member_number}/incomes")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public Boolean getMemberIncomes(@PathVariable("member_number") Integer memberNumber) {
|
||||||
|
return memberService.hasIncomes(memberNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/number/{member_number}/has-paid")
|
||||||
|
public Boolean getMemberHasPaid(@PathVariable("member_number") Integer memberNumber) {
|
||||||
|
return memberService.hasPaid(memberNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/number/{member_number}/has-collaborator")
|
||||||
|
public Boolean getMemberHasCollaborator(@PathVariable("member_number") Integer memberNumber) {
|
||||||
|
return memberService.hasCollaborator(memberNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/number/{member_number}/has-greenhouse")
|
||||||
|
public Boolean getMemberHasGreenhouse(@PathVariable("member_number") Integer memberNumber) {
|
||||||
|
return memberService.hasGreenhouse(memberNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/number/{member_number}/has-collaborator-request")
|
||||||
|
public Boolean getMemberHasCollaboratorRequest(@PathVariable("member_number") Integer memberNumber) {
|
||||||
|
return memberService.hasCollaboratorRequest(memberNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/number/{member_number}/has-greenhouse-request")
|
||||||
|
public Boolean getMemberHasGreenhouseRequest(@PathVariable("member_number") Integer memberNumber) {
|
||||||
|
return memberService.hasGreenhouseRequest(memberNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/plot/{plot_number}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public MemberDto getByPlotNumber(@PathVariable("plot_number") Integer plotNumber) {
|
||||||
|
return memberService.getByPlotNumber(plotNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/dni/{dni}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public MemberDto getByDni(@PathVariable("dni") String dni) {
|
||||||
|
return memberService.getByDni(dni);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package net.miarma.backend.huertos.controller;
|
||||||
|
|
||||||
|
import net.miarma.backend.huertos.dto.PreUserDto;
|
||||||
|
import net.miarma.backend.huertos.mapper.PreUserMapper;
|
||||||
|
import net.miarma.backend.huertos.model.PreUser;
|
||||||
|
import net.miarma.backend.huertos.service.PreUserService;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/pre_users")
|
||||||
|
public class PreUserController {
|
||||||
|
|
||||||
|
private final PreUserService preUserService;
|
||||||
|
|
||||||
|
public PreUserController(PreUserService preUserService) {
|
||||||
|
this.preUserService = preUserService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<List<PreUserDto.Response>> getAll() {
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
preUserService.getAll()
|
||||||
|
.stream()
|
||||||
|
.map(PreUserMapper::toResponse)
|
||||||
|
.toList()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{pre_user_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<PreUserDto.Response> getById(@PathVariable("pre_user_id") UUID preUserId) {
|
||||||
|
PreUser preUser = preUserService.getById(preUserId);
|
||||||
|
return ResponseEntity.ok(PreUserMapper.toResponse(preUser));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{pre_user_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<PreUserDto.Response> update(
|
||||||
|
@PathVariable("pre_user_id") UUID preUserId,
|
||||||
|
@RequestBody PreUserDto.Request dto
|
||||||
|
) {
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
PreUserMapper.toResponse(preUserService.update(preUserId, dto))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{pre_user_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<Map<String, String>> delete(@PathVariable("pre_user_id") UUID preUserId) {
|
||||||
|
preUserService.delete(preUserId);
|
||||||
|
return ResponseEntity.ok(Map.of("message", "Deleted pre_user: " + preUserId));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
package net.miarma.backend.huertos.controller;
|
||||||
|
|
||||||
|
import net.miarma.backend.huertos.dto.RequestCountDto;
|
||||||
|
import net.miarma.backend.huertos.dto.RequestDto;
|
||||||
|
import net.miarma.backend.huertos.dto.view.VRequestsWithPreUsersDto;
|
||||||
|
import net.miarma.backend.huertos.mapper.RequestMapper;
|
||||||
|
import net.miarma.backend.huertos.mapper.view.VIncomesWithFullNamesMapper;
|
||||||
|
import net.miarma.backend.huertos.mapper.view.VRequestsWithPreUsersMapper;
|
||||||
|
import net.miarma.backend.huertos.model.Request;
|
||||||
|
import net.miarma.backend.huertos.model.view.VRequestsWithPreUsers;
|
||||||
|
import net.miarma.backend.huertos.service.RequestService;
|
||||||
|
import net.miarma.backend.huertos.service.view.VRequestsWithPreUsersService;
|
||||||
|
import net.miarma.backlib.security.JwtService;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.access.prepost.PreAuthorize;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/requests")
|
||||||
|
public class RequestController {
|
||||||
|
|
||||||
|
private final RequestService requestService;
|
||||||
|
private final VRequestsWithPreUsersService vRequestsWithPreUsersService;
|
||||||
|
private final JwtService jwtService;
|
||||||
|
|
||||||
|
public RequestController(RequestService requestService, VRequestsWithPreUsersService vRequestsWithPreUsersService, JwtService jwtService) {
|
||||||
|
this.requestService = requestService;
|
||||||
|
this.vRequestsWithPreUsersService = vRequestsWithPreUsersService;
|
||||||
|
this.jwtService = jwtService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<List<RequestDto.Response>> getAll() {
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
requestService.getAll()
|
||||||
|
.stream()
|
||||||
|
.map(RequestMapper::toResponse)
|
||||||
|
.toList()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/count")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<RequestCountDto> getRequestCount() {
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
requestService.getAll()
|
||||||
|
.stream()
|
||||||
|
.map(RequestMapper::toResponse)
|
||||||
|
.collect(Collectors.collectingAndThen(
|
||||||
|
Collectors.counting(),
|
||||||
|
RequestCountDto::new
|
||||||
|
))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/mine")
|
||||||
|
public ResponseEntity<List<RequestDto.Response>> getMine(@RequestHeader("Authorization") String authHeader) {
|
||||||
|
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
|
||||||
|
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
String token = authHeader.substring(7);
|
||||||
|
|
||||||
|
UUID userId;
|
||||||
|
try {
|
||||||
|
userId = jwtService.getUserId(token);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
requestService.getByUserId(userId)
|
||||||
|
.stream()
|
||||||
|
.map(RequestMapper::toResponse)
|
||||||
|
.toList()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/full")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<List<VRequestsWithPreUsersDto>> getAllWithPreUsers() {
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
vRequestsWithPreUsersService.getAll()
|
||||||
|
.stream()
|
||||||
|
.map(VRequestsWithPreUsersMapper::toResponse)
|
||||||
|
.toList()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/full/{request_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<VRequestsWithPreUsersDto> getByIdWithPreUsers(@PathVariable("request_id") UUID requestId) {
|
||||||
|
VRequestsWithPreUsers request = vRequestsWithPreUsersService.getById(requestId);
|
||||||
|
return ResponseEntity.ok(VRequestsWithPreUsersMapper.toResponse(request));
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping("/{request_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<RequestDto.Response> getById(@PathVariable("request_id") UUID requestId) {
|
||||||
|
Request request = requestService.getById(requestId);
|
||||||
|
return ResponseEntity.ok(RequestMapper.toResponse(request));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{request_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<RequestDto.Response> update(
|
||||||
|
@PathVariable("request_id") UUID requestId,
|
||||||
|
@RequestBody RequestDto.Request dto
|
||||||
|
) {
|
||||||
|
return ResponseEntity.ok(
|
||||||
|
RequestMapper.toResponse(requestService.update(requestId, dto))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{request_id}/accept")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<Map<String, String>> acceptRequest(@PathVariable("request_id") UUID requestId) {
|
||||||
|
requestService.acceptRequest(requestId);
|
||||||
|
return ResponseEntity.ok(Map.of("message", "Accepted request: " + requestId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@PutMapping("/{request_id}/reject")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<Map<String, String>> rejectRequest(@PathVariable("request_id") UUID requestId) {
|
||||||
|
requestService.rejectRequest(requestId);
|
||||||
|
return ResponseEntity.ok(Map.of("message", "Denied request: " + requestId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@DeleteMapping("/{request_id}")
|
||||||
|
@PreAuthorize("hasAnyRole('HUERTOS_ROLE_ADMIN', 'HUERTOS_ROLE_DEV')")
|
||||||
|
public ResponseEntity<Map<String, String>> delete(@PathVariable("request_id") UUID requestId) {
|
||||||
|
requestService.delete(requestId);
|
||||||
|
return ResponseEntity.ok(Map.of("message", "Deleted request: " + requestId));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package net.miarma.backend.huertos.dto;
|
||||||
|
|
||||||
|
import net.miarma.backlib.dto.CredentialDto;
|
||||||
|
import net.miarma.backlib.dto.UserDto;
|
||||||
|
|
||||||
|
public record MemberDto(UserDto user,
|
||||||
|
CredentialDto account,
|
||||||
|
HuertosUserMetadataDto metadata) {}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package net.miarma.backend.huertos.dto;
|
||||||
|
|
||||||
|
public record RequestCountDto(Long count) {
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package net.miarma.backend.huertos.dto;
|
||||||
|
|
||||||
|
public class WaitlistCensoredDto {
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,70 +1,71 @@
|
|||||||
package net.miarma.backend.huertos.dto.view;
|
package net.miarma.backend.huertos.dto.view;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
|
|
||||||
public class VBalanceWithTotalsDto {
|
public class VBalanceWithTotalsDto {
|
||||||
private Long id;
|
private Byte id;
|
||||||
private Double initialBank;
|
private BigDecimal initialBank;
|
||||||
private Double initialCash;
|
private BigDecimal initialCash;
|
||||||
private Double totalBankExpenses;
|
private BigDecimal totalBankExpenses;
|
||||||
private Double totalCashExpenses;
|
private BigDecimal totalCashExpenses;
|
||||||
private Double totalBankIncomes;
|
private BigDecimal totalBankIncomes;
|
||||||
private Double totalCashIncomes;
|
private BigDecimal totalCashIncomes;
|
||||||
private Instant createdAt;
|
private Instant createdAt;
|
||||||
|
|
||||||
public Long getId() {
|
public Byte getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setId(Long id) {
|
public void setId(Byte id) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Double getInitialBank() {
|
public BigDecimal getInitialBank() {
|
||||||
return initialBank;
|
return initialBank;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setInitialBank(Double initialBank) {
|
public void setInitialBank(BigDecimal initialBank) {
|
||||||
this.initialBank = initialBank;
|
this.initialBank = initialBank;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Double getInitialCash() {
|
public BigDecimal getInitialCash() {
|
||||||
return initialCash;
|
return initialCash;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setInitialCash(Double initialCash) {
|
public void setInitialCash(BigDecimal initialCash) {
|
||||||
this.initialCash = initialCash;
|
this.initialCash = initialCash;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Double getTotalBankExpenses() {
|
public BigDecimal getTotalBankExpenses() {
|
||||||
return totalBankExpenses;
|
return totalBankExpenses;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setTotalBankExpenses(Double totalBankExpenses) {
|
public void setTotalBankExpenses(BigDecimal totalBankExpenses) {
|
||||||
this.totalBankExpenses = totalBankExpenses;
|
this.totalBankExpenses = totalBankExpenses;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Double getTotalCashExpenses() {
|
public BigDecimal getTotalCashExpenses() {
|
||||||
return totalCashExpenses;
|
return totalCashExpenses;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setTotalCashExpenses(Double totalCashExpenses) {
|
public void setTotalCashExpenses(BigDecimal totalCashExpenses) {
|
||||||
this.totalCashExpenses = totalCashExpenses;
|
this.totalCashExpenses = totalCashExpenses;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Double getTotalBankIncomes() {
|
public BigDecimal getTotalBankIncomes() {
|
||||||
return totalBankIncomes;
|
return totalBankIncomes;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setTotalBankIncomes(Double totalBankIncomes) {
|
public void setTotalBankIncomes(BigDecimal totalBankIncomes) {
|
||||||
this.totalBankIncomes = totalBankIncomes;
|
this.totalBankIncomes = totalBankIncomes;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Double getTotalCashIncomes() {
|
public BigDecimal getTotalCashIncomes() {
|
||||||
return totalCashIncomes;
|
return totalCashIncomes;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setTotalCashIncomes(Double totalCashIncomes) {
|
public void setTotalCashIncomes(BigDecimal totalCashIncomes) {
|
||||||
this.totalCashIncomes = totalCashIncomes;
|
this.totalCashIncomes = totalCashIncomes;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ package net.miarma.backend.huertos.dto.view;
|
|||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
public class VHuertosMemberDto {
|
public class VHuertosMembersDto {
|
||||||
private UUID userId;
|
private UUID userId;
|
||||||
private String displayName;
|
private String displayName;
|
||||||
private String avatar;
|
private String avatar;
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package net.miarma.backend.huertos.dto.view;
|
package net.miarma.backend.huertos.dto.view;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@@ -8,7 +9,7 @@ public class VIncomesWithFullNamesDto {
|
|||||||
private UUID userId;
|
private UUID userId;
|
||||||
private String displayName;
|
private String displayName;
|
||||||
private String concept;
|
private String concept;
|
||||||
private Double amount;
|
private BigDecimal amount;
|
||||||
private Byte type;
|
private Byte type;
|
||||||
private Byte frequency;
|
private Byte frequency;
|
||||||
private Instant createdAt;
|
private Instant createdAt;
|
||||||
@@ -45,11 +46,11 @@ public class VIncomesWithFullNamesDto {
|
|||||||
this.concept = concept;
|
this.concept = concept;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Double getAmount() {
|
public BigDecimal getAmount() {
|
||||||
return amount;
|
return amount;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setAmount(Double amount) {
|
public void setAmount(BigDecimal amount) {
|
||||||
this.amount = amount;
|
this.amount = amount;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import java.util.UUID;
|
|||||||
|
|
||||||
public class AnnouncementMapper {
|
public class AnnouncementMapper {
|
||||||
|
|
||||||
public static AnnouncementDto.Response toDto(Announcement entity) {
|
public static AnnouncementDto.Response toResponse(Announcement entity) {
|
||||||
AnnouncementDto.Response dto = new AnnouncementDto.Response();
|
AnnouncementDto.Response dto = new AnnouncementDto.Response();
|
||||||
dto.setAnnounceId(entity.getAnnounceId());
|
dto.setAnnounceId(entity.getAnnounceId());
|
||||||
dto.setBody(entity.getBody());
|
dto.setBody(entity.getBody());
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
package net.miarma.backend.huertos.mapper.view;
|
package net.miarma.backend.huertos.mapper.view;
|
||||||
|
|
||||||
import net.miarma.backend.huertos.dto.view.VHuertosMemberDto;
|
import net.miarma.backend.huertos.dto.view.VHuertosMembersDto;
|
||||||
import net.miarma.backend.huertos.model.view.VHuertosMember;
|
import net.miarma.backend.huertos.model.view.VHuertosMembers;
|
||||||
|
|
||||||
public class VHuertosMemberMapper {
|
public class VHuertosMembersMapper {
|
||||||
|
|
||||||
public static VHuertosMemberDto toDto(VHuertosMember entity) {
|
public static VHuertosMembersDto toResponse(VHuertosMembers entity) {
|
||||||
VHuertosMemberDto dto = new VHuertosMemberDto();
|
VHuertosMembersDto dto = new VHuertosMembersDto();
|
||||||
dto.setUserId(entity.getUserId());
|
dto.setUserId(entity.getUserId());
|
||||||
dto.setDisplayName(entity.getDisplayName());
|
dto.setDisplayName(entity.getDisplayName());
|
||||||
dto.setAvatar(entity.getAvatar());
|
dto.setAvatar(entity.getAvatar());
|
||||||
@@ -5,7 +5,7 @@ import net.miarma.backend.huertos.model.view.VIncomesWithFullNames;
|
|||||||
|
|
||||||
public class VIncomesWithFullNamesMapper {
|
public class VIncomesWithFullNamesMapper {
|
||||||
|
|
||||||
public static VIncomesWithFullNamesDto toDto(VIncomesWithFullNames entity) {
|
public static VIncomesWithFullNamesDto toResponse(VIncomesWithFullNames entity) {
|
||||||
VIncomesWithFullNamesDto dto = new VIncomesWithFullNamesDto();
|
VIncomesWithFullNamesDto dto = new VIncomesWithFullNamesDto();
|
||||||
dto.setIncomeId(entity.getIncomeId());
|
dto.setIncomeId(entity.getIncomeId());
|
||||||
dto.setUserId(entity.getUserId());
|
dto.setUserId(entity.getUserId());
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import net.miarma.backend.huertos.model.view.VRequestsWithPreUsers;
|
|||||||
|
|
||||||
public class VRequestsWithPreUsersMapper {
|
public class VRequestsWithPreUsersMapper {
|
||||||
|
|
||||||
public static VRequestsWithPreUsersDto toDto(VRequestsWithPreUsers entity) {
|
public static VRequestsWithPreUsersDto toResponse(VRequestsWithPreUsers entity) {
|
||||||
VRequestsWithPreUsersDto dto = new VRequestsWithPreUsersDto();
|
VRequestsWithPreUsersDto dto = new VRequestsWithPreUsersDto();
|
||||||
dto.setRequestId(entity.getRequestId());
|
dto.setRequestId(entity.getRequestId());
|
||||||
dto.setRequestType(entity.getRequestType());
|
dto.setRequestType(entity.getRequestType());
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
package net.miarma.backend.huertos.model;
|
package net.miarma.backend.huertos.model;
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
|
import java.time.Duration;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
@@ -62,6 +64,17 @@ public class Income {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public boolean isPaid() {
|
||||||
|
Instant now = Instant.now();
|
||||||
|
if (frequency == 0) { // BIYEARLY
|
||||||
|
return Duration.between(createdAt, now).toDays() <= 6L * 30;
|
||||||
|
} else if (frequency == 1) { // YEARLY
|
||||||
|
return Duration.between(createdAt, now).toDays() <= 12L * 30;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public UUID getIncomeId() {
|
public UUID getIncomeId() {
|
||||||
return incomeId;
|
return incomeId;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import jakarta.persistence.Id;
|
|||||||
import jakarta.persistence.Table;
|
import jakarta.persistence.Table;
|
||||||
import org.hibernate.annotations.Immutable;
|
import org.hibernate.annotations.Immutable;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@@ -14,54 +15,54 @@ import java.time.Instant;
|
|||||||
public class VBalanceWithTotals {
|
public class VBalanceWithTotals {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
private Long id;
|
private Byte id;
|
||||||
|
|
||||||
@Column(name = "initial_bank")
|
@Column(name = "initial_bank")
|
||||||
private Double initialBank;
|
private BigDecimal initialBank;
|
||||||
|
|
||||||
@Column(name = "initial_cash")
|
@Column(name = "initial_cash")
|
||||||
private Double initialCash;
|
private BigDecimal initialCash;
|
||||||
|
|
||||||
@Column(name = "total_bank_expenses")
|
@Column(name = "total_bank_expenses")
|
||||||
private Double totalBankExpenses;
|
private BigDecimal totalBankExpenses;
|
||||||
|
|
||||||
@Column(name = "total_cash_expenses")
|
@Column(name = "total_cash_expenses")
|
||||||
private Double totalCashExpenses;
|
private BigDecimal totalCashExpenses;
|
||||||
|
|
||||||
@Column(name = "total_bank_incomes")
|
@Column(name = "total_bank_incomes")
|
||||||
private Double totalBankIncomes;
|
private BigDecimal totalBankIncomes;
|
||||||
|
|
||||||
@Column(name = "total_cash_incomes")
|
@Column(name = "total_cash_incomes")
|
||||||
private Double totalCashIncomes;
|
private BigDecimal totalCashIncomes;
|
||||||
|
|
||||||
@Column(name = "created_at")
|
@Column(name = "created_at")
|
||||||
private Instant createdAt;
|
private Instant createdAt;
|
||||||
|
|
||||||
public Long getId() {
|
public Byte getId() {
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Double getInitialBank() {
|
public BigDecimal getInitialBank() {
|
||||||
return initialBank;
|
return initialBank;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Double getInitialCash() {
|
public BigDecimal getInitialCash() {
|
||||||
return initialCash;
|
return initialCash;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Double getTotalBankExpenses() {
|
public BigDecimal getTotalBankExpenses() {
|
||||||
return totalBankExpenses;
|
return totalBankExpenses;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Double getTotalCashExpenses() {
|
public BigDecimal getTotalCashExpenses() {
|
||||||
return totalCashExpenses;
|
return totalCashExpenses;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Double getTotalBankIncomes() {
|
public BigDecimal getTotalBankIncomes() {
|
||||||
return totalBankIncomes;
|
return totalBankIncomes;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Double getTotalCashIncomes() {
|
public BigDecimal getTotalCashIncomes() {
|
||||||
return totalCashIncomes;
|
return totalCashIncomes;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,11 +9,11 @@ import java.util.UUID;
|
|||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Immutable
|
@Immutable
|
||||||
@Table(name = "v_huertos_member")
|
@Table(name = "v_huertos_members")
|
||||||
public class VHuertosMember {
|
public class VHuertosMembers {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@Column(name = "user_id")
|
@Column(name = "user_id", columnDefinition = "BINARY(16)")
|
||||||
private byte[] userIdBin;
|
private byte[] userIdBin;
|
||||||
|
|
||||||
@Transient
|
@Transient
|
||||||
@@ -4,6 +4,7 @@ import jakarta.persistence.*;
|
|||||||
import net.miarma.backlib.util.UuidUtil;
|
import net.miarma.backlib.util.UuidUtil;
|
||||||
import org.hibernate.annotations.Immutable;
|
import org.hibernate.annotations.Immutable;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
@@ -13,13 +14,13 @@ import java.util.UUID;
|
|||||||
public class VIncomesWithFullNames {
|
public class VIncomesWithFullNames {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@Column(name = "income_id")
|
@Column(name = "income_id", columnDefinition = "BINARY(16)")
|
||||||
private byte[] incomeIdBin;
|
private byte[] incomeIdBin;
|
||||||
|
|
||||||
@Transient
|
@Transient
|
||||||
private UUID incomeId;
|
private UUID incomeId;
|
||||||
|
|
||||||
@Column(name = "user_id")
|
@Column(name = "user_id", columnDefinition = "BINARY(16)")
|
||||||
private byte[] userIdBin;
|
private byte[] userIdBin;
|
||||||
|
|
||||||
@Transient
|
@Transient
|
||||||
@@ -29,7 +30,7 @@ public class VIncomesWithFullNames {
|
|||||||
private String displayName;
|
private String displayName;
|
||||||
|
|
||||||
private String concept;
|
private String concept;
|
||||||
private Double amount;
|
private BigDecimal amount;
|
||||||
private Byte type;
|
private Byte type;
|
||||||
private Byte frequency;
|
private Byte frequency;
|
||||||
|
|
||||||
@@ -63,7 +64,7 @@ public class VIncomesWithFullNames {
|
|||||||
return concept;
|
return concept;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Double getAmount() {
|
public BigDecimal getAmount() {
|
||||||
return amount;
|
return amount;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import java.util.UUID;
|
|||||||
public class VRequestsWithPreUsers {
|
public class VRequestsWithPreUsers {
|
||||||
|
|
||||||
@Id
|
@Id
|
||||||
@Column(name = "request_id")
|
@Column(name = "request_id", columnDefinition = "BINARY(16)")
|
||||||
private byte[] requestIdBin;
|
private byte[] requestIdBin;
|
||||||
|
|
||||||
@Transient
|
@Transient
|
||||||
@@ -25,7 +25,7 @@ public class VRequestsWithPreUsers {
|
|||||||
@Column(name = "request_status")
|
@Column(name = "request_status")
|
||||||
private Byte requestStatus;
|
private Byte requestStatus;
|
||||||
|
|
||||||
@Column(name = "requested_by")
|
@Column(name = "requested_by", columnDefinition = "BINARY(16)")
|
||||||
private byte[] requestedByBin;
|
private byte[] requestedByBin;
|
||||||
|
|
||||||
@Transient
|
@Transient
|
||||||
@@ -34,7 +34,7 @@ public class VRequestsWithPreUsers {
|
|||||||
@Column(name = "requested_by_name")
|
@Column(name = "requested_by_name")
|
||||||
private String requestedByName;
|
private String requestedByName;
|
||||||
|
|
||||||
@Column(name = "target_user_id")
|
@Column(name = "target_user_id", columnDefinition = "BINARY(16)")
|
||||||
private byte[] targetUserIdBin;
|
private byte[] targetUserIdBin;
|
||||||
|
|
||||||
@Transient
|
@Transient
|
||||||
@@ -44,7 +44,7 @@ public class VRequestsWithPreUsers {
|
|||||||
private Instant requestCreatedAt;
|
private Instant requestCreatedAt;
|
||||||
|
|
||||||
// --- PreUser ---
|
// --- PreUser ---
|
||||||
@Column(name = "pre_user_id")
|
@Column(name = "pre_user_id", columnDefinition = "BINARY(16)")
|
||||||
private byte[] preUserIdBin;
|
private byte[] preUserIdBin;
|
||||||
|
|
||||||
@Transient
|
@Transient
|
||||||
|
|||||||
@@ -3,5 +3,4 @@ package net.miarma.backend.huertos.repository;
|
|||||||
import net.miarma.backend.huertos.model.Expense;
|
import net.miarma.backend.huertos.model.Expense;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
public interface ExpenseRepository extends JpaRepository<Expense, byte[]> {
|
public interface ExpenseRepository extends JpaRepository<Expense, byte[]> {}
|
||||||
}
|
|
||||||
|
|||||||
@@ -3,5 +3,8 @@ package net.miarma.backend.huertos.repository;
|
|||||||
import net.miarma.backend.huertos.model.HuertosUserMetadata;
|
import net.miarma.backend.huertos.model.HuertosUserMetadata;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
public interface HuertosUserMetadataRepository extends JpaRepository<HuertosUserMetadata, byte[]> {
|
public interface HuertosUserMetadataRepository extends JpaRepository<HuertosUserMetadata, byte[]> {
|
||||||
|
Optional<HuertosUserMetadata> findByMemberNumber(Integer memberNumber);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
package net.miarma.backend.huertos.repository.view;
|
|
||||||
|
|
||||||
import net.miarma.backend.huertos.model.view.VHuertosMember;
|
|
||||||
import org.springframework.data.repository.Repository;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
public interface VHuertosMemberRepository extends Repository<VHuertosMember, byte[]> {
|
|
||||||
List<VHuertosMember> findAll();
|
|
||||||
Optional<VHuertosMember> findById(byte[] userId);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package net.miarma.backend.huertos.repository.view;
|
||||||
|
|
||||||
|
import net.miarma.backend.huertos.model.view.VHuertosMembers;
|
||||||
|
import org.springframework.data.repository.Repository;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
public interface VHuertosMembersRepository extends Repository<VHuertosMembers, byte[]> {
|
||||||
|
List<VHuertosMembers> findAll();
|
||||||
|
Optional<VHuertosMembers> findById(byte[] userId);
|
||||||
|
}
|
||||||
@@ -4,8 +4,8 @@ import jakarta.servlet.FilterChain;
|
|||||||
import jakarta.servlet.ServletException;
|
import jakarta.servlet.ServletException;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
import net.miarma.backend.huertos.model.view.VHuertosMember;
|
import net.miarma.backend.huertos.model.view.VHuertosMembers;
|
||||||
import net.miarma.backend.huertos.service.view.VHuertosMemberService;
|
import net.miarma.backend.huertos.service.view.VHuertosMembersService;
|
||||||
import net.miarma.backlib.security.JwtService;
|
import net.miarma.backlib.security.JwtService;
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
@@ -19,9 +19,9 @@ import java.util.UUID;
|
|||||||
public class HuertosJwtFilter extends OncePerRequestFilter {
|
public class HuertosJwtFilter extends OncePerRequestFilter {
|
||||||
|
|
||||||
private final JwtService jwtService;
|
private final JwtService jwtService;
|
||||||
private final VHuertosMemberService huertosUserService;
|
private final VHuertosMembersService huertosUserService;
|
||||||
|
|
||||||
public HuertosJwtFilter(JwtService jwtService, VHuertosMemberService huertosUserService) {
|
public HuertosJwtFilter(JwtService jwtService, VHuertosMembersService huertosUserService) {
|
||||||
this.jwtService = jwtService;
|
this.jwtService = jwtService;
|
||||||
this.huertosUserService = huertosUserService;
|
this.huertosUserService = huertosUserService;
|
||||||
}
|
}
|
||||||
@@ -37,14 +37,16 @@ public class HuertosJwtFilter extends OncePerRequestFilter {
|
|||||||
|
|
||||||
if (jwtService.validateToken(token)) {
|
if (jwtService.validateToken(token)) {
|
||||||
UUID userId = jwtService.getUserId(token);
|
UUID userId = jwtService.getUserId(token);
|
||||||
|
Byte serviceId = jwtService.getServiceId(token);
|
||||||
|
|
||||||
VHuertosMember huertosUser = huertosUserService.getById(userId);
|
VHuertosMembers huertosUser = huertosUserService.getById(userId);
|
||||||
|
|
||||||
if (huertosUser != null) {
|
if (huertosUser != null) {
|
||||||
var principal = new HuertosPrincipal(
|
var principal = new HuertosPrincipal(
|
||||||
userId,
|
userId,
|
||||||
huertosUser.getRole(),
|
huertosUser.getRole(),
|
||||||
huertosUser.getType()
|
huertosUser.getType(),
|
||||||
|
serviceId
|
||||||
);
|
);
|
||||||
|
|
||||||
var auth = new UsernamePasswordAuthenticationToken(
|
var auth = new UsernamePasswordAuthenticationToken(
|
||||||
|
|||||||
@@ -14,16 +14,19 @@ public class HuertosPrincipal implements UserDetails {
|
|||||||
private final UUID userId;
|
private final UUID userId;
|
||||||
private final Byte role;
|
private final Byte role;
|
||||||
private final Byte type;
|
private final Byte type;
|
||||||
|
private final Byte serviceId;
|
||||||
|
|
||||||
public HuertosPrincipal(UUID userId, Byte role, Byte type) {
|
public HuertosPrincipal(UUID userId, Byte role, Byte type, Byte serviceId) {
|
||||||
this.userId = userId;
|
this.userId = userId;
|
||||||
this.role = role;
|
this.role = role;
|
||||||
this.type = type;
|
this.type = type;
|
||||||
|
this.serviceId = serviceId;
|
||||||
}
|
}
|
||||||
|
|
||||||
public UUID getUserId() { return userId; }
|
public UUID getUserId() { return userId; }
|
||||||
public Byte getHuertosRole() { return role; }
|
public Byte getHuertosRole() { return role; }
|
||||||
public Byte getHuertosType() { return type; }
|
public Byte getHuertosType() { return type; }
|
||||||
|
public Byte getServiceId() { return serviceId; }
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package net.miarma.backend.huertos.security;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clase de utilidad para censurar nombres.
|
||||||
|
* Censura los nombres dejando las primeras 3 letras visibles y el resto con asteriscos.
|
||||||
|
* Si el nombre es muy largo, lo acorta a 16 caracteres y añade "..." al final.
|
||||||
|
* @author José Manuel Amador Gallardo
|
||||||
|
*/
|
||||||
|
public class NameCensorer {
|
||||||
|
|
||||||
|
public static String censor(String name) {
|
||||||
|
if (name == null || name.isBlank()) return "";
|
||||||
|
|
||||||
|
String[] words = name.trim().split("\\s+");
|
||||||
|
|
||||||
|
for (int i = 0; i < words.length; i++) {
|
||||||
|
String word = words[i];
|
||||||
|
int len = word.length();
|
||||||
|
|
||||||
|
if (len > 3) {
|
||||||
|
words[i] = word.substring(0, 3) + "*".repeat(len - 3);
|
||||||
|
} else if (len > 0) {
|
||||||
|
words[i] = word.charAt(0) + "*".repeat(len - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String censored = String.join(" ", words);
|
||||||
|
|
||||||
|
if (censored.length() > 16) {
|
||||||
|
censored = censored.substring(0, 16) + "...";
|
||||||
|
}
|
||||||
|
|
||||||
|
return censored;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package net.miarma.backend.huertos.service;
|
package net.miarma.backend.huertos.service;
|
||||||
|
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
|
import net.miarma.backend.huertos.dto.AnnouncementDto;
|
||||||
import net.miarma.backend.huertos.model.Announcement;
|
import net.miarma.backend.huertos.model.Announcement;
|
||||||
import net.miarma.backend.huertos.repository.AnnouncementRepository;
|
import net.miarma.backend.huertos.repository.AnnouncementRepository;
|
||||||
import net.miarma.backlib.util.UuidUtil;
|
import net.miarma.backlib.util.UuidUtil;
|
||||||
@@ -38,7 +39,7 @@ public class AnnouncementService {
|
|||||||
return announcementRepository.save(announcement);
|
return announcementRepository.save(announcement);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Announcement update(UUID announceId, Announcement dto) {
|
public Announcement update(UUID announceId, AnnouncementDto.Request dto) {
|
||||||
byte[] idBytes = UuidUtil.uuidToBin(announceId);
|
byte[] idBytes = UuidUtil.uuidToBin(announceId);
|
||||||
Announcement announcement = announcementRepository.findById(idBytes)
|
Announcement announcement = announcementRepository.findById(idBytes)
|
||||||
.orElseThrow(() -> new RuntimeException("Announcement not found"));
|
.orElseThrow(() -> new RuntimeException("Announcement not found"));
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package net.miarma.backend.huertos.service;
|
package net.miarma.backend.huertos.service;
|
||||||
|
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
|
import net.miarma.backend.huertos.dto.ExpenseDto;
|
||||||
import net.miarma.backend.huertos.model.Expense;
|
import net.miarma.backend.huertos.model.Expense;
|
||||||
import net.miarma.backend.huertos.repository.ExpenseRepository;
|
import net.miarma.backend.huertos.repository.ExpenseRepository;
|
||||||
import net.miarma.backlib.util.UuidUtil;
|
import net.miarma.backlib.util.UuidUtil;
|
||||||
@@ -50,7 +51,7 @@ public class ExpenseService {
|
|||||||
return expenseRepository.save(expense);
|
return expenseRepository.save(expense);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Expense update(UUID expenseId, Expense dto) {
|
public Expense update(UUID expenseId, ExpenseDto.Request dto) {
|
||||||
byte[] idBytes = UuidUtil.uuidToBin(expenseId);
|
byte[] idBytes = UuidUtil.uuidToBin(expenseId);
|
||||||
Expense expense = expenseRepository.findById(idBytes)
|
Expense expense = expenseRepository.findById(idBytes)
|
||||||
.orElseThrow(() -> new RuntimeException("Expense not found"));
|
.orElseThrow(() -> new RuntimeException("Expense not found"));
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package net.miarma.backend.huertos.service;
|
|||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
@@ -10,6 +11,8 @@ import jakarta.transaction.Transactional;
|
|||||||
import net.miarma.backend.huertos.model.HuertosUserMetadata;
|
import net.miarma.backend.huertos.model.HuertosUserMetadata;
|
||||||
import net.miarma.backend.huertos.repository.HuertosUserMetadataRepository;
|
import net.miarma.backend.huertos.repository.HuertosUserMetadataRepository;
|
||||||
import net.miarma.backlib.util.UuidUtil;
|
import net.miarma.backlib.util.UuidUtil;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Transactional
|
@Transactional
|
||||||
@@ -31,6 +34,16 @@ public class HuertosUserMetadataService {
|
|||||||
.orElseThrow(() -> new RuntimeException("User metadata not found"));
|
.orElseThrow(() -> new RuntimeException("User metadata not found"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public HuertosUserMetadata getByMemberNumber(Integer memberNumber) {
|
||||||
|
return repository.findByMemberNumber(memberNumber)
|
||||||
|
.orElseThrow(() -> new RuntimeException("User metadata not found"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean existsById(UUID userId) {
|
||||||
|
byte[] idBytes = UuidUtil.uuidToBin(userId);
|
||||||
|
return repository.existsById(idBytes);
|
||||||
|
}
|
||||||
|
|
||||||
public HuertosUserMetadata create(HuertosUserMetadata meta) {
|
public HuertosUserMetadata create(HuertosUserMetadata meta) {
|
||||||
if (meta.getUserId() == null) {
|
if (meta.getUserId() == null) {
|
||||||
throw new RuntimeException("userId is required");
|
throw new RuntimeException("userId is required");
|
||||||
@@ -79,4 +92,16 @@ public class HuertosUserMetadataService {
|
|||||||
}
|
}
|
||||||
repository.deleteById(idBytes);
|
repository.deleteById(idBytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Integer getLatestMemberNumber() {
|
||||||
|
return repository.findAll()
|
||||||
|
.stream()
|
||||||
|
.map(HuertosUserMetadata::getMemberNumber)
|
||||||
|
.max(Integer::compareTo)
|
||||||
|
.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean existsByMemberNumber(Integer memberNumber) {
|
||||||
|
return getByMemberNumber(memberNumber).getUserId() != null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,9 @@ import java.time.Instant;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
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 org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
@@ -15,25 +18,27 @@ import net.miarma.backlib.util.UuidUtil;
|
|||||||
@Transactional
|
@Transactional
|
||||||
public class IncomeService {
|
public class IncomeService {
|
||||||
|
|
||||||
private final IncomeRepository repository;
|
private final IncomeRepository incomeRepository;
|
||||||
|
private final HuertosUserMetadataService metadataService;
|
||||||
|
|
||||||
public IncomeService(IncomeRepository repository) {
|
public IncomeService(IncomeRepository incomeRepository,
|
||||||
this.repository = repository;
|
HuertosUserMetadataService metadataService) {
|
||||||
|
this.incomeRepository = incomeRepository;
|
||||||
|
this.metadataService = metadataService;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Income> getAll() {
|
public List<Income> getAll() {
|
||||||
return repository.findAll();
|
return incomeRepository.findAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Income getById(UUID incomeId) {
|
public Income getById(UUID incomeId) {
|
||||||
byte[] idBytes = UuidUtil.uuidToBin(incomeId);
|
byte[] idBytes = UuidUtil.uuidToBin(incomeId);
|
||||||
return repository.findById(idBytes)
|
return incomeRepository.findById(idBytes)
|
||||||
.orElseThrow(() -> new RuntimeException("Income not found"));
|
.orElseThrow(() -> new RuntimeException("Income not found"));
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Income> getByUserId(UUID userId) {
|
public List<Income> getByUserId(UUID userId) {
|
||||||
byte[] idBytes = UuidUtil.uuidToBin(userId);
|
return incomeRepository.findAll().stream()
|
||||||
return repository.findAll().stream()
|
|
||||||
.filter(i -> i.getUserId().equals(userId))
|
.filter(i -> i.getUserId().equals(userId))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
@@ -52,13 +57,13 @@ public class IncomeService {
|
|||||||
income.setIncomeId(UUID.randomUUID());
|
income.setIncomeId(UUID.randomUUID());
|
||||||
income.setCreatedAt(Instant.now());
|
income.setCreatedAt(Instant.now());
|
||||||
|
|
||||||
return repository.save(income);
|
return incomeRepository.save(income);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Income update(UUID incomeId, Income dto) {
|
public Income update(UUID incomeId, IncomeDto.Request dto) {
|
||||||
byte[] idBytes = UuidUtil.uuidToBin(incomeId);
|
byte[] idBytes = UuidUtil.uuidToBin(incomeId);
|
||||||
|
|
||||||
Income income = repository.findById(idBytes)
|
Income income = incomeRepository.findById(idBytes)
|
||||||
.orElseThrow(() -> new RuntimeException("Income not found"));
|
.orElseThrow(() -> new RuntimeException("Income not found"));
|
||||||
|
|
||||||
if (dto.getConcept() != null) income.setConcept(dto.getConcept());
|
if (dto.getConcept() != null) income.setConcept(dto.getConcept());
|
||||||
@@ -71,16 +76,31 @@ public class IncomeService {
|
|||||||
if (dto.getType() != null) income.setType(dto.getType());
|
if (dto.getType() != null) income.setType(dto.getType());
|
||||||
if (dto.getFrequency() != null) income.setFrequency(dto.getFrequency());
|
if (dto.getFrequency() != null) income.setFrequency(dto.getFrequency());
|
||||||
|
|
||||||
return repository.save(income);
|
return incomeRepository.save(income);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void delete(UUID incomeId) {
|
public void delete(UUID incomeId) {
|
||||||
byte[] idBytes = UuidUtil.uuidToBin(incomeId);
|
byte[] idBytes = UuidUtil.uuidToBin(incomeId);
|
||||||
|
|
||||||
if (!repository.existsById(idBytes)) {
|
if (!incomeRepository.existsById(idBytes)) {
|
||||||
throw new RuntimeException("Income not found");
|
throw new RuntimeException("Income not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
repository.deleteById(idBytes);
|
incomeRepository.deleteById(idBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean existsByMemberNumber(Integer memberNumber) {
|
||||||
|
try {
|
||||||
|
UUID userId = metadataService.getByMemberNumber(memberNumber).getUserId();
|
||||||
|
return !getByUserId(userId).isEmpty();
|
||||||
|
} catch (RuntimeException e) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean hasPaid(Integer memberNumber) {
|
||||||
|
UUID userId = metadataService.getByMemberNumber(memberNumber).getUserId();
|
||||||
|
List<Income> incomes = getByUserId(userId);
|
||||||
|
return !incomes.isEmpty() && incomes.stream().allMatch(Income::isPaid);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
package net.miarma.backend.huertos.service;
|
||||||
|
|
||||||
|
import net.miarma.backend.huertos.client.HuertosWebClient;
|
||||||
|
import net.miarma.backend.huertos.dto.MemberDto;
|
||||||
|
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 org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.UUID;
|
||||||
|
import java.util.function.Predicate;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class MemberService {
|
||||||
|
private final HuertosWebClient huertosWebClient;
|
||||||
|
private final IncomeService incomeService;
|
||||||
|
private final RequestService requestService;
|
||||||
|
private final HuertosUserMetadataService metadataService;
|
||||||
|
|
||||||
|
public MemberService(HuertosWebClient huertosWebClient,
|
||||||
|
IncomeService incomeService,
|
||||||
|
RequestService requestService,
|
||||||
|
HuertosUserMetadataService metadataService) {
|
||||||
|
this.huertosWebClient = huertosWebClient;
|
||||||
|
this.incomeService = incomeService;
|
||||||
|
this.requestService = requestService;
|
||||||
|
this.metadataService = metadataService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MemberDto getById(UUID userId, Byte serviceId) {
|
||||||
|
var uwc = huertosWebClient.getUserWithCredential(userId, serviceId);
|
||||||
|
var meta = metadataService.getById(userId);
|
||||||
|
|
||||||
|
return new MemberDto(uwc.user(), uwc.account(),
|
||||||
|
HuertosUserMetadataMapper.toDto(meta));
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<MemberDto> getAll(Byte serviceId) {
|
||||||
|
List<UserWithCredentialDto> all = huertosWebClient.getAllUsersWithCredentials(serviceId);
|
||||||
|
|
||||||
|
return all.stream()
|
||||||
|
.filter(uwc -> metadataService.existsById(uwc.user().getUserId()))
|
||||||
|
.map(uwc -> {
|
||||||
|
var meta = metadataService.getById(uwc.user().getUserId());
|
||||||
|
return new MemberDto(
|
||||||
|
uwc.user(),
|
||||||
|
uwc.account(),
|
||||||
|
HuertosUserMetadataMapper.toDto(meta)
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getLatestMemberNumber() {
|
||||||
|
return metadataService.getLatestMemberNumber();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<MemberDto> getWaitlist() {
|
||||||
|
List<UserWithCredentialDto> all = huertosWebClient.getAllUsersWithCredentials((byte)1);
|
||||||
|
|
||||||
|
return all.stream()
|
||||||
|
.filter(uwc -> metadataService.existsById(uwc.user().getUserId()))
|
||||||
|
.filter(uwc -> uwc.account().getStatus() != 0)
|
||||||
|
.map(uwc -> {
|
||||||
|
var meta = metadataService.getById(uwc.user().getUserId());
|
||||||
|
return new MemberDto(uwc.user(), uwc.account(),
|
||||||
|
HuertosUserMetadataMapper.toDto(meta));
|
||||||
|
})
|
||||||
|
.filter(dto -> dto.metadata().getType().equals((byte) 0))
|
||||||
|
.sorted(Comparator.comparing(dto -> dto.metadata().getCreatedAt()))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<WaitlistCensoredDto> getWaitlistLimited() {
|
||||||
|
return getWaitlist().stream()
|
||||||
|
.map(dto -> {
|
||||||
|
WaitlistCensoredDto censored = new WaitlistCensoredDto();
|
||||||
|
censored.setName(NameCensorer.censor(dto.user().getDisplayName()));
|
||||||
|
return censored;
|
||||||
|
})
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public MemberDto getByMemberNumber(Integer memberNumber) {
|
||||||
|
return getAll((byte)1).stream()
|
||||||
|
.filter(dto -> dto.metadata().getMemberNumber().equals(memberNumber))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() -> new RuntimeException("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"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public MemberDto getByDni(String dni) {
|
||||||
|
return getAll((byte)1).stream()
|
||||||
|
.filter(dto -> dni.equals(dto.metadata().getDni()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() -> new RuntimeException("Member not found"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean hasIncomes(Integer memberNumber) {
|
||||||
|
return incomeService.existsByMemberNumber(memberNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean hasPaid(Integer memberNumber) {
|
||||||
|
return incomeService.hasPaid(memberNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean hasCollaborator(Integer memberNumber) {
|
||||||
|
List<MemberDto> all = getAll((byte)1);
|
||||||
|
|
||||||
|
var member = all.stream()
|
||||||
|
.filter(dto -> dto.metadata().getMemberNumber().equals(memberNumber))
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
if (member == null) return false;
|
||||||
|
|
||||||
|
Integer plotNumber = member.metadata().getPlotNumber();
|
||||||
|
if (plotNumber == null) return false;
|
||||||
|
|
||||||
|
List<MemberDto> plotMembers = all.stream()
|
||||||
|
.filter(dto -> plotNumber.equals(dto.metadata().getPlotNumber()))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
return plotMembers.stream()
|
||||||
|
.anyMatch(dto -> dto.metadata().getType().equals((byte)2));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean hasGreenhouse(Integer memberNumber) {
|
||||||
|
return metadataService.existsByMemberNumber(memberNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean hasCollaboratorRequest(Integer memberNumber) {
|
||||||
|
return requestService.existsCollaboratorRequest(memberNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean hasGreenhouseRequest(Integer memberNumber) {
|
||||||
|
return requestService.existsGreenhouseRequest(memberNumber);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import java.time.Instant;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import net.miarma.backend.huertos.dto.PreUserDto;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
@@ -65,7 +66,7 @@ public class PreUserService {
|
|||||||
return repository.save(preUser);
|
return repository.save(preUser);
|
||||||
}
|
}
|
||||||
|
|
||||||
public PreUser update(UUID preUserId, PreUser dto) {
|
public PreUser update(UUID preUserId, PreUserDto.Request dto) {
|
||||||
byte[] idBytes = UuidUtil.uuidToBin(preUserId);
|
byte[] idBytes = UuidUtil.uuidToBin(preUserId);
|
||||||
|
|
||||||
PreUser preUser = repository.findById(idBytes)
|
PreUser preUser = repository.findById(idBytes)
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import java.time.Instant;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import net.miarma.backend.huertos.dto.RequestDto;
|
||||||
|
import net.miarma.backend.huertos.model.HuertosUserMetadata;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
@@ -15,30 +17,39 @@ import net.miarma.backlib.util.UuidUtil;
|
|||||||
@Transactional
|
@Transactional
|
||||||
public class RequestService {
|
public class RequestService {
|
||||||
|
|
||||||
private final RequestRepository repository;
|
private final RequestRepository requestRepository;
|
||||||
|
private final HuertosUserMetadataService metadataService;
|
||||||
|
|
||||||
public RequestService(RequestRepository repository) {
|
public RequestService(RequestRepository requestRepository,
|
||||||
this.repository = repository;
|
HuertosUserMetadataService metadataSertice) {
|
||||||
|
this.requestRepository = requestRepository;
|
||||||
|
this.metadataService = metadataSertice;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Request> getAll() {
|
public List<Request> getAll() {
|
||||||
return repository.findAll();
|
return requestRepository.findAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Request getById(UUID requestId) {
|
public Request getById(UUID requestId) {
|
||||||
byte[] idBytes = UuidUtil.uuidToBin(requestId);
|
byte[] idBytes = UuidUtil.uuidToBin(requestId);
|
||||||
return repository.findById(idBytes)
|
return requestRepository.findById(idBytes)
|
||||||
.orElseThrow(() -> new RuntimeException("Request not found"));
|
.orElseThrow(() -> new RuntimeException("Request not found"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<Request> getByUserId(UUID userId) {
|
||||||
|
return requestRepository.findAll().stream()
|
||||||
|
.filter(r -> r.getRequestedBy().equals(userId))
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
public List<Request> getByRequestedBy(UUID requestedBy) {
|
public List<Request> getByRequestedBy(UUID requestedBy) {
|
||||||
return repository.findAll().stream()
|
return requestRepository.findAll().stream()
|
||||||
.filter(r -> r.getRequestedBy() != null && r.getRequestedBy().equals(requestedBy))
|
.filter(r -> r.getRequestedBy() != null && r.getRequestedBy().equals(requestedBy))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Request> getByTargetUserId(UUID targetUserId) {
|
public List<Request> getByTargetUserId(UUID targetUserId) {
|
||||||
return repository.findAll().stream()
|
return requestRepository.findAll().stream()
|
||||||
.filter(r -> r.getTargetUserId() != null && r.getTargetUserId().equals(targetUserId))
|
.filter(r -> r.getTargetUserId() != null && r.getTargetUserId().equals(targetUserId))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
@@ -57,13 +68,13 @@ public class RequestService {
|
|||||||
request.setRequestId(UUID.randomUUID());
|
request.setRequestId(UUID.randomUUID());
|
||||||
request.setCreatedAt(Instant.now());
|
request.setCreatedAt(Instant.now());
|
||||||
|
|
||||||
return repository.save(request);
|
return requestRepository.save(request);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Request update(UUID requestId, Request dto) {
|
public Request update(UUID requestId, RequestDto.Request dto) {
|
||||||
byte[] idBytes = UuidUtil.uuidToBin(requestId);
|
byte[] idBytes = UuidUtil.uuidToBin(requestId);
|
||||||
|
|
||||||
Request request = repository.findById(idBytes)
|
Request request = requestRepository.findById(idBytes)
|
||||||
.orElseThrow(() -> new RuntimeException("Request not found"));
|
.orElseThrow(() -> new RuntimeException("Request not found"));
|
||||||
|
|
||||||
if (dto.getType() != null) request.setType(dto.getType());
|
if (dto.getType() != null) request.setType(dto.getType());
|
||||||
@@ -71,16 +82,46 @@ public class RequestService {
|
|||||||
if (dto.getRequestedBy() != null) request.setRequestedBy(dto.getRequestedBy());
|
if (dto.getRequestedBy() != null) request.setRequestedBy(dto.getRequestedBy());
|
||||||
if (dto.getTargetUserId() != null) request.setTargetUserId(dto.getTargetUserId());
|
if (dto.getTargetUserId() != null) request.setTargetUserId(dto.getTargetUserId());
|
||||||
|
|
||||||
return repository.save(request);
|
return requestRepository.save(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Request acceptRequest(UUID requestId) {
|
||||||
|
byte[] idBytes = UuidUtil.uuidToBin(requestId);
|
||||||
|
Request request = requestRepository.findById(idBytes)
|
||||||
|
.orElseThrow(() -> new RuntimeException("Request not found"));
|
||||||
|
request.setStatus((byte)1);
|
||||||
|
return requestRepository.save(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Request rejectRequest(UUID requestId) {
|
||||||
|
byte[] idBytes = UuidUtil.uuidToBin(requestId);
|
||||||
|
Request request = requestRepository.findById(idBytes)
|
||||||
|
.orElseThrow(() -> new RuntimeException("Request not found"));
|
||||||
|
request.setStatus((byte)2);
|
||||||
|
return requestRepository.save(request);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void delete(UUID requestId) {
|
public void delete(UUID requestId) {
|
||||||
byte[] idBytes = UuidUtil.uuidToBin(requestId);
|
byte[] idBytes = UuidUtil.uuidToBin(requestId);
|
||||||
|
|
||||||
if (!repository.existsById(idBytes)) {
|
if (!requestRepository.existsById(idBytes)) {
|
||||||
throw new RuntimeException("Request not found");
|
throw new RuntimeException("Request not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
repository.deleteById(idBytes);
|
requestRepository.deleteById(idBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean existsCollaboratorRequest(Integer memberNumber) {
|
||||||
|
UUID userId = metadataService.getByMemberNumber(memberNumber).getUserId();
|
||||||
|
return getByUserId(userId).stream()
|
||||||
|
.anyMatch(r -> r.getType().equals((byte)2) ||
|
||||||
|
r.getType().equals((byte)3));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean existsGreenhouseRequest(Integer memberNumber) {
|
||||||
|
UUID userId = metadataService.getByMemberNumber(memberNumber).getUserId();
|
||||||
|
return getByUserId(userId).stream()
|
||||||
|
.anyMatch(r -> r.getType().equals((byte)4) ||
|
||||||
|
r.getType().equals((byte)5));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,25 +6,25 @@ import java.util.UUID;
|
|||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
import net.miarma.backend.huertos.model.view.VHuertosMember;
|
import net.miarma.backend.huertos.model.view.VHuertosMembers;
|
||||||
import net.miarma.backend.huertos.repository.view.VHuertosMemberRepository;
|
import net.miarma.backend.huertos.repository.view.VHuertosMembersRepository;
|
||||||
import net.miarma.backlib.util.UuidUtil;
|
import net.miarma.backlib.util.UuidUtil;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Transactional
|
@Transactional
|
||||||
public class VHuertosMemberService {
|
public class VHuertosMembersService {
|
||||||
|
|
||||||
private final VHuertosMemberRepository repository;
|
private final VHuertosMembersRepository repository;
|
||||||
|
|
||||||
public VHuertosMemberService(VHuertosMemberRepository repository) {
|
public VHuertosMembersService(VHuertosMembersRepository repository) {
|
||||||
this.repository = repository;
|
this.repository = repository;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<VHuertosMember> getAll() {
|
public List<VHuertosMembers> getAll() {
|
||||||
return repository.findAll();
|
return repository.findAll();
|
||||||
}
|
}
|
||||||
|
|
||||||
public VHuertosMember getById(UUID userId) {
|
public VHuertosMembers getById(UUID userId) {
|
||||||
byte[] idBytes = UuidUtil.uuidToBin(userId);
|
byte[] idBytes = UuidUtil.uuidToBin(userId);
|
||||||
return repository.findById(idBytes)
|
return repository.findById(idBytes)
|
||||||
.orElseThrow(() -> new RuntimeException("Member not found"));
|
.orElseThrow(() -> new RuntimeException("Member not found"));
|
||||||
@@ -16,7 +16,7 @@ spring:
|
|||||||
jpa:
|
jpa:
|
||||||
open-in-view: false
|
open-in-view: false
|
||||||
hibernate:
|
hibernate:
|
||||||
ddl-auto: update
|
ddl-auto: validate
|
||||||
properties:
|
properties:
|
||||||
hibernate:
|
hibernate:
|
||||||
format_sql: true
|
format_sql: true
|
||||||
@@ -35,6 +35,32 @@ logging:
|
|||||||
org.hibernate.orm.jdbc.bind: TRACE
|
org.hibernate.orm.jdbc.bind: TRACE
|
||||||
org.springframework.security: INFO
|
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:
|
management:
|
||||||
endpoints:
|
endpoints:
|
||||||
web:
|
web:
|
||||||
|
|||||||
Reference in New Issue
Block a user