package cn.com.victorysoft.business.utils;

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

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

public class JwtUtilsA {

    private static final String SIGN_KEY = "victory_soft";

    /**
     签发对象：这个用户的id
     签发时间：现在
     有效时间：12小时
     加密密钥：字符串
     */
    public static String createToken(String userId) {

        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.HOUR,12);
        Date expiresDate = nowTime.getTime();

        return JWT.create().withAudience(userId)   //签发对象
                .withIssuedAt(new Date())    //发行时间
                .withExpiresAt(expiresDate)  //有效时间
//                .withClaim("realName", realName)    //载荷，随便写几个都可以
                .sign(Algorithm.HMAC256(SIGN_KEY));   //加密
    }

    /**
     * 检验合法性
     */
    public static boolean verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SIGN_KEY)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            e.printStackTrace();
            //效验失败
            return false;
        }
        return jwt != null;
    }

    /**
     * 获取签发对象
     */
    public static String getAudience(String token) {
        return JWT.decode(token).getAudience().get(0);
    }


    /**
     * 通过载荷名字获取载荷的值
     */
    public static Claim getClaimByName(String token, String name){
        return JWT.decode(token).getClaim(name);
    }
}
