package com.ag.secp.platform.jwt;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.jwt.*;
import cn.hutool.jwt.signers.JWTSignerUtil;

import java.util.HashMap;
import java.util.Map;
/**
 * Description: JWT HS256 对称加密
 * Author: songwp
 * Version: 1.0
 * Create Date: 2021/7/13
 */
public class JWTTokenForHS256 {

    //token密钥
    private static final String TOKEN_SECRET = "SDFSFEGEIFNEWERETSDFSD";
    //间隔时间
    public static final long EXPIRE_DATE = 1000*1000;

    public static byte[] getTokenSecretByte(){
        return TOKEN_SECRET.getBytes();
    }

    /**
     * Description：生成token
     * @param payload
     * @param expireDate 过期间隔毫秒数
     * @return: java.lang.String
     * @Author songwp
     * Create Date  2021/12/24
     */
    public static String createToken(Map<String,Object> payload,long expireDate) {

        //设置头部信息
        Map<String,Object> header = new HashMap<>();
        header.put("typ","JWT");
        header.put("alg","HS256");
        //设置payload内容
//        //签发时间
//        payload.put(JWTPayload.ISSUED_AT, System.currentTimeMillis());
//        //生效时间
//        payload.put(JWTPayload.NOT_BEFORE, System.currentTimeMillis());
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, DateUtil.date(System.currentTimeMillis() + expireDate));
        return JWTUtil.createToken(header,payload,getTokenSecretByte());
    }

    /**
     * Description：验证token
     * @param token
     * @return: boolean
     * @Author songwp
     * Create Date  2021/12/24
     */
    public static boolean verifyToken(String token) {
        boolean isSuccess;

        try {
            //验证签名
            isSuccess = JWTUtil.verify(token, getTokenSecretByte());
            //验证算法
            JWTValidator.of(token).validateAlgorithm(JWTSignerUtil.hs256(getTokenSecretByte())).validateDate(DateUtil.date());
        }catch (ValidateException exception){
            isSuccess = false;
        }

        return isSuccess;
    }

    /**
     * Description：解释数据
     * @param token
     * @return: JWTInfo
     * @Author songwp
     * Create Date  2021/12/24
     */
    public static JWTInfo parseToken(String token) {
        JWTInfo jwtInfo = new JWTInfo();
        final JWT jwt = JWTUtil.parseToken(token);
        jwtInfo.setTyp(jwt.getHeader(JWTHeader.TYPE).toString());
        jwtInfo.setAlg(jwt.getHeader(JWTHeader.ALGORITHM).toString());
        jwtInfo.setExpireTime(Long.parseLong(jwt.getPayload(JWTPayload.EXPIRES_AT).toString()));;
        jwtInfo.setName(jwt.getPayload("name").toString());
        jwtInfo.setUid(jwt.getPayload("uid").toString());
        return jwtInfo;
    }


}
