package com.sdut.labex.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * File: JWTUtil
 * Created: 2023/6/11
 * Author: springforest
 * Description:
 */


public class JWTUtil {
    // 签名密钥
    private static final String SECRET = "LabEx";
    // token过期时间（秒）
    private static final int EXPIRATION = 7 * 24 * 60 * 60;

    /**
     * 生成token
     *
     * @param payload token携带的信息
     * @return token字符串
     */
    public static String getTokenByMap(Map<String, String> payload) {
        // 指定token过期时间(秒)
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, EXPIRATION);

        JWTCreator.Builder builder = JWT.create();
        // 构建payload，填入信息
        payload.forEach(builder::withClaim);
        // 指定过期时间和签名算法
        return builder.withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 解析token
     *
     * @param token token字符串
     * @return 解析后的token
     * 获取数据：String userId = jwtVerifier.verify(token).getClaim("userId").asString();
     */
    public static DecodedJWT decode(String token) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        return jwtVerifier.verify(token);
    }

    /**
     * 判断token是否过期
     *
     * @param token token字符串
     * @return 布尔值
     * true已过期；false未过期
     */
    public static boolean isExpired(String token) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = jwtVerifier.verify(token);
        //1. 获取exp参数值
        long expTime = jwt.getClaim("exp").asLong();
        //2. 将exp参数值转换为Date类型
        Date expDate = new Date(expTime * 1000);
        //3. 判断是否过期
        return expDate.before(new Date());
    }
}

