package com.simuwang.shiro.utils;

import com.simuwang.shiro.core.ShiroUser;
import org.apache.shiro.authc.AuthenticationException;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wangzaijun
 * @date 2024/9/14 15:39
 * @description 登录用户工具
 */
public class UserUtils {
    private static final ThreadLocal<Map<String, Object>> TOKEN_PRINCIPAL_THREAD = ThreadLocal.withInitial(HashMap::new);

    public static Object getPrincipal() {
        return TOKEN_PRINCIPAL_THREAD.get().get("principal");
    }

    public static void setPrincipal(Object principal) {
        TOKEN_PRINCIPAL_THREAD.get().put("principal", principal);
    }

//    public static Subject getSubject() {
//        return SecurityUtils.getSubject();
//    }

//    /**
//     * 获取当前登录的用户信息
//     *
//     * @return 当前登录用户
//     */
//    public static ShiroUser getLoginUser() {
//        Subject subject = SecurityUtils.getSubject();
//        return getLoginUser(subject);
//    }

    /**
     * 获取当前登录的用户信息
     *
     * @return 当前登录用户
     */
    public static ShiroUser getLoginUser() {
        Object principal = getPrincipal();
        if (principal instanceof ShiroUser shiroUser) {
            return shiroUser;
        }
        throw new AuthenticationException();
    }
}
