package com.yami.shop.security.platform.util;

import com.yami.shop.security.comment.exception.UnauthorizedException;
import com.yami.shop.security.platform.model.YamiSysUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

/**
 *
 * @author LGH
 */
@UtilityClass
public class SecurityUtils {


    /**
     * 获取用户
     */
    public YamiSysUser getSysUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null) {
            throw new UnauthorizedException("无法获取用户信息");
        }

        if (!(authentication instanceof OAuth2Authentication)) {
            throw new UnauthorizedException("无法获取用户信息");
        }
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication)authentication;

        YamiSysUser details = (YamiSysUser) oAuth2Authentication.getUserAuthentication().getDetails();
        if (details == null) {
            throw new UnauthorizedException("无法获取用户信息");
        }
        return details;
    }
}
