package com.jkcredit.invoice.service.user.impl;

import cn.hutool.json.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.jkcredit.invoice.common.CommonConstants;
import com.jkcredit.invoice.model.entity.user.User;
import com.jkcredit.invoice.service.user.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: sunzhaoning
 * @create: 2019-05-29 14:04
 * @version: V1.0
 **/
@Service
public class AuthenticationServiceImpl implements AuthenticationService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String getToken(User user) {
        String token = "";
        try {

            token = JWT.create()
                    // 将 user id 保存到 token 里面
                    .withAudience(user.getId().toString())
                    // 以 password 作为 token 的密钥
                    .sign(Algorithm.HMAC256(user.getPassword() + user.getUserName() + System.currentTimeMillis()));
            redisTemplate.opsForValue().set(CommonConstants.TOKEN_KEY + token, new JSONObject(user), 60 * 60 * 24, TimeUnit.SECONDS);
        } catch (UnsupportedEncodingException ignore) {
        }
        return token;
    }
}
