package com.ruoyi.framework.web.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.RedisUtils;
import com.ruoyi.common.utils.ServletUtils;
import lombok.SneakyThrows;

import java.net.URLDecoder;

/**
 * @Description: TODO
 * @Author: huangcheng
 * @Date: 2022/2/24
 * @Version V1.0
 */
public class UserUtil {

    /**
     * 从缓存中取用户信息
     *
     * @return
     */
    @SneakyThrows
    public static LoginUser getCacheLoginUser() {
        String userStr = ServletUtils.getRequest().getHeader("user");
        if (StrUtil.isBlank(userStr)) {
            throw new ServiceException("请重新登录系统！", 90000);
        }
        userStr = URLDecoder.decode(userStr, "UTF-8");
        JSONObject userJsonObject = JSONUtil.parseObj(userStr);
        String id = userJsonObject.getStr("id");
        // 先从缓存中获取
        String userKey = Constants.LOGIN_TOKEN_KEY + id;
        LoginUser user = RedisUtils.getCacheObject(userKey);
        if (ObjectUtil.isNull(user)) {
            throw new ServiceException("登录失效，请重新登录-90004");
        }
        return user;
    }
}
