package com.inkasso.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.inkasso.adapter.bean.AbstractUser;
import com.inkasso.adapter.constance.AuthConstance;
import com.inkasso.auth.annotation.AuthenticationType;
import com.inkasso.auth.service.AbstractAuthentication;
import com.inkasso.factoring.system.user.model.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@AuthenticationType(type = "backendUser")
public class BackEndUserCheckAuthentication implements AbstractAuthentication {

    @Autowired
    private RedisTemplate redisTemplate;

    private final static String prefix = "backend:";

    @Override
    public AbstractUser auth(HttpServletRequest request) {
        //获取request 中的 token
        String access = request.getHeader(AuthConstance.X_Token);
        if (StringUtils.hasLength(access)) {
            JSONObject obj = (JSONObject) redisTemplate.opsForValue().get(prefix + access);
            if (obj != null) {
                UserDTO abstractUser = JSONObject.toJavaObject(obj, UserDTO.class);
                return abstractUser;
            }
        }
        return null;
    }
}
