package com.ningdatech.kqapi.security.password;

import cn.hutool.core.util.StrUtil;
import com.ningdatech.kqapi.common.exception.BizException;
import com.ningdatech.kqapi.security.constant.AuthConst;
import com.ningdatech.kqapi.security.model.WebRequestDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
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;

/**
 * <p>
 * UsernamePasswordAuthFilter
 * </p>
 *
 * @author WendyYang
 * @since 2023/9/1
 **/
@Slf4j
public class UsernamePasswordAuthFilter extends AbstractAuthenticationProcessingFilter {

    private final Boolean postOnly;

    public UsernamePasswordAuthFilter(String processingUrl, Boolean postOnly) {
        super(new AntPathRequestMatcher(processingUrl, HttpMethod.POST.name()));
        this.postOnly = postOnly;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        LocalDateTime now = LocalDateTime.now();
        if (Boolean.TRUE.equals(postOnly) && !request.getMethod().equals(HttpMethod.POST.name())) {
            throw BizException.wrap("请求方法错误");
        }
        String username = StrUtil.trim(request.getParameter(AuthConst.USERNAME));
        String password = StrUtil.trim(request.getParameter(AuthConst.PASSWORD));
        try {
            UsernamePasswordAuthToken authRequest = new UsernamePasswordAuthToken(username, password);
            authRequest.setDetails(new WebRequestDetails(request, now));
            return this.getAuthenticationManager().authenticate(authRequest);
        } catch (BadCredentialsException | UsernameNotFoundException e) {
            throw e;
        } catch (Exception e) {
            log.error("登录失败：{}", e.getMessage());
            throw BizException.wrap("登录失败，请联系管理员！");
        }
    }


}
