package com.njzscloud.common.security.support;

import cn.hutool.core.util.StrUtil;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.authentication.AuthenticationDetailsSource;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>用户认证详情</p>
 * <p>获取用户 IP, Nginx 反向代理 $remote_addr X-Real-IP</p>
 * <p>获取用户代理, Nginx 反向代理 $http_user_agent X-Real-UA</p>
 */
@Getter
@Setter
@EqualsAndHashCode
public class AuthenticationDetails {

    /**
     * 从请求对象中获取额外登录信息, IP 或 用户代理
     */
    private static final AuthenticationDetailsSource<HttpServletRequest, AuthenticationDetails> AUTHENTICATION_DETAILS_SOURCE = AuthenticationDetails::new;


    /**
     * 用户 IP
     */
    private final String remoteAddress;

    /**
     * 用户 Http 代理
     */
    private final String userAgent;

    public AuthenticationDetails(HttpServletRequest request) {
        String x_real_ip = request.getHeader("X-Real-IP");
        if (StrUtil.isBlank(x_real_ip)) {
            this.remoteAddress = request.getRemoteAddr();
        } else {
            this.remoteAddress = x_real_ip;
        }
        String x_real_ua = request.getHeader("X-Real-UA");
        if (StrUtil.isBlank(x_real_ua)) {
            this.userAgent = request.getHeader("UserDetail-Agent");
        } else {
            this.userAgent = x_real_ua;
        }
    }

    public static AuthenticationDetails create(HttpServletRequest request) {
        return AUTHENTICATION_DETAILS_SOURCE.buildDetails(request);
    }
}
