package com.zzwtec.wechat.util.security;


import static com.zzwtec.wechat.config.WeChatConfig.weChatConfig;

/**
 * 接口的token相关工具类
 * @author 毛文超
 * */
public class TokenUtil {
    /**
     * 默认过期时间为15秒
     * */
    private static final long DEFAULT_TIME_OUT = 15000;

    /**
     * 使用当前系统时间进行xtea加密来生产一个token
     * @return token
     * */
    public static String getToken(){
        //获取系统时间
        long timeMillis = System.currentTimeMillis();
        String xteaIv = weChatConfig.getXteaIv();
        String xteaKey = weChatConfig.getXteaKey();
        if(xteaIv == null || xteaKey == null){
            return null;
        }
        return XTEA.decrypt(xteaKey,xteaIv,String.valueOf(timeMillis));
    }
    /**
     * 判断token是否有效
     * @param token token
     * @return true有效 false无效
     * */
    public static boolean isValid(String token){
        //获取系统时间
        long timeMillis = System.currentTimeMillis();
        String xteaIv = weChatConfig.getXteaIv();
        String xteaKey = weChatConfig.getXteaKey();
        if(xteaIv == null || xteaKey == null){
            return false;
        }

        String encrypt = XTEA.encrypt(xteaKey, xteaIv, token);
        if(encrypt == null){
            return false;
        }

        long tokenContent;
        try {
            tokenContent = Long.parseLong(encrypt);
        } catch (NumberFormatException e) {
            return false;
        }
        return timeMillis - tokenContent <= DEFAULT_TIME_OUT;

    }


}
