package com.jpsoft.shinestar.modules.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Base64;
import java.util.Date;

public class JwtUtil {
    public static String createToken(String jwtSecret, String subject, Date expiration) {
        //token有效时间天
        byte[] privateKey = Base64.getDecoder().decode(jwtSecret);

        Key key = Keys.hmacShaKeyFor(privateKey);

        String token = Jwts.builder()
                    .setSubject(subject)
                //设置自定义claims后，setSubject值将失效
//               .setClaims(extraInfo)
                    .signWith(key)
                    .setExpiration(expiration)
                    .compact();

        return "Bearer " + token;
    }

    public static String decodeToken(String jwtSecret,String token) throws Exception{
        String prefix = "Bearer ";

        if (token==null || token.length() < prefix.length()){
            throw new Exception("未传递令牌或未带前缀Bearer!");
        }

        token = token.substring(prefix.length());

        byte[] privateKey = Base64.getDecoder().decode(jwtSecret);

        Key key = Keys.hmacShaKeyFor(privateKey);

        Claims claims = Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(token)
                .getBody();

        String subject = claims.getSubject();

        return subject;
    }
}
