package com.supServer.common;


import com.supServer.common.exception.user.UserPasswordNotMatchException;
import com.supServer.framework.redis.RedisCache;
import com.supServer.framework.security.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 短信登录自定义校验类
 */

@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException, UserPasswordNotMatchException {
        String name = authentication.getName();
        String password = (String) authentication.getCredentials();
        UserDetails user = userDetailsService.loadUserByUsername(name);
        String encoderPassword = bCryptPasswordEncoder.encode(password);
        // 数据库账号密码的校验能通过就通过
        if (bCryptPasswordEncoder.matches(password, user.getPassword())) {
            return new UsernamePasswordAuthenticationToken(user, encoderPassword);
        }
        Boolean checkValid = checkValid(name, password);
        if (checkValid && null != user) {
            return new UsernamePasswordAuthenticationToken(user, password);
        } else {
            // 如果都登录不了，就返回异常输出
            throw new UserPasswordNotMatchException();
        }
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }


    /**
     * 非账号密码登录-验证合法,短信登陆已经验证过验证码，直接返回 true
     * @param userName
     * @param pwd
     */
    public boolean checkValid(String userName, String pwd) {
//        Object code = redisCache.getCacheObject(userName);
//        if (null != code &&  code.toString().equals(pwd)) {
//            return true;
//        }
        return true;
    }

}
