package com.ningdatech.kqapi.security.model;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import lombok.Getter;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <p>
 * WebRequestDetails
 * </p>
 *
 * @author WendyYang
 * @since 2023/6/7
 **/
@Getter
public class WebRequestDetails extends WebAuthenticationDetails {

    private static final long serialVersionUID = -4466339683132696235L;

    private final String requestIp;

    private final String requestUri;

    private final String method;

    private final String servletPath;

    private final String requestUrl;

    private final String userAgent;

    private final LocalDateTime loginTime;

    /**
     * Records the remote address and will also set the session Id if a session already
     * exists (it won't create one).
     *
     * @param request that the authentication request was received from
     */
    public WebRequestDetails(HttpServletRequest request, LocalDateTime loginTime) {
        super(request);
        this.requestUri = request.getRequestURI();
        this.method = request.getMethod();
        this.servletPath = request.getServletPath();
        this.requestUrl = request.getRequestURL().toString();
        this.requestIp = ServletUtil.getClientIP(request);
        this.userAgent = StrUtil.sub(request.getHeader("user-agent"), 0, 500);
        this.loginTime = loginTime;
    }

}
