package com.qs.mp.framework.security.mobile.auth;

import cn.jsms.api.ValidSMSResult;
import com.qs.mp.common.exception.user.CaptchaExpireException;
import com.qs.mp.common.jsms.JSMSUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;


/**
 *
 * @auther duota
 * @create 2021 2021/9/3 11:57 上午
 * @describe
 *
 */

public class SmsCodeAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {



        SmsCodeAuthenticationToken smsCodeAuthenticationToken = (SmsCodeAuthenticationToken) authentication;
        UserDetails user = userDetailsService.loadUserByUsername((String)smsCodeAuthenticationToken.getPrincipal());
        logger.info("load provider...Principal:"+(String)smsCodeAuthenticationToken.getPrincipal() +" Credentials:"+smsCodeAuthenticationToken.getCredentials());
        if(user == null){
            throw new InternalAuthenticationServiceException("用户不存在");
        }
        //校验短信验证码
        ValidSMSResult res = JSMSUtils.sendValidSMSCode(
            (String) smsCodeAuthenticationToken.getCredentials(), smsCodeAuthenticationToken.getCode());

        if(res == null || !res.getIsValid()){
            throw new CaptchaExpireException();
        }
        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(user,user.getAuthorities());
        authenticationResult.setDetails(smsCodeAuthenticationToken.getDetails());

        return authenticationResult;
    }

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

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

}
