package com.cpop.core.gateway.sys;

import com.cpop.core.base.enums.UserType;
import com.cpop.core.gateway.miniProgram.MiniProgramAuthenticationToken;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationServiceException;
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.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author DB
 * @createTime 2023/10/19 9:27
 * @description
 */
public class SysAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public SysAuthenticationFilter() {
        super(new AntPathRequestMatcher("/login", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if (!"POST".equals(request.getMethod())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        //读取表单
        ObjectMapper mapper = new ObjectMapper();
        InputStream inputStream;
        Map authenticationBean;
        try {
            inputStream = request.getInputStream();
            authenticationBean = mapper.readValue(inputStream, Map.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String principal = (String) authenticationBean.get("username");
        String password = (String) authenticationBean.get("password");
        UserType userType = UserType.valueOf(authenticationBean.get("userType").toString());
        principal = principal.trim();
        //传递信息
        HashMap<String, Object> credentials = new HashMap<>(2);
        credentials.put("password", password);
        credentials.put("userType", userType);
        SysAuthenticationToken authRequest = new SysAuthenticationToken(principal, credentials);
        this.setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

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