package com.org.utils;

import com.org.system.entity.LoginUser;
import com.org.utils.exception.CustomException;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/** 安全服务工具类 **/
public class SecurityUtil {

    /** 获取Authentication **/
    public static Authentication getAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); }

    /**
     * 当前是否登录
     *
     * @return
     */
    public static boolean isLogin(){
        String principal = getAuthentication().getPrincipal().toString();
        if("anonymousUser".equals(principal)) return false;
        return true;
    }

    /** 获取用户 **/
    public static LoginUser getLoginUser() {
        try {
            return (LoginUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw new CustomException("获取用户信息异常", HttpStatus.UNAUTHORIZED.value());
        }
    }

    /** 获取用户ID **/
    public static Long getUserId() {
        try {
            return getLoginUser().getUser().getId();
        } catch (Exception e) {
            throw new CustomException("获取用户账户异常", HttpStatus.UNAUTHORIZED.value());
        }
    }

    /** 获取用户账户 **/
    public static String getUsername() {
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            throw new CustomException("获取用户账户异常", HttpStatus.UNAUTHORIZED.value());
        }
    }

}
