package se.bilhalsning.security; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.Jwts; import java.nio.charset.StandardCharsets; import java.util.Date; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class JwtService { private static final long DEFAULT_EXPIRATION_MS = 86_400_000; private final SecretKey secretKey; private final long expirationMs; public JwtService(String secret) { this(secret, DEFAULT_EXPIRATION_MS); } public JwtService(String secret, long expirationMs) { this.secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); this.expirationMs = expirationMs; } public String generateToken(String email) { return generateToken(email, "user"); } public String generateToken(String email, String role) { return Jwts.builder() .subject(email) .claim("role", role) .issuedAt(new Date()) .expiration(new Date(System.currentTimeMillis() + expirationMs)) .signWith(secretKey) .compact(); } public String extractUsername(String token) { return Jwts.parser() .verifyWith(secretKey) .build() .parseSignedClaims(token) .getPayload() .getSubject(); } public String extractRole(String token) { return Jwts.parser() .verifyWith(secretKey) .build() .parseSignedClaims(token) .getPayload() .get("role", String.class); } public boolean isTokenValid(String token) { try { Jwts.parser() .verifyWith(secretKey) .build() .parseSignedClaims(token); return true; } catch (ExpiredJwtException e) { return false; } catch (Exception e) { return false; } } }