@@ -0,0 +1,22 @@
|
||||
package com.aellis.cases;
|
||||
|
||||
import org.springframework.boot.*;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
|
||||
@SpringBootApplication
|
||||
@ConfigurationPropertiesScan
|
||||
public class CasesApplication {
|
||||
public static void main(String[] args) { SpringApplication.run(CasesApplication.class,args); }
|
||||
@Bean ApplicationRunner verifyDatabase(JdbcClient jdbc) {
|
||||
return args -> {
|
||||
jdbc.sql("SELECT id,name,description,created,updated,id_created,id_client,id_status FROM cases WHERE FALSE").query().listOfRows();
|
||||
jdbc.sql("SELECT id_user,id_case FROM user_case WHERE FALSE").query().listOfRows();
|
||||
jdbc.sql("SELECT id,identdocument,businessname,id_documenttype FROM client WHERE FALSE").query().listOfRows();
|
||||
jdbc.sql("SELECT id,name,lastname,acronym,id_status FROM users WHERE FALSE").query().listOfRows();
|
||||
jdbc.sql("SELECT id FROM status WHERE FALSE").query().listOfRows();
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.aellis.cases.api;
|
||||
|
||||
public class ApiException extends RuntimeException {
|
||||
private final int status;
|
||||
public ApiException(int status, String message) { super(message); this.status = status; }
|
||||
public int status() { return status; }
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.aellis.cases.api;
|
||||
|
||||
import com.aellis.cases.api.CaseDtos.ApiResponse;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.*;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class ApiExceptionHandler {
|
||||
@ExceptionHandler(ApiException.class) ResponseEntity<?> application(ApiException error) {
|
||||
return ResponseEntity.status(error.status()).body(ApiResponse.fail(error.getMessage()));
|
||||
}
|
||||
@ExceptionHandler(DuplicateKeyException.class) ResponseEntity<?> duplicate() { return ResponseEntity.status(409).body(ApiResponse.fail("Conflict.")); }
|
||||
@ExceptionHandler(DataIntegrityViolationException.class) ResponseEntity<?> constraint() {
|
||||
return ResponseEntity.status(409).body(ApiResponse.fail("La operación entra en conflicto con datos relacionados."));
|
||||
}
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class) ResponseEntity<?> invalid(HttpMessageNotReadableException error) {
|
||||
for (Throwable cause = error; cause != null; cause = cause.getCause()) {
|
||||
if (cause instanceof com.aellis.cases.config.RequestFilter.BodyTooLargeException) return ResponseEntity.status(413).body(ApiResponse.fail("Request body too large."));
|
||||
}
|
||||
return ResponseEntity.badRequest().body(ApiResponse.fail("Invalid request."));
|
||||
}
|
||||
@ExceptionHandler(Exception.class) ResponseEntity<?> unexpected(Exception error) {
|
||||
if (error instanceof org.springframework.web.ErrorResponse response) return ResponseEntity.status(response.getStatusCode())
|
||||
.headers(response.getHeaders()).body(ApiResponse.fail("Invalid request."));
|
||||
LoggerFactory.getLogger(getClass()).error("case_service_error type={}", error.getClass().getSimpleName());
|
||||
return ResponseEntity.internalServerError().body(ApiResponse.fail("Internal server error."));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.aellis.cases.api;
|
||||
|
||||
import com.aellis.cases.api.CaseDtos.*;
|
||||
import com.aellis.cases.repository.CaseRepository;
|
||||
import com.aellis.cases.service.CaseService;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.util.*;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/cases")
|
||||
public class CaseController {
|
||||
private final CaseService cases;
|
||||
public CaseController(CaseService cases) { this.cases=cases; }
|
||||
@PostMapping("/create") public ApiResponse<?> create(@AuthenticationPrincipal Jwt jwt,@RequestBody Payload body,HttpServletResponse response) {
|
||||
int id=cases.create(who(jwt),CaseDtos.parse(body,true),requestId(response));
|
||||
return ApiResponse.ok(Map.of("message","Caso registrado exitosamente.","id_case",id));
|
||||
}
|
||||
@PutMapping("/update/{id}") public ApiResponse<?> update(@AuthenticationPrincipal Jwt jwt,@PathVariable String id,@RequestBody Payload body,HttpServletResponse response) {
|
||||
cases.update(who(jwt),CaseDtos.positiveId(id),CaseDtos.parse(body,false),requestId(response)); return message("Caso editado exitosamente.");
|
||||
}
|
||||
@RequestMapping(value="/disable/{id}",method={RequestMethod.GET,RequestMethod.PATCH})
|
||||
public ApiResponse<?> disable(@AuthenticationPrincipal Jwt jwt,@PathVariable String id,HttpServletResponse response) {
|
||||
cases.disable(who(jwt),CaseDtos.positiveId(id),requestId(response)); return message("Caso eliminado exitosamente.");
|
||||
}
|
||||
@GetMapping("/all") public ApiResponse<?> all(@AuthenticationPrincipal Jwt jwt) { return ApiResponse.ok(Map.of("cases",cases.all(who(jwt),true))); }
|
||||
@GetMapping("/all/notfilter") public ApiResponse<?> allNotFilter(@AuthenticationPrincipal Jwt jwt) { return ApiResponse.ok(Map.of("cases",cases.all(who(jwt),false))); }
|
||||
@GetMapping("/get/{id}") public ApiResponse<?> find(@AuthenticationPrincipal Jwt jwt,@PathVariable String id) { return ApiResponse.ok(CaseRepository.map("case",cases.find(who(jwt),CaseDtos.positiveId(id)))); }
|
||||
@GetMapping("/assing/{id}") public ApiResponse<?> assigned(@AuthenticationPrincipal Jwt jwt,@PathVariable String id) { return ApiResponse.ok(Map.of("cases",cases.assigned(who(jwt),CaseDtos.positiveId(id)))); }
|
||||
@PostMapping("/assing") public ApiResponse<?> assign(@AuthenticationPrincipal Jwt jwt,@RequestBody List<Payload> body,HttpServletResponse response) {
|
||||
cases.assign(who(jwt),CaseDtos.assignments(body),requestId(response)); return message("Casos asignados exitosamente.");
|
||||
}
|
||||
@PostMapping("/unassing") public ApiResponse<?> unassign(@AuthenticationPrincipal Jwt jwt,@RequestBody Payload body,HttpServletResponse response) {
|
||||
cases.unassign(who(jwt),CaseDtos.assignment(body),requestId(response)); return message("Caso desasignado exitosamente.");
|
||||
}
|
||||
@GetMapping("/client/assing") public ApiResponse<?> clients(@AuthenticationPrincipal Jwt jwt) { return ApiResponse.ok(Map.of("clients",cases.clients(who(jwt)))); }
|
||||
@GetMapping("/client/case/assing/{id}") public ApiResponse<?> assignedByClient(@AuthenticationPrincipal Jwt jwt,@PathVariable String id) { return ApiResponse.ok(Map.of("cases",cases.assignedByClient(who(jwt),CaseDtos.positiveId(id)))); }
|
||||
@GetMapping("/client/{id}") public ApiResponse<?> byClient(@AuthenticationPrincipal Jwt jwt,@PathVariable String id) { return ApiResponse.ok(Map.of("cases",cases.byClient(who(jwt),CaseDtos.positiveId(id)))); }
|
||||
@GetMapping("/case/assing/{id}") public ApiResponse<?> users(@AuthenticationPrincipal Jwt jwt,@PathVariable String id) { return ApiResponse.ok(Map.of("users",cases.users(who(jwt),CaseDtos.positiveId(id),true))); }
|
||||
@GetMapping("/case/unassing/{id}") public ApiResponse<?> otherUsers(@AuthenticationPrincipal Jwt jwt,@PathVariable String id) { return ApiResponse.ok(Map.of("users",cases.users(who(jwt),CaseDtos.positiveId(id),false))); }
|
||||
private static Requester who(Jwt jwt) { return new Requester(Integer.parseInt(jwt.getClaimAsString("id")),jwt.getClaimAsString("rol")); }
|
||||
private static String requestId(HttpServletResponse response) { return response.getHeader("X-Request-Id"); }
|
||||
private static ApiResponse<Message> message(String text) { return ApiResponse.ok(new Message(text)); }
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.aellis.cases.api;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public final class CaseDtos {
|
||||
private CaseDtos() {}
|
||||
public record ApiResponse<T>(T data,String status) {
|
||||
public static <T> ApiResponse<T> ok(T data) { return new ApiResponse<>(data,"success"); }
|
||||
public static ApiResponse<Message> fail(String message) { return new ApiResponse<>(new Message(message),"error"); }
|
||||
}
|
||||
public record Message(String message) {}
|
||||
public record Requester(int id,String role) { public boolean admin() { return "admin".equals(role); } }
|
||||
public record Input(Map<String,Object> fields) {}
|
||||
public record Assignment(int userId,int caseId) {}
|
||||
public static class Payload extends LinkedHashMap<String,Object> {
|
||||
@Override public String toString() { return "[case request body redacted]"; }
|
||||
}
|
||||
public static Input parse(Map<String,Object> body,boolean creating) {
|
||||
if (body==null || body.isEmpty() || !Set.of("name","description","id_client","id_status").containsAll(body.keySet())
|
||||
|| (creating && !body.keySet().containsAll(Set.of("name","id_client")))) throw invalid();
|
||||
var fields = new LinkedHashMap<String,Object>();
|
||||
for (var entry:body.entrySet()) {
|
||||
String key=entry.getKey(); Object raw=entry.getValue();
|
||||
if (key.startsWith("id_")) fields.put(key,positiveId(raw));
|
||||
else if (key.equals("description") && raw==null) fields.put(key,null);
|
||||
else {
|
||||
if (!(raw instanceof String value) || value.length()>255 || (key.equals("name") && value.isBlank())) throw invalid();
|
||||
fields.put(key,value);
|
||||
}
|
||||
}
|
||||
return new Input(Collections.unmodifiableMap(fields));
|
||||
}
|
||||
public static Assignment assignment(Map<String,Object> body) {
|
||||
if (body==null || !body.keySet().equals(Set.of("id_user","id_case"))) throw invalid();
|
||||
return new Assignment(positiveId(body.get("id_user")),positiveId(body.get("id_case")));
|
||||
}
|
||||
public static List<Assignment> assignments(List<Payload> body) {
|
||||
if (body==null || body.isEmpty() || body.size()>100) throw invalid();
|
||||
return body.stream().map(CaseDtos::assignment).distinct().toList();
|
||||
}
|
||||
public static int positiveId(Object raw) {
|
||||
try {
|
||||
double n=raw instanceof Number number?number.doubleValue():raw instanceof String s?Double.parseDouble(s.strip()):Double.NaN;
|
||||
if (!Double.isFinite(n) || n<=0 || n>Integer.MAX_VALUE || n!=Math.rint(n)) throw invalid();
|
||||
return (int)n;
|
||||
} catch (NumberFormatException exception) { throw invalid(); }
|
||||
}
|
||||
public static ApiException invalid() { return new ApiException(400,"Invalid request."); }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.aellis.cases.api;
|
||||
|
||||
import java.util.Map;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
public class HealthController {
|
||||
@GetMapping("/health") public Map<String, Boolean> health() { return Map.of("ok", true); }
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.aellis.cases.audit;
|
||||
|
||||
import com.aellis.cases.api.ApiException;
|
||||
import jakarta.servlet.http.*;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.config.annotation.*;
|
||||
|
||||
@Configuration
|
||||
public class AuditReasonValidation implements WebMvcConfigurer {
|
||||
@Override public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry.addInterceptor(new HandlerInterceptor() {
|
||||
@Override public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) {
|
||||
var headers=request.getHeaders("X-Audit-Reason");
|
||||
if(!headers.hasMoreElements()) return true;
|
||||
String reason=headers.nextElement();
|
||||
if(headers.hasMoreElements() || reason.length()>500 || reason.codePoints().anyMatch(Character::isISOControl))
|
||||
throw new ApiException(400,"X-Audit-Reason debe tener como maximo 500 caracteres y no contener caracteres de control.");
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package com.aellis.cases.audit;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.oauth2.jwt.Jwt;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.web.context.request.*;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Contract v1: allowlisted persisted values, atomic with the business transaction. */
|
||||
@Component
|
||||
public class BusinessAudit implements ApplicationRunner {
|
||||
public record Context(long actorId, String actorName, UUID operationId, String requestId, String reason) {}
|
||||
private static final Map<String,List<String>> FIELDS = Map.of(
|
||||
"cases", List.of("name","description","id_client","id_status","id_created"),
|
||||
"activities", List.of("description","hours","rate","amount","payment","id_case","id_category","id_paytype","id_status","id_created"),
|
||||
"client", List.of("identdocument","businessname","description","id_recomended","id_documenttype","id_status"),
|
||||
"users", List.of("name","lastname","email","rate","acronym","id_specialization","id_rol","id_status"),
|
||||
"specialization", List.of("name"));
|
||||
private final JdbcClient jdbc;
|
||||
private final JsonMapper json;
|
||||
public BusinessAudit(JdbcClient jdbc, JsonMapper json) { this.jdbc=jdbc; this.json=json; }
|
||||
@Override public void run(ApplicationArguments args) {
|
||||
try {
|
||||
jdbc.sql("SELECT id,occurred_at,service,action,entity_type,entity_id,actor_id,actor_name,case_id,before_values,after_values,reason,operation_id,request_id,format_version FROM business_audit_events WHERE FALSE").query().listOfRows();
|
||||
} catch (RuntimeException e) { throw new IllegalStateException("Falta el esquema de historial de negocio. Aplica business-audit-schema.sql o la migracion de Auth antes de arrancar.", e); }
|
||||
}
|
||||
public Context context() {
|
||||
var authentication=SecurityContextHolder.getContext().getAuthentication();
|
||||
if(authentication==null || !(authentication.getPrincipal() instanceof Jwt jwt))
|
||||
throw new IllegalStateException("Business audit requires an authenticated actor");
|
||||
return context(Long.parseLong(jwt.getClaimAsString("id")));
|
||||
}
|
||||
public Context context(long actor) {
|
||||
requireTransaction();
|
||||
String name=jdbc.sql("SELECT concat_ws(' ',to_jsonb(u)->>'name',to_jsonb(u)->>'lastname') FROM users u WHERE id=:id").param("id",actor).query(String.class).optional().orElse("Usuario "+actor);
|
||||
if(name.isBlank()) name="Usuario "+actor;
|
||||
String requestId=null, reason=null;
|
||||
if(RequestContextHolder.getRequestAttributes() instanceof ServletRequestAttributes attributes) {
|
||||
HttpServletRequest request=attributes.getRequest();
|
||||
requestId=attributes.getResponse()==null?null:attributes.getResponse().getHeader("X-Request-Id");
|
||||
reason=request.getHeader("X-Audit-Reason");
|
||||
}
|
||||
return new Context(actor,name,UUID.randomUUID(),requestId,reason);
|
||||
}
|
||||
/** Preserve the caller's validated metadata for non-HTTP invocations too. */
|
||||
public Context context(long actor,String requestId) {
|
||||
var context=context(actor);
|
||||
String effective=context.requestId()!=null?context.requestId():requestId;
|
||||
if(effective!=null && !effective.matches("[A-Za-z0-9._:-]{1,128}"))
|
||||
throw new IllegalArgumentException("Invalid audit request identifier");
|
||||
return new Context(context.actorId(),context.actorName(),context.operationId(),effective,context.reason());
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
public Map<String,Object> snapshot(String table,long id) {
|
||||
requireTransaction();
|
||||
var fields=FIELDS.get(table);
|
||||
if(fields==null) throw new IllegalArgumentException("Unknown audited table");
|
||||
String projection=String.join(",",fields.stream().map(field->"'"+field+"',to_jsonb(t)->'"+field+"'").toList());
|
||||
return jdbc.sql("SELECT jsonb_build_object("+projection+")::text FROM "+table+" t WHERE id=:id")
|
||||
.param("id",id).query((rs,row)->(Map<String,Object>)json.readValue(rs.getString(1),Map.class)).optional()
|
||||
.orElseThrow(()->new IllegalStateException("Missing audited entity"));
|
||||
}
|
||||
public void change(Context context,String action,String type,long id,Integer caseId,Map<String,Object> before,Map<String,Object> after) {
|
||||
requireTransaction();
|
||||
List<String> allowed=FIELDS.get(switch(type) {
|
||||
case "case" -> "cases"; case "activity","payment" -> "activities"; case "client" -> "client";
|
||||
case "user" -> "users"; case "specialization" -> "specialization";
|
||||
case "assignment" -> ""; default -> throw new IllegalArgumentException("Unknown audited entity type");
|
||||
});
|
||||
if(type.equals("assignment")) allowed=List.of("id_user","id_case");
|
||||
if(allowed==null || !allowed.containsAll(before.keySet()) || !allowed.containsAll(after.keySet()))
|
||||
throw new IllegalArgumentException("Disallowed audit fields");
|
||||
var oldValues=new LinkedHashMap<String,Object>();
|
||||
var newValues=new LinkedHashMap<String,Object>();
|
||||
var keys=new LinkedHashSet<>(before.keySet()); keys.addAll(after.keySet());
|
||||
for(String key:keys) {
|
||||
if(before.containsKey(key)==after.containsKey(key) && equal(before.get(key),after.get(key))) continue;
|
||||
if(before.containsKey(key)) oldValues.put(key,before.get(key));
|
||||
if(after.containsKey(key)) newValues.put(key,after.get(key));
|
||||
}
|
||||
if(oldValues.isEmpty() && newValues.isEmpty()) return;
|
||||
insert(context,action,type,id,caseId,oldValues,newValues);
|
||||
}
|
||||
public void passwordChanged(Context context,long id,String action) {
|
||||
insert(context,action,"user",id,null,Map.of(),Map.of());
|
||||
}
|
||||
private static boolean equal(Object first,Object second) {
|
||||
if(first instanceof Number && second instanceof Number)
|
||||
return new BigDecimal(first.toString()).compareTo(new BigDecimal(second.toString()))==0;
|
||||
return Objects.equals(first,second);
|
||||
}
|
||||
private void insert(Context context,String action,String type,long id,Integer caseId,Map<String,Object> before,Map<String,Object> after) {
|
||||
requireTransaction();
|
||||
jdbc.sql("""
|
||||
INSERT INTO business_audit_events(service,action,entity_type,entity_id,actor_id,actor_name,case_id,before_values,after_values,reason,operation_id,request_id)
|
||||
VALUES(:service,:action,:type,:id,:actor,:name,:caseId,CAST(:before AS JSONB),CAST(:after AS JSONB),:reason,:operation,:request)
|
||||
""").param("service","cases").param("action",action).param("type",type).param("id",id)
|
||||
.param("actor",context.actorId()).param("name",context.actorName()).param("caseId",caseId)
|
||||
.param("before",json.writeValueAsString(before)).param("after",json.writeValueAsString(after))
|
||||
.param("reason",context.reason()).param("operation",context.operationId()).param("request",context.requestId()).update();
|
||||
}
|
||||
private static void requireTransaction() {
|
||||
if(!TransactionSynchronizationManager.isActualTransactionActive()) throw new IllegalStateException("Business audit requires an active transaction");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.aellis.cases.config;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import jakarta.validation.constraints.*;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
@Validated
|
||||
@ConfigurationProperties("cases")
|
||||
public record CaseProperties(@NotBlank String jwtAlgorithm, Resource publicKey, String tokenSecret,
|
||||
@NotBlank String issuer, @NotBlank String audience, boolean checkSession, @NotNull Duration jwtMaxAge,
|
||||
@NotEmpty List<String> allowedOrigins, @Min(0) int rateLimitMax, @Min(1) long rateLimitWindowMs,
|
||||
@Min(1) int rateLimitMemoryMaxKeys, @Min(1000) long rateLimitRedisBackoffMs,
|
||||
@NotBlank String rateLimitPrefix, String redisUrl, boolean requestLogEnabled) {
|
||||
public CaseProperties {
|
||||
if (!List.of("RS256", "HS256").contains(jwtAlgorithm)) throw new IllegalArgumentException("JWT_ALGORITHM debe ser RS256 o HS256");
|
||||
if (jwtMaxAge != null && (jwtMaxAge.isNegative() || jwtMaxAge.isZero())) throw new IllegalArgumentException("JWT_MAX_AGE debe ser positivo");
|
||||
if (allowedOrigins != null && allowedOrigins.contains("*")) throw new IllegalArgumentException("Configura origenes CORS explicitos");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.aellis.cases.config;
|
||||
|
||||
import jakarta.servlet.*;
|
||||
import jakarta.servlet.http.*;
|
||||
import java.io.*;
|
||||
import java.time.Clock;
|
||||
import java.util.*;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
@Component
|
||||
public class RequestFilter extends OncePerRequestFilter {
|
||||
private static final long MAX_BODY = 1024 * 1024;
|
||||
private record Window(long count, long resetAt) {}
|
||||
record Limit(long count, long resetAt, boolean allowed) {}
|
||||
private static final DefaultRedisScript<List> REDIS_SCRIPT = new DefaultRedisScript<>("""
|
||||
local count=redis.call('INCR',KEYS[1])
|
||||
local ttl=redis.call('PTTL',KEYS[1])
|
||||
if count==1 or ttl<0 then redis.call('PEXPIRE',KEYS[1],ARGV[1]); ttl=tonumber(ARGV[1]) end
|
||||
return {count,ttl}
|
||||
""", List.class);
|
||||
private final Map<String, Window> memory = new LinkedHashMap<>();
|
||||
private final CaseProperties properties;
|
||||
private final Clock clock;
|
||||
private final StringRedisTemplate redis;
|
||||
private volatile long redisDisabledUntil;
|
||||
public RequestFilter(CaseProperties properties, Clock clock, StringRedisTemplate redis) {
|
||||
this.properties = properties; this.clock = clock; this.redis = redis;
|
||||
}
|
||||
synchronized Limit memoryLimit(String key) {
|
||||
long now = clock.millis();
|
||||
var window = memory.get(key);
|
||||
if (window == null || window.resetAt() <= now) {
|
||||
if (memory.size() >= properties.rateLimitMemoryMaxKeys()) {
|
||||
memory.entrySet().removeIf(entry -> entry.getValue().resetAt() <= now);
|
||||
if (memory.size() >= properties.rateLimitMemoryMaxKeys() && !memory.containsKey(key)) {
|
||||
return new Limit(properties.rateLimitMax(), now + properties.rateLimitWindowMs(), false);
|
||||
}
|
||||
}
|
||||
window = new Window(1, now + properties.rateLimitWindowMs());
|
||||
} else window = new Window(Math.min(window.count() + 1, properties.rateLimitMax() + 1L), window.resetAt());
|
||||
memory.put(key, window);
|
||||
return new Limit(window.count(), window.resetAt(), window.count() <= properties.rateLimitMax());
|
||||
}
|
||||
private Limit limit(String key) {
|
||||
long now = clock.millis();
|
||||
if (properties.redisUrl() != null && !properties.redisUrl().isBlank() && now >= redisDisabledUntil) {
|
||||
try {
|
||||
List<?> result = redis.execute(REDIS_SCRIPT, List.of(properties.rateLimitPrefix() + ":" + key), Long.toString(properties.rateLimitWindowMs()));
|
||||
if (result != null && result.size() == 2) {
|
||||
long count = ((Number) result.get(0)).longValue(); long ttl = ((Number) result.get(1)).longValue();
|
||||
return new Limit(count, now + Math.max(ttl, 0), count <= properties.rateLimitMax());
|
||||
}
|
||||
} catch (RuntimeException exception) {
|
||||
redisDisabledUntil = now + properties.rateLimitRedisBackoffMs();
|
||||
LoggerFactory.getLogger(getClass()).warn("redis_rate_limit_unavailable; using local limiter");
|
||||
}
|
||||
}
|
||||
return memoryLimit(key);
|
||||
}
|
||||
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
String supplied = request.getHeader("X-Request-Id");
|
||||
String requestId = supplied != null && supplied.matches("[A-Za-z0-9._:-]{1,128}") ? supplied : UUID.randomUUID().toString();
|
||||
response.setHeader("X-Request-Id", requestId); response.setHeader("Cache-Control", "no-store");
|
||||
response.setHeader("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
|
||||
response.setHeader("X-DNS-Prefetch-Control", "off");
|
||||
if (properties.rateLimitMax() > 0) {
|
||||
var limit = limit(request.getRemoteAddr());
|
||||
response.setHeader("X-RateLimit-Limit", Integer.toString(properties.rateLimitMax()));
|
||||
response.setHeader("X-RateLimit-Remaining", Long.toString(Math.max(0, properties.rateLimitMax() - limit.count())));
|
||||
response.setHeader("X-RateLimit-Reset", Long.toString((limit.resetAt() + 999) / 1000));
|
||||
if (!limit.allowed()) {
|
||||
response.setHeader("Retry-After", Long.toString(Math.max(1, (limit.resetAt() - clock.millis() + 999) / 1000)));
|
||||
error(response, 429, "Too many requests."); return;
|
||||
}
|
||||
}
|
||||
if (request.getContentLengthLong() > MAX_BODY) { error(response, 413, "Request body too large."); return; }
|
||||
long start = clock.millis();
|
||||
try { chain.doFilter(new LimitedRequest(request), response); }
|
||||
finally {
|
||||
if (properties.requestLogEnabled()) LoggerFactory.getLogger(getClass()).info("request method={} path={} status={} durationMs={} requestId={}",
|
||||
request.getMethod(), request.getServletPath(), response.getStatus(), clock.millis() - start, requestId);
|
||||
}
|
||||
}
|
||||
public static void error(HttpServletResponse response, int status, String message) throws IOException {
|
||||
response.setStatus(status); response.setCharacterEncoding("UTF-8"); response.setContentType("application/json");
|
||||
if (status == 401) response.setHeader("WWW-Authenticate", "Bearer");
|
||||
response.getWriter().write("{\"data\":{\"message\":\"" + message + "\"},\"status\":\"error\"}");
|
||||
}
|
||||
@Bean FilterRegistrationBean<RequestFilter> disableDoubleRegistration() {
|
||||
var registration = new FilterRegistrationBean<>(this); registration.setEnabled(false); return registration;
|
||||
}
|
||||
public static class BodyTooLargeException extends IOException {}
|
||||
private static class LimitedRequest extends HttpServletRequestWrapper {
|
||||
private ServletInputStream input;
|
||||
LimitedRequest(HttpServletRequest request) { super(request); }
|
||||
@Override public ServletInputStream getInputStream() throws IOException {
|
||||
if (input == null) {
|
||||
var original = super.getInputStream();
|
||||
input = new ServletInputStream() {
|
||||
long count;
|
||||
private void check(int read) throws IOException { if (read > 0 && (count += read) > MAX_BODY) throw new BodyTooLargeException(); }
|
||||
@Override public int read() throws IOException { int value = original.read(); check(value < 0 ? 0 : 1); return value; }
|
||||
@Override public int read(byte[] bytes, int offset, int length) throws IOException { int value = original.read(bytes, offset, length); check(value); return value; }
|
||||
@Override public boolean isFinished() { return original.isFinished(); }
|
||||
@Override public boolean isReady() { return original.isReady(); }
|
||||
@Override public void setReadListener(ReadListener listener) { original.setReadListener(listener); }
|
||||
};
|
||||
}
|
||||
return input;
|
||||
}
|
||||
@Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream(), java.nio.charset.StandardCharsets.UTF_8)); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.aellis.cases.config;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.security.spec.X509EncodedKeySpec;
|
||||
import java.time.*;
|
||||
import java.util.*;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.springframework.context.annotation.*;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.oauth2.core.*;
|
||||
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
|
||||
import org.springframework.security.oauth2.jwt.*;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
|
||||
import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.web.cors.*;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfig {
|
||||
@Bean Clock clock() { return Clock.systemUTC(); }
|
||||
|
||||
@Bean JwtDecoder jwtDecoder(CaseProperties properties, JdbcClient jdbc, Clock clock) throws Exception {
|
||||
NimbusJwtDecoder decoder;
|
||||
if (properties.jwtAlgorithm().equals("HS256")) {
|
||||
byte[] secret = properties.tokenSecret().getBytes(StandardCharsets.UTF_8);
|
||||
if (secret.length < 32) throw new IllegalArgumentException("TOKEN_SECRET debe tener al menos 32 bytes para HS256");
|
||||
decoder = NimbusJwtDecoder.withSecretKey(new SecretKeySpec(secret, "HmacSHA256")).macAlgorithm(MacAlgorithm.HS256).build();
|
||||
} else {
|
||||
byte[] encoded;
|
||||
try (var input = properties.publicKey().getInputStream()) {
|
||||
encoded = Base64.getDecoder().decode(new String(input.readAllBytes(), StandardCharsets.US_ASCII)
|
||||
.replaceAll("-----[^-]+-----", "").replaceAll("\\s", ""));
|
||||
}
|
||||
var key = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(encoded));
|
||||
if (key.getModulus().bitLength() < 3072) throw new IllegalArgumentException("La clave RSA debe tener al menos 3072 bits");
|
||||
decoder = NimbusJwtDecoder.withPublicKey(key).build();
|
||||
}
|
||||
OAuth2TokenValidator<Jwt> claims = jwt -> {
|
||||
try {
|
||||
long id = Long.parseLong(jwt.getClaimAsString("id"));
|
||||
String role = jwt.getClaimAsString("rol");
|
||||
if (id <= 0 || id > Integer.MAX_VALUE || role == null || role.isBlank()
|
||||
|| jwt.getExpiresAt() == null || jwt.getIssuedAt() == null
|
||||
|| !jwt.getAudience().contains(properties.audience())
|
||||
|| jwt.getIssuedAt().isAfter(clock.instant().plusSeconds(30))
|
||||
|| jwt.getIssuedAt().plus(properties.jwtMaxAge()).isBefore(clock.instant().minusSeconds(30))
|
||||
|| (jwt.getSubject() != null && !jwt.getSubject().equals(Long.toString(id)))
|
||||
|| ("RS256".equals(properties.jwtAlgorithm()) && !"access".equals(jwt.getClaimAsString("token_use")))
|
||||
|| (jwt.hasClaim("token_use") && !"access".equals(jwt.getClaimAsString("token_use")))) return invalid();
|
||||
boolean active = jdbc.sql("""
|
||||
SELECT EXISTS(SELECT 1 FROM users u JOIN rol r ON r.id=u.id_rol
|
||||
WHERE u.id=:id AND u.id_status<>2 AND lower(r.name)=:role)
|
||||
""").param("id", id).param("role", role).query(Boolean.class).single();
|
||||
if (!active) return invalid();
|
||||
if (properties.checkSession()) {
|
||||
UUID session = UUID.fromString(jwt.getClaimAsString("sid"));
|
||||
boolean valid = jdbc.sql("""
|
||||
SELECT EXISTS(SELECT 1 FROM auth_session WHERE id=:session AND user_id=:id
|
||||
AND NOT revoked AND expires_at>CURRENT_TIMESTAMP)
|
||||
""").param("session", session).param("id", id).query(Boolean.class).single();
|
||||
if (!valid) return invalid();
|
||||
}
|
||||
return OAuth2TokenValidatorResult.success();
|
||||
} catch (IllegalArgumentException | NullPointerException exception) { return invalid(); }
|
||||
};
|
||||
decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(JwtValidators.createDefaultWithIssuer(properties.issuer()), claims));
|
||||
return decoder;
|
||||
}
|
||||
private static OAuth2TokenValidatorResult invalid() { return OAuth2TokenValidatorResult.failure(new OAuth2Error("invalid_token")); }
|
||||
|
||||
@Bean SecurityFilterChain security(HttpSecurity http, CaseProperties properties, RequestFilter filter) throws Exception {
|
||||
var converter = new JwtAuthenticationConverter();
|
||||
converter.setJwtGrantedAuthoritiesConverter(jwt -> List.of(new SimpleGrantedAuthority("ROLE_" + jwt.getClaimAsString("rol").toUpperCase(Locale.ROOT))));
|
||||
return http.cors(cors -> cors.configurationSource(cors(properties)))
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.requestCache(cache -> cache.disable()).formLogin(login -> login.disable()).httpBasic(basic -> basic.disable()).logout(logout -> logout.disable())
|
||||
.headers(headers -> headers.contentSecurityPolicy(csp -> csp.policyDirectives("default-src 'none'; frame-ancestors 'none'"))
|
||||
.referrerPolicy(policy -> policy.policy(org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER)))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers(org.springframework.http.HttpMethod.GET, "/health", "/actuator/health").permitAll()
|
||||
.requestMatchers(org.springframework.http.HttpMethod.POST, "/cases/create", "/cases/assing", "/cases/unassing").hasRole("ADMIN")
|
||||
.requestMatchers(org.springframework.http.HttpMethod.PUT, "/cases/update/*").hasRole("ADMIN")
|
||||
.requestMatchers(org.springframework.http.HttpMethod.PATCH, "/cases/disable/*").hasRole("ADMIN")
|
||||
.requestMatchers(org.springframework.http.HttpMethod.GET, "/cases/client/assing").hasAnyRole("ADMIN", "USER")
|
||||
.requestMatchers(org.springframework.http.HttpMethod.GET, "/cases/disable/*", "/cases/client/*", "/cases/case/assing/*", "/cases/case/unassing/*").hasRole("ADMIN")
|
||||
.requestMatchers(org.springframework.http.HttpMethod.GET, "/cases/all", "/cases/get/*", "/cases/assing/*", "/cases/all/notfilter", "/cases/client/case/assing/*").hasAnyRole("ADMIN", "USER")
|
||||
.anyRequest().denyAll())
|
||||
.exceptionHandling(errors -> errors.authenticationEntryPoint((req, res, ex) -> RequestFilter.error(res, 401, "Unauthorized"))
|
||||
.accessDeniedHandler((req, res, ex) -> RequestFilter.error(res, 403, "Forbidden")))
|
||||
.oauth2ResourceServer(resource -> resource.jwt(jwt -> jwt.jwtAuthenticationConverter(converter))
|
||||
.authenticationEntryPoint((req, res, ex) -> RequestFilter.error(res, 401, "Unauthorized")))
|
||||
.addFilterBefore(filter, BearerTokenAuthenticationFilter.class).build();
|
||||
}
|
||||
private CorsConfigurationSource cors(CaseProperties properties) {
|
||||
var configuration = new CorsConfiguration();
|
||||
configuration.setAllowedOrigins(properties.allowedOrigins());
|
||||
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
|
||||
configuration.setAllowedHeaders(List.of("X-Audit-Reason", "Content-Type", "Authorization", "X-Request-Id"));
|
||||
configuration.setExposedHeaders(List.of("X-Request-Id", "X-RateLimit-Limit", "X-RateLimit-Remaining", "X-RateLimit-Reset", "Retry-After"));
|
||||
configuration.setAllowCredentials(false);
|
||||
var source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.aellis.cases.repository;
|
||||
|
||||
import com.aellis.cases.api.CaseDtos.*;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
@Repository
|
||||
public class CaseRepository {
|
||||
private static final String FIELDS="ca.id,ca.name,ca.description,ca.created,ca.updated,ca.id_status,ca.id_created,ca.id_client";
|
||||
private static final String CLIENT="cl.id AS client_id,cl.identdocument,cl.businessname,cl.id_documenttype";
|
||||
private static final String JOIN=" LEFT JOIN client cl ON cl.id=ca.id_client";
|
||||
private static final String ASSIGNED="EXISTS(SELECT 1 FROM user_case uc WHERE uc.id_case=ca.id AND uc.id_user=:viewer)";
|
||||
private static final Set<String> WRITABLE=Set.of("name","description","id_client","id_status");
|
||||
private final JdbcClient jdbc;
|
||||
public CaseRepository(JdbcClient jdbc) { this.jdbc=jdbc; }
|
||||
public boolean catalog(String field,int id) {
|
||||
String table=switch(field) { case "id_client" -> "client"; case "id_status" -> "status"; default -> throw new IllegalArgumentException("Unknown catalog"); };
|
||||
return jdbc.sql("SELECT EXISTS(SELECT 1 FROM "+table+" WHERE id=:id)").param("id",id).query(Boolean.class).single();
|
||||
}
|
||||
public int create(Input input,int creator) {
|
||||
var values=input.fields();
|
||||
return jdbc.sql("""
|
||||
INSERT INTO cases(name,description,id_client,id_status,id_created,created)
|
||||
VALUES(:name,:description,:client,:status,:creator,CURRENT_TIMESTAMP) RETURNING id
|
||||
""").param("name",values.get("name")).param("description",values.get("description")).param("client",values.get("id_client"))
|
||||
.param("status",values.getOrDefault("id_status",4)).param("creator",creator).query(Integer.class).single();
|
||||
}
|
||||
public Optional<Integer> lock(int id) { return jdbc.sql("SELECT id_status FROM cases WHERE id=:id FOR UPDATE").param("id",id).query(Integer.class).optional(); }
|
||||
public boolean lockActiveUser(int id) {
|
||||
return jdbc.sql("SELECT id FROM users WHERE id=:id AND id_status=1 FOR SHARE").param("id",id).query(Integer.class).optional().isPresent();
|
||||
}
|
||||
public void update(int id,Map<String,Object> values) {
|
||||
if (values.isEmpty() || !WRITABLE.containsAll(values.keySet())) throw new IllegalArgumentException("Invalid update");
|
||||
String fields=String.join(",",values.keySet().stream().map(key -> key+"=:"+key).toList());
|
||||
jdbc.sql("UPDATE cases SET "+fields+",updated=CURRENT_TIMESTAMP WHERE id=:target").params(values).param("target",id).update();
|
||||
}
|
||||
public List<Integer> assignmentUserIds(int id) { return jdbc.sql("SELECT DISTINCT id_user FROM user_case WHERE id_case=:id ORDER BY id_user").param("id",id).query(Integer.class).list(); }
|
||||
public int clearAssignments(int id) { return jdbc.sql("DELETE FROM user_case WHERE id_case=:id").param("id",id).update(); }
|
||||
public int unassign(Assignment item) { return jdbc.sql("DELETE FROM user_case WHERE id_user=:user AND id_case=:caseId").param("user",item.userId()).param("caseId",item.caseId()).update(); }
|
||||
public int assign(Assignment item) {
|
||||
return jdbc.sql("""
|
||||
INSERT INTO user_case(id_user,id_case) SELECT :user,:caseId
|
||||
WHERE NOT EXISTS(SELECT 1 FROM user_case WHERE id_user=:user AND id_case=:caseId)
|
||||
""").param("user",item.userId()).param("caseId",item.caseId()).update();
|
||||
}
|
||||
public List<Map<String,Object>> list(Integer viewer,boolean activeOnly,boolean client,Integer clientId) {
|
||||
String sql="SELECT "+FIELDS+(client?","+CLIENT:"")+" FROM cases ca"+(client?JOIN:"")+" WHERE TRUE";
|
||||
if (activeOnly) sql+=" AND ca.id_status=4";
|
||||
if (viewer!=null) sql+=" AND "+ASSIGNED;
|
||||
if (clientId!=null) sql+=" AND ca.id_client=:clientId";
|
||||
var query=jdbc.sql(sql+" ORDER BY ca.name ASC,ca.id ASC");
|
||||
if (viewer!=null) query.param("viewer",viewer);
|
||||
if (clientId!=null) query.param("clientId",clientId);
|
||||
return query.query((rs,row) -> mapCase(rs,client)).list();
|
||||
}
|
||||
public boolean assigned(int user,int id) { return jdbc.sql("SELECT EXISTS(SELECT 1 FROM user_case WHERE id_user=:user AND id_case=:id)").param("user",user).param("id",id).query(Boolean.class).single(); }
|
||||
public Optional<Map<String,Object>> find(int id) {
|
||||
return jdbc.sql("SELECT "+FIELDS+","+CLIENT+" FROM cases ca"+JOIN+" WHERE ca.id=:id").param("id",id).query((rs,row) -> mapCase(rs,true)).optional();
|
||||
}
|
||||
public List<Map<String,Object>> assignedCases(int user) {
|
||||
return jdbc.sql("SELECT ca.id,ca.name,ca.id_client,"+CLIENT+" FROM cases ca"+JOIN+" WHERE ca.id_status=4 AND "+ASSIGNED+" ORDER BY ca.name,ca.id")
|
||||
.param("viewer",user).query((rs,row) -> {
|
||||
var mini=map("id",rs.getInt("id"),"name",rs.getString("name"),"id_client",rs.getObject("id_client"),"client",mapClient(rs));
|
||||
return map("id_user",user,"case",mini);
|
||||
}).list();
|
||||
}
|
||||
public List<Map<String,Object>> assignedClients(int user) {
|
||||
return rows("""
|
||||
SELECT DISTINCT cl.id,cl.identdocument,cl.businessname,cl.id_documenttype FROM client cl
|
||||
JOIN cases ca ON ca.id_client=cl.id JOIN user_case uc ON uc.id_case=ca.id
|
||||
WHERE uc.id_user=:user ORDER BY cl.businessname,cl.id
|
||||
""",Map.of("user",user));
|
||||
}
|
||||
public List<Map<String,Object>> assignedByClient(int user,int client) {
|
||||
return rows("SELECT ca.id,ca.name FROM cases ca WHERE ca.id_status=4 AND ca.id_client=:client AND "+ASSIGNED+" ORDER BY ca.name,ca.id",Map.of("client",client,"viewer",user));
|
||||
}
|
||||
public List<Map<String,Object>> users(int caseId,boolean assigned) {
|
||||
return rows("SELECT u.id,u.name,u.lastname,u.acronym FROM users u WHERE u.id_status=1 AND "+(assigned?"":"NOT ")
|
||||
+"EXISTS(SELECT 1 FROM user_case uc WHERE uc.id_user=u.id AND uc.id_case=:id) ORDER BY u.name,u.id",Map.of("id",caseId));
|
||||
}
|
||||
private List<Map<String,Object>> rows(String sql,Map<String,Object> params) {
|
||||
return jdbc.sql(sql).params(params).query((rs,row) -> {
|
||||
var result=new LinkedHashMap<String,Object>(); var metadata=rs.getMetaData();
|
||||
for(int i=1;i<=metadata.getColumnCount();i++) result.put(metadata.getColumnLabel(i),rs.getObject(i));
|
||||
return (Map<String,Object>)result;
|
||||
}).list();
|
||||
}
|
||||
private Map<String,Object> mapCase(ResultSet rs,boolean client) throws SQLException {
|
||||
var item=new LinkedHashMap<String,Object>();
|
||||
for(String field:List.of("id","name","description","created","updated","id_status","id_created","id_client")) {
|
||||
Object value=rs.getObject(field);
|
||||
if(value instanceof Timestamp timestamp) value=timestamp.toInstant();
|
||||
else if(value instanceof java.time.OffsetDateTime timestamp) value=timestamp.toInstant();
|
||||
item.put(field,value);
|
||||
}
|
||||
if(client) item.put("client",mapClient(rs));
|
||||
return item;
|
||||
}
|
||||
private Map<String,Object> mapClient(ResultSet rs) throws SQLException {
|
||||
return rs.getObject("client_id")==null?null:map("id",rs.getObject("client_id"),"identdocument",rs.getObject("identdocument"),"businessname",rs.getString("businessname"),"id_documenttype",rs.getObject("id_documenttype"));
|
||||
}
|
||||
public static Map<String,Object> map(Object... pairs) {
|
||||
var result=new LinkedHashMap<String,Object>(); for(int i=0;i<pairs.length;i+=2) result.put((String)pairs[i],pairs[i+1]); return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.aellis.cases.service;
|
||||
|
||||
import com.aellis.cases.api.*;
|
||||
import com.aellis.cases.api.CaseDtos.*;
|
||||
import com.aellis.cases.repository.CaseRepository;
|
||||
import java.util.*;
|
||||
import com.aellis.cases.audit.BusinessAudit;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Service
|
||||
public class CaseService {
|
||||
private final CaseRepository cases;
|
||||
private final BusinessAudit history;
|
||||
public CaseService(CaseRepository cases,BusinessAudit history) { this.cases=cases; this.history=history; }
|
||||
@Transactional public int create(Requester who,Input input,String requestId) {
|
||||
admin(who); var fields=new LinkedHashMap<>(input.fields()); fields.putIfAbsent("id_status",4); validate(fields);
|
||||
var context=history.context(who.id(),requestId);
|
||||
int id=cases.create(new Input(fields),who.id()); history.change(context,"case.create","case",id,id,Map.of(),history.snapshot("cases",id)); return id;
|
||||
}
|
||||
@Transactional public void update(Requester who,int id,Input input,String requestId) {
|
||||
admin(who); cases.lock(id).orElseThrow(CaseService::missing); var context=history.context(who.id(),requestId);
|
||||
var before=history.snapshot("cases",id); validate(input.fields()); cases.update(id,input.fields());
|
||||
if(Integer.valueOf(7).equals(input.fields().get("id_status"))) clearAssignments(context,id);
|
||||
history.change(context,"case.update","case",id,id,before,history.snapshot("cases",id));
|
||||
}
|
||||
@Transactional public void disable(Requester who,int id,String requestId) {
|
||||
admin(who); cases.lock(id).orElseThrow(CaseService::missing); validate(Map.of("id_status",7));
|
||||
var context=history.context(who.id(),requestId); var before=history.snapshot("cases",id);
|
||||
cases.update(id,Map.of("id_status",7)); clearAssignments(context,id);
|
||||
history.change(context,"case.disable","case",id,id,before,history.snapshot("cases",id));
|
||||
}
|
||||
@Transactional public void assign(Requester who,List<Assignment> items,String requestId) {
|
||||
admin(who);
|
||||
for(int id:items.stream().map(Assignment::userId).distinct().sorted().toList())
|
||||
if(!cases.lockActiveUser(id)) throw new ApiException(400,"Usuarios inválidos.");
|
||||
for(int id:items.stream().map(Assignment::caseId).distinct().sorted().toList())
|
||||
if(cases.lock(id).orElse(-1)!=4) throw new ApiException(400,"Casos inválidos.");
|
||||
var context=history.context(who.id(),requestId);
|
||||
for(var item:items) if(cases.assign(item)>0) assignment(context,item,true);
|
||||
}
|
||||
@Transactional public void unassign(Requester who,Assignment item,String requestId) {
|
||||
admin(who); cases.lock(item.caseId());
|
||||
var context=history.context(who.id(),requestId);
|
||||
if(cases.unassign(item)==0) throw new ApiException(404,"Asignación no encontrada.");
|
||||
assignment(context,item,false);
|
||||
}
|
||||
public List<Map<String,Object>> all(Requester who,boolean active) { return cases.list(who.admin()?null:who.id(),active,active,null); }
|
||||
public Map<String,Object> find(Requester who,int id) {
|
||||
if(!who.admin() && !cases.assigned(who.id(),id)) throw missing();
|
||||
return cases.find(id).orElse(null);
|
||||
}
|
||||
public List<Map<String,Object>> assigned(Requester who,int user) {
|
||||
if(!who.admin() && who.id()!=user) throw new ApiException(403,"Forbidden."); return cases.assignedCases(user);
|
||||
}
|
||||
public List<Map<String,Object>> clients(Requester who) { return cases.assignedClients(who.id()); }
|
||||
public List<Map<String,Object>> assignedByClient(Requester who,int client) { return cases.assignedByClient(who.id(),client); }
|
||||
public List<Map<String,Object>> byClient(Requester who,int client) { admin(who); return cases.list(null,true,false,client); }
|
||||
public List<Map<String,Object>> users(Requester who,int id,boolean assigned) { admin(who); return cases.users(id,assigned); }
|
||||
private void validate(Map<String,Object> fields) {
|
||||
if(fields.containsKey("id_client") && !cases.catalog("id_client",(Integer)fields.get("id_client"))) throw new ApiException(400,"Cliente inválido");
|
||||
if(fields.containsKey("id_status") && !cases.catalog("id_status",(Integer)fields.get("id_status"))) throw new ApiException(400,"Estado inválido");
|
||||
}
|
||||
private static void admin(Requester who) { if(!who.admin()) throw new ApiException(403,"Forbidden."); }
|
||||
private static ApiException missing() { return new ApiException(404,"Caso no encontrado"); }
|
||||
private void clearAssignments(BusinessAudit.Context context,int id) {
|
||||
for(int user:cases.assignmentUserIds(id)) assignment(context,new Assignment(user,id),false);
|
||||
cases.clearAssignments(id);
|
||||
}
|
||||
private void assignment(BusinessAudit.Context context,Assignment item,boolean added) {
|
||||
var values=Map.<String,Object>of("id_user",item.userId(),"id_case",item.caseId());
|
||||
history.change(context,added?"case.assign":"case.unassign","assignment",item.caseId(),item.caseId(),
|
||||
added?Map.of():values,added?values:Map.of());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
spring:
|
||||
application:
|
||||
name: genesis-case
|
||||
datasource:
|
||||
url: ${DB_URL:jdbc:postgresql://localhost:5432/genesis_auth}
|
||||
username: ${DB_USER:genesis}
|
||||
password: ${DB_PASSWORD}
|
||||
hikari:
|
||||
maximum-pool-size: 10
|
||||
connection-timeout: 5000
|
||||
data:
|
||||
redis:
|
||||
url: ${REDIS_URL:redis://localhost:6379}
|
||||
connect-timeout: 500ms
|
||||
timeout: 500ms
|
||||
jackson:
|
||||
deserialization:
|
||||
fail-on-unknown-properties: true
|
||||
server:
|
||||
port: ${SERVER_PORT:8084}
|
||||
shutdown: graceful
|
||||
forward-headers-strategy: none
|
||||
max-http-request-header-size: 16KB
|
||||
error:
|
||||
include-message: never
|
||||
include-stacktrace: never
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
exposure:
|
||||
include: health
|
||||
endpoint:
|
||||
health:
|
||||
show-details: never
|
||||
health:
|
||||
redis:
|
||||
enabled: false
|
||||
cases:
|
||||
jwt-algorithm: ${JWT_ALGORITHM:RS256}
|
||||
public-key: ${JWT_PUBLIC_KEY:file:.secrets/public.pem}
|
||||
token-secret: ${TOKEN_SECRET:}
|
||||
issuer: ${JWT_ISSUER:http://localhost:8080}
|
||||
audience: ${JWT_AUDIENCE:genesis-api}
|
||||
check-session: ${JWT_CHECK_SESSION:true}
|
||||
jwt-max-age: ${JWT_MAX_AGE:15m}
|
||||
allowed-origins: ${CORS_ALLOWED_ORIGINS:${FRONTEND_URL:http://localhost:3000}}
|
||||
rate-limit-max: ${RATE_LIMIT_MAX:300}
|
||||
rate-limit-window-ms: ${RATE_LIMIT_WINDOW_MS:60000}
|
||||
rate-limit-memory-max-keys: ${RATE_LIMIT_MEMORY_MAX_KEYS:10000}
|
||||
rate-limit-redis-backoff-ms: ${RATE_LIMIT_REDIS_BACKOFF_MS:60000}
|
||||
rate-limit-prefix: ${RATE_LIMIT_PREFIX:genesis-case:rate}
|
||||
redis-url: ${REDIS_URL:}
|
||||
request-log-enabled: ${REQUEST_LOG_ENABLED:true}
|
||||
Reference in New Issue
Block a user