package com.cpop.core.gateway.miniProgram;

import com.cpop.core.base.entity.LoginUser;
import com.cpop.core.base.enums.UserType;
import com.cpop.core.service.CoreService;
import com.cpop.core.utils.SpringUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import java.util.Map;

/**
 * @author DB
 * @Description: 自定义校验过程
 * @create 2023-08-23 21:13
 */
public class MiniProgramAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 这个获取表单输入中返回的用户名;
        String phone =(String) authentication.getPrincipal();
        // 这个是表单中输入的密码；
        Map<String,Object> credentials = (Map<String, Object>) authentication.getCredentials();
        UserType userType = (UserType) credentials.get("userType");
        LoginUser loginUser = SpringUtils.getBean(CoreService.class).loadUserByPhone(phone, userType, credentials);
        loginUser.setUserType(UserType.MINI_USER);
        MiniProgramAuthenticationToken result = new MiniProgramAuthenticationToken(phone, loginUser);
        result.setDetails(loginUser);
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        //providerManager会遍历所有;securityConfig中注册的provider集合;根据此方法返回true或false来决定由哪个provider;去校验请求过来的authentication
        return (MiniProgramAuthenticationToken.class.isAssignableFrom(authentication));
    }

}
