package ink.wgink.login.base.authentication.user;

import ink.wgink.login.base.authentication.BaseAuthenticationProcessingFilter;
import ink.wgink.login.base.exceptions.UserAuthenticationException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: WebLoginAuthenticationFilter
 * @Description: web端登录过滤器
 * @Author: WangGeng
 * @Date: 2020/5/24 9:24 下午
 * @Version: 1.0
 **/
public class UserAuthenticationFilter extends BaseAuthenticationProcessingFilter {

    public UserAuthenticationFilter(String loginProcessUrl) {
        super(new AntPathRequestMatcher(loginProcessUrl, "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        checkVerificationCode(request);
        checkPostMethod(request);
        checkReferToken(request);

        String username = request.getParameter(KEY_USERNAME);
        String password = request.getParameter(KEY_PASSWORD);
        if (StringUtils.isBlank(username)) {
            throw new UserAuthenticationException("用户名不能为空");
        }
        if (StringUtils.isBlank(password)) {
            throw new UserAuthenticationException("密码不能为空");
        }
        username = username.trim();
        UserAuthenticationToken authRequest = new UserAuthenticationToken(username, password);
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected void setDetails(HttpServletRequest request, UserAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}
