package com.imdroid.sec_exapi.auth;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class TokenUtils {
    //生成token
    public static String getToken(String APIKey, String APISecret) {
        Date start = new Date();
        long currentTime = System.currentTimeMillis() + 60* 60 * 1000;//一小时有效时间
        Date end = new Date(currentTime);
        String token = "";

        token = JWT.create().withAudience(APIKey)
                .withIssuedAt(start).withExpiresAt(end)
                .sign(Algorithm.HMAC256(APISecret));
        return token;
    }

    public static String getTokenAPIKey() {
        String token = getRequest().getHeader("token");// 从 http 请求头中取出 token
        String APIKey = JWT.decode(token).getAudience().get(0);
        return APIKey;
    }

    /**
     * 获取request
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return requestAttributes == null ? null : requestAttributes.getRequest();
    }

}