JwtUserDetailsService.java 2.3 KB
Newer Older
1
package me.zhengjie.modules.security.service;
郑杰 已提交
2

3 4 5 6
import me.zhengjie.modules.system.domain.Permission;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.exception.EntityNotFoundException;
7 8
import me.zhengjie.modules.system.repository.PermissionRepository;
import me.zhengjie.modules.system.repository.RoleRepository;
9
import me.zhengjie.modules.security.security.JwtUser;
10
import me.zhengjie.modules.system.service.UserService;
郑杰 已提交
11
import org.springframework.beans.factory.annotation.Autowired;
12
import org.springframework.cache.annotation.Cacheable;
郑杰 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

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

    @Autowired
34
    private UserService userService;
郑杰 已提交
35

36
    @Autowired
37
    private JwtPermissionService permissionService;
38

郑杰 已提交
39 40 41
    @Override
    public UserDetails loadUserByUsername(String username){

42
        User user = userService.findByName(username);
郑杰 已提交
43 44 45
        if (user == null) {
            throw new EntityNotFoundException(User.class, "name", username);
        } else {
46
            return createJwtUser(user);
郑杰 已提交
47 48 49
        }
    }

50
    public UserDetails createJwtUser(User user) {
郑杰 已提交
51 52 53 54 55 56
        return new JwtUser(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                user.getAvatar(),
                user.getEmail(),
57 58 59 60
                user.getPhone(),
                user.getDept().getName(),
                user.getJob().getName(),
                permissionService.mapToGrantedAuthorities(user),
郑杰 已提交
61
                user.getEnabled(),
62
                user.getCreateTime(),
郑杰 已提交
63 64 65 66
                user.getLastPasswordResetTime()
        );
    }
}