LoginServiceImpl.java 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. package jnpf.service.impl;
  2. import cn.hutool.core.bean.BeanUtil;
  3. import cn.hutool.core.collection.CollectionUtil;
  4. import cn.hutool.core.net.url.UrlBuilder;
  5. import cn.hutool.core.util.BooleanUtil;
  6. import cn.hutool.core.util.ObjectUtil;
  7. import cn.hutool.http.useragent.UserAgent;
  8. import cn.hutool.http.useragent.UserAgentUtil;
  9. import jnpf.base.KeyNameModel;
  10. import jnpf.base.UserInfo;
  11. import jnpf.base.UserOrgPosModel;
  12. import jnpf.base.entity.SuperBaseEntity;
  13. import jnpf.base.entity.SystemEntity;
  14. import jnpf.base.model.base.SystemBaeModel;
  15. import jnpf.base.model.button.ButtonModel;
  16. import jnpf.base.model.column.ColumnModel;
  17. import jnpf.base.model.form.ModuleFormModel;
  18. import jnpf.base.model.module.ModuleModel;
  19. import jnpf.base.model.resource.ResourceModel;
  20. import jnpf.base.service.ModuleService;
  21. import jnpf.base.service.SignService;
  22. import jnpf.base.service.SysconfigService;
  23. import jnpf.base.service.SystemService;
  24. import jnpf.config.ConfigValueUtil;
  25. import jnpf.constant.EventConst;
  26. import jnpf.constant.JnpfConst;
  27. import jnpf.constant.MsgCode;
  28. import jnpf.constant.PermissionConst;
  29. import jnpf.database.util.TenantDataSourceUtil;
  30. import jnpf.exception.LoginException;
  31. import jnpf.exception.NoPermiLoginException;
  32. import jnpf.exception.TenantDatabaseException;
  33. import jnpf.granter.UserDetailsServiceBuilder;
  34. import jnpf.message.entity.MessageTemplateConfigEntity;
  35. import jnpf.message.service.MessageService;
  36. import jnpf.message.service.MessageTemplateConfigService;
  37. import jnpf.model.BaseSystemInfo;
  38. import jnpf.model.BuildUserCommonInfoModel;
  39. import jnpf.model.login.*;
  40. import jnpf.model.tenant.TenantVO;
  41. import jnpf.module.ProjectEventBuilder;
  42. import jnpf.permission.entity.*;
  43. import jnpf.permission.model.authorize.AuthorizeVO;
  44. import jnpf.permission.model.authorize.OtherModel;
  45. import jnpf.permission.service.*;
  46. import jnpf.portal.service.PortalDataService;
  47. import jnpf.properties.SecurityProperties;
  48. import jnpf.service.LoginService;
  49. import jnpf.util.*;
  50. import jnpf.util.context.RequestContext;
  51. import jnpf.util.treeutil.SumTree;
  52. import jnpf.util.treeutil.newtreeutil.TreeDotUtils;
  53. import lombok.extern.slf4j.Slf4j;
  54. import org.springframework.beans.factory.annotation.Autowired;
  55. import org.springframework.stereotype.Service;
  56. import java.util.*;
  57. import java.util.stream.Collectors;
  58. import static jnpf.util.Constants.ADMIN_KEY;
  59. /**
  60. * @author JNPF开发平台组
  61. * @version V3.1.0
  62. * @copyright 引迈信息技术有限公司(<a href="https://www.jnpfsoft.com">...</a>)
  63. * @date 2021/3/16
  64. */
  65. @Slf4j
  66. @Service
  67. public class LoginServiceImpl implements LoginService {
  68. @Autowired
  69. private ConfigValueUtil configValueUtil;
  70. @Autowired
  71. private SecurityProperties securityProperties;
  72. @Autowired
  73. private UserService userApi;
  74. @Autowired
  75. private UserRelationService userRelationApi;
  76. @Autowired
  77. private RoleRelationService roleRelationApi;
  78. @Autowired
  79. private OrganizeService organizeApi;
  80. @Autowired
  81. private PositionService positionApi;
  82. @Autowired
  83. private RoleService roleApi;
  84. @Autowired
  85. private GroupService groupApi;
  86. @Autowired
  87. private AuthorizeService authorizeApi;
  88. @Autowired
  89. private SysconfigService sysconfigApi;
  90. @Autowired
  91. private PortalDataService portalDataService;
  92. @Autowired
  93. private RedisUtil redisUtil;
  94. @Autowired
  95. private CacheKeyUtil cacheKeyUtil;
  96. @Autowired
  97. private SystemService systemApi;
  98. @Autowired
  99. private UserDetailsServiceBuilder userDetailsServiceBuilder;
  100. @Autowired
  101. private SignService signService;
  102. @Autowired
  103. private MessageTemplateConfigService messageTemplateApi;
  104. @Autowired
  105. private MessageService sentMessageApi;
  106. @Autowired
  107. private ModuleService moduleApi;
  108. @Autowired
  109. private RoleRelationService roleRelationService;
  110. @Autowired
  111. private UserExtraService userExtraService;
  112. @Override
  113. public UserInfo getTenantAccount(UserInfo userInfo) throws LoginException {
  114. String tenantId = null;
  115. if (configValueUtil.isMultiTenancy()) {
  116. String[] tenantAccount = userInfo.getUserAccount().split("\\@");
  117. if (tenantAccount.length == 1) {
  118. //只输入账号, 1:配置的二级域名下只输入账号, 2:主域名下输入了租户号
  119. String referer = ServletUtil.getHeader("Referer");
  120. if (StringUtil.isNotEmpty(referer)) {
  121. String remoteHost = UrlBuilder.of(referer).getHost();
  122. String apiHost = UrlBuilder.of(RequestContext.isOrignPc() ? configValueUtil.getFrontDomain() : configValueUtil.getAppDomain()).getHost();
  123. if (!ObjectUtil.equals(remoteHost, apiHost)
  124. && remoteHost.endsWith(apiHost)) {
  125. //二级域名访问, 输入的是账号
  126. tenantId = remoteHost.split("\\.")[0];
  127. userInfo.setUserAccount(tenantAccount[0]);
  128. }
  129. }
  130. if (tenantId == null) {
  131. //主域名访问, 输入的是租户号
  132. tenantId = tenantAccount[0];
  133. userInfo.setUserAccount(ADMIN_KEY);
  134. }
  135. } else {
  136. //租户号@账号
  137. tenantId = tenantAccount[0];
  138. userInfo.setUserAccount(tenantAccount[1]);
  139. }
  140. if (StringUtil.isEmpty(tenantId) || tenantAccount.length > 2 || StringUtil.isEmpty(userInfo.getUserAccount())) {
  141. throw new LoginException(MsgCode.LOG102.get());
  142. }
  143. TenantVO tenantVO = TenantDataSourceUtil.getRemoteTenantInfo(tenantId);
  144. TenantDataSourceUtil.switchTenant(tenantId, tenantVO);
  145. //切换成租户库
  146. userInfo.setTenantId(tenantId);
  147. userInfo.setTenantDbConnectionString(tenantVO.getDbName());
  148. userInfo.setTenantDbType(tenantVO.getType());
  149. //查库测试
  150. BaseSystemInfo baseSystemInfo = null;
  151. try {
  152. baseSystemInfo = getBaseSystemConfig(userInfo.getTenantId());
  153. } catch (Exception e) {
  154. log.error("登录获取系统配置失败: {}", e.getMessage());
  155. }
  156. if (baseSystemInfo == null || baseSystemInfo.getSingleLogin() == null) {
  157. throw new TenantDatabaseException();
  158. }
  159. }
  160. return userInfo;
  161. }
  162. @Override
  163. public UserInfo userInfo(UserInfo userInfo, BaseSystemInfo sysConfigInfo) throws LoginException {
  164. //获取账号信息
  165. UserEntity userEntity = LoginHolder.getUserEntity();
  166. if (userEntity == null) {
  167. userEntity = userDetailsServiceBuilder.getUserDetailService(userInfo.getUserDetailKey()).loadUserEntity(userInfo);
  168. LoginHolder.setUserEntity(userEntity);
  169. }
  170. checkUser(userEntity, userInfo, sysConfigInfo);
  171. userInfo.setUserId(userEntity.getId());
  172. userInfo.setUserAccount(userEntity.getAccount());
  173. userInfo.setUserName(userEntity.getRealName());
  174. userInfo.setUserIcon(userEntity.getHeadIcon());
  175. userInfo.setTheme(userEntity.getTheme());
  176. userInfo.setOrganizeId(userEntity.getOrganizeId());
  177. userInfo.setPortalId(userEntity.getPortalId());
  178. userInfo.setIsAdministrator(BooleanUtil.toBoolean(String.valueOf((userEntity.getIsAdministrator()))));
  179. if (!ADMIN_KEY.equals(userInfo.getUserAccount())) {
  180. if (ObjectUtil.isNotEmpty(userEntity.getStanding())) {
  181. userInfo.setIsAdministrator(Objects.equals(userEntity.getStanding(), 1));
  182. }
  183. }
  184. // 添加过期时间
  185. String time = sysConfigInfo.getTokenTimeout();
  186. if (StringUtil.isNotEmpty(time)) {
  187. Integer minu = Integer.valueOf(time);
  188. userInfo.setOverdueTime(DateUtil.dateAddMinutes(null, minu));
  189. userInfo.setTokenTimeout(minu);
  190. }
  191. String ipAddr = IpUtil.getIpAddr();
  192. userInfo.setLoginIpAddress(ipAddr);
  193. userInfo.setLoginIpAddressName(IpUtil.getIpCity(ipAddr));
  194. userInfo.setLoginTime(DateUtil.getmmNow());
  195. UserAgent userAgent = UserAgentUtil.parse(ServletUtil.getUserAgent());
  196. if (userAgent != null) {
  197. userInfo.setLoginPlatForm(userAgent.getPlatform().getName() + " " + userAgent.getOsVersion());
  198. userInfo.setBrowser(userAgent.getBrowser().getName() + " " + userAgent.getVersion());
  199. }
  200. userInfo.setPrevLoginTime(userEntity.getPrevLogTime());
  201. userInfo.setPrevLoginIpAddress(userEntity.getPrevLogIp());
  202. userInfo.setPrevLoginIpAddressName(IpUtil.getIpCity(userEntity.getPrevLogIp()));
  203. // 生成id
  204. String token = RandomUtil.uuId();
  205. userInfo.setId(cacheKeyUtil.getLoginToken(userInfo.getTenantId()) + token);
  206. createUserOnline(userInfo);
  207. return userInfo;
  208. }
  209. @Override
  210. public void updatePasswordMessage() {
  211. UserInfo userInfo = UserProvider.getUser();
  212. UserEntity userEntity = userApi.getInfo(userInfo.getUserId());
  213. BaseSystemInfo baseSystemInfo = sysconfigApi.getSysInfo();
  214. if (baseSystemInfo.getPasswordIsUpdatedRegularly() == 1) {
  215. Date changePasswordDate = userEntity.getCreatorTime();
  216. if (userEntity.getChangePasswordDate() != null) {
  217. changePasswordDate = userEntity.getChangePasswordDate();
  218. }
  219. //当前时间
  220. Date nowDate = DateUtil.getNowDate();
  221. //更新周期
  222. Integer updateCycle = baseSystemInfo.getUpdateCycle();
  223. //提前N天提醒
  224. Integer updateInAdvance = baseSystemInfo.getUpdateInAdvance();
  225. Integer day = DateUtil.getDiffDays(changePasswordDate, nowDate);
  226. if (day >= (updateCycle - updateInAdvance)) {
  227. MessageTemplateConfigEntity entity = messageTemplateApi.getInfoByEnCode("XTXXTX001", "1");
  228. if (entity != null) {
  229. List<String> toUserIds = new ArrayList<>();
  230. toUserIds.add(userInfo.getUserId());
  231. sentMessageApi.sentMessage(toUserIds, entity.getTitle(), entity.getContent(), userInfo, Integer.parseInt(entity.getMessageSource()), Integer.parseInt(entity.getMessageType()));
  232. }
  233. }
  234. }
  235. }
  236. /**
  237. * 创建用户在线信息
  238. *
  239. * @param userInfo
  240. */
  241. private void createUserOnline(UserInfo userInfo) {
  242. String userId = userInfo.getUserId();
  243. // long time= DateUtil.getTime(userInfo.getOverdueTime()) - DateUtil.getTime(new Date());
  244. String authorize = String.valueOf(redisUtil.getString(cacheKeyUtil.getUserAuthorize() + userId));
  245. // String loginOnlineKey=cacheKeyUtil.getLoginOnline() + userId;
  246. redisUtil.remove(authorize);
  247. //记录Token
  248. // redisUtil.insert(userInfo.getId(), userInfo,time);
  249. //记录在线
  250. if (ServletUtil.getIsMobileDevice()) {
  251. // redisUtil.insert(cacheKeyUtil.getMobileLoginOnline() + userId, userInfo.getId(), time);
  252. //记录移动设备CID,用于消息推送
  253. if (ServletUtil.getHeader("clientId") != null) {
  254. String clientId = ServletUtil.getHeader("clientId");
  255. Map<String, String> map = new HashMap<>(16);
  256. map.put(userInfo.getUserId(), clientId);
  257. redisUtil.insert(cacheKeyUtil.getMobileDeviceList(), map);
  258. }
  259. } else {
  260. // redisUtil.insert(loginOnlineKey, userInfo.getId(), time);
  261. }
  262. }
  263. private UserCommonInfoVO data(BuildUserCommonInfoModel buildUserCommonInfoModel) {
  264. UserInfo userInfo = buildUserCommonInfoModel.getUserInfo();
  265. UserEntity userEntity = buildUserCommonInfoModel.getUserEntity();
  266. UserExtraEntity userExtraByUserId = userExtraService.getUserExtraByUserId(userInfo.getUserId());
  267. //userInfo 填充信息
  268. UserOrgPosModel uopm = this.userInfo(userInfo, userEntity);
  269. //返回前端vo
  270. BaseSystemInfo baseSystemInfo = buildUserCommonInfoModel.getBaseSystemInfo();
  271. UserCommonInfoVO infoVO = JsonUtil.getJsonToBean(userInfo, UserCommonInfoVO.class);
  272. infoVO.setPrevLogin(baseSystemInfo.getLastLoginTimeSwitch() == 1 ? 1 : 0);
  273. if (BeanUtil.isNotEmpty(userExtraByUserId)) {
  274. infoVO.setPreferenceJson(userExtraByUserId.getPreferenceJson());
  275. }
  276. //最后一次修改密码时间
  277. infoVO.setChangePasswordDate(userEntity.getChangePasswordDate());
  278. // 姓名
  279. infoVO.setUserName(userEntity.getRealName());
  280. // 组织名称
  281. KeyNameModel defaultOrg = uopm.getOrganizeList().stream().filter(t -> t.getId().equals(userInfo.getOrganizeId())).findFirst().orElse(new KeyNameModel());
  282. infoVO.setOrganizeName(defaultOrg.getFullName());
  283. // 岗位名称
  284. KeyNameModel defaultPos = uopm.getPositionList().stream().filter(t -> t.getId().equals(userInfo.getPositionId())).findFirst().orElse(new KeyNameModel());
  285. infoVO.setPositionName(defaultPos.getFullName());
  286. //是否超级管理员
  287. infoVO.setIsAdministrator(BooleanUtil.toBoolean(String.valueOf(userEntity.getIsAdministrator())));
  288. if (!ADMIN_KEY.equals(userEntity.getAccount())) {
  289. if (ObjectUtil.isNotEmpty(userEntity.getStanding())) {
  290. userInfo.setIsAdministrator(Objects.equals(userEntity.getStanding(), 1));
  291. infoVO.setIsAdministrator(Objects.equals(userEntity.getStanding(), 1));
  292. }
  293. }
  294. infoVO.setSecurityKey(userInfo.getSecurityKey());
  295. return infoVO;
  296. }
  297. public UserEntity checkUser(UserEntity userEntity, UserInfo userInfo, BaseSystemInfo sysConfigInfo) throws LoginException {
  298. if (userEntity == null) {
  299. throw new LoginException(MsgCode.LOG101.get());
  300. }
  301. //判断是否组织、岗位、角色、部门主管是否为空,为空则抛出异常
  302. //判断是否为管理员,是否为Admin(Admin为最高账号,不受限制)
  303. if (!ADMIN_KEY.equals(userEntity.getAccount()) || userEntity.getIsAdministrator() != 1) {
  304. List<String> posAndRole = new ArrayList<>();
  305. //没岗位,且没用户角色时直接提示没权限
  306. List<UserRelationEntity> userPos = userRelationApi.getListByUserIdAndObjType(userEntity.getId(), PermissionConst.POSITION);
  307. List<String> userPosIds = userPos.stream().map(t -> t.getObjectId()).collect(Collectors.toList());
  308. userPosIds.add(userEntity.getId());
  309. List<RoleRelationEntity> userRole = roleRelationApi.getListByObjectId(userPosIds, null);
  310. posAndRole.addAll(userPosIds);
  311. posAndRole.addAll(userRole.stream().map(t -> t.getRoleId()).collect(Collectors.toList()));
  312. //有岗位角色但是没有权限
  313. if (CollectionUtil.isEmpty(posAndRole) || CollectionUtil.isEmpty(authorizeApi.getListByObjectId(posAndRole))) {
  314. throw new LoginException(MsgCode.LOG004.get());
  315. }
  316. }
  317. if (userEntity.getIsAdministrator() == 0) {
  318. if (userEntity.getEnabledMark() == null) {
  319. throw new LoginException(MsgCode.LOG005.get());
  320. }
  321. if (userEntity.getEnabledMark() == 0) {
  322. throw new LoginException(MsgCode.LOG006.get());
  323. }
  324. }
  325. if (userEntity.getDeleteMark() != null && userEntity.getDeleteMark() == 1) {
  326. throw new LoginException(MsgCode.LOG007.get());
  327. }
  328. //安全验证
  329. String ipAddr = IpUtil.getIpAddr();
  330. userInfo.setLoginIpAddress(IpUtil.getIpAddr());
  331. // 判断白名单
  332. if (!ADMIN_KEY.equals(userEntity.getAccount()) && "1".equals(sysConfigInfo.getWhitelistSwitch())) {
  333. List<String> ipList = Arrays.asList(sysConfigInfo.getWhitelistIp().split(","));
  334. if (!ipList.contains(ipAddr)) {
  335. throw new LoginException(MsgCode.LOG010.get());
  336. }
  337. }
  338. // 判断当前账号是否被锁定
  339. Integer lockMark = userEntity.getEnabledMark();
  340. if (Objects.nonNull(lockMark) && lockMark == 2) {
  341. // 获取解锁时间
  342. Date unlockTime = userEntity.getUnlockTime();
  343. // 账号锁定
  344. if (sysConfigInfo.getLockType() == 1 || Objects.isNull(unlockTime)) {
  345. throw new LoginException(MsgCode.LOG012.get());
  346. }
  347. // 延迟登陆锁定
  348. long millis = System.currentTimeMillis();
  349. // 系统设置的错误次数
  350. int passwordErrorsNumber = sysConfigInfo.getPasswordErrorsNumber() != null ? sysConfigInfo.getPasswordErrorsNumber() : 0;
  351. // 用户登录错误次数
  352. int logErrorCount = userEntity.getLogErrorCount() != null ? userEntity.getLogErrorCount() : 0;
  353. if (unlockTime.getTime() > millis) {
  354. // 转成分钟
  355. int time = (int) ((unlockTime.getTime() - millis) / (1000 * 60));
  356. throw new LoginException(MsgCode.LOG108.get(time + 1));
  357. } else if (unlockTime.getTime() < millis && logErrorCount >= passwordErrorsNumber) {
  358. // 已经接触错误时间锁定的话就重置错误次数
  359. userEntity.setLogErrorCount(0);
  360. userEntity.setEnabledMark(1);
  361. userApi.updateById(userEntity);
  362. }
  363. }
  364. return userEntity;
  365. }
  366. /**
  367. * 获取用户登陆信息
  368. *
  369. * @return
  370. */
  371. @Override
  372. public PcUserVO getCurrentUser(String type, String systemCode, Integer isBackend) {
  373. UserInfo userInfo = UserProvider.getUser();
  374. UserEntity userEntity = userApi.getInfo(userInfo.getUserId());
  375. if (userEntity == null) {
  376. return null;
  377. }
  378. userInfo.setIsBackend(isBackend);
  379. BaseSystemInfo baseSystemInfo = sysconfigApi.getSysInfo();
  380. BuildUserCommonInfoModel buildUserCommonInfoModel = new BuildUserCommonInfoModel(userInfo, userEntity, baseSystemInfo, type);
  381. //添加userInfo信息
  382. UserCommonInfoVO infoVO = this.data(buildUserCommonInfoModel);
  383. //获取权限
  384. if (StringUtil.isEmpty(systemCode) && JnpfConst.WEB.equals(type)) {
  385. systemCode = JnpfConst.MAIN_SYSTEM_CODE;
  386. } else if (StringUtil.isEmpty(systemCode) && JnpfConst.APP.equals(type)) {
  387. SystemEntity sysInfo = systemApi.getInfo(userEntity.getAppSystemId());
  388. systemCode = sysInfo != null ? sysInfo.getEnCode() : null;
  389. }
  390. AuthorizeVO authorizeModel = authorizeApi.getAuthorize(false, systemCode, isBackend);
  391. OtherModel otherModel = authorizeModel.getOtherModel();
  392. userInfo.setIsManageRole(otherModel.getIsManageRole());
  393. userInfo.setIsDevRole(otherModel.getIsDevRole());
  394. userInfo.setIsUserRole(otherModel.getIsUserRole());
  395. userInfo.setIsOtherRole(otherModel.getIsOtherRole());
  396. userInfo.setWorkflowEnabled(otherModel.getWorkflowEnabled());
  397. infoVO.setIsManageRole(userInfo.getIsManageRole());
  398. infoVO.setIsDevRole(userInfo.getIsDevRole());
  399. infoVO.setIsUserRole(userInfo.getIsUserRole());
  400. infoVO.setIsOtherRole(userInfo.getIsOtherRole());
  401. infoVO.setWorkflowEnabled(userInfo.getWorkflowEnabled());
  402. //当前系统信息
  403. SystemEntity currentSystem = authorizeModel.getCurrentSystem();
  404. if (currentSystem != null) {
  405. userInfo.setAppSystemId(currentSystem.getId());
  406. infoVO.setSystemId(currentSystem.getId());
  407. infoVO.setSystemName(currentSystem.getFullName());
  408. infoVO.setSystemCode(currentSystem.getEnCode());
  409. infoVO.setSystemIcon(currentSystem.getIcon());
  410. infoVO.setSystemColor(currentSystem.getBackgroundColor());
  411. }
  412. //身份
  413. infoVO.setStandingList(authorizeModel.getStandingList());
  414. List<SystemBaeModel> systemList = authorizeModel.getSystemList();
  415. // 获取菜单权限
  416. List<ModuleModel> moduleList = authorizeModel.getModuleList();
  417. //当前pc或app权限过滤
  418. List<ModuleModel> moduleListRes = moduleList.stream().filter(t -> type.equals(t.getCategory())).sorted(Comparator.comparing(ModuleModel::getSortCode)).collect(Collectors.toList());
  419. List<PermissionModel> models = new ArrayList<>();
  420. for (ModuleModel moduleModel : moduleListRes) {
  421. PermissionModel model = new PermissionModel();
  422. model.setModelId(moduleModel.getId());
  423. model.setModuleName(moduleModel.getFullName());
  424. List<ButtonModel> buttonModels = authorizeModel.getButtonList().stream().filter(t -> moduleModel.getId().equals(t.getModuleId())).collect(Collectors.toList());
  425. List<ColumnModel> columnModels = authorizeModel.getColumnList().stream().filter(t -> moduleModel.getId().equals(t.getModuleId())).collect(Collectors.toList());
  426. List<ResourceModel> resourceModels = authorizeModel.getResourceList().stream().filter(t -> moduleModel.getId().equals(t.getModuleId())).collect(Collectors.toList());
  427. List<ModuleFormModel> moduleFormModels = authorizeModel.getFormsList().stream().filter(t -> moduleModel.getId().equals(t.getModuleId())).collect(Collectors.toList());
  428. model.setButton(JsonUtil.getJsonToList(buttonModels, PermissionVO.class));
  429. model.setColumn(JsonUtil.getJsonToList(columnModels, PermissionVO.class));
  430. model.setResource(JsonUtil.getJsonToList(resourceModels, PermissionVO.class));
  431. model.setForm(JsonUtil.getJsonToList(moduleFormModels, PermissionVO.class));
  432. if (moduleModel.getType() != 1) {
  433. models.add(model);
  434. }
  435. }
  436. // 获取签名信息
  437. SignEntity signEntity = signService.getDefaultByUserId(userEntity.getId());
  438. infoVO.setSignImg(signEntity != null ? signEntity.getSignImg() : "");
  439. infoVO.setSignId(signEntity != null ? signEntity.getId() : "");
  440. List<ModuleModel> collect = moduleListRes.stream().sorted(Comparator.comparing(ModuleModel::getSystemId).thenComparing(ModuleModel::getSortCode)).collect(Collectors.toList());
  441. List<AllUserMenuModel> needList = JsonUtil.getJsonToList(collect, AllUserMenuModel.class);
  442. List<SumTree<AllUserMenuModel>> needTree = TreeDotUtils.convertListToTreeDotFilter(needList);
  443. List<AllMenuSelectVO> menuvo = JsonUtil.getJsonToList(needTree, AllMenuSelectVO.class);
  444. SystemInfo jsonToBean = JsonUtil.getJsonToBean(baseSystemInfo, SystemInfo.class);
  445. jsonToBean.setJnpfDomain(configValueUtil.getApiDomain());
  446. PcUserVO userVO = new PcUserVO(menuvo, models, infoVO, jsonToBean);
  447. userVO.setCurrentSystemId(currentSystem != null ? currentSystem.getId() : null);
  448. userVO.getUserInfo().setHeadIcon(UploaderUtil.uploaderImg(userInfo.getUserIcon()));
  449. // 更新userInfo对象
  450. if (StringUtil.isNotEmpty(userInfo.getId())) {
  451. UserProvider.setLoginUser(userInfo);
  452. UserProvider.setLocalLoginUser(userInfo);
  453. }
  454. if (JnpfConst.WEB.equals(type)) {
  455. if (!JnpfConst.MAIN_SYSTEM_CODE.equals(systemCode)) {
  456. if (CollectionUtil.isEmpty(systemList)) {
  457. throw new NoPermiLoginException(MsgCode.PS032.get());
  458. }
  459. }
  460. } else {
  461. if (CollectionUtil.isEmpty(systemList) || !systemList.stream().anyMatch(t -> !Objects.equals(t.getIsMain(), 1))) {
  462. // throw new NoPermiLoginException(MsgCode.LOG004.get());
  463. userVO.setCurrentSystemId(null); //如果需要自动切不提示替换成这段代码
  464. }
  465. }
  466. //判断开发者-有无后台
  467. List<String> sysIdList = systemApi.getAuthListByUser(userInfo.getUserId(), true).stream().map(SystemEntity::getId).collect(Collectors.toList());
  468. if (currentSystem != null && sysIdList.contains(currentSystem.getId())) {
  469. infoVO.setHasBackend(true);
  470. }
  471. //无后台权限
  472. if (Objects.equals(isBackend, 1) && !userInfo.getIsAdministrator() && !sysIdList.contains(currentSystem.getId())) {
  473. throw new LoginException(MsgCode.PS039.get());
  474. }
  475. //获取默认门户
  476. if (currentSystem != null && !JnpfConst.MAIN_SYSTEM_CODE.equals(currentSystem.getEnCode())) {
  477. List<String> webPortalIds = authorizeModel.getModuleList().stream().filter(t -> Objects.equals(t.getType(), 8)
  478. && t.getCategory().equals(JnpfConst.WEB))
  479. .map(ModuleModel::getId).collect(Collectors.toList());
  480. List<String> appPortalIds = authorizeModel.getModuleList().stream().filter(t -> Objects.equals(t.getType(), 8)
  481. && t.getCategory().equals(JnpfConst.APP))
  482. .map(ModuleModel::getId).collect(Collectors.toList());
  483. // 门户Web
  484. infoVO.setPortalId(portalDataService.getCurrentDefault(webPortalIds, currentSystem.getId(), userEntity.getId(), JnpfConst.WEB));
  485. // 门户App
  486. infoVO.setAppPortalId(portalDataService.getCurrentDefault(appPortalIds, currentSystem.getId(), userEntity.getId(), JnpfConst.APP));
  487. }
  488. //初始化接口权限
  489. if (securityProperties.isEnablePreAuth()) {
  490. // 如需使用远程事件, 改用publish
  491. PublishEventUtil.publishLocalEvent(new ProjectEventBuilder(EventConst.EVENT_INIT_LOGIN_PERMISSION, authorizeModel).setAsync(false));
  492. }
  493. return userVO;
  494. }
  495. @Override
  496. public BaseSystemInfo getBaseSystemConfig(String tenantId) {
  497. if (tenantId != null) {
  498. TenantDataSourceUtil.switchTenant(tenantId);
  499. }
  500. return sysconfigApi.getSysInfo();
  501. }
  502. private List<AllMenuSelectVO> buildModule(List<SystemBaeModel> systemList, List<ModuleModel> moduleList, String type, UserEntity entity, UserCommonInfoVO infoVO, String systemCode, BaseSystemInfo baseSystemInfo) {
  503. List<String> moduleCode = new ArrayList<>(JnpfConst.MODULE_CODE);
  504. if (!Objects.equals(baseSystemInfo.getFlowSign(), 1)) {
  505. moduleCode.remove(JnpfConst.WORK_FLOWSIGN);
  506. }
  507. if (!Objects.equals(baseSystemInfo.getFlowTodo(), 1)) {
  508. moduleCode.remove(JnpfConst.WORK_FLOWTODO);
  509. }
  510. moduleList = moduleList.stream().filter(t -> type.equals(t.getCategory())).sorted(Comparator.comparing(ModuleModel::getSortCode)).collect(Collectors.toList());
  511. List<AllUserMenuModel> list = JsonUtil.getJsonToList(moduleList, AllUserMenuModel.class);
  512. list.forEach(t -> {
  513. if ("-1".equals(t.getParentId())) {
  514. t.setParentId(t.getSystemId());
  515. }
  516. });
  517. List<AllUserMenuModel> jsonToList = JsonUtil.getJsonToList(systemList, AllUserMenuModel.class);
  518. jsonToList.forEach(t -> {
  519. t.setType(0);
  520. t.setParentId("-1");
  521. });
  522. list.addAll(jsonToList);
  523. List<SumTree<AllUserMenuModel>> menuList = TreeDotUtils.convertListToTreeDotFilter(list);
  524. List<AllMenuSelectVO> menuvo = JsonUtil.getJsonToList(menuList, AllMenuSelectVO.class);
  525. return menuvo;
  526. }
  527. /**
  528. * userInfo添加组织、岗位、分组、角色的关系
  529. * 默认组织和默认岗位
  530. *
  531. * @param userInfo
  532. * @param userEntity
  533. */
  534. private UserOrgPosModel userInfo(UserInfo userInfo, UserEntity userEntity) {
  535. UserOrgPosModel uopm= new UserOrgPosModel();
  536. // 得到用户和组织、岗位、分组、角色的关系
  537. List<UserRelationEntity> data = userRelationApi.getListByUserId(userInfo.getUserId());
  538. List<String> positionIds = data.stream().filter(t -> PermissionConst.POSITION.equalsIgnoreCase(t.getObjectType())).map(UserRelationEntity::getObjectId).collect(Collectors.toList());
  539. List<String> groupIds = data.stream().filter(t -> PermissionConst.GROUP.equalsIgnoreCase(t.getObjectType())).map(UserRelationEntity::getObjectId).collect(Collectors.toList());
  540. List<PositionEntity> positionList = positionApi.getListByIds(positionIds);
  541. List<String> orgIds = new ArrayList<>(positionList.stream().map(PositionEntity::getOrganizeId).collect(Collectors.toSet()));
  542. List<OrganizeEntity> organizeList = organizeApi.getListByIds(orgIds);
  543. List<GroupEntity> groupList = groupApi.getListByIds(groupIds);
  544. List<String> allIds = new ArrayList<>();
  545. allIds.addAll(orgIds);
  546. allIds.addAll(positionIds);
  547. allIds.add(userEntity.getId());
  548. List<RoleRelationEntity> roleRelationList = roleRelationService.getListByObjectId(allIds, null);
  549. List<String> roleIds = roleRelationList.stream().map(RoleRelationEntity::getRoleId).collect(Collectors.toList());
  550. List<RoleEntity> roleList = roleApi.getListByIds(roleIds);
  551. userInfo.setOrganizeIds(orgIds);
  552. userInfo.setPositionIds(positionIds);
  553. userInfo.setGroupIds(groupIds);
  554. userInfo.setRoleIds(roleIds);
  555. //组织全名,岗位全名
  556. List<KeyNameModel> organizeListRes = organizeList.stream().map(t -> {
  557. KeyNameModel jsonb = JsonUtil.getJsonToBean(t, KeyNameModel.class);
  558. jsonb.setTreeName(t.getOrgNameTree());
  559. jsonb.setTreeId(t.getOrganizeIdTree());
  560. return jsonb;
  561. }).collect(Collectors.toList());
  562. List<KeyNameModel> positionListRes = positionList.stream().map(t -> {
  563. KeyNameModel jsonb = JsonUtil.getJsonToBean(t, KeyNameModel.class);
  564. OrganizeEntity organizeEntity = organizeList.stream().filter(m -> m.getId().equals(t.getOrganizeId())).findFirst().orElse(new OrganizeEntity());
  565. jsonb.setTreeName(organizeEntity.getOrgNameTree() + "/" + t.getFullName());
  566. jsonb.setTreeId(t.getPositionIdTree());
  567. return jsonb;
  568. }).collect(Collectors.toList());
  569. uopm.setOrganizeList(organizeListRes);
  570. uopm.setPositionList(positionListRes);
  571. uopm.setGroupList(JsonUtil.getJsonToList(groupList, KeyNameModel.class));
  572. uopm.setRoleList(JsonUtil.getJsonToList(roleList, KeyNameModel.class));
  573. userInfo.setIsManageRole(false);
  574. userInfo.setIsDevRole(false);
  575. userInfo.setIsUserRole(false);
  576. userInfo.setIsOtherRole(false);
  577. for (RoleEntity roleEntity : roleList) {
  578. if (PermissionConst.MANAGER_CODE.equals(roleEntity.getEnCode())) {
  579. userInfo.setIsManageRole(true);
  580. } else if (PermissionConst.DEVELOPER_CODE.equals(roleEntity.getEnCode())) {
  581. userInfo.setIsDevRole(true);
  582. } else if (PermissionConst.USER_CODE.equals(roleEntity.getEnCode())) {
  583. userInfo.setIsUserRole(true);
  584. } else {
  585. userInfo.setIsOtherRole(true);
  586. }
  587. }
  588. //默认组织和默认岗位
  589. String organizeId = userEntity.getOrganizeId();
  590. String positionId = userEntity.getPositionId();
  591. if (CollectionUtil.isNotEmpty(orgIds)) {
  592. if (!orgIds.contains(userEntity.getOrganizeId())) {
  593. organizeId = orgIds.get(0);
  594. }
  595. }
  596. if (CollectionUtil.isNotEmpty(positionIds)) {
  597. if (!positionIds.contains(userEntity.getPositionId())) {
  598. positionId = positionIds.get(0);
  599. }
  600. }
  601. userInfo.setOrganizeId(organizeId);
  602. userInfo.setPositionId(positionId);
  603. // 修改用户信息
  604. userEntity.setOrganizeId(organizeId);
  605. userEntity.setPositionId(positionId);
  606. userApi.updateById(userEntity);
  607. //todo 我的下属。重写
  608. userInfo.setManagerId(userEntity.getManagerId());
  609. //获取岗位
  610. List<UserRelationEntity> listByObjectType = userRelationApi.getListByObjectType(userInfo.getUserId(), PermissionConst.POSITION);
  611. if (CollectionUtil.isNotEmpty(listByObjectType)) {
  612. List<String> collect = listByObjectType.stream()
  613. .map(UserRelationEntity::getObjectId)
  614. .collect(Collectors.toList());
  615. //获取子岗位
  616. List<String> sonPositionIdList = positionApi.getListByParentIds(collect).stream()
  617. .map(SuperBaseEntity.SuperIBaseEntity::getId)
  618. .collect(Collectors.toList());
  619. if (CollectionUtil.isNotEmpty(sonPositionIdList)) {
  620. List<String> userIds = userRelationApi.getListByObjectIdAll(sonPositionIdList).stream()
  621. .map(UserRelationEntity::getUserId)
  622. .collect(Collectors.toList());
  623. userIds.add(userInfo.getUserId());
  624. userInfo.setSubordinateIds(userIds);
  625. }
  626. }
  627. userInfo.setLoginTime(DateUtil.getmmNow());
  628. return uopm;
  629. }
  630. }