blob: 6b93c9d5f5c9e77c5391f7ecab3e348c123a70ad [file] [log] [blame]
package com.pt.utils;
import com.pt.constant.Constants;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class JWTUtils {
private final static String SECRET_KEY = "U2VjcmV0S2V5Rm9ySldUVXNlT25seUluU2VjdXJlRW52aXJvbm1lbnQ=";
public static String createToken(Map<String, Object> params, long ttlMills){
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long expMillis = System.currentTimeMillis() + ttlMills;
Date exp = new Date(expMillis);
return Jwts.builder()
.setClaims(params)
.signWith(signatureAlgorithm, SECRET_KEY.getBytes(StandardCharsets.UTF_8))
.setExpiration(exp)
.compact();
}
public static Map<String, Object> parseToken(String token){
try{
return Jwts.parser()
.setSigningKey(SECRET_KEY.getBytes(StandardCharsets.UTF_8))
.parseClaimsJws(token).getBody();
}catch (Exception e){
return null;
}
}
public static boolean checkToken(String token, String username, Constants.UserRole userType) {
Map<String, Object> claims = parseToken(token);
if(claims == null) {
System.out.println("Token is invalid or expired");
return false;
}
String tokenUsername = (String) claims.get("username");
int tokenUserType = (int) claims.get("userType");
System.out.printf("Token username: %s, Token userType: %d, Provided username: %s, Provided userType: %d%n",
tokenUsername, tokenUserType, username, userType.getValue());
return tokenUsername.equals(username) && tokenUserType >= userType.getValue();
}
public static String generateToken(String username,
Constants.UserRole userType,
long expireTime) {
Map<String, Object> claims = new HashMap<>();
claims.put("username", username);
claims.put("userType", userType.getValue());
return createToken(claims, expireTime);
}
}