package cn.hnthyy.thmz.Utils;

import cn.hnthyy.thmz.common.Constants;
import cn.hnthyy.thmz.entity.MzException;
import cn.hnthyy.thmz.entity.thmz.User;
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);
    }

    /**
     * 获取用户
     * @param httpServletRequest
     * @return
     * @throws MzException
     */
    public static User getUser(HttpServletRequest httpServletRequest) throws MzException {
        String token = TokenUtil.getToken(httpServletRequest);
        if (StringUtils.isBlank(token)) {
            throw new MzException("业务处理失败,用户Token不存在");
        }
        DecodedJWT decodedJWT = TokenUtil.parseJWT(token);
        return (User) JsonUtil.jsontoObject(decodedJWT.getSubject(), User.class);
    }

}
