package com.njcn.auth.security.provider;

import com.njcn.auth.security.token.SmsCodeAuthenticationToken;
import com.njcn.auth.service.UserDetailsServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.user.enums.UserResponseEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * 手机短信码验证完后，返回用户的
 * @author hongawen
 * @version 1.0.0
 * @date 2021年06月08日 15:43
 */
@Slf4j
@Component
@AllArgsConstructor
public class SmsAuthenticationProvider extends AbstractSmsAuthenticationProvider {

    private final UserDetailsServiceImpl userDetailsService;


    /**
     * 校验密码有效性.
     * 因为手机号验证码登录，验证码没问题后，密码无需校验，直接返回该用户的token信息便可以
     *
     * @param userDetails    用户详细信息
     * @param authentication 用户登录的密码
     * @throws AuthenticationException .
     */
    @Override
    protected void additionalAuthenticationChecks(
            UserDetails userDetails, SmsCodeAuthenticationToken authentication)
            throws AuthenticationException {

    }

    /**
     * 获取用户
     *
     * @param phone       手机号
     * @param authentication 认证token
     * @throws AuthenticationException .
     */
    @Override
    protected UserDetails retrieveUser(
            String phone, SmsCodeAuthenticationToken authentication)
            throws AuthenticationException {
        //根据手机号获取用户信息
        UserDetails loadedUser = userDetailsService.loadUserByPhone(phone);
        if (loadedUser == null) {
            throw new BusinessException(UserResponseEnum.LOGIN_PHONE_NOT_REGISTER);
        }
        return loadedUser;
    }


    /**
     * 授权持久化.
     */
    @Override
    protected Authentication createSuccessAuthentication(Object principal,
                                                         Authentication authentication, UserDetails user) {
        return super.createSuccessAuthentication(principal, authentication, user);
    }


}