wuyouming666
2024-05-08 f188d9b3bfd147f8e6fc8342f800df3ee2e74fec
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package com.mes.userinfo.service.impl;
 
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.mes.common.config.Const;
import com.mes.common.utils.JwtUtil;
import com.mes.common.utils.RedisUtil;
import com.mes.common.utils.UserInfoUtils;
import com.mes.entity.request.GeneralRequest;
import com.mes.menu.mapper.SysMenuMapper;
import com.mes.role.entity.SysRole;
import com.mes.role.entity.SysRoleMenu;
import com.mes.role.service.SysRoleService;
import com.mes.userinfo.entity.LoginUser;
import com.mes.userinfo.entity.SysUser;
import com.mes.userinfo.entity.SysUserRole;
import com.mes.userinfo.entity.vo.SysUserVO;
import com.mes.userinfo.mapper.SysUserMapper;
import com.mes.userinfo.service.SysUserRoleService;
import com.mes.userinfo.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
 
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author zhoush
 * @since 2024-04-11
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService, UserDetailsService {
 
    @Autowired
    private AuthenticationManager authenticationManager;
 
    @Autowired
    private RedisUtil redisUtil;
 
    @Resource
    private SysMenuMapper sysMenuMapper;
 
    @Resource
    private SysUserRoleService sysUserRoleService;
 
    @Resource
    private SysRoleService sysRoleService;
 
    @Resource
    BCryptPasswordEncoder passwordEncoder;
 
    @Override
    public Map<String, String> login(SysUser user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.generateToken(userId);
 
        //查询权限信息
//        List<String> perms = sysMenuMapper.selectPermsByUserId(userId);
        //authenticate存入redis
        redisUtil.setCacheObject("login:" + userId, loginUser);
        //把token响应给前端
        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return map;
    }
 
    @Override
    public String logout() {
        log.info("用户退出");
        SysUser user = UserInfoUtils.get();
        redisUtil.deleteObject("login:" + user.getId());
        return "注销成功";
    }
 
    @Transactional
    @Override
    public String saveUser(SysUserVO user) {
        log.info("保存用户信息");
        // 默认密码
        String password = passwordEncoder.encode(Const.DEFULT_PASSWORD);
        user.setPassword(password);
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(user, sysUser);
        this.save(sysUser);
        saveUserRole(user.getRoleList(), sysUser.getId());
        return "success";
    }
 
    @Transactional
    @Override
    public SysUserVO updateUser(SysUserVO user) {
        log.info("更新用户信息");
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(user, sysUser);
        this.updateById(sysUser);
        log.info("删除用户角色信息");
        List<Long> roleIds = user.getRoleList().stream().map(SysRole::getId).collect(Collectors.toList());
        sysUserRoleService.remove(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, sysUser.getId()).in(CollectionUtil.isNotEmpty(roleIds), SysUserRole::getRoleId, roleIds));
        log.info("保存用户角色信息");
        saveUserRole(user.getRoleList(), sysUser.getId());
        return user;
    }
 
    @Override
    public String resetPassword(Long userId) {
        log.info("重置密码为{}", Const.DEFULT_PASSWORD);
        SysUser sysUser = new SysUser();
        sysUser.setId(userId);
        String password = passwordEncoder.encode(Const.DEFULT_PASSWORD);
        sysUser.setPassword(password);
        this.updateById(sysUser);
        return "success";
    }
 
    @Override
    public SysUser queryByUserName(String userName) {
        return baseMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, userName));
    }
 
    @Override
    public List<SysUserVO> listByUserName(GeneralRequest request) {
        MPJLambdaWrapper<SysUser> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(SysUser.class)
                .selectCollection(SysRole.class, SysUserVO::getRoleList)
                .leftJoin(SysUserRole.class, SysUserRole::getUserId, SysUser::getId)
                .leftJoin(SysRole.class, SysRole::getId, SysUserRole::getRoleId)
                .like(StringUtils.hasText(request.getKey()), SysUser::getUserName, request.getKey());
        return baseMapper.selectJoinList(SysUserVO.class, wrapper);
    }
 
    @Transactional
    @Override
    public String deleteUser(List<Long> ids) {
        this.removeByIds(ids);
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("user_id", ids));
        return "success";
 
    }
 
    @Override
    public List<String> getUserAuthorityInfo(Long userId) {
        SysUser sysUser = baseMapper.selectById(userId);
 
        //  ROLE_admin,ROLE_normal,sys:user:list,....
        String authority = "";
        if (redisUtil.hasKey("GrantedAuthority:" + sysUser.getUserName())) {
            authority = redisUtil.getCacheObject("GrantedAuthority:" + sysUser.getUserName());
 
        } else {
            // 获取角色编码
            List<SysRole> roles = sysRoleService.list(new QueryWrapper<SysRole>()
                    .inSql("id", "select role_id from sys_user_role where user_id = " + userId));
 
            if (roles.size() > 0) {
                String roleCodes = roles.stream().map(r -> "ROLE_" + r.getRoleKey()).collect(Collectors.joining(","));
                authority = roleCodes.concat(",");
            }
 
            // 获取菜单操作编码
            List<String> perms = sysMenuMapper.selectPermsByUserId(userId);
            if (perms.size() > 0) {
                String menuPerms = String.join(",", perms);
                authority = authority.concat(menuPerms);
            }
 
            redisUtil.setCacheObject("GrantedAuthority:" + sysUser.getUserName(), authority, 60 * 60, TimeUnit.SECONDS);
        }
        return Arrays.stream(authority.split(",")).collect(Collectors.toList());
    }
 
    @Override
    public void clearUserAuthorityInfo(String userName) {
        redisUtil.deleteObject("GrantedAuthority:" + userName);
    }
 
    @Override
    public void clearUserAuthorityInfoByRoleId(Long roleId) {
        List<SysUser> sysUsers = this.list(new QueryWrapper<SysUser>()
                .inSql("id", "select user_id from sys_user_role where role_id = " + roleId));
 
        sysUsers.forEach(u -> {
            this.clearUserAuthorityInfo(u.getUserName());
        });
 
    }
 
    @Override
    public void clearUserAuthorityInfoByMenuId(Long menuId) {
        MPJLambdaWrapper<SysUserRole> wrapper = new MPJLambdaWrapper<SysUserRole>().selectAll(SysUser.class).distinct()
                .leftJoin(SysUser.class, SysUser::getId, SysUserRole::getUserId)
                .leftJoin(SysRoleMenu.class, SysRoleMenu::getRoleId, SysUserRole::getRoleId)
                .eq(SysRoleMenu::getMenuId, menuId);
        List<SysUser> sysUsers = sysUserRoleService.selectJoinList(SysUser.class, wrapper);
        sysUsers.forEach(u -> {
            this.clearUserAuthorityInfo(u.getUserName());
        });
    }
 
    /**
     * 实现UserDetailsService接口,从数据库内获取用户及权限信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysUser::getUserName, username);
        SysUser user = this.baseMapper.selectOne(lqw);
        //判断是否为空
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //查询权限信息
        List<String> perms = sysMenuMapper.selectPermsByUserId(user.getId());
 
        return new LoginUser(user, perms);
    }
 
 
    private void saveUserRole(List<SysRole> roles, Long userId) {
        log.info("保存用户角色信息");
        List<SysUserRole> userRoles = new ArrayList<>();
        if (CollectionUtils.isEmpty(roles)) {
            log.info("保存用户角色信息为空,给默认普通用户角色");
            userRoles.add(new SysUserRole(userId, Const.DEFULT_ROLE));
        } else {
            log.info("保存用户角色信息");
            userRoles = roles.stream().map(e -> new SysUserRole(userId, e.getId())).collect(Collectors.toList());
        }
        sysUserRoleService.saveBatch(userRoles);
    }
 
}