blob: 6b93c9d5f5c9e77c5391f7ecab3e348c123a70ad [file] [log] [blame]
2230110210198562025-05-17 16:27:12 +08001package com.pt.utils;
2
3import com.pt.constant.Constants;
4import io.jsonwebtoken.Jwts;
5import io.jsonwebtoken.SignatureAlgorithm;
6
7import java.nio.charset.StandardCharsets;
8import java.util.Date;
9import java.util.HashMap;
10import java.util.Map;
11import java.util.Objects;
12
13public 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
22301102aa5adbc2025-05-18 17:51:55 +080054 return tokenUsername.equals(username) && tokenUserType >= userType.getValue();
2230110210198562025-05-17 16:27:12 +080055 }
56
57 public static String generateToken(String username,
58 Constants.UserRole userType,
22301102f5670302025-06-08 14:10:02 +080059 long expireTime) {
2230110210198562025-05-17 16:27:12 +080060 Map<String, Object> claims = new HashMap<>();
61 claims.put("username", username);
62 claims.put("userType", userType.getValue());
63 return createToken(claims, expireTime);
64 }
65}