package com.ai.da.common.security;

import com.ai.da.common.config.RsaProperties;
import com.ai.da.common.utils.RsaDecryptUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * @author: dangweijian
 * @description: 登录校验处理类
 * @create: 2020-07-09 14:39
 **/
@Component
public class UserAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        try {
            password = RsaDecryptUtils.decrypt(password, RsaProperties.privateKey);
        } catch (Exception e) {
            throw new BadCredentialsException("用户名或密码错误");
        }
//        User user = userService.getByUsername(userName);
//        if (user == null) {
//            throw new UsernameNotFoundException("用户名或密码错误");
//        }
//        //账号已冻结
//        if(user.getStatus() == 1){
//            throw new LockedException("账号已冻结");
//        }
//        if(!passwordEncoder.matches(password, user.getPassword())){
//            throw new BadCredentialsException("用户名或密码错误");
//        }
//        //超级管理员
//        Set<SimpleGrantedAuthority> authorities = new HashSet<>();
//        if(user.getIsAdmin()) {
//            authorities.add(new SimpleGrantedAuthority("admin"));
//            return new UsernamePasswordAuthenticationToken(user, password, authorities);
//        }else {
//            List<RoleMenuDto> userMenus = menuService.getRoleMenusByUserId(user.getId(), null);
//            if(CollUtil.isNotEmpty(userMenus)){
//                authorities.addAll(userMenus.stream().map(RoleMenuDto::getPermission).filter(StringUtils::isNotEmpty).map(SimpleGrantedAuthority::new).collect(Collectors.toSet()));
//            }
//            return new UsernamePasswordAuthenticationToken(user, password, authorities);
//        }
        return null;
    }

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