package com.amms.security;

import com.amms.domain.SysUser;
import com.amms.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class SysUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * SpringSecurity会调用这个方法验证用户名和密码
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException 用户不存在异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 根据用户名查询用户
        SysUser sysUser = sysUserMapper.selectByUsername(username);

        // 如果查到了用户，就返回一个SpringSecurity的UserDetails
        if (sysUser != null) {
            return sysUser;
        } else {
            throw new UsernameNotFoundException(username);
        }
    }
}
