#
Junjie
2 天以前 d9411a6692197efabcf132d61c051e51cb85e219
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
package com.zy.common.web;
 
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.core.annotations.ManagerAuth;
import com.core.common.Cools;
import com.core.common.R;
import com.core.exception.CoolException;
import com.zy.common.CodeRes;
import com.zy.common.auth.MfaLoginTicketManager;
import com.zy.common.i18n.I18nMessageService;
import com.zy.common.entity.Parameter;
import com.zy.common.model.PowerDto;
import com.zy.common.model.enums.HtmlNavIconType;
import com.zy.common.utils.MfaTotpUtil;
import com.zy.common.utils.QrCode;
import com.zy.common.utils.RandomValidateCodeUtil;
import com.zy.system.entity.*;
import com.zy.system.service.*;
import com.zy.system.timer.LicenseTimer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import jakarta.servlet.http.HttpServletResponse;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.*;
 
/**
 * Created by vincent on 2019-07-30
 */
@RestController
public class AuthController extends BaseController {
 
    @Value("${super.pwd}")
    private String superPwd;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private RoleResourceService roleResourceService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private LicenseTimer licenseTimer;
    @Autowired
    private I18nMessageService i18nMessageService;
    @Autowired
    private MfaLoginTicketManager mfaLoginTicketManager;
 
    @RequestMapping("/login.action")
    @ManagerAuth(value = ManagerAuth.Auth.NONE, memo = "登录")
    public R loginAction(String mobile, String password){
        //验证许可证是否有效
        if (!licenseTimer.getSystemSupport()){
            return new R(20001, i18nMessageService.getMessage("response.system.licenseExpired"));
        }
        if (Cools.isEmpty(mobile, password)) {
            return new R(10003, i18nMessageService.getMessage("response.user.passwordMismatch"));
        }
        if (mobile.equals("super") && password.equals(Cools.md5(superPwd))) {
            Map<String, Object> res = new HashMap<>();
            res.put("username", mobile);
            res.put("token", Cools.enToken(System.currentTimeMillis() + mobile, superPwd));
            return R.ok(res);
        }
        User user = userService.getByMobileWithMfa(mobile);
        if (Cools.isEmpty(user)){
            return new R(10001, i18nMessageService.getMessage("response.user.notFound"));
        }
        if (user.getStatus()!=1){
            return new R(10002, i18nMessageService.getMessage("response.user.disabled"));
        }
        if (!user.getPassword().equals(password)){
            return new R(10003, i18nMessageService.getMessage("response.user.passwordMismatch"));
        }
        if (requiresMfa(user)) {
            Map<String, Object> res = new HashMap<>();
            res.put("username", user.getUsername());
            res.put("mfaRequired", true);
            res.put("mfaTicket", mfaLoginTicketManager.create(user.getId()));
            return R.ok(res);
        }
        return R.ok(buildLoginSuccess(user));
    }
 
    @RequestMapping("/login/mfa.action")
    @ManagerAuth(value = ManagerAuth.Auth.NONE, memo = "MFA登录")
    public R loginMfaAction(String ticket, String code) {
        Long userId = mfaLoginTicketManager.getUserId(ticket);
        if (userId == null) {
            return new R(10004, i18nMessageService.getMessage("response.user.mfaTicketExpired"));
        }
        User user = userService.getByIdWithMfa(userId);
        if (Cools.isEmpty(user)) {
            mfaLoginTicketManager.remove(ticket);
            return new R(10001, i18nMessageService.getMessage("response.user.notFound"));
        }
        if (user.getStatus() != 1) {
            mfaLoginTicketManager.remove(ticket);
            return new R(10002, i18nMessageService.getMessage("response.user.disabled"));
        }
        if (!requiresMfa(user)) {
            mfaLoginTicketManager.remove(ticket);
            return new R(10005, i18nMessageService.getMessage("response.user.mfaNotEnabled"));
        }
        if (!MfaTotpUtil.verifyCode(user.getMfaSecret(), code, 1)) {
            return new R(10006, i18nMessageService.getMessage("response.user.mfaCodeMismatch"));
        }
        mfaLoginTicketManager.remove(ticket);
        return R.ok(buildLoginSuccess(user));
    }
 
    @RequestMapping("/code/switch.action")
    public R code() {
        return R.ok().add(Parameter.get().getCodeSwitch());
    }
 
    @RequestMapping("/code.action")
    public void code(@RequestParam String sd, HttpServletResponse response) {
        RandomValidateCodeUtil.getRandcode(sd, response);
    }
 
    @RequestMapping("/code.do")
    public String codeDo(@RequestParam String sd) throws Exception {
        String code = null;
        int time = 0;
        while (time < 3000) {
            code = RandomValidateCodeUtil.code.get(sd);
            if (!Cools.isEmpty(code)){
                break;
            } else {
                Thread.sleep(10);
                time = time + 100;
            }
        }
        RandomValidateCodeUtil.code.remove(sd);
        return code;
    }
 
    @RequestMapping("/user/detail/auth")
    @ManagerAuth
    public R userDetail(){
        User user = userService.getByIdWithMfa(getUserId());
        if (Cools.isEmpty(user)) {
            return R.ok();
        }
        return R.ok(buildSafeUserDetail(user));
    }
 
    @RequestMapping("/user/mfa/setup/auth")
    @ManagerAuth
    public R userMfaSetup() {
        User user = userService.getByIdWithMfa(getUserId());
        if (Cools.isEmpty(user)) {
            return new R(10001, i18nMessageService.getMessage("response.user.notFound"));
        }
        if (!Integer.valueOf(1).equals(user.getMfaAllow())) {
            return new R(10007, i18nMessageService.getMessage("response.user.mfaNotAllowed"));
        }
        String secret = MfaTotpUtil.generateSecret();
        String account = !Cools.isEmpty(user.getMobile())
                ? user.getMobile()
                : (!Cools.isEmpty(user.getUsername()) ? user.getUsername() : String.valueOf(user.getId()));
        String otpAuth = MfaTotpUtil.buildOtpAuthUri("WCS", account, secret);
        Map<String, Object> data = new HashMap<>();
        data.put("secret", secret);
        data.put("otpAuth", otpAuth);
        data.put("qrCode", renderQrCodeDataUri(otpAuth));
        return R.ok(data);
    }
 
    @RequestMapping("/user/mfa/enable/auth")
    @ManagerAuth
    @Transactional
    public R userMfaEnable(String currentPassword, String secret, String code) {
        User user = userService.getByIdWithMfa(getUserId());
        if (Cools.isEmpty(user)) {
            return new R(10001, i18nMessageService.getMessage("response.user.notFound"));
        }
        if (!Integer.valueOf(1).equals(user.getMfaAllow())) {
            return new R(10007, i18nMessageService.getMessage("response.user.mfaNotAllowed"));
        }
        if (!Cools.eq(user.getPassword(), currentPassword)) {
            return new R(10008, i18nMessageService.getMessage("response.user.oldPasswordMismatch"));
        }
        String normalizedSecret = normalizeSecret(secret);
        if (Cools.isEmpty(normalizedSecret) || !MfaTotpUtil.verifyCode(normalizedSecret, code, 1)) {
            return new R(10006, i18nMessageService.getMessage("response.user.mfaCodeMismatch"));
        }
        userService.update(new com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<User>()
                .eq("id", user.getId())
                .set("mfa_allow", 1)
                .set("mfa_enabled", 1)
                .set("mfa_secret", normalizedSecret)
                .set("mfa_bound_time", new Date()));
        return R.ok();
    }
 
    @RequestMapping("/user/mfa/disable/auth")
    @ManagerAuth
    @Transactional
    public R userMfaDisable(String currentPassword, String code) {
        User user = userService.getByIdWithMfa(getUserId());
        if (Cools.isEmpty(user)) {
            return new R(10001, i18nMessageService.getMessage("response.user.notFound"));
        }
        if (!requiresMfa(user)) {
            return new R(10005, i18nMessageService.getMessage("response.user.mfaNotEnabled"));
        }
        if (!Cools.eq(user.getPassword(), currentPassword)) {
            return new R(10008, i18nMessageService.getMessage("response.user.oldPasswordMismatch"));
        }
        if (!MfaTotpUtil.verifyCode(user.getMfaSecret(), code, 1)) {
            return new R(10006, i18nMessageService.getMessage("response.user.mfaCodeMismatch"));
        }
        userService.update(new com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper<User>()
                .eq("id", user.getId())
                .set("mfa_enabled", 0)
                .set("mfa_secret", null)
                .set("mfa_bound_time", null));
        return R.ok();
    }
 
    @RequestMapping("/menu/auth")
    @ManagerAuth(memo = "首页菜单")
    public R menu(){
        // 获取所有一级菜单
        List<Resource> oneLevel = resourceService.list(new QueryWrapper<Resource>().eq("level", 1).eq("status", 1).orderBy(true, true, "sort"));
        User user = null;
        QueryWrapper<Resource> resourceWrapper;
        if (getUserId() == 9527) {
            resourceWrapper = new QueryWrapper<Resource>().eq("level", 2).eq("status", 1).orderBy(true, true, "sort");
        } else {
            // 获取当前用户的所有二级菜单
            user = userService.getById(getUserId());
            List<RoleResource> roleResources = roleResourceService.list(new QueryWrapper<RoleResource>().eq("role_id", user.getRoleId()));
            List<Long> resourceIds = new ArrayList<>();
            roleResources.forEach(roleResource -> resourceIds.add(roleResource.getResourceId()));
            if (resourceIds.isEmpty()){
                return R.ok();
            }
            resourceWrapper = new QueryWrapper<Resource>().in("id", resourceIds).eq("level", 2).eq("status", 1).orderBy(true, true, "sort");
        }
        List<Resource> twoLevel = resourceService.list(resourceWrapper);
        List<Map<String, Object>> result = new ArrayList<>();
        for (Resource menu : oneLevel) {
            Map<String, Object> map = new HashMap<>();
            List<Resource> subMenu = new ArrayList<>();
            Iterator<Resource> iterator = twoLevel.iterator();
            while (iterator.hasNext()) {
                Resource resource = iterator.next();
                if (resource.getResourceId() != null && resource.getResourceId().equals(menu.getId())) {
 
                    // 是否拥有查看权限
                    if (getUserId() != 9527) {
                        Resource view = firstResource(new QueryWrapper<Resource>()
                                .eq("resource_id", resource.getId())
                                .like("code", "view"));
                        if (!Cools.isEmpty(view)){
                            RoleResource param = new RoleResource();
                            param.setResourceId(view.getId());
                            param.setRoleId(user.getRoleId());
                            if (!existsRoleResource(new QueryWrapper<>(param))){
                                continue;
                            }
                        }
                    }
 
                    resource.setName(localizeResourceName(resource));
                    subMenu.add(resource);
                    iterator.remove();
                }
            }
            if (subMenu.isEmpty()) {
                continue;
            }
            map.put("menuId", menu.getId());
            map.put("menuCode", menu.getCode());
            map.put("menuIcon", HtmlNavIconType.get(menu.getCode()));
            map.put("menu", localizeResourceName(menu));
            map.put("subMenu", subMenu);
            result.add(map);
        }
        return R.ok(result);
    }
 
    @RequestMapping("/power/list/auth")
    @ManagerAuth
    public R powerList(){
        List<Resource> oneLevels = resourceService.list(new QueryWrapper<Resource>().eq("level", 1).eq("status", 1).orderBy(true, true, "sort"));
        List<Map> result = new ArrayList<>();
        // 一级
        for (Resource oneLevel : oneLevels){
            List<Map> twoLevelsList = new ArrayList<>();
            Map<String, Object> oneLevelMap = new HashMap<>();
            oneLevelMap.put("title", localizeResourceName(oneLevel));
            oneLevelMap.put("id", oneLevel.getId());
            oneLevelMap.put("spread", true);
            oneLevelMap.put("children", twoLevelsList);
            List<Resource> twoLevels = resourceService.list(new QueryWrapper<Resource>().eq("resource_id", oneLevel.getId()).eq("level", 2).eq("status", 1).orderBy(true, true, "sort"));
            // 二级
            for (Resource twoLevel : twoLevels){
                Map<String, Object> twoLevelMap = new HashMap<>();
                twoLevelMap.put("title", localizeResourceName(twoLevel));
                twoLevelMap.put("id", twoLevel.getId());
                twoLevelMap.put("spread", false);
 
                List<Map> threeLevelsList = new ArrayList<>();
                twoLevelMap.put("children", threeLevelsList);
                // 三级
                List<Resource> threeLevels = resourceService.list(new QueryWrapper<Resource>().eq("resource_id", twoLevel.getId()).eq("level", 3).eq("status", 1).orderBy(true, true, "sort"));
                for (Resource threeLevel : threeLevels){
                    Map<String, Object> threeLevelMap = new HashMap<>();
                    threeLevelMap.put("title", localizeResourceName(threeLevel));
                    threeLevelMap.put("id", threeLevel.getId());
                    threeLevelMap.put("checked", false);
                    threeLevelsList.add(threeLevelMap);
                }
 
                twoLevelsList.add(twoLevelMap);
            }
            result.add(oneLevelMap);
        }
 
        // 功能模块
        Map<String, Object> functions = new HashMap<>();
        functions.put("title", i18nMessageService.getMessage("permission.function"));
        functions.put("id", "function");
        functions.put("spread", true);
        List<Map> funcs = new ArrayList<>();
        functions.put("children", funcs);
        List<Permission> permissions = permissionService.list(new QueryWrapper<Permission>().eq("status", 1));
        for (Permission permission : permissions) {
            Map<String, Object> func = new HashMap<>();
            func.put("title", i18nMessageService.resolvePermissionText(permission.getName(), permission.getAction(), permission.getId()));
            func.put("id", permission.getAction());
            func.put("spread", true);
            funcs.add(func);
        }
        result.add(functions);
 
        return R.ok(result);
    }
 
    private Map<String, Object> buildLoginSuccess(User user) {
        String token = Cools.enToken(System.currentTimeMillis() + user.getMobile(), user.getPassword());
        userLoginService.remove(new QueryWrapper<UserLogin>().eq("user_id", user.getId()).eq("system_type", "WCS"));
        UserLogin userLogin = new UserLogin();
        userLogin.setUserId(user.getId());
        userLogin.setToken(token);
        userLogin.setSystemType("WCS");
        userLoginService.save(userLogin);
        Map<String, Object> result = new HashMap<>();
        result.put("username", user.getUsername());
        result.put("token", token);
        result.put("mfaRequired", false);
        return result;
    }
 
    private boolean requiresMfa(User user) {
        return user != null
                && Integer.valueOf(1).equals(user.getMfaAllow())
                && Integer.valueOf(1).equals(user.getMfaEnabled())
                && !Cools.isEmpty(user.getMfaSecret());
    }
 
    private Map<String, Object> buildSafeUserDetail(User user) {
        Map<String, Object> result = new HashMap<>();
        result.put("id", user.getId());
        result.put("roleName", user.getRoleName());
        result.put("username", user.getUsername());
        result.put("mobile", user.getMobile());
        result.put("createTime$", user.getCreateTime$());
        result.put("mfaAllow", user.getMfaAllow());
        result.put("mfaAllow$", user.getMfaAllow$());
        result.put("mfaEnabled", user.getMfaEnabled());
        result.put("mfaEnabled$", user.getMfaEnabled$());
        result.put("mfaBoundTime$", user.getMfaBoundTime$());
        result.put("mfaMaskedSecret", MfaTotpUtil.maskSecret(user.getMfaSecret()));
        return result;
    }
 
    private String renderQrCodeDataUri(String content) {
        try {
            BufferedImage image = QrCode.createImg(content, 220);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            return "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(outputStream.toByteArray());
        } catch (Exception e) {
            return "";
        }
    }
 
    private String normalizeSecret(String secret) {
        if (Cools.isEmpty(secret)) {
            return "";
        }
        return String.valueOf(secret)
                .trim()
                .replace(" ", "")
                .replace("-", "")
                .toUpperCase(Locale.ROOT);
    }
 
    private String localizeResourceName(Resource resource) {
        return i18nMessageService.resolveResourceText(resource.getName(), resource.getCode(), resource.getId());
    }
 
    @RequestMapping(value = "/power/{roleId}/auth")
    @ManagerAuth
    public R get(@PathVariable("roleId") Long roleId) {
        List<Object> result = new ArrayList<>();
        // 菜单
        List<RoleResource> roleResources = roleResourceService.list(new QueryWrapper<RoleResource>().eq("role_id", roleId));
        for (RoleResource roleResource : roleResources){
            Resource resource = resourceService.getById(roleResource.getResourceId());
            if (!Cools.isEmpty(resource)){
                if (resource.getLevel() == 3){
                    result.add(resource.getId());
                }
            }
        }
        // 功能
        List<RolePermission> rolePermissions = rolePermissionService.list(new QueryWrapper<RolePermission>().eq("role_id", roleId));
        for (RolePermission rolePermission : rolePermissions){
            Permission permission = permissionService.getById(rolePermission.getPermissionId());
            if (!Cools.isEmpty(permission)){
                result.add(permission.getAction());
            }
        }
        return R.ok(result);
    }
 
    @RequestMapping("/power/auth")
    @ManagerAuth(memo = "授权")
    @Transactional
    public R power(Long roleId, String powers){
        Role role = roleService.getById(roleId);
        Long leaderId = role.getLeader();
        roleResourceService.remove(new QueryWrapper<RoleResource>().eq("role_id", roleId));
        rolePermissionService.remove(new QueryWrapper<RolePermission>().eq("role_id", roleId));
        if (!Cools.isEmpty(powers)){
            List<PowerDto> dtos = JSON.parseArray(powers, PowerDto.class);
            for (PowerDto dto : dtos) {
                Resource resource = resourceService.getOne(new QueryWrapper<Resource>().eq("id", dto.getTwo()).eq("level", 2));
                if (!Cools.isEmpty(resource)) {
                    // 校验上级权限
                    if (leaderId != null) {
                        RoleResource roleResource = roleResourceService.getOne(new QueryWrapper<RoleResource>().eq("role_id", leaderId).eq("resource_id", resource.getId()));
                        if (null == roleResource) {
                            throw new CoolException(resource.getName().concat("无法授权给").concat(role.getName()));
                        }
                    }
                    RoleResource roleResource = new RoleResource();
                    roleResource.setRoleId(roleId);
                    roleResource.setResourceId(resource.getId());
                    roleResourceService.save(roleResource);
                } else {
                    Permission permission = permissionService.getOne(new QueryWrapper<Permission>().eq("action", dto.getTwo()));
                    if (!Cools.isEmpty(permission)){
                        RolePermission rolePermission = new RolePermission();
                        rolePermission.setRoleId(roleId);
                        rolePermission.setPermissionId(permission.getId());
                        rolePermissionService.save(rolePermission);
                    }
                }
                for (String three : dto.getThree()){
                    Resource resource1 = resourceService.getOne(new QueryWrapper<Resource>().eq("id", three).eq("level", 3));
                    if (!Cools.isEmpty(resource1)) {
                        // 校验上级权限
                        if (leaderId != null) {
                            RoleResource roleResource = roleResourceService.getOne(new QueryWrapper<RoleResource>().eq("role_id", leaderId).eq("resource_id", resource1.getId()));
                            if (null == roleResource) {
                                throw new CoolException(resource.getName().concat("的").concat(resource1.getName().concat("无法授权给").concat(role.getName())));
                            }
                        }
                        RoleResource roleResource = new RoleResource();
                        roleResource.setRoleId(roleId);
                        roleResource.setResourceId(resource1.getId());
                        roleResourceService.save(roleResource);
                    }
                }
            }
        }
        return R.ok();
    }
 
    @RequestMapping(value = "/power/menu/{resourceId}/auth")
    @ManagerAuth
    public R buttonResource(@PathVariable("resourceId") Long resourceId) {
        List<Resource> resources;
        if (getUserId() == 9527) {
            resources = resourceService.list(new QueryWrapper<Resource>().eq("level", 3).eq("resource_id", resourceId));
        } else {
            resources = roleResourceService.getMenuButtomResource(resourceId, getUserId());
        }
        for (Resource resource : resources) {
            resource.setCode(resource.getCode().split("#")[1]);
        }
        return R.ok(resources);
    }
 
    private Resource firstResource(QueryWrapper<Resource> wrapper) {
        wrapper.last("limit 1");
        List<Resource> list = resourceService.list(wrapper);
        return list.isEmpty() ? null : list.get(0);
    }
 
    private boolean existsRoleResource(QueryWrapper<RoleResource> wrapper) {
        wrapper.last("limit 1");
        return !roleResourceService.list(wrapper).isEmpty();
    }
 
 
}