Files
elder-scrolls-legends/src/main/java/ch/gtache/elderscrollslegends/service/account/JWTService.java
2025-04-30 18:18:21 +02:00

63 lines
2.0 KiB
Java

package ch.gtache.elderscrollslegends.service.account;
import ch.gtache.elderscrollslegends.service.Token;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.jboss.logging.Logger;
import java.time.Duration;
import java.time.Instant;
@ApplicationScoped
class JWTService {
private static final Logger logger = Logger.getLogger(JWTService.class.getName());
private static final String ISSUER = "TESL";
private final Algorithm algorithm;
private final Duration timeToLive;
private final JWTVerifier verifier;
@Inject
JWTService(@ConfigProperty(name = "jwt.hs256.key.secret") final String key,
@ConfigProperty(name = "jwt.token.ttl.seconds") final int ttlSeconds) {
this.algorithm = Algorithm.HMAC256(key);
this.timeToLive = Duration.ofSeconds(ttlSeconds);
this.verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
}
public String getSteamID(final String token) {
try {
final var decoded = verifier.verify(token);
return decoded.getSubject();
} catch (final JWTVerificationException e) {
logger.warn("Invalid token " + token, e);
return null;
}
}
public boolean isValid(final String token) {
try {
verifier.verify(token);
return true;
} catch (final JWTVerificationException e) {
return false;
}
}
Token createToken(final String steamID) {
final var expiration = Instant.now().plus(timeToLive);
final var token = JWT.create()
.withSubject(steamID)
.withIssuer(ISSUER)
.withIssuedAt(Instant.now())
.withExpiresAt(expiration).sign(algorithm);
return new Token(token, expiration);
}
}