Created
March 8, 2024 08:03
-
-
Save klaudiusmiskinis/2ff9055bca156c170ee5723abf04cafd to your computer and use it in GitHub Desktop.
PreAuthorize y CanAccess
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Anotación para indicar que esta clase es un servicio de Spring | |
@Service | |
public class AccessControlService { | |
// Inyección de dependencias de Spring para obtener una instancia de EndpointAccessRepository | |
@Autowired | |
private EndpointAccessRepository repository; | |
// Método para verificar si se puede acceder a un endpoint específico | |
public boolean canAccess(String endpoint) { | |
LocalDateTime now = LocalDateTime.now(); // Hora actual | |
return repository.findByEndpoint(endpoint).map(access -> { | |
// Calcula el próximo acceso permitido sumando directamente el intervalo de acceso en minutos. | |
LocalDateTime nextAllowedAccess = access.getLastAccess().plusMinutes(access.getAccessInterval()); | |
// Comprueba si la hora actual es posterior al próximo acceso permitido. | |
return now.isAfter(nextAllowedAccess); | |
}).orElse(true); // Permite el acceso si el endpoint no existe en el repositorio. | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@RestController | |
public class MyController { | |
@GetMapping("/mi-endpoint") | |
@PreAuthorize("@accessControlService.canAccess('/mi-endpoint')") | |
public String miEndpoint() { | |
return "Acceso concedido"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Faltaria crear el BO y el Repository pero eso depende de la tabla, nombres, etc...
Tabla con 3 campos (o más) intervalo, último acceso y endpoint.