package com.hz.pm.api.user.security.auth.code;

import cn.hutool.core.util.StrUtil;
import com.hz.pm.api.common.util.StrUtils;
import com.hz.pm.api.user.manage.AuthCodeLoginManage;
import com.hz.pm.api.user.security.model.WebRequestDetails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
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;

/**
 * <p>
 * AuthCodeFilter
 * </p>
 *
 * @author WendyYang
 * @since 13:25 2023/12/28
 */
public class AuthCodeLoginFilter extends AbstractAuthenticationProcessingFilter {

    private static final String AUTH_CODE = "authCode";

    private final AuthCodeLoginManage authCodeLoginManage;

    // ===================================================================================================

    public AuthCodeLoginFilter(String processingUrl, AuthCodeLoginManage authCodeLoginManage) {
        super(new AntPathRequestMatcher(processingUrl, HttpMethod.GET.name()));
        this.authCodeLoginManage = authCodeLoginManage;
    }

    // ========================================================================================================

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {
        String authCode = StrUtils.trim(request.getParameter(AUTH_CODE));
        if (StringUtils.isBlank(authCode)) {
            throw new BadCredentialsException("授权码不能为空");
        }
        String userId = authCodeLoginManage.getUserIdByAuthCode(authCode);
        if (StrUtil.isBlank(userId)) {
            throw new BadCredentialsException("授权码无效");
        }
        try {
            AuthCodeToken authRequest = new AuthCodeToken(userId, userId);
            authRequest.setDetails(new WebRequestDetails(request));
            return this.getAuthenticationManager().authenticate(authRequest);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BadCredentialsException("授权失败");
        }
    }

}
