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

import com.yami.shop.common.util.HttpContextUtils;
import com.yami.shop.common.util.IPHelper;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.comment.exception.UnauthorizedException;
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 YamiUser getUser() {
        if (!HttpContextUtils.getHttpServletRequest().getRequestURI().startsWith("/prod/")){
            if (!HttpContextUtils.getHttpServletRequest().getRequestURI().startsWith("/p/") &&
                    !HttpContextUtils.getHttpServletRequest().getRequestURI().startsWith("/user/registerOrBindUser")) {
                throw new RuntimeException("用户相关的请求，应该以/p开头！！！");
            }
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

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

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

        YamiUser details = (YamiUser) oAuth2Authentication.getUserAuthentication().getDetails();

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