package com.hys.app.framework.security.impl;

import com.hys.app.framework.ErpConfig;
import com.hys.app.framework.auth.AuthUser;
import com.hys.app.framework.auth.Token;
import com.hys.app.framework.auth.TokenParseException;
import com.hys.app.framework.auth.impl.JwtTokenCreater;
import com.hys.app.framework.auth.impl.JwtTokenParser;
import com.hys.app.framework.security.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * token管理基于twt的实现
 * @author kingapex
 * @version 1.0
 * @since 7.1.0
 * 2019/12/25
 */

@Service
public class TokenManagerImpl implements TokenManager {

    @Autowired
    private ErpConfig erpConfig;

    @Override
    public Token create(AuthUser user) {
        JwtTokenCreater tokenCreater = new JwtTokenCreater(erpConfig.getTokenSecret());
        tokenCreater.setAccessTokenExp(erpConfig.getAccessTokenTimeout());
        tokenCreater.setRefreshTokenExp(erpConfig.getRefreshTokenTimeout());
        return tokenCreater.create(user);

    }

    @Override
    public Token create(AuthUser user, int accessTokenExp, int refreshTokenExp) {
        JwtTokenCreater tokenCreater = new JwtTokenCreater(erpConfig.getTokenSecret());
        tokenCreater.setAccessTokenExp(accessTokenExp);
        tokenCreater.setRefreshTokenExp(refreshTokenExp);
        return tokenCreater.create(user);
    }

    @Override
    public <T> T parse(Class<T> clz, String token) throws TokenParseException {
        JwtTokenParser tokenParser = new JwtTokenParser(erpConfig.getTokenSecret());
        return tokenParser.parse(clz, token);
    }

    @Override
    public Token create(AuthUser user,Integer tokenOutTime,Integer refreshTokenOutTime) {
        JwtTokenCreater tokenCreater = new JwtTokenCreater(erpConfig.getTokenSecret());
        if (null == tokenOutTime){
            tokenCreater.setAccessTokenExp(erpConfig.getAccessTokenTimeout());
        }else{
            tokenCreater.setAccessTokenExp(tokenOutTime);
        }
        if (null == refreshTokenOutTime){
            tokenCreater.setRefreshTokenExp(erpConfig.getRefreshTokenTimeout());
        }else{
            tokenCreater.setRefreshTokenExp(refreshTokenOutTime);
        }
        return tokenCreater.create(user);

    }
}
