package cn.reghao.oss.store.util;

import cn.reghao.oss.storeapi.dto.OssPayload;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * JWT 令牌
 *
 * @author reghao
 * @date 2023-08-23 09:10:58
 */
public class JwtUtil {
    public static String createToken(OssPayload ossPayload, long expireAt, String signKey) {
        return Jwts.builder()
                .claim("action", ossPayload.getAction())
                .claim("channelId", ossPayload.getChannelId())
                .setSubject(String.valueOf(ossPayload.getUserId()))
                .setExpiration(new Date(expireAt))
                .signWith(SignatureAlgorithm.HS256, signKey)
                .compact();
    }

    public static OssPayload getOssPayload(String token, String signKey) {
        Claims claims = Jwts.parser().setSigningKey(signKey).parseClaimsJws(token).getBody();
        String action = (String) claims.get("action");
        int channelId = (Integer) claims.get("channelId");
        String userIdStr = claims.getSubject();
        return new OssPayload(action, channelId, Integer.parseInt(userIdStr));
    }
}
