package cn.reghao.tnb.common.auth;

import java.util.HashSet;
import java.util.Set;

/**
 * @author reghao
 * @date 2023-06-02 10:48:59
 */
public class UserContext implements AutoCloseable {
    static final ThreadLocal<LoginUser> CURRENT = new ThreadLocal<>();

    public UserContext(LoginUser loginUser) {
        CURRENT.set(loginUser);
    }

    public static LoginUser getLoginUser() {
        return CURRENT.get();
    }

    public static long getUserId() {
        LoginUser loginUser = CURRENT.get();
        return loginUser != null ? loginUser.getUserId() : -1;
    }

    public static String getLoginId() {
        LoginUser loginUser = CURRENT.get();
        return loginUser != null ? loginUser.getLoginId() : "-1";
    }

    public static Set<String> getUserRoles() {
        LoginUser loginUser = CURRENT.get();
        return loginUser != null ? loginUser.getRoles() : new HashSet<>();
    }

    @Override
    public void close() {
        CURRENT.remove();
    }
}
