package com.ningdatech.pmapi.user.security.auth.agent;

import com.ningdatech.basic.exception.BizException;
import com.ningdatech.pmapi.user.security.auth.model.WebRequestDetails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

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

/**
 * @Author LiuXinXin
 * @Date 2020/8/3 8:46 下午
 * @Version 1.0
 **/
public class AgentAuthFilter extends AbstractAuthenticationProcessingFilter {

    private boolean postOnly = true;

    private static final String USER_ID_PARAMETER = "userId";

    // ~ Constructors
    // ===================================================================================================

    public AgentAuthFilter(String processingUrl) {
        super(new AntPathRequestMatcher(processingUrl, HttpMethod.POST.name()));
    }

    // ~ Methods
    // ========================================================================================================

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        if (postOnly && !request.getMethod().equals(HttpMethod.POST.name())) {
            throw new AuthenticationServiceException("请求方法错误");
        }
        String userId = request.getParameter(USER_ID_PARAMETER);
        if (StringUtils.isBlank(userId)) {
            throw new BadCredentialsException("用户id 不能为空");
        }

        userId = trim(userId);
        try {
            AgentAuthToken authRequest = new AgentAuthToken(userId, userId);
            authRequest.setDetails(new WebRequestDetails(request));
            return this.getAuthenticationManager().authenticate(authRequest);
        } catch (AuthenticationException e) {
            throw new BadCredentialsException("用户id 不能为空");
        } catch (BizException e) {
            throw new BadCredentialsException(e.getMessage());
        } catch (Exception e) {
            throw new InternalAuthenticationServiceException("授权失败：", e);
        }
    }

    private String trim(String trimStr) {
        if (StringUtils.isNotBlank(trimStr)) {
            return trimStr.trim();
        }
        return null;
    }
}
