ny
昨天 b6f169fe43a2b13f351aefc152374fc7f0bc8cb7
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
package jnpf.service.impl;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import jnpf.base.*;
import jnpf.base.entity.SuperBaseEntity;
import jnpf.base.entity.SystemEntity;
import jnpf.base.model.base.SystemBaeModel;
import jnpf.base.model.button.ButtonModel;
import jnpf.base.model.column.ColumnModel;
import jnpf.base.model.form.ModuleFormModel;
import jnpf.base.model.module.ModuleModel;
import jnpf.base.model.resource.ResourceModel;
import jnpf.config.ConfigValueUtil;
import jnpf.constant.EventConst;
import jnpf.constant.JnpfConst;
import jnpf.constant.MsgCode;
import jnpf.constant.PermissionConst;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.exception.LoginException;
import jnpf.exception.NoPermiLoginException;
import jnpf.exception.TenantDatabaseException;
import jnpf.granter.UserDetailsServiceBuilder;
import jnpf.message.MessageTemplateConfigApi;
import jnpf.message.SentMessageApi;
import jnpf.message.entity.MessageTemplateConfigEntity;
import jnpf.model.BaseSystemInfo;
import jnpf.model.BuildUserCommonInfoModel;
import jnpf.model.login.*;
import jnpf.model.tenant.TenantVO;
import jnpf.module.ProjectEventBuilder;
import jnpf.permission.*;
import jnpf.permission.entity.*;
import jnpf.permission.model.authorize.AuthorizeVO;
import jnpf.permission.model.authorize.OtherModel;
import jnpf.permission.model.rolerelaiton.RoleRelationModel;
import jnpf.permission.model.user.UserUpdateModel;
import jnpf.portal.PortalApi;
import jnpf.portal.model.DefaultModel;
import jnpf.properties.SecurityProperties;
import jnpf.service.LoginService;
import jnpf.util.*;
import jnpf.util.context.RequestContext;
import jnpf.util.treeutil.SumTree;
import jnpf.util.treeutil.newtreeutil.TreeDotUtils;
import jnpf.utils.LoginHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;
 
import static jnpf.util.Constants.ADMIN_KEY;
 
/**
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司(<a href="https://www.jnpfsoft.com">...</a>)
 * @date 2021/3/16
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private SecurityProperties securityProperties;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CacheKeyUtil cacheKeyUtil;
    @Autowired
    private SysConfigApi sysconfigApi;
 
    @Autowired
    private UserApi userApi;
    @Autowired
    private UserRelationApi userRelationApi;
    @Autowired
    private RoleRelationApi roleRelationApi;
    @Autowired
    private OrganizeApi organizeApi;
    @Autowired
    private PositionApi positionApi;
    @Autowired
    private RoleApi roleApi;
    @Autowired
    private GroupApi groupApi;
    @Autowired
    private AuthorizeApi authorizeApi;
    @Autowired
    private PortalApi portalDataService;
    @Autowired
    private SystemApi systemApi;
    @Autowired
    private UserDetailsServiceBuilder userDetailsServiceBuilder;
    @Autowired
    private SignApi signService;
    @Autowired
    private MessageTemplateConfigApi messageTemplateApi;
    @Autowired
    private SentMessageApi sentMessageApi;
    @Autowired
    private UserSettingApi userExtraService;
 
    @Override
    public UserInfo getTenantAccount(UserInfo userInfo) throws LoginException {
        String tenantId = null;
        if (configValueUtil.isMultiTenancy()) {
            String[] tenantAccount = userInfo.getUserAccount().split("\\@");
            if (tenantAccount.length == 1) {
                //只输入账号, 1:配置的二级域名下只输入账号, 2:主域名下输入了租户号
                String referer = ServletUtil.getHeader("Referer");
                if (StringUtil.isNotEmpty(referer)) {
                    String remoteHost = UrlBuilder.of(referer).getHost();
                    String apiHost = UrlBuilder.of(RequestContext.isOrignPc() ? configValueUtil.getFrontDomain() : configValueUtil.getAppDomain()).getHost();
                    if (!ObjectUtil.equals(remoteHost, apiHost)
                            && remoteHost.endsWith(apiHost)) {
                        //二级域名访问, 输入的是账号
                        tenantId = remoteHost.split("\\.")[0];
                        userInfo.setUserAccount(tenantAccount[0]);
                    }
                }
                if (tenantId == null) {
                    //主域名访问, 输入的是租户号
                    tenantId = tenantAccount[0];
                    userInfo.setUserAccount(ADMIN_KEY);
                }
            } else {
                //租户号@账号
                tenantId = tenantAccount[0];
                userInfo.setUserAccount(tenantAccount[1]);
            }
            if (StringUtil.isEmpty(tenantId) || tenantAccount.length > 2 || StringUtil.isEmpty(userInfo.getUserAccount())) {
                throw new LoginException(MsgCode.LOG102.get());
            }
            TenantVO tenantVO = TenantDataSourceUtil.getRemoteTenantInfo(tenantId);
            TenantDataSourceUtil.switchTenant(tenantId, tenantVO);
            //切换成租户库
            userInfo.setTenantId(tenantId);
            userInfo.setTenantDbConnectionString(tenantVO.getDbName());
            userInfo.setTenantDbType(tenantVO.getType());
            //查库测试
            BaseSystemInfo baseSystemInfo = null;
            try {
                baseSystemInfo = getBaseSystemConfig(userInfo.getTenantId());
            } catch (Exception e) {
                log.error("登录获取系统配置失败: {}", e.getMessage());
            }
            if (baseSystemInfo == null || baseSystemInfo.getSingleLogin() == null) {
                throw new TenantDatabaseException();
            }
        }
        return userInfo;
    }
 
    @Override
    public UserInfo userInfo(UserInfo userInfo, BaseSystemInfo sysConfigInfo) throws LoginException {
        //获取账号信息
        UserEntity userEntity = LoginHolder.getUserEntity();
        if (userEntity == null) {
            userEntity = userDetailsServiceBuilder.getUserDetailService(userInfo.getUserDetailKey()).loadUserEntity(userInfo);
            LoginHolder.setUserEntity(userEntity);
        }
 
        checkUser(userEntity, userInfo, sysConfigInfo);
 
        userInfo.setUserId(userEntity.getId());
        userInfo.setUserAccount(userEntity.getAccount());
        userInfo.setUserName(userEntity.getRealName());
        userInfo.setUserIcon(userEntity.getHeadIcon());
        userInfo.setTheme(userEntity.getTheme());
        userInfo.setOrganizeId(userEntity.getOrganizeId());
        userInfo.setPortalId(userEntity.getPortalId());
        userInfo.setIsAdministrator(BooleanUtil.toBoolean(String.valueOf((userEntity.getIsAdministrator()))));
        if (!ADMIN_KEY.equals(userInfo.getUserAccount())) {
            if (ObjectUtil.isNotEmpty(userEntity.getStanding())) {
                userInfo.setIsAdministrator(Objects.equals(userEntity.getStanding(), 1));
            }
        }
        // 添加过期时间
        String time = sysConfigInfo.getTokenTimeout();
        if (StringUtil.isNotEmpty(time)) {
            Integer minu = Integer.valueOf(time);
            userInfo.setOverdueTime(DateUtil.dateAddMinutes(null, minu));
            userInfo.setTokenTimeout(minu);
        }
 
        String ipAddr = IpUtil.getIpAddr();
        userInfo.setLoginIpAddress(ipAddr);
        userInfo.setLoginIpAddressName(IpUtil.getIpCity(ipAddr));
        userInfo.setLoginTime(DateUtil.getmmNow());
        UserAgent userAgent = UserAgentUtil.parse(ServletUtil.getUserAgent());
        if (userAgent != null) {
            userInfo.setLoginPlatForm(userAgent.getPlatform().getName() + " " + userAgent.getOsVersion());
            userInfo.setBrowser(userAgent.getBrowser().getName() + " " + userAgent.getVersion());
        }
        userInfo.setPrevLoginTime(userEntity.getPrevLogTime());
        userInfo.setPrevLoginIpAddress(userEntity.getPrevLogIp());
        userInfo.setPrevLoginIpAddressName(IpUtil.getIpCity(userEntity.getPrevLogIp()));
        // 生成id
        String token = RandomUtil.uuId();
        userInfo.setId(cacheKeyUtil.getLoginToken(userInfo.getTenantId()) + token);
 
        createUserOnline(userInfo);
        return userInfo;
    }
 
    @Override
    public void updatePasswordMessage() {
        UserInfo userInfo = UserProvider.getUser();
        UserEntity userEntity = userApi.getInfoById(userInfo.getUserId());
        BaseSystemInfo baseSystemInfo = sysconfigApi.getSysConfigInfo();
        if (baseSystemInfo.getPasswordIsUpdatedRegularly() == 1) {
            Date changePasswordDate = userEntity.getCreatorTime();
            if (userEntity.getChangePasswordDate() != null) {
                changePasswordDate = userEntity.getChangePasswordDate();
            }
            //当前时间
            Date nowDate = DateUtil.getNowDate();
            //更新周期
            Integer updateCycle = baseSystemInfo.getUpdateCycle();
            //提前N天提醒
            Integer updateInAdvance = baseSystemInfo.getUpdateInAdvance();
            Integer day = DateUtil.getDiffDays(changePasswordDate, nowDate);
            if (day >= (updateCycle - updateInAdvance)) {
                MessageTemplateConfigEntity entity = messageTemplateApi.getInfoByEnCode("XTXXTX001");
                if (entity != null) {
                    List<String> toUserIds = new ArrayList<>();
                    toUserIds.add(userInfo.getUserId());
                    sentMessageApi.sentMessage(toUserIds, entity.getTitle(), entity.getContent(), Integer.parseInt(entity.getMessageSource()), Integer.parseInt(entity.getMessageType()), userInfo);
                }
            }
        }
    }
 
    /**
     * 创建用户在线信息
     *
     * @param userInfo
     */
    private void createUserOnline(UserInfo userInfo) {
        String userId = userInfo.getUserId();
//        long time= DateUtil.getTime(userInfo.getOverdueTime()) - DateUtil.getTime(new Date());
 
        String authorize = String.valueOf(redisUtil.getString(cacheKeyUtil.getUserAuthorize() + userId));
//        String loginOnlineKey=cacheKeyUtil.getLoginOnline() + userId;
        redisUtil.remove(authorize);
        //记录Token
//        redisUtil.insert(userInfo.getId(), userInfo,time);
        //记录在线
        if (ServletUtil.getIsMobileDevice()) {
//            redisUtil.insert(cacheKeyUtil.getMobileLoginOnline() + userId, userInfo.getId(), time);
            //记录移动设备CID,用于消息推送
            if (ServletUtil.getHeader("clientId") != null) {
                String clientId = ServletUtil.getHeader("clientId");
                Map<String, String> map = new HashMap<>(16);
                map.put(userInfo.getUserId(), clientId);
                redisUtil.insert(cacheKeyUtil.getMobileDeviceList(), map);
            }
        } else {
//            redisUtil.insert(loginOnlineKey, userInfo.getId(), time);
        }
    }
 
    private UserCommonInfoVO data(BuildUserCommonInfoModel buildUserCommonInfoModel) {
        UserInfo userInfo = buildUserCommonInfoModel.getUserInfo();
        UserEntity userEntity = buildUserCommonInfoModel.getUserEntity();
        UserExtraEntity userExtraByUserId = userExtraService.getUserExtraByUserId(userInfo.getUserId());
        //userInfo 填充信息
        UserOrgPosModel uopm = this.userInfo(userInfo, userEntity);
        //返回前端vo
        BaseSystemInfo baseSystemInfo = buildUserCommonInfoModel.getBaseSystemInfo();
        UserCommonInfoVO infoVO = JsonUtil.getJsonToBean(userInfo, UserCommonInfoVO.class);
        infoVO.setOrganizeList(uopm.getOrganizeList());
        infoVO.setPositionList(uopm.getPositionList());
        infoVO.setGroupList(uopm.getGroupList());
        infoVO.setRoleList(uopm.getRoleList());
        infoVO.setPrevLogin(baseSystemInfo.getLastLoginTimeSwitch() == 1 ? 1 : 0);
        if (BeanUtil.isNotEmpty(userExtraByUserId)) {
            infoVO.setPreferenceJson(userExtraByUserId.getPreferenceJson());
        }
        //最后一次修改密码时间
        infoVO.setChangePasswordDate(userEntity.getChangePasswordDate());
        // 姓名
        infoVO.setUserName(userEntity.getRealName());
        // 组织名称
        KeyNameModel defaultOrg = uopm.getOrganizeList().stream().filter(t -> t.getId().equals(userInfo.getOrganizeId())).findFirst().orElse(new KeyNameModel());
        infoVO.setOrganizeName(defaultOrg.getFullName());
        // 岗位名称
        KeyNameModel defaultPos = uopm.getPositionList().stream().filter(t -> t.getId().equals(userInfo.getPositionId())).findFirst().orElse(new KeyNameModel());
        infoVO.setPositionName(defaultPos.getFullName());
        //是否超级管理员
        infoVO.setIsAdministrator(BooleanUtil.toBoolean(String.valueOf(userEntity.getIsAdministrator())));
        if (!ADMIN_KEY.equals(userEntity.getAccount())) {
            if (ObjectUtil.isNotEmpty(userEntity.getStanding())) {
                userInfo.setIsAdministrator(Objects.equals(userEntity.getStanding(), 1));
                infoVO.setIsAdministrator(Objects.equals(userEntity.getStanding(), 1));
            }
        }
        infoVO.setSecurityKey(userInfo.getSecurityKey());
        if (StringUtil.isNotEmpty(userInfo.getId())) {
            UserProvider.setLoginUser(userInfo);
            UserProvider.setLocalLoginUser(userInfo);
        }
        return infoVO;
    }
 
    public UserEntity checkUser(UserEntity userEntity, UserInfo userInfo, BaseSystemInfo sysConfigInfo) throws LoginException {
        if (userEntity == null) {
            throw new LoginException(MsgCode.LOG101.get());
        }
        //判断是否组织、岗位、角色、部门主管是否为空,为空则抛出异常
        //判断是否为管理员,是否为Admin(Admin为最高账号,不受限制)
        if (!ADMIN_KEY.equals(userEntity.getAccount()) || userEntity.getIsAdministrator() != 1) {
            //没岗位,且没用户角色时直接提示没权限
            List<String> posAndRole = userRelationApi.getUserPosAndRole(userEntity.getId(), PermissionConst.POSITION, userInfo.getTenantId());
            //有岗位角色但是没有权限
            if (CollectionUtil.isEmpty(posAndRole) || CollectionUtil.isEmpty(authorizeApi.GetListByObjectIdTenant(posAndRole, userInfo.getTenantId()))) {
                throw new LoginException(MsgCode.LOG004.get());
            }
 
        }
        if (userEntity.getIsAdministrator() == 0) {
            if (userEntity.getEnabledMark() == null) {
                throw new LoginException(MsgCode.LOG005.get());
            }
            if (userEntity.getEnabledMark() == 0) {
                throw new LoginException(MsgCode.LOG006.get());
            }
        }
        if (userEntity.getDeleteMark() != null && userEntity.getDeleteMark() == 1) {
            throw new LoginException(MsgCode.LOG007.get());
        }
        //安全验证
        String ipAddr = IpUtil.getIpAddr();
        userInfo.setLoginIpAddress(IpUtil.getIpAddr());
        // 判断白名单
        if (!ADMIN_KEY.equals(userEntity.getAccount()) && "1".equals(sysConfigInfo.getWhitelistSwitch())) {
            List<String> ipList = Arrays.asList(sysConfigInfo.getWhitelistIp().split(","));
            if (!ipList.contains(ipAddr)) {
                throw new LoginException(MsgCode.LOG010.get());
            }
        }
        // 判断当前账号是否被锁定
        Integer lockMark = userEntity.getEnabledMark();
        if (Objects.nonNull(lockMark) && lockMark == 2) {
            // 获取解锁时间
            Date unlockTime = userEntity.getUnlockTime();
            // 账号锁定
            if (sysConfigInfo.getLockType() == 1 || Objects.isNull(unlockTime)) {
                throw new LoginException(MsgCode.LOG012.get());
            }
            // 延迟登陆锁定
            long millis = System.currentTimeMillis();
            // 系统设置的错误次数
            int passwordErrorsNumber = sysConfigInfo.getPasswordErrorsNumber() != null ? sysConfigInfo.getPasswordErrorsNumber() : 0;
            // 用户登录错误次数
            int logErrorCount = userEntity.getLogErrorCount() != null ? userEntity.getLogErrorCount() : 0;
            if (unlockTime.getTime() > millis) {
                // 转成分钟
                int time = (int) ((unlockTime.getTime() - millis) / (1000 * 60));
                throw new LoginException(MsgCode.LOG108.get(time + 1));
            } else if (unlockTime.getTime() < millis && logErrorCount >= passwordErrorsNumber) {
                // 已经接触错误时间锁定的话就重置错误次数
                userEntity.setLogErrorCount(0);
                userEntity.setEnabledMark(1);
                userApi.updateById(new UserUpdateModel(userEntity, userInfo.getTenantId()));
            }
        }
        return userEntity;
    }
 
    /**
     * 获取用户登陆信息
     *
     * @return
     */
    @Override
    public PcUserVO getCurrentUser(String type, String systemCode, Integer isBackend) {
        UserInfo userInfo = UserProvider.getUser();
        UserEntity userEntity = userApi.getInfoById(userInfo.getUserId());
        if (userEntity == null) {
            return null;
        }
        userInfo.setIsBackend(isBackend);
        BaseSystemInfo baseSystemInfo = sysconfigApi.getSysConfigInfo();
        BuildUserCommonInfoModel buildUserCommonInfoModel = new BuildUserCommonInfoModel(userInfo, userEntity, baseSystemInfo, type);
        //添加userInfo信息
        UserCommonInfoVO infoVO = this.data(buildUserCommonInfoModel);
        //获取权限
        if (StringUtil.isEmpty(systemCode) && JnpfConst.WEB.equals(type)) {
            systemCode = JnpfConst.MAIN_SYSTEM_CODE;
        } else if (StringUtil.isEmpty(systemCode) && JnpfConst.APP.equals(type)) {
            SystemEntity sysInfo = systemApi.getInfoById(userEntity.getAppSystemId());
            systemCode = sysInfo != null ? sysInfo.getEnCode() : null;
        }
 
        if (StringUtil.isNotEmpty(systemCode)) {
            try {
                systemCode = URLDecoder.decode(systemCode, "UTF-8");
            } catch (Exception e) {
            }
            if (systemApi.getInfoByEnCode(systemCode) == null) {
                throw new NoPermiLoginException(MsgCode.PS032.get());
            }
        }
        AuthorizeVO authorizeModel = authorizeApi.getAuthorize(false, systemCode, isBackend);
 
        OtherModel otherModel = authorizeModel.getOtherModel();
        userInfo.setIsManageRole(otherModel.getIsManageRole());
        userInfo.setIsDevRole(otherModel.getIsDevRole());
        userInfo.setIsUserRole(otherModel.getIsUserRole());
        userInfo.setIsOtherRole(otherModel.getIsOtherRole());
        userInfo.setWorkflowEnabled(otherModel.getWorkflowEnabled());
        infoVO.setIsManageRole(userInfo.getIsManageRole());
        infoVO.setIsDevRole(userInfo.getIsDevRole());
        infoVO.setIsUserRole(userInfo.getIsUserRole());
        infoVO.setIsOtherRole(userInfo.getIsOtherRole());
        infoVO.setWorkflowEnabled(userInfo.getWorkflowEnabled());
        //当前系统信息
        SystemEntity currentSystem = authorizeModel.getCurrentSystem();
        if (currentSystem != null) {
            userInfo.setAppSystemId(currentSystem.getId());
            infoVO.setSystemId(currentSystem.getId());
            infoVO.setSystemName(currentSystem.getFullName());
            infoVO.setSystemCode(currentSystem.getEnCode());
            infoVO.setSystemIcon(currentSystem.getIcon());
            infoVO.setSystemColor(currentSystem.getBackgroundColor());
        }
 
 
        //身份
        infoVO.setStandingList(authorizeModel.getStandingList());
        List<SystemBaeModel> systemList = authorizeModel.getSystemList();
 
        // 获取菜单权限
        List<ModuleModel> moduleList = new ArrayList<>(authorizeModel.getModuleList());
        //当前pc或app权限过滤
        List<String> appComModule = new ArrayList<>();
        appComModule.add(JnpfConst.APP_BACKEND);
        appComModule.addAll(JnpfConst.APP_CONFIG_MODULE);
        appComModule.addAll(JnpfConst.ONLINE_DEV_MODULE);
        List<ModuleModel> moduleListRes = moduleList.stream().filter(t -> type.equals(t.getCategory())
                && (Objects.equals(isBackend, 1) || !appComModule.contains(t.getEnCode()))
                && !JnpfConst.APP_BACKEND.equals(t.getEnCode())
        ).sorted(Comparator.comparing(ModuleModel::getSortCode)).collect(Collectors.toList());
        List<PermissionModel> models = new ArrayList<>();
        for (ModuleModel moduleModel : moduleListRes) {
            if (JnpfConst.APP_CONFIG_CODE.equals(moduleModel.getEnCode()) || JnpfConst.ONLINE_DEV_CODE.equals(moduleModel.getEnCode())) {
                moduleModel.setParentId("-1");
            }
            PermissionModel model = new PermissionModel();
            model.setModelId(moduleModel.getId());
            model.setModuleName(moduleModel.getFullName());
            List<ButtonModel> buttonModels = authorizeModel.getButtonList().stream().filter(t -> moduleModel.getId().equals(t.getModuleId())).collect(Collectors.toList());
            List<ColumnModel> columnModels = authorizeModel.getColumnList().stream().filter(t -> moduleModel.getId().equals(t.getModuleId())).collect(Collectors.toList());
            List<ResourceModel> resourceModels = authorizeModel.getResourceList().stream().filter(t -> moduleModel.getId().equals(t.getModuleId())).collect(Collectors.toList());
            List<ModuleFormModel> moduleFormModels = authorizeModel.getFormsList().stream().filter(t -> moduleModel.getId().equals(t.getModuleId())).collect(Collectors.toList());
            model.setButton(JsonUtil.getJsonToList(buttonModels, PermissionVO.class));
            model.setColumn(JsonUtil.getJsonToList(columnModels, PermissionVO.class));
            model.setResource(JsonUtil.getJsonToList(resourceModels, PermissionVO.class));
            model.setForm(JsonUtil.getJsonToList(moduleFormModels, PermissionVO.class));
            if (moduleModel.getType() != 1) {
                models.add(model);
            }
        }
 
        // 获取签名信息
        SignEntity signEntity = signService.getDefaultByUserId(userEntity.getId());
        infoVO.setSignImg(signEntity != null ? signEntity.getSignImg() : "");
        infoVO.setSignId(signEntity != null ? signEntity.getId() : "");
 
        List<ModuleModel> collect = moduleListRes.stream().sorted(Comparator.comparing(ModuleModel::getSystemId).thenComparing(ModuleModel::getSortCode)).collect(Collectors.toList());
        List<AllUserMenuModel> needList = JsonUtil.getJsonToList(collect, AllUserMenuModel.class);
        List<SumTree<AllUserMenuModel>> needTree = TreeDotUtils.convertListToTreeDotFilter(needList);
        List<AllMenuSelectVO> menuvo = JsonUtil.getJsonToList(needTree, AllMenuSelectVO.class);
 
        SystemInfo jsonToBean = JsonUtil.getJsonToBean(baseSystemInfo, SystemInfo.class);
        jsonToBean.setJnpfDomain(configValueUtil.getApiDomain());
        PcUserVO userVO = new PcUserVO(menuvo, models, infoVO, jsonToBean);
        userVO.setCurrentSystemId(currentSystem != null ? currentSystem.getId() : null);
        userVO.getUserInfo().setHeadIcon(UploaderUtil.uploaderImg(userInfo.getUserIcon()));
        // 更新userInfo对象
        if (StringUtil.isNotEmpty(userInfo.getId())) {
            UserProvider.setLoginUser(userInfo);
            UserProvider.setLocalLoginUser(userInfo);
        }
 
        if (JnpfConst.WEB.equals(type)) {
            if (!JnpfConst.MAIN_SYSTEM_CODE.equals(systemCode)) {
                if (CollectionUtil.isEmpty(systemList)) {
                    throw new NoPermiLoginException(MsgCode.PS032.get());
                }
            }
        } else {
            if (CollectionUtil.isEmpty(systemList) || !systemList.stream().anyMatch(t -> !Objects.equals(t.getIsMain(), 1))) {
//                throw new NoPermiLoginException(MsgCode.LOG004.get());
                userVO.setCurrentSystemId(null); //如果需要自动切不提示替换成这段代码
            }
        }
 
        //判断开发者-有无后台
        List<String> sysIdList = systemApi.getAuthListByUser(userInfo.getUserId(), true).stream().map(SystemEntity::getId).collect(Collectors.toList());
        if (currentSystem != null && sysIdList.contains(currentSystem.getId())) {
            infoVO.setHasBackend(true);
        }
        //无后台权限
        if (Objects.equals(isBackend, 1) && !userInfo.getIsAdministrator() && !sysIdList.contains(currentSystem.getId())) {
            throw new LoginException(MsgCode.PS039.get());
        }
 
        //获取默认门户
        if (currentSystem != null && !JnpfConst.MAIN_SYSTEM_CODE.equals(currentSystem.getEnCode())) {
            List<String> webPortalIds = authorizeModel.getModuleList().stream().filter(t -> Objects.equals(t.getType(), 8)
                            && t.getCategory().equals(JnpfConst.WEB))
                    .map(ModuleModel::getId).collect(Collectors.toList());
            List<String> appPortalIds = authorizeModel.getModuleList().stream().filter(t -> Objects.equals(t.getType(), 8)
                            && t.getCategory().equals(JnpfConst.APP))
                    .map(ModuleModel::getId).collect(Collectors.toList());
            // 门户Web
            infoVO.setPortalId(portalDataService.getCurrentDefault(new DefaultModel(webPortalIds, currentSystem.getId(), userEntity.getId(), JnpfConst.WEB)));
            // 门户App
            infoVO.setAppPortalId(portalDataService.getCurrentDefault(new DefaultModel(appPortalIds, currentSystem.getId(), userEntity.getId(), JnpfConst.APP)));
        }
 
        //初始化接口权限
        if (securityProperties.isEnablePreAuth()) {
            // 如需使用远程事件, 改用publish
            PublishEventUtil.publishLocalEvent(new ProjectEventBuilder(EventConst.EVENT_INIT_LOGIN_PERMISSION, authorizeModel).setAsync(false));
        }
        return userVO;
    }
 
    @Override
    public BaseSystemInfo getBaseSystemConfig(String tenantId) {
        if (tenantId != null) {
            TenantDataSourceUtil.switchTenant(tenantId);
        }
        return sysconfigApi.getSysInfo(tenantId);
    }
 
    private List<AllMenuSelectVO> buildModule(List<SystemBaeModel> systemList, List<ModuleModel> moduleList, String type, UserEntity entity, UserCommonInfoVO infoVO, String systemCode, BaseSystemInfo baseSystemInfo) {
        List<String> moduleCode = new ArrayList<>(JnpfConst.MODULE_CODE);
        if (!Objects.equals(baseSystemInfo.getFlowSign(), 1)) {
            moduleCode.remove(JnpfConst.WORK_FLOWSIGN);
        }
        if (!Objects.equals(baseSystemInfo.getFlowTodo(), 1)) {
            moduleCode.remove(JnpfConst.WORK_FLOWTODO);
        }
        moduleList = moduleList.stream().filter(t -> type.equals(t.getCategory())).sorted(Comparator.comparing(ModuleModel::getSortCode)).collect(Collectors.toList());
        List<AllUserMenuModel> list = JsonUtil.getJsonToList(moduleList, AllUserMenuModel.class);
        list.forEach(t -> {
            if ("-1".equals(t.getParentId())) {
                t.setParentId(t.getSystemId());
            }
        });
        List<AllUserMenuModel> jsonToList = JsonUtil.getJsonToList(systemList, AllUserMenuModel.class);
        jsonToList.forEach(t -> {
            t.setType(0);
            t.setParentId("-1");
        });
        list.addAll(jsonToList);
        List<SumTree<AllUserMenuModel>> menuList = TreeDotUtils.convertListToTreeDotFilter(list);
        List<AllMenuSelectVO> menuvo = JsonUtil.getJsonToList(menuList, AllMenuSelectVO.class);
        return menuvo;
    }
 
    /**
     * userInfo添加组织、岗位、分组、角色的关系
     * 默认组织和默认岗位
     *
     * @param userInfo
     * @param userEntity
     */
    private UserOrgPosModel userInfo(UserInfo userInfo, UserEntity userEntity) {
        UserOrgPosModel uopm = new UserOrgPosModel();
        // 得到用户和组织、岗位、分组、角色的关系
        List<UserRelationEntity> data = userRelationApi.getListByUserId(userInfo.getUserId());
        List<String> positionIds = data.stream().filter(t -> PermissionConst.POSITION.equalsIgnoreCase(t.getObjectType())).map(UserRelationEntity::getObjectId).collect(Collectors.toList());
        List<String> groupIds = data.stream().filter(t -> PermissionConst.GROUP.equalsIgnoreCase(t.getObjectType())).map(UserRelationEntity::getObjectId).collect(Collectors.toList());
 
        List<PositionEntity> positionList = positionApi.getListByIds(positionIds);
        List<String> orgIds = new ArrayList<>(positionList.stream().map(PositionEntity::getOrganizeId).collect(Collectors.toSet()));
        List<OrganizeEntity> organizeList = organizeApi.getListByIds(orgIds);
        List<GroupEntity> groupList = groupApi.getListByIds(groupIds);
 
        List<String> allIds = new ArrayList<>();
        allIds.addAll(orgIds);
        allIds.addAll(positionIds);
        allIds.add(userEntity.getId());
        List<RoleRelationEntity> roleRelationList = roleRelationApi.getListByObjectId(new RoleRelationModel(allIds, null));
        List<String> roleIds = roleRelationList.stream().map(RoleRelationEntity::getRoleId).collect(Collectors.toList());
        List<RoleEntity> roleList = roleApi.getListByIds(roleIds);
 
        userInfo.setOrganizeIds(orgIds);
        userInfo.setPositionIds(positionIds);
        userInfo.setGroupIds(groupIds);
        userInfo.setRoleIds(roleIds);
 
        //组织全名,岗位全名
        List<KeyNameModel> organizeListRes = organizeList.stream().map(t -> {
            KeyNameModel jsonb = JsonUtil.getJsonToBean(t, KeyNameModel.class);
            jsonb.setTreeName(t.getOrgNameTree());
            jsonb.setTreeId(t.getOrganizeIdTree());
            return jsonb;
        }).collect(Collectors.toList());
        List<KeyNameModel> positionListRes = positionList.stream().map(t -> {
            KeyNameModel jsonb = JsonUtil.getJsonToBean(t, KeyNameModel.class);
            OrganizeEntity organizeEntity = organizeList.stream().filter(m -> m.getId().equals(t.getOrganizeId())).findFirst().orElse(new OrganizeEntity());
            jsonb.setTreeName(organizeEntity.getOrgNameTree() + "/" + t.getFullName());
            jsonb.setTreeId(t.getPositionIdTree());
            return jsonb;
        }).collect(Collectors.toList());
        uopm.setOrganizeList(organizeListRes);
        uopm.setPositionList(positionListRes);
        uopm.setGroupList(JsonUtil.getJsonToList(groupList, KeyNameModel.class));
        uopm.setRoleList(JsonUtil.getJsonToList(roleList, KeyNameModel.class));
        userInfo.setIsManageRole(false);
        userInfo.setIsDevRole(false);
        userInfo.setIsUserRole(false);
        userInfo.setIsOtherRole(false);
        for (RoleEntity roleEntity : roleList) {
            if (PermissionConst.MANAGER_CODE.equals(roleEntity.getEnCode())) {
                userInfo.setIsManageRole(true);
            } else if (PermissionConst.DEVELOPER_CODE.equals(roleEntity.getEnCode())) {
                userInfo.setIsDevRole(true);
            } else if (PermissionConst.USER_CODE.equals(roleEntity.getEnCode())) {
                userInfo.setIsUserRole(true);
            } else {
                userInfo.setIsOtherRole(true);
            }
        }
 
        //默认组织和默认岗位
        String organizeId = userEntity.getOrganizeId();
        String positionId = userEntity.getPositionId();
        if (CollectionUtil.isNotEmpty(orgIds)) {
            if (!orgIds.contains(userEntity.getOrganizeId())) {
                organizeId = orgIds.get(0);
            }
        }
        if (CollectionUtil.isNotEmpty(positionIds)) {
            if (!positionIds.contains(userEntity.getPositionId())) {
                positionId = positionIds.get(0);
            }
        }
        userInfo.setOrganizeId(organizeId);
        userInfo.setPositionId(positionId);
 
        // 修改用户信息
        userEntity.setOrganizeId(organizeId);
        userEntity.setPositionId(positionId);
        userApi.updateById(new UserUpdateModel(userEntity, userInfo.getTenantId()));
 
        //todo 我的下属。重写
        userInfo.setManagerId(userEntity.getManagerId());
        //获取岗位
        List<UserRelationEntity> listByObjectType = userRelationApi.getListByUserIdAndObjType(userInfo.getUserId(), PermissionConst.POSITION);
        if (CollectionUtil.isNotEmpty(listByObjectType)) {
            List<String> collect = listByObjectType.stream()
                    .map(UserRelationEntity::getObjectId)
                    .collect(Collectors.toList());
            //获取子岗位
            List<String> sonPositionIdList = positionApi.getListByParentIds(collect).stream()
                    .map(SuperBaseEntity.SuperIBaseEntity::getId)
                    .collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(sonPositionIdList)) {
                List<String> userIds = userRelationApi.getListByObjectIdAll(sonPositionIdList).stream()
                        .map(UserRelationEntity::getUserId)
                        .collect(Collectors.toList());
                userIds.add(userInfo.getUserId());
                userInfo.setSubordinateIds(userIds);
 
            }
 
        }
        userInfo.setLoginTime(DateUtil.getmmNow());
        return uopm;
    }
 
}