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

import cn.reghao.tnb.auth.app.model.constant.LoginType;
import cn.reghao.tnb.auth.app.service.AccountLoginService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * 对用户登入进行认证
 *
 * @author reghao
 * @date 2022-07-08 14:57:40
 */
@Component
public class AccountAuthProvider implements AuthenticationProvider {
    private final AccountLoginService accountLoginService;

    public AccountAuthProvider(AccountLoginService accountLoginService) {
        this.accountLoginService = accountLoginService;
    }

    /**
     * 对 Authentication 对象进行认证
     * 参照 DaoAuthenticationProvider
     *
     * @param
     * @return
     * @date 2020-05-06 上午11:16
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        AccountAuthToken preAuthToken = (AccountAuthToken) authentication;
        int loginType = preAuthToken.getLoginType();
        AccountAuthToken authToken;
        if (loginType == LoginType.mobileCode.getValue()) {
            authToken = accountLoginService.authByVerifyCode(preAuthToken);
        } else if (loginType == LoginType.usernamePassword.getValue()) {
            authToken = accountLoginService.authByPassword(preAuthToken);
        } else {
            throw new DisabledException("登入类型错误");
        }
        return authToken;
    }

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