22301102 | 1019856 | 2025-05-17 16:27:12 +0800 | [diff] [blame] | 1 | package com.pt.utils; |
| 2 | |
| 3 | import com.pt.constant.Constants; |
| 4 | import io.jsonwebtoken.Jwts; |
| 5 | import io.jsonwebtoken.SignatureAlgorithm; |
| 6 | |
| 7 | import java.nio.charset.StandardCharsets; |
| 8 | import java.util.Date; |
| 9 | import java.util.HashMap; |
| 10 | import java.util.Map; |
| 11 | import java.util.Objects; |
| 12 | |
| 13 | public class JWTUtils { |
| 14 | |
| 15 | private final static String SECRET_KEY = "U2VjcmV0S2V5Rm9ySldUVXNlT25seUluU2VjdXJlRW52aXJvbm1lbnQ="; |
| 16 | |
| 17 | |
| 18 | public static String createToken(Map<String, Object> params, long ttlMills){ |
| 19 | |
| 20 | SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; |
| 21 | long expMillis = System.currentTimeMillis() + ttlMills; |
| 22 | Date exp = new Date(expMillis); |
| 23 | return Jwts.builder() |
| 24 | .setClaims(params) |
| 25 | .signWith(signatureAlgorithm, SECRET_KEY.getBytes(StandardCharsets.UTF_8)) |
| 26 | .setExpiration(exp) |
| 27 | .compact(); |
| 28 | |
| 29 | } |
| 30 | |
| 31 | public static Map<String, Object> parseToken(String token){ |
| 32 | try{ |
| 33 | return Jwts.parser() |
| 34 | .setSigningKey(SECRET_KEY.getBytes(StandardCharsets.UTF_8)) |
| 35 | .parseClaimsJws(token).getBody(); |
| 36 | }catch (Exception e){ |
| 37 | return null; |
| 38 | } |
| 39 | |
| 40 | } |
| 41 | |
| 42 | public static boolean checkToken(String token, String username, Constants.UserRole userType) { |
| 43 | Map<String, Object> claims = parseToken(token); |
| 44 | if(claims == null) { |
| 45 | System.out.println("Token is invalid or expired"); |
| 46 | return false; |
| 47 | } |
| 48 | String tokenUsername = (String) claims.get("username"); |
| 49 | int tokenUserType = (int) claims.get("userType"); |
| 50 | |
| 51 | System.out.printf("Token username: %s, Token userType: %d, Provided username: %s, Provided userType: %d%n", |
| 52 | tokenUsername, tokenUserType, username, userType.getValue()); |
| 53 | |
22301102 | aa5adbc | 2025-05-18 17:51:55 +0800 | [diff] [blame] | 54 | return tokenUsername.equals(username) && tokenUserType >= userType.getValue(); |
22301102 | 1019856 | 2025-05-17 16:27:12 +0800 | [diff] [blame] | 55 | } |
| 56 | |
| 57 | public static String generateToken(String username, |
| 58 | Constants.UserRole userType, |
22301102 | f567030 | 2025-06-08 14:10:02 +0800 | [diff] [blame^] | 59 | long expireTime) { |
22301102 | 1019856 | 2025-05-17 16:27:12 +0800 | [diff] [blame] | 60 | Map<String, Object> claims = new HashMap<>(); |
| 61 | claims.put("username", username); |
| 62 | claims.put("userType", userType.getValue()); |
| 63 | return createToken(claims, expireTime); |
| 64 | } |
| 65 | } |