package cn.hnthyy.thmz.Utils;

import cn.hnthyy.thmz.common.Constants;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * token 工具类
 */
public class TokenUtil {
    /**
     * 从消息头中取出token
     * @param httpServletRequest
     * @return
     */
    public static String getToken(HttpServletRequest httpServletRequest){
        // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader("Authorization");
        if (StringUtils.isNotBlank(token)) {
            return token.replace("Bearer ", "");
        }
        return token;
    }


    /**
     * 创建token
     * @param subject 负载对象
     * @param deadTime 失效时间
     * @return
     */
    public static String createJWT(String subject,Date deadTime) {
        return JWT.create()
                .withIssuer(Constants.JWT_ID).withExpiresAt(deadTime).withSubject(subject)
                .sign(Algorithm.HMAC256(Constants.JWT_SECRET));
    }

    /**
     * 解析jwt
     * @param jwt
     */
    public static DecodedJWT  parseJWT(String jwt) {
        return JWT.decode(jwt);
    }

}
