| [700e2f9] | 1 | package com.finki.icare.service;
|
|---|
| 2 |
|
|---|
| 3 | import io.jsonwebtoken.Claims;
|
|---|
| 4 | import io.jsonwebtoken.Jwts;
|
|---|
| 5 | import io.jsonwebtoken.security.Keys;
|
|---|
| 6 | import org.springframework.beans.factory.annotation.Value;
|
|---|
| 7 | import org.springframework.stereotype.Service;
|
|---|
| 8 |
|
|---|
| 9 | import javax.crypto.SecretKey;
|
|---|
| 10 | import java.nio.charset.StandardCharsets;
|
|---|
| 11 | import java.util.Date;
|
|---|
| 12 | import java.util.HashMap;
|
|---|
| 13 | import java.util.Map;
|
|---|
| 14 |
|
|---|
| 15 | @Service
|
|---|
| 16 | public class JwtService {
|
|---|
| 17 |
|
|---|
| 18 | @Value("${JWT_SECRET}")
|
|---|
| 19 | private String secretKey;
|
|---|
| 20 |
|
|---|
| 21 | @Value("${JWT_EXPIRATION}")
|
|---|
| 22 | private long jwtExpiration;
|
|---|
| 23 |
|
|---|
| 24 | private SecretKey getSigningKey() {
|
|---|
| 25 | return Keys.hmacShaKeyFor(secretKey.getBytes(StandardCharsets.UTF_8));
|
|---|
| 26 | }
|
|---|
| 27 |
|
|---|
| 28 | public String generateToken(String username, Integer userId, String userType) {
|
|---|
| 29 | Map<String, Object> claims = new HashMap<>();
|
|---|
| 30 | claims.put("userId", userId);
|
|---|
| 31 | claims.put("userType", userType);
|
|---|
| 32 |
|
|---|
| 33 | return Jwts.builder()
|
|---|
| 34 | .claims(claims)
|
|---|
| 35 | .subject(username)
|
|---|
| 36 | .issuedAt(new Date(System.currentTimeMillis()))
|
|---|
| 37 | .expiration(new Date(System.currentTimeMillis() + jwtExpiration))
|
|---|
| 38 | .signWith(getSigningKey())
|
|---|
| 39 | .compact();
|
|---|
| 40 | }
|
|---|
| 41 |
|
|---|
| 42 | public String extractUsername(String token) {
|
|---|
| 43 | return extractClaims(token).getSubject();
|
|---|
| 44 | }
|
|---|
| 45 |
|
|---|
| 46 | public Integer extractUserId(String token) {
|
|---|
| 47 | return extractClaims(token).get("userId", Integer.class);
|
|---|
| 48 | }
|
|---|
| 49 |
|
|---|
| 50 | public String extractUserType(String token) {
|
|---|
| 51 | return extractClaims(token).get("userType", String.class);
|
|---|
| 52 | }
|
|---|
| 53 |
|
|---|
| 54 | public boolean isTokenValid(String token, String username) {
|
|---|
| 55 | final String extractedUsername = extractUsername(token);
|
|---|
| 56 | return (extractedUsername.equals(username) && !isTokenExpired(token));
|
|---|
| 57 | }
|
|---|
| 58 |
|
|---|
| 59 | private boolean isTokenExpired(String token) {
|
|---|
| 60 | return extractClaims(token).getExpiration().before(new Date());
|
|---|
| 61 | }
|
|---|
| 62 |
|
|---|
| 63 | private Claims extractClaims(String token) {
|
|---|
| 64 | return Jwts.parser()
|
|---|
| 65 | .verifyWith(getSigningKey())
|
|---|
| 66 | .build()
|
|---|
| 67 | .parseSignedClaims(token)
|
|---|
| 68 | .getPayload();
|
|---|
| 69 | }
|
|---|
| 70 | }
|
|---|
| 71 |
|
|---|