package me.zhengjie.modules.security.service;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.*;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Zheng Jie
 * @date 2018-11-22
 */
@Service("userDetailsService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;

    private final RoleService roleService;

    public UserDetailsServiceImpl(UserService userService, RoleService roleService) {
        this.userService = userService;
        this.roleService = roleService;
    }

    @Override
    public JwtUserDto loadUserByUsername(String username){
        UserDto user = userService.findByName(username);
        if (user == null) {
            throw new BadRequestException("账号不存在");
        } else {
            if (!user.getEnabled()) {
                throw new BadRequestException("账号未激活");
            }
            return new JwtUserDto(
                    user,
                    roleService.mapToGrantedAuthorities(user)
            );
        }
    }
}

@@ -86,24 +86,78 @@
 tException;%0A
+import me.zhengjie.exception.EntityNotFoundException;%0A
 import me.zh
@@ -360,17 +360,23 @@
 ice.dto.
-*
+UserDto
 ;%0Aimport
@@ -434,32 +434,112 @@
 DetailsService;%0A
+import org.springframework.security.core.userdetails.UsernameNotFoundException;%0A
 import org.sprin
@@ -1278,16 +1278,17 @@
 sername)
+ 
 %7B%0A      
@@ -1297,16 +1297,48 @@
 UserDto 
+user;%0A        try %7B%0A            
 user = u
@@ -1370,16 +1370,212 @@
 rname);%0A
+        %7D catch (EntityNotFoundException e) %7B%0A            // SpringSecurity%E4%BC%9A%E8%87%AA%E5%8A%A8%E8%BD%AC%E6%8D%A2UsernameNotFoundException%E4%B8%BABadCredentialsException%0A            throw new UsernameNotFoundException(%22%22, e);%0A        %7D%0A
         
@@ -1612,34 +1612,40 @@
   throw new 
-BadRequest
+UsernameNotFound
 Exception(%22%E8%B4%A6
@@ -1647,13 +1647,8 @@
 on(%22
-%E8%B4%A6%E5%8F%B7%E4%B8%8D%E5%AD%98%E5%9C%A8
 %22);%0A

修复不存在账号登录时，userService.findByName抛出异常，而loadUserByUsername未将其捕获处理的bug