package com.palmnest.webapp.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.ServletException;
import java.util.Date;

/**
 * @Desc:Jwt相关
 **/
public class JwtUtil {

	final static String base64EncodedSecretKey = "base64EncodedSecretKey";//私钥

	public static String getToken(String userName) {
		return Jwts.builder()
				.setSubject(userName)
				.setIssuedAt(new Date())
				.signWith(SignatureAlgorithm.HS256, base64EncodedSecretKey)
				.compact();
	}

	/**
	 * @Desc:检查token,只要不正确就会抛出异常
	 **/
	public static boolean checkToken(String token) throws ServletException {
		try {
			final Claims claims = Jwts.parser().setSigningKey(base64EncodedSecretKey).parseClaimsJws(token).getBody();
			return true;
		} catch (ExpiredJwtException e1) {
			throw new ServletException("token expired");
		} catch (Exception e) {
			throw new ServletException("other token exception");
		}
	}

}