package com.xkrs.common.tool;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;

import javax.crypto.SecretKey;
import java.util.List;

/**
 * token工具
 * @author tajochen
 */
public class TokenUtil {
    /**
     * Token前缀
     */
    static public final String TOKEN_PREFIX = "Bearer";

    static public final String SECRETKEY = "0Y9H364Q9Y908262F25LMXGIKIN5N858XM3674GWL2DD8X1DS4W6I722IRY8PS4XPNB6U30345" +
            "HBVCUL94STG8C3Z53T7A09JJ100I56YE9894CI11PX9J71HIZ8L5Y2O504C4E2K8276425UA8734833F45K36878FXAG799QV9LXUJ" +
            "OI3XA2046UPG8TB2OT84R5T6ZB127N9ZPJ7AJMC41JVHB2WK2B6H8NL45LZNAZ666KHZH3QUT65UX6F8";

    static SecretKey key = Keys.hmacShaKeyFor(SECRETKEY.getBytes());

    public static String getTokenUserName(String token) {
        String userName = "";
        if (token != null) {
            try {
                // 解析 Token
                Claims claims = Jwts.parserBuilder()
                        .setSigningKey(key).build()
                        // 去掉 Bearer
                        .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                        .getBody();
                // 获取用户名
                userName = claims.getSubject();
                // 获取权限
                List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("auths"));
            } catch(Exception e) {
                // the sub field was missing or did not have a 'jsmith' value
                return null;
            }
        } else {
            return null;
        }
        return userName;
    }
}
