package com.sky.ioc.tool;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sky.ioc.entity.domain.system.Users;
import org.springframework.beans.factory.annotation.Value;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {

    @Value("${sky.security.key}")
    private static final String secretKey = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9";

    /**
     * 生成token
     *
     * @param users
     * @return
     */
    public static String genJwtToken(Users users) {
        String token = JWT.create().withJWTId(UUID.randomUUID().toString()).withAudience("user").withIssuer("sky-ioc-server").withIssuedAt(new Date()).withSubject(users.getUserName()).withClaim("userID", users.getId()).withExpiresAt(Instant.now().plus(16, ChronoUnit.HOURS)).sign(Algorithm.HMAC256(secretKey));
        return token;

    }

    /**
     * 解析JWT字符串
     *
     * @param token
     * @return 用户名
     */
    public static String parseJWT(String token) {
        JWTVerifier build = JWT.require(Algorithm.HMAC256(secretKey)).build();
        DecodedJWT verify = build.verify(token);
        String username = verify.getSubject();
        return username;
    }

}

