package com.zksy.framework.security.moblie;

import com.zksy.common.core.domain.model.LoginUser;
import com.zksy.common.exception.ServiceException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

/**
 * @author ：BIN.LI
 * @date ：2022/4/27 10:35
 * @description：
 */
public class MobileAuthenticationProvider implements AuthenticationProvider {
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken) authentication;
        LoginUser loginUser = (LoginUser) mobileAuthenticationToken.getPrincipal();
        LoginUser userVo = userService.findUserByMobile(loginUser.getUser());
        if (userVo == null) {
            throw new ServiceException("手机号不存在:" + userVo.getUser().getPhonenumber());
        }
        MobileAuthenticationToken authenticationToken = new MobileAuthenticationToken(userVo, userVo.getAuthorities());
        authenticationToken.setDetails(mobileAuthenticationToken.getDetails());
        return authenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MobileAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
