package com.hs.api.common.utils;

import com.hs.api.model.SysUser;
import com.hs.common.utils.JWTUtil;
import com.hs.common.utils.RedisUtil;

public class TokenUtil {
    public final static long TOKEN_TIME_OUT = 2L * 60 * 60;
    public final static long OLD_TOKEN_DURATION = 5L * 60;

    /**
     * 获取token，并将token存入redis
     *
     * @param secret 密码
     * @param user 用户信息
     * @return token
     */
    public static String getToken(String secret,SysUser user) {
        String time = String.valueOf(System.currentTimeMillis());
        String token = JWTUtil.create(secret,time,String.valueOf(user.getId()));
        RedisUtil.set(token,user,TOKEN_TIME_OUT);
        return token;
    }

    /**
     * 刷新token，并将旧token设置过期时间为5分钟
     *
     * @param oldToken 旧的token
     * @return 新的token
     */
    public static String refresh(String oldToken) {
        String token = null;
        SysUser user = (SysUser)RedisUtil.get(oldToken);
        if(checkToken(oldToken)){
            RedisUtil.expire(oldToken,OLD_TOKEN_DURATION);
            token = getToken(user.getPassword(),user);
        }
        return token;
    }

    /**
     * 校验token
     *
     * @param token token
     * @return 返回校验结果
     */
    public static boolean checkToken(String token) {
        SysUser user = (SysUser)RedisUtil.get(token);
        boolean result = user != null && JWTUtil.verifier(token,user.getPassword());
        if(result){
            RedisUtil.expire(token,TOKEN_TIME_OUT);
        }
        return result;
    }
}
