package cn.reghao.tnb.auth.app.security.form;

import cn.reghao.tnb.common.web.ServletUtil;
import cn.reghao.tnb.auth.app.model.constant.LoginPlat;
import cn.reghao.tnb.auth.app.model.constant.LoginType;
import org.springframework.security.authentication.DisabledException;
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 jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 第三方登入 filter
 *
 * @author reghao
 * @date 2023-07-31 15:55:59
 */
public class ThirdPartyAuthFilter extends AbstractAuthenticationProcessingFilter {
    public ThirdPartyAuthFilter(String authUrl, String httpMethod) {
        super(new AntPathRequestMatcher(authUrl, httpMethod));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException, ServletException {
        String uri = request.getRequestURI();
        String oauthName = uri.replace("/oauth/redirect/", "");

        String code = request.getParameter("code");
        if (code == null) {
            String errMsg = String.format("没有获取到 %s 的 code", oauthName);
            throw new DisabledException(errMsg);
        }

        int plat = LoginPlat.web.getValue();
        String loginId = ServletUtil.getSessionId();
        int loginType = LoginType.thirdParty.getValue();
        boolean rememberMe = true;
        String principal = oauthName;
        String credential = code;
        AccountAuthToken preAuthToken = new AccountAuthToken(plat, loginId, loginType, rememberMe, principal, credential);
        return this.getAuthenticationManager().authenticate(preAuthToken);
    }
}
