Files
erp-imprimelibros/src/main/java/com/imprimelibros/erp/externalApi/AuthService.java
2025-08-05 10:07:04 +02:00

42 lines
1.2 KiB
Java

package com.imprimelibros.erp.externalApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
@Service
public class AuthService {
@Value("${safekat.api.url}")
private String skApiUrl;
@Value("${safekat.api.email}")
private String skApiEmail;
@Value("${safekat.api.password}")
private String skApiPassword;
private final RestTemplate restTemplate = new RestTemplate();
private String currentToken;
public synchronized String getToken() {
if (currentToken == null) {
currentToken = fetchNewToken();
}
return currentToken;
}
public synchronized void invalidateToken() {
currentToken = null;
}
private String fetchNewToken() {
Map<String, String> credentials = Map.of(
"email", this.skApiEmail,
"password", this.skApiPassword);
ResponseEntity<Map> response = restTemplate.postForEntity(this.skApiUrl + "auth/jwt", credentials, Map.class);
return (String) response.getBody().get("access_token");
}
}