package com.cool.bang.common.tools.secure;

import com.cool.bang.modules.system.domain.po.User;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Spring Security (安全框架工具类)
 *
 * @author PeiZhi Guo
 * 2021-2-18 15:11
 */
public class SecurityUtil {

    /**
     * 获取用户
     *
     * Return SysUser
     **/
    public static User getCurrentUser() {
        return (User) getAuthentication().getPrincipal();
    }

    /**
     * 获取 Authentication
     *
     * Return Authentication 权鉴对象
     */
    public static Authentication getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            return authentication;
        }
        return null;
    }

    /**
     * 验证当前用户是否登录
     *
     * Return boolean 是否登录
     */
    public static boolean isAuthentication() {
        // if security session eq s-id is not null to index
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return !(auth instanceof AnonymousAuthenticationToken);
    }
}
