平安校园
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

1165 строки
49 KiB

  1. //
  2. using SafeCampus.Core.Extension;
  3. namespace SafeCampus.System;
  4. /// <summary>
  5. /// <inheritdoc cref="ISysUserService"/>
  6. /// </summary>
  7. public class SysUserService : DbRepository<SysUser>, ISysUserService
  8. {
  9. private readonly ILogger<ILogger> _logger;
  10. private readonly ISimpleCacheService _simpleCacheService;
  11. private readonly IRelationService _relationService;
  12. private readonly IResourceService _resourceService;
  13. private readonly ISysOrgService _sysOrgService;
  14. private readonly ISysRoleService _sysRoleService;
  15. private readonly IImportExportService _importExportService;
  16. private readonly ISysPositionService _sysPositionService;
  17. private readonly IDictService _dictService;
  18. private readonly IConfigService _configService;
  19. private readonly IBatchEditService _batchEditService;
  20. public SysUserService(ILogger<ILogger> logger, ISimpleCacheService simpleCacheService, IRelationService relationService,
  21. IResourceService resourceService, ISysOrgService orgService, ISysRoleService sysRoleService,
  22. IImportExportService importExportService, ISysPositionService sysPositionService, IDictService dictService,
  23. IConfigService configService, IBatchEditService updateBatchService)
  24. {
  25. _logger = logger;
  26. _simpleCacheService = simpleCacheService;
  27. _relationService = relationService;
  28. _resourceService = resourceService;
  29. _sysOrgService = orgService;
  30. _sysRoleService = sysRoleService;
  31. _importExportService = importExportService;
  32. _sysPositionService = sysPositionService;
  33. _dictService = dictService;
  34. _configService = configService;
  35. _batchEditService = updateBatchService;
  36. }
  37. #region 查询
  38. /// <inheritdoc/>
  39. public async Task<string> GetUserAvatar(long userId)
  40. {
  41. //先从缓存拿
  42. var avatar = _simpleCacheService.HashGetOne<string>(SystemConst.CACHE_SYS_USER_AVATAR, userId.ToString());
  43. if (string.IsNullOrEmpty(avatar))
  44. {
  45. //单查获取用户头像
  46. avatar = await GetFirstAsync(it => it.Id == userId, it => it.Avatar);
  47. if (!string.IsNullOrEmpty(avatar))
  48. {
  49. //插入缓存
  50. _simpleCacheService.HashAdd(SystemConst.CACHE_SYS_USER_AVATAR, userId.ToString(), avatar);
  51. }
  52. }
  53. return avatar;
  54. }
  55. /// <inheritdoc/>
  56. public async Task<SysUser> GetUserByAccount(string account, long? tenantId = null)
  57. {
  58. var userId = await GetIdByAccount(account, tenantId);//获取用户ID
  59. if (userId != SafeCampusConst.ZERO)
  60. {
  61. var sysUser = await GetUserById(userId);//获取用户信息
  62. if (sysUser.Account == account)//这里做了比较用来限制大小写
  63. return sysUser;
  64. return null;
  65. }
  66. return null;
  67. }
  68. /// <inheritdoc/>
  69. public async Task<SysUser> GetUserByPhone(string phone, long? tenantId = null)
  70. {
  71. var userId = await GetIdByPhone(phone, tenantId);//获取用户ID
  72. if (userId > 0)
  73. {
  74. return await GetUserById(userId);//获取用户信息
  75. }
  76. return null;
  77. }
  78. /// <inheritdoc/>
  79. public async Task<long> GetIdByPhone(string phone, long? tenantId = null)
  80. {
  81. var orgIds = new List<long>();
  82. var key = SystemConst.CACHE_SYS_USER_PHONE;
  83. if (tenantId != null)
  84. {
  85. key += $":{tenantId}";
  86. orgIds = await _sysOrgService.GetOrgChildIds(tenantId.Value);//获取下级机构
  87. }
  88. //先从缓存拿
  89. var userId = _simpleCacheService.HashGetOne<long>(key, phone);
  90. if (userId == 0)
  91. {
  92. var sm4Phone = CryptogramUtil.Sm4Encrypt(phone);//SM4加密一下
  93. //单查获取用户手机号对应的账号
  94. userId = await Context.Queryable<SysUser>()
  95. .Where(it => it.Phone == sm4Phone)
  96. .WhereIF(orgIds.Count > 0, it => orgIds.Contains(it.OrgId))
  97. .Select(it => it.Id)
  98. .FirstAsync();
  99. if (userId > 0)
  100. {
  101. //插入缓存
  102. _simpleCacheService.HashAdd(key, phone, userId);
  103. }
  104. }
  105. return userId;
  106. }
  107. /// <inheritdoc/>
  108. public async Task<SysUser> GetUserById(long userId)
  109. {
  110. //先从缓存拿
  111. var sysUser = _simpleCacheService.HashGetOne<SysUser>(SystemConst.CACHE_SYS_USER, userId.ToString());
  112. if (sysUser == null)
  113. {
  114. sysUser = await GetUserFromDb(userId);//从数据库拿用户信息
  115. }
  116. return sysUser;
  117. }
  118. /// <inheritdoc/>
  119. public async Task<T> GetUserById<T>(long userId)
  120. {
  121. var user = await GetUserById(userId);
  122. return user.Adapt<T>();
  123. }
  124. /// <inheritdoc/>
  125. public async Task<long> GetIdByAccount(string account, long? tenantId = null)
  126. {
  127. var orgIds = new List<long>();
  128. var key = SystemConst.CACHE_SYS_USER_ACCOUNT;
  129. if (tenantId != null)
  130. {
  131. key += $":{tenantId}";
  132. orgIds = await _sysOrgService.GetOrgChildIds(tenantId.Value);//获取下级机构
  133. }
  134. //先从缓存拿
  135. var userId = _simpleCacheService.HashGetOne<long>(key, account);
  136. if (userId == 0)
  137. {
  138. //单查获取用户账号对应ID
  139. userId = await Context.Queryable<SysUser>()
  140. .Where(it => it.Account == account)
  141. .WhereIF(orgIds.Count > 0, it => orgIds.Contains(it.OrgId))
  142. .Select(it => it.Id)
  143. .FirstAsync();
  144. if (userId != 0)
  145. {
  146. //插入缓存
  147. _simpleCacheService.HashAdd(key, account, userId);
  148. }
  149. }
  150. return userId;
  151. }
  152. /// <inheritdoc/>
  153. public async Task<List<string>> GetButtonCodeList(long userId)
  154. {
  155. var buttonCodeList = new List<string>();//按钮ID集合
  156. //获取用户资源集合
  157. var resourceList = await _relationService.GetRelationListByObjectIdAndCategory(userId, CateGoryConst.RELATION_SYS_USER_HAS_RESOURCE);
  158. var buttonIdList = new List<long>();//按钮ID集合
  159. if (resourceList.Count == 0)//如果有表示用户单独授权了不走用户角色
  160. {
  161. //获取用户角色关系集合
  162. var roleList = await _relationService.GetRelationListByObjectIdAndCategory(userId, CateGoryConst.RELATION_SYS_USER_HAS_ROLE);
  163. var roleIdList = roleList.Select(x => x.TargetId.ToLong()).ToList();//角色ID列表
  164. if (roleIdList.Count > 0)//如果该用户有角色
  165. {
  166. resourceList = await _relationService.GetRelationListByObjectIdListAndCategory(roleIdList,
  167. CateGoryConst.RELATION_SYS_ROLE_HAS_RESOURCE);//获取资源集合
  168. }
  169. }
  170. resourceList.ForEach(it =>
  171. {
  172. if (!string.IsNullOrEmpty(it.ExtJson))
  173. buttonIdList.AddRange(it.ExtJson.ToJsonEntity<RelationRoleResource>().ButtonInfo);//如果有按钮权限,将按钮ID放到buttonIdList
  174. });
  175. if (buttonIdList.Count > 0)
  176. {
  177. buttonCodeList = await _resourceService.GetCodeByIds(buttonIdList, CateGoryConst.RESOURCE_BUTTON);
  178. }
  179. return buttonCodeList;
  180. }
  181. /// <inheritdoc/>
  182. public async Task<List<DataScope>> GetPermissionListByUserId(long userId, long orgId)
  183. {
  184. var permissions = new List<DataScope>();//权限集合
  185. var sysRelations =
  186. await _relationService.GetRelationListByObjectIdAndCategory(userId, CateGoryConst.RELATION_SYS_USER_HAS_PERMISSION);//根据用户ID获取用户权限
  187. if (sysRelations.Count == 0)//如果有表示用户单独授权了不走用户角色
  188. {
  189. var roleIdList =
  190. await _relationService.GetRelationListByObjectIdAndCategory(userId, CateGoryConst.RELATION_SYS_USER_HAS_ROLE);//根据用户ID获取角色ID
  191. if (roleIdList.Count > 0)//如果角色ID不为空
  192. {
  193. //获取角色权限信息
  194. sysRelations = await _relationService.GetRelationListByObjectIdListAndCategory(roleIdList.Select(it => it.TargetId.ToLong()).ToList(),
  195. CateGoryConst.RELATION_SYS_ROLE_HAS_PERMISSION);
  196. }
  197. }
  198. var relationGroup = sysRelations.GroupBy(it => it.TargetId).ToList();//根据目标ID,也就是接口名分组,因为存在一个用户多个角色
  199. //遍历分组
  200. foreach (var it in relationGroup)
  201. {
  202. var scopeSet = new HashSet<long>();//定义不可重复列表
  203. var relationList = it.ToList();//关系列表
  204. var scopeCategory = CateGoryConst.SCOPE_SELF;//数据权限分类,默认为仅自己
  205. //获取角色权限信息列表
  206. var rolePermissions = relationList.Select(it => it.ExtJson.ToJsonEntity<RelationRolePermission>()).ToList();
  207. if (rolePermissions.Any(role => role.ScopeCategory == CateGoryConst.SCOPE_ALL))//如果有全部
  208. scopeCategory = CateGoryConst.SCOPE_ALL;//标记为全部
  209. else if (rolePermissions.Any(role => role.ScopeCategory == CateGoryConst.SCOPE_ORG_CHILD))//如果有机构及以下机构
  210. scopeCategory = CateGoryConst.SCOPE_ORG_CHILD;//标记为机构及以下机构
  211. else if (rolePermissions.Any(role => role.ScopeCategory == CateGoryConst.SCOPE_ORG))//如果有仅自己机构
  212. scopeCategory = CateGoryConst.SCOPE_ORG;//标记为仅自己机构
  213. else if (rolePermissions.Any(role => role.ScopeCategory == CateGoryConst.SCOPE_ORG_DEFINE))//如果有自定义机构
  214. {
  215. scopeCategory = CateGoryConst.SCOPE_ORG_DEFINE;//标记为仅自己
  216. rolePermissions.ForEach(s =>
  217. {
  218. scopeSet.AddRange(s.ScopeDefineOrgIdList);//添加自定义范围的机构ID
  219. });
  220. }
  221. var dataScopes = scopeSet.ToList();//获取范围列表转列表
  222. permissions.Add(new DataScope
  223. {
  224. ApiUrl = it.Key,
  225. ScopeCategory = scopeCategory,
  226. DataScopes = dataScopes
  227. });//将改URL的权限集合加入权限集合列表
  228. }
  229. return permissions;
  230. }
  231. /// <inheritdoc/>
  232. public async Task<SqlSugarPagedList<UserSelectorOutPut>> Selector(UserSelectorInput input)
  233. {
  234. var orgIds = await _sysOrgService.GetOrgChildIds(input.OrgId);//获取下级机构
  235. var result = await Context.Queryable<SysUser>()
  236. .WhereIF(input.OrgId > 0, u => orgIds.Contains(u.OrgId))//指定机构
  237. .WhereIF(input.OrgIds != null, u => input.OrgIds.Contains(u.OrgId))//在指定机构列表查询
  238. .WhereIF(input.PositionId > 0, u => u.PositionId == input.PositionId)//指定职位
  239. .WhereIF(input.RoleId > 0,
  240. u => SqlFunc.Subqueryable<SysRelation>()
  241. .Where(r => r.TargetId == input.RoleId.ToString() && r.ObjectId == u.Id && r.Category == CateGoryConst.RELATION_SYS_USER_HAS_ROLE)
  242. .Any())//指定角色
  243. .WhereIF(!string.IsNullOrEmpty(input.Account), u => u.Account.Contains(input.Account))//根据关键字查询
  244. .Select<UserSelectorOutPut>().ToPagedListAsync(input.PageNum, input.PageSize);
  245. return result;
  246. }
  247. /// <inheritdoc/>
  248. public async Task<SqlSugarPagedList<SysUser>> Page(UserPageInput input)
  249. {
  250. var query = await GetQuery(input);//获取查询条件
  251. var pageInfo = await query.ToPagedListAsync(input.PageNum, input.PageSize);//分页
  252. return pageInfo;
  253. }
  254. /// <inheritdoc/>
  255. public async Task<List<SysUser>> List(UserPageInput input)
  256. {
  257. var query = await GetQuery(input);//获取查询条件
  258. var list = await query.ToListAsync();
  259. return list;
  260. }
  261. /// <inheritdoc/>
  262. public async Task<List<RoleSelectorOutPut>> OwnRole(BaseIdInput input)
  263. {
  264. var relations = await _relationService.GetRelationListByObjectIdAndCategory(input.Id, CateGoryConst.RELATION_SYS_USER_HAS_ROLE);
  265. var roleIds = relations.Select(it => it.TargetId.ToLong()).ToList();
  266. var roleList = await Context.Queryable<SysRole>().Where(it => roleIds.Contains(it.Id)).Select<RoleSelectorOutPut>().ToListAsync();
  267. return roleList;
  268. }
  269. /// <inheritdoc />
  270. public async Task<RoleOwnResourceOutput> OwnResource(BaseIdInput input)
  271. {
  272. return await _sysRoleService.OwnResource(input, CateGoryConst.RELATION_SYS_USER_HAS_RESOURCE);
  273. }
  274. /// <inheritdoc />
  275. public async Task<RoleOwnPermissionOutput> OwnPermission(BaseIdInput input)
  276. {
  277. var roleOwnPermission = new RoleOwnPermissionOutput
  278. {
  279. Id = input.Id
  280. };//定义结果集
  281. var grantInfoList = new List<RelationRolePermission>();//已授权信息集合
  282. //获取关系列表
  283. var relations = await _relationService.GetRelationListByObjectIdAndCategory(input.Id, CateGoryConst.RELATION_SYS_USER_HAS_PERMISSION);
  284. //遍历关系表
  285. relations.ForEach(it =>
  286. {
  287. //将扩展信息转为实体
  288. var relationPermission = it.ExtJson.ToJsonEntity<RelationRolePermission>();
  289. grantInfoList.Add(relationPermission);//添加到已授权信息
  290. });
  291. roleOwnPermission.GrantInfoList = grantInfoList;//赋值已授权信息
  292. return roleOwnPermission;
  293. }
  294. /// <inheritdoc />
  295. public async Task<List<string>> UserPermissionTreeSelector(BaseIdInput input)
  296. {
  297. var permissionTreeSelectors = new List<string>();//授权树结果集
  298. //获取用户资源关系
  299. var relationsRes = await _relationService.GetRelationByCategory(CateGoryConst.RELATION_SYS_USER_HAS_RESOURCE);
  300. var menuIds = relationsRes.Where(it => it.ObjectId == input.Id).Select(it => it.TargetId.ToLong()).ToList();
  301. if (menuIds.Any())
  302. {
  303. //获取菜单信息
  304. var menus = await _resourceService.GetResourcesByIds(menuIds, CateGoryConst.RESOURCE_MENU);
  305. //获取权限授权树
  306. var permissions = _resourceService.PermissionTreeSelector(menus.Select(it => it.Path).ToList());
  307. if (permissions.Count > 0)
  308. {
  309. permissionTreeSelectors = permissions.Select(it => it.PermissionName).ToList();//返回授权树权限名称列表
  310. }
  311. }
  312. return permissionTreeSelectors;
  313. }
  314. /// <inheritdoc />
  315. public async Task<List<UserSelectorOutPut>> GetUserListByIdList(IdListInput input)
  316. {
  317. var userList = await Context.Queryable<SysUser>().Where(it => input.IdList.Contains(it.Id)).Select<UserSelectorOutPut>().ToListAsync();
  318. return userList;
  319. }
  320. /// <inheritdoc />
  321. public async Task<SysUser> Detail(BaseIdInput input)
  322. {
  323. var user = await GetUserById(input.Id);
  324. if (user != null)
  325. {
  326. user.Password = null;//清空密码
  327. }
  328. return user;
  329. }
  330. #endregion 查询
  331. #region 数据范围相关
  332. /// <inheritdoc/>
  333. public async Task<List<long>?> GetLoginUserApiDataScope()
  334. {
  335. var userInfo = await GetUserById(UserManager.UserId);//获取用户信息
  336. // 路由名称
  337. var routeName = App.HttpContext.Request.Path.Value;
  338. //获取当前url的数据范围
  339. var dataScope = userInfo.DataScopeList.Where(it => it.ApiUrl == routeName).FirstOrDefault();
  340. if (dataScope != null)
  341. {
  342. //根据数据范围分类获取数据范围
  343. //null:代表拥有全部数据权限
  344. //[xx,xx]:代表拥有部分机构的权限
  345. //[]:代表仅自己权限
  346. switch (dataScope.ScopeCategory)
  347. {
  348. case CateGoryConst.SCOPE_ALL:
  349. return null;
  350. case CateGoryConst.SCOPE_ORG_CHILD:
  351. return userInfo.ScopeOrgChildList;
  352. case CateGoryConst.SCOPE_ORG:
  353. return new List<long> { userInfo.OrgId };
  354. case CateGoryConst.SCOPE_ORG_DEFINE:
  355. return dataScope.DataScopes;
  356. case CateGoryConst.SCOPE_SELF:
  357. return new List<long>();
  358. }
  359. }
  360. return new List<long>();
  361. }
  362. /// <inheritdoc/>
  363. public async Task<bool> CheckApiDataScope(long? orgId, long? createUerId, string errMsg = "")
  364. {
  365. var hasPermission = true;
  366. //判断数据范围
  367. var dataScope = await GetLoginUserApiDataScope();
  368. if (dataScope is { Count: > 0 })//如果有机构
  369. {
  370. if (orgId == null || !dataScope.Contains(orgId.Value))//判断机构id是否在数据范围
  371. hasPermission = false;
  372. }
  373. else if (dataScope is { Count: 0 })// 表示仅自己
  374. {
  375. if (createUerId != UserManager.UserId)
  376. hasPermission = false;//机构的创建人不是自己则报错
  377. }
  378. //如果传了错误信息,直接抛出异常
  379. if (!hasPermission && !string.IsNullOrEmpty(errMsg))
  380. throw Oops.Bah(errMsg);
  381. return hasPermission;
  382. }
  383. public async Task<bool> CheckApiDataScope(List<long> orgIds, List<long> createUerIds, string errMsg = "")
  384. {
  385. var hasPermission = true;
  386. //判断数据范围
  387. var dataScope = await GetLoginUserApiDataScope();
  388. if (dataScope is { Count: > 0 })//如果有机构
  389. {
  390. if (orgIds == null || !dataScope.ContainsAll(orgIds))//判断机构id列表是否全在数据范围
  391. hasPermission = false;
  392. }
  393. else if (dataScope is { Count: 0 })// 表示仅自己
  394. {
  395. if (createUerIds.Any(it => it != UserManager.UserId))//如果创建者id里有任何不是自己创建的机构
  396. hasPermission = false;
  397. }
  398. //如果传了错误信息,直接抛出异常
  399. if (!hasPermission && !string.IsNullOrEmpty(errMsg))
  400. throw Oops.Bah(errMsg);
  401. return hasPermission;
  402. }
  403. #endregion
  404. #region 新增
  405. /// <inheritdoc/>
  406. public async Task Add(UserAddInput input)
  407. {
  408. await CheckInput(input);//检查参数
  409. var sysUser = input.Adapt<SysUser>();//实体转换
  410. //默认头像
  411. sysUser.Avatar = AvatarUtil.GetNameImageBase64(sysUser.Name);
  412. //获取默认密码
  413. sysUser.Password = await GetDefaultPassWord(true);//设置密码
  414. sysUser.Status = CommonStatusConst.ENABLE;//默认状态
  415. await InsertAsync(sysUser);//添加数据
  416. }
  417. #endregion 新增
  418. #region 编辑
  419. /// <inheritdoc/>
  420. public async Task Edit(UserEditInput input)
  421. {
  422. await CheckInput(input);//检查参数
  423. var exist = await GetUserById(input.Id);//获取用户信息
  424. if (exist != null)
  425. {
  426. var isSuperAdmin = exist.Account == SysRoleConst.SUPER_ADMIN;//判断是否有超管
  427. if (isSuperAdmin && !UserManager.SuperAdmin)
  428. throw Oops.Bah("不可修改系统内置超管用户账号");
  429. var name = exist.Name;//姓名
  430. var sysUser = input.Adapt<SysUser>();//实体转换
  431. if (name != input.Name)
  432. sysUser.Avatar = AvatarUtil.GetNameImageBase64(input.Name);//如果姓名改变了,重新生成头像
  433. if (await Context.Updateable(sysUser).IgnoreColumns(it => new
  434. {
  435. //忽略更新字段
  436. it.Password,
  437. it.LastLoginAddress,
  438. it.LastLoginDevice,
  439. it.LastLoginIp,
  440. it.LastLoginTime,
  441. it.LatestLoginAddress,
  442. it.LatestLoginDevice,
  443. it.LatestLoginIp,
  444. it.LatestLoginTime
  445. }).IgnoreColumnsIF(name == input.Name, it => it.Avatar).ExecuteCommandAsync() > 0
  446. )//修改数据
  447. {
  448. DeleteUserFromRedis(sysUser.Id);//删除用户缓存
  449. //删除用户token缓存
  450. _simpleCacheService.HashDel<List<TokenInfo>>(CacheConst.CACHE_USER_TOKEN, sysUser.Id.ToString());
  451. }
  452. }
  453. }
  454. /// <inheritdoc/>
  455. public async Task Edits(BatchEditInput input)
  456. {
  457. //获取参数字典
  458. var data = await _batchEditService.GetUpdateBatchConfigDict(input.Code, input.Columns);
  459. if (data.Count > 0)
  460. {
  461. await Context.Updateable<SysUser>(data).Where(it => input.Ids.Contains(it.Id)).ExecuteCommandAsync();
  462. }
  463. }
  464. /// <inheritdoc/>
  465. public async Task DisableUser(BaseIdInput input)
  466. {
  467. var sysUser = await GetUserById(input.Id);//获取用户信息
  468. if (sysUser != null)
  469. {
  470. var isSuperAdmin = sysUser.Account == SysRoleConst.SUPER_ADMIN;//判断是否有超管
  471. if (isSuperAdmin)
  472. throw Oops.Bah("不可禁用系统内置超管用户账号");
  473. CheckSelf(input.Id, SystemConst.DISABLE);//判断是不是自己
  474. //设置状态为禁用
  475. if (await UpdateSetColumnsTrueAsync(it => new SysUser
  476. {
  477. Status = CommonStatusConst.DISABLED
  478. }, it => it.Id == input.Id))
  479. DeleteUserFromRedis(input.Id);//从缓存删除用户信息
  480. }
  481. }
  482. /// <inheritdoc/>
  483. public async Task EnableUser(BaseIdInput input)
  484. {
  485. CheckSelf(input.Id, SystemConst.ENABLE);//判断是不是自己
  486. //设置状态为启用
  487. if (await UpdateSetColumnsTrueAsync(it => new SysUser
  488. {
  489. Status = CommonStatusConst.ENABLE
  490. }, it => it.Id == input.Id))
  491. DeleteUserFromRedis(input.Id);//从缓存删除用户信息
  492. }
  493. /// <inheritdoc/>
  494. public async Task ResetPassword(BaseIdInput input)
  495. {
  496. var password = await GetDefaultPassWord(true);//获取默认密码,这里不走Aop所以需要加密一下
  497. //重置密码
  498. if (await UpdateSetColumnsTrueAsync(it => new SysUser
  499. {
  500. Password = password
  501. }, it => it.Id == input.Id))
  502. DeleteUserFromRedis(input.Id);//从缓存删除用户信息
  503. }
  504. /// <inheritdoc />
  505. public async Task GrantRole(UserGrantRoleInput input)
  506. {
  507. var sysUser = await GetUserById(input.Id);//获取用户信息
  508. if (sysUser != null)
  509. {
  510. var isSuperAdmin = sysUser.Account == SysRoleConst.SUPER_ADMIN;//判断是否有超管
  511. if (isSuperAdmin)
  512. throw Oops.Bah("不能给超管分配角色");
  513. CheckSelf(input.Id, SystemConst.GRANT_ROLE);//判断是不是自己
  514. //给用户赋角色
  515. await _relationService.SaveRelationBatch(CateGoryConst.RELATION_SYS_USER_HAS_ROLE, input.Id,
  516. input.RoleIdList.Select(it => it.ToString()).ToList(), null, true);
  517. DeleteUserFromRedis(input.Id);//从缓存删除用户信息
  518. }
  519. }
  520. /// <inheritdoc />
  521. public async Task GrantResource(UserGrantResourceInput input)
  522. {
  523. var menuIds = input.GrantInfoList.Select(it => it.MenuId).ToList();//菜单ID
  524. var extJsons = input.GrantInfoList.Select(it => it.ToJson()).ToList();//拓展信息
  525. var relationRoles = new List<SysRelation>();//要添加的用户资源和授权关系表
  526. var sysUser = await GetUserById(input.Id);//获取用户
  527. if (sysUser != null)
  528. {
  529. #region 用户资源处理
  530. //遍历角色列表
  531. for (var i = 0; i < menuIds.Count; i++)
  532. {
  533. //将用户资源添加到列表
  534. relationRoles.Add(new SysRelation
  535. {
  536. ObjectId = sysUser.Id,
  537. TargetId = menuIds[i].ToString(),
  538. Category = CateGoryConst.RELATION_SYS_USER_HAS_RESOURCE,
  539. ExtJson = extJsons == null ? null : extJsons[i]
  540. });
  541. }
  542. #endregion 用户资源处理
  543. #region 用户权限处理.
  544. var relationRolePer = new List<SysRelation>();//要添加的用户有哪些权限列表
  545. var defaultDataScope = input.DefaultDataScope;//获取默认数据范围
  546. //获取菜单信息
  547. var menus = await _resourceService.GetResourcesByIds(menuIds, CateGoryConst.RESOURCE_MENU);
  548. if (menus.Count > 0)
  549. {
  550. #region 用户模块关系
  551. //获取我的模块信息Id列表
  552. var moduleIds = menus.Select(it => it.Module.Value).Distinct().ToList();
  553. moduleIds.ForEach(it =>
  554. {
  555. //将角色资源添加到列表
  556. relationRoles.Add(new SysRelation
  557. {
  558. ObjectId = sysUser.Id,
  559. TargetId = it.ToString(),
  560. Category = CateGoryConst.RELATION_SYS_USER_HAS_MODULE
  561. });
  562. });
  563. #endregion
  564. //获取权限授权树
  565. var permissions = _resourceService.PermissionTreeSelector(menus.Select(it => it.Path).ToList());
  566. permissions.ForEach(it =>
  567. {
  568. //新建角色权限关系
  569. relationRolePer.Add(new SysRelation
  570. {
  571. ObjectId = sysUser.Id,
  572. TargetId = it.ApiRoute,
  573. Category = CateGoryConst.RELATION_SYS_USER_HAS_PERMISSION,
  574. ExtJson = new RelationRolePermission
  575. {
  576. ApiUrl = it.ApiRoute,
  577. ScopeCategory = defaultDataScope.ScopeCategory,
  578. ScopeDefineOrgIdList = defaultDataScope.ScopeDefineOrgIdList
  579. }.ToJson()
  580. });
  581. });
  582. }
  583. relationRoles.AddRange(relationRolePer);//合并列表
  584. #endregion 用户权限处理.
  585. #region 保存数据库
  586. //事务
  587. var result = await Tenant.UseTranAsync(async () =>
  588. {
  589. var relationRep = ChangeRepository<DbRepository<SysRelation>>();//切换仓储
  590. await relationRep.DeleteAsync(it => it.ObjectId == sysUser.Id && (it.Category == CateGoryConst.RELATION_SYS_USER_HAS_PERMISSION
  591. || it.Category == CateGoryConst.RELATION_SYS_USER_HAS_RESOURCE) || it.Category == CateGoryConst.RELATION_SYS_USER_HAS_MODULE);
  592. await relationRep.InsertRangeAsync(relationRoles);//添加新的
  593. });
  594. if (result.IsSuccess)//如果成功了
  595. {
  596. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_USER_HAS_PERMISSION);//刷新关系缓存
  597. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_USER_HAS_RESOURCE);//刷新关系缓存
  598. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_USER_HAS_MODULE);//刷新关系缓存
  599. DeleteUserFromRedis(input.Id);//删除该用户缓存
  600. }
  601. else
  602. {
  603. //写日志
  604. _logger.LogError(result.ErrorMessage, result.ErrorException);
  605. throw Oops.Oh(ErrorCodeEnum.A0003);
  606. }
  607. #endregion 保存数据库
  608. }
  609. }
  610. /// <inheritdoc />
  611. public async Task GrantPermission(GrantPermissionInput input)
  612. {
  613. var sysUser = await GetUserById(input.Id);//获取用户
  614. if (sysUser != null)
  615. {
  616. var apiUrls = input.GrantInfoList.Select(it => it.ApiUrl).ToList();//apiurl列表
  617. var extJsons = input.GrantInfoList.Select(it => it.ToJson()).ToList();//拓展信息
  618. await _relationService.SaveRelationBatch(CateGoryConst.RELATION_SYS_USER_HAS_PERMISSION, input.Id, apiUrls, extJsons,
  619. true);//添加到数据库
  620. DeleteUserFromRedis(input.Id);
  621. }
  622. }
  623. #endregion 编辑
  624. #region 删除
  625. /// <inheritdoc/>
  626. public async Task Delete(BaseIdListInput input)
  627. {
  628. //获取所有ID
  629. var ids = input.Ids;
  630. if (ids.Count > 0)
  631. {
  632. var containsSuperAdmin = await IsAnyAsync(it => it.Account == SysRoleConst.SUPER_ADMIN && ids.Contains(it.Id));//判断是否有超管
  633. if (containsSuperAdmin)
  634. throw Oops.Bah("不可删除系统内置超管用户");
  635. if (ids.Contains(UserManager.UserId))
  636. throw Oops.Bah("不可删除自己");
  637. //定义删除的关系
  638. var delRelations = new List<string>
  639. {
  640. CateGoryConst.RELATION_SYS_USER_HAS_RESOURCE,
  641. CateGoryConst.RELATION_SYS_USER_HAS_PERMISSION,
  642. CateGoryConst.RELATION_SYS_USER_HAS_ROLE,
  643. CateGoryConst.RELATION_SYS_USER_HAS_MODULE,
  644. CateGoryConst.RELATION_SYS_USER_SCHEDULE_DATA,
  645. CateGoryConst.RELATION_SYS_USER_WORKBENCH_DATA
  646. };
  647. //事务
  648. var result = await Tenant.UseTranAsync(async () =>
  649. {
  650. //清除该用户作为主管信息
  651. await UpdateAsync(it => new SysUser
  652. {
  653. DirectorId = null
  654. }, it => ids.Contains(it.DirectorId.Value));
  655. //删除用户
  656. await DeleteByIdsAsync(ids.Cast<object>().ToArray());
  657. var relationRep = ChangeRepository<DbRepository<SysRelation>>();//切换仓储
  658. //删除关系表用户与资源关系,用户与权限关系,用户与角色关系
  659. await relationRep.DeleteAsync(it => ids.Contains(it.ObjectId) && delRelations.Contains(it.Category));
  660. var orgRep = ChangeRepository<DbRepository<SysOrg>>();//切换仓储
  661. //删除组织表主管信息
  662. await orgRep.DeleteAsync(it => ids.Contains(it.DirectorId.Value));
  663. });
  664. if (result.IsSuccess)//如果成功了
  665. {
  666. DeleteUserFromRedis(ids);//缓存删除用户
  667. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_USER_HAS_ROLE);//关系表刷新SYS_USER_HAS_ROLE缓存
  668. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_USER_HAS_RESOURCE);//关系表刷新SYS_USER_HAS_ROLE缓存
  669. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_USER_HAS_PERMISSION);//关系表刷新SYS_USER_HAS_ROLE缓存
  670. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_USER_HAS_MODULE);//关系表刷新RELATION_SYS_USER_HAS_MODULE缓存
  671. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_USER_SCHEDULE_DATA);//关系表刷新RELATION_SYS_USER_SCHEDULE_DATA缓存
  672. await _relationService.RefreshCache(CateGoryConst.RELATION_SYS_USER_WORKBENCH_DATA);//关系表刷新RELATION_SYS_USER_WORKBENCH_DATA缓存
  673. // TODO 此处需要将这些用户踢下线,并永久注销这些用户
  674. var idArray = ids.Select(it => it.ToString()).ToArray();
  675. //从列表中删除
  676. _simpleCacheService.HashDel<List<TokenInfo>>(CacheConst.CACHE_USER_TOKEN, idArray);
  677. }
  678. else
  679. {
  680. //写日志
  681. _logger.LogError(result.ErrorMessage, result.ErrorException);
  682. throw Oops.Oh(ErrorCodeEnum.A0002);
  683. }
  684. }
  685. }
  686. /// <inheritdoc />
  687. public void DeleteUserFromRedis(long userId)
  688. {
  689. DeleteUserFromRedis(new List<long>
  690. {
  691. userId
  692. });
  693. }
  694. /// <inheritdoc />
  695. public void DeleteUserFromRedis(List<long> ids)
  696. {
  697. var userIds = ids.Select(it => it.ToString()).ToArray();//id转string列表
  698. var sysUsers = _simpleCacheService.HashGet<SysUser>(SystemConst.CACHE_SYS_USER, userIds);//获取用户列表
  699. sysUsers = sysUsers.Where(it => it != null).ToList();//过滤掉不存在的
  700. if (sysUsers.Count > 0)
  701. {
  702. var accounts = sysUsers.Select(it => it.Account).ToArray();//账号集合
  703. var phones = sysUsers.Select(it => it.Phone).ToArray();//手机号集合
  704. //删除用户信息
  705. _simpleCacheService.HashDel<SysUser>(SystemConst.CACHE_SYS_USER, userIds);
  706. //删除用户头像信息
  707. _simpleCacheService.HashDel<string>(SystemConst.CACHE_SYS_USER_AVATAR, userIds);
  708. var userAccountKey = SystemConst.CACHE_SYS_USER_ACCOUNT;
  709. var userPhoneKey = SystemConst.CACHE_SYS_USER_PHONE;
  710. if (sysUsers.Any(it => it.TenantId != null))//如果有租户id不是空的表示是多租户模式
  711. {
  712. var tenantIds = sysUsers.Where(it => it.TenantId != null).Select(it => it.TenantId.Value).Distinct().ToArray();//租户id列表
  713. foreach (var tenantId in tenantIds)
  714. {
  715. userAccountKey = $"{userAccountKey}:{tenantId}";
  716. userPhoneKey = $"{userPhoneKey}:{tenantId}";
  717. //删除账号
  718. _simpleCacheService.HashDel<long>(userAccountKey, accounts);
  719. //删除手机
  720. if (phones != null)
  721. _simpleCacheService.HashDel<long>(userPhoneKey, phones);
  722. }
  723. }
  724. else
  725. {
  726. //删除账号
  727. _simpleCacheService.HashDel<long>(userAccountKey, accounts);
  728. //删除手机
  729. if (phones != null)
  730. _simpleCacheService.HashDel<long>(userPhoneKey, phones);
  731. }
  732. }
  733. }
  734. #endregion 删除
  735. #region 导入导出
  736. /// <inheritdoc/>
  737. public async Task<FileStreamResult> Template()
  738. {
  739. var templateName = "用户信息";
  740. //var result = _importExportService.GenerateLocalTemplate(templateName);
  741. var result = await _importExportService.GenerateTemplate<SysUserImportInput>(templateName);
  742. return result;
  743. }
  744. /// <inheritdoc/>
  745. public async Task<ImportPreviewOutput<SysUserImportInput>> Preview(ImportPreviewInput input)
  746. {
  747. var importPreview = await _importExportService.GetImportPreview<SysUserImportInput>(input.File);
  748. importPreview.Data = await CheckImport(importPreview.Data);//检查导入数据
  749. return importPreview;
  750. }
  751. /// <inheritdoc/>
  752. public async Task<ImportResultOutPut<SysUserImportInput>> Import(ImportResultInput<SysUserImportInput> input)
  753. {
  754. var data = await CheckImport(input.Data, true);//检查数据格式
  755. var result = _importExportService.GetImportResultPreview(data, out var importData);
  756. var sysUsers = importData.Adapt<List<SysUser>>();//转实体
  757. await SetUserDefault(sysUsers);//设置默认值
  758. await InsertOrBulkCopy(sysUsers);// 数据导入
  759. return result;
  760. }
  761. /// <inheritdoc/>
  762. public async Task<FileStreamResult> Export(UserPageInput input)
  763. {
  764. var genTests = await List(input);
  765. var data = genTests.Adapt<List<SysUserExportOutput>>();//转为Dto
  766. var result = await _importExportService.Export(data, "用户信息");
  767. return result;
  768. }
  769. /// <inheritdoc/>
  770. public async Task<List<T>> CheckImport<T>(List<T> data, bool clearError = false) where T : SysUserImportInput
  771. {
  772. #region 校验要用到的数据
  773. var accounts = data.Select(it => it.Account).ToList();//当前导入数据账号列表
  774. var phones = data.Where(it => !string.IsNullOrEmpty(it.Phone)).Select(it => it.Phone).ToList();//当前导入数据手机号列表
  775. var emails = data.Where(it => !string.IsNullOrEmpty(it.Email)).Select(it => it.Email).ToList();//当前导入数据邮箱列表
  776. var sysUsers = await GetListAsync(it => true, it => new SysUser
  777. {
  778. Account = it.Account,
  779. Phone = it.Phone,
  780. Email = it.Email
  781. });//获取数据用户信息
  782. var dbAccounts = sysUsers.Select(it => it.Account).ToList();//数据库账号列表
  783. var dbPhones = sysUsers.Where(it => !string.IsNullOrEmpty(it.Phone)).Select(it => it.Phone).ToList();//数据库手机号列表
  784. var dbEmails = sysUsers.Where(it => !string.IsNullOrEmpty(it.Email)).Select(it => it.Email).ToList();//邮箱账号列表
  785. var sysOrgList = await _sysOrgService.GetListAsync();
  786. var sysPositions = await _sysPositionService.GetListAsync();
  787. var dictList = await _dictService.GetListAsync();
  788. #endregion 校验要用到的数据
  789. foreach (var item in data)
  790. {
  791. if (clearError)//如果需要清除错误
  792. {
  793. item.ErrorInfo = new Dictionary<string, string>();
  794. item.HasError = false;
  795. }
  796. #region 校验账号
  797. if (dbAccounts.Contains(item.Account))
  798. item.ErrorInfo.Add(nameof(item.Account), $"系统已存在账号{item.Account}");
  799. if (accounts.Where(u => u == item.Account).Count() > 1)
  800. item.ErrorInfo.Add(nameof(item.Account), "账号重复");
  801. #endregion 校验账号
  802. #region 校验手机号
  803. if (!string.IsNullOrEmpty(item.Phone))
  804. {
  805. if (dbPhones.Contains(item.Phone))
  806. item.ErrorInfo.Add(nameof(item.Phone), $"系统已存在手机号{item.Phone}的用户");
  807. if (phones.Where(u => u == item.Phone).Count() > 1)
  808. item.ErrorInfo.Add(nameof(item.Phone), "手机号重复");
  809. }
  810. #endregion 校验手机号
  811. #region 校验邮箱
  812. if (!string.IsNullOrEmpty(item.Email))
  813. {
  814. if (dbEmails.Contains(item.Email))
  815. item.ErrorInfo.Add(nameof(item.Email), $"系统已存在邮箱{item.Email}");
  816. if (emails.Where(u => u == item.Email).Count() > 1)
  817. item.ErrorInfo.Add(nameof(item.Email), "邮箱重复");
  818. }
  819. #endregion 校验邮箱
  820. #region 校验部门和职位
  821. if (!string.IsNullOrEmpty(item.OrgName))
  822. {
  823. var org = sysOrgList.Where(u => u.Names == item.OrgName).FirstOrDefault();
  824. if (org != null) item.OrgId = org.Id;//赋值组织Id
  825. else item.ErrorInfo.Add(nameof(item.OrgName), $"部门{org}不存在");
  826. }
  827. //校验职位
  828. if (!string.IsNullOrEmpty(item.PositionName))
  829. {
  830. if (string.IsNullOrEmpty(item.OrgName))
  831. item.ErrorInfo.Add(nameof(item.PositionName), "请填写部门");
  832. else
  833. {
  834. //根据部门ID和职位名判断是否有职位
  835. var position = sysPositions.FirstOrDefault(u => u.OrgId == item.OrgId && u.Name == item.PositionName);
  836. if (position != null) item.PositionId = position.Id;
  837. else item.ErrorInfo.Add(nameof(item.PositionName), $"职位{item.PositionName}不存在");
  838. }
  839. }
  840. #endregion 校验部门和职位
  841. #region 校验性别等字典
  842. var genders = await _dictService.GetValuesByDictValue(SysDictConst.GENDER, dictList);
  843. if (!genders.Contains(item.Gender))
  844. item.ErrorInfo.Add(nameof(item.Gender), "性别只能是男和女");
  845. if (!string.IsNullOrEmpty(item.Nation))
  846. {
  847. var nations = await _dictService.GetValuesByDictValue(SysDictConst.NATION, dictList);
  848. if (!nations.Contains(item.Nation))
  849. item.ErrorInfo.Add(nameof(item.Nation), "不存在的民族");
  850. }
  851. if (!string.IsNullOrEmpty(item.IdCardType))
  852. {
  853. var idCarTypes = await _dictService.GetValuesByDictValue(SysDictConst.ID_CARD_TYPE, dictList);
  854. if (!idCarTypes.Contains(item.IdCardType))
  855. item.ErrorInfo.Add(nameof(item.IdCardType), "证件类型错误");
  856. }
  857. if (!string.IsNullOrEmpty(item.CultureLevel))
  858. {
  859. var cultureLevels = await _dictService.GetValuesByDictValue(SysDictConst.CULTURE_LEVEL, dictList);
  860. if (!cultureLevels.Contains(item.CultureLevel))
  861. item.ErrorInfo.Add(nameof(item.CultureLevel), "文化程度有误");
  862. }
  863. #endregion 校验性别等字典
  864. if (item.ErrorInfo.Count > 0) item.HasError = true;//如果错误信息数量大于0则表示有错误
  865. }
  866. data = data.OrderByDescending(it => it.HasError).ToList();//排序
  867. return data;
  868. }
  869. /// <inheritdoc/>
  870. public async Task SetUserDefault(List<SysUser> sysUsers)
  871. {
  872. var defaultPassword = await GetDefaultPassWord(true);//默认密码
  873. //默认值赋值
  874. sysUsers.ForEach(user =>
  875. {
  876. user.Status = CommonStatusConst.ENABLE;//状态
  877. user.Phone = CryptogramUtil.Sm4Encrypt(user.Phone);//手机号
  878. user.Password = defaultPassword;//默认密码
  879. user.Avatar = AvatarUtil.GetNameImageBase64(user.Name);//默认头像
  880. });
  881. }
  882. #endregion 导入导出
  883. #region 方法
  884. /// <summary>
  885. /// 获取默认密码
  886. /// </summary>
  887. /// <returns></returns>
  888. private async Task<string> GetDefaultPassWord(bool isSm4 = false)
  889. {
  890. //获取默认密码
  891. var defaultPassword = (await _configService.GetByConfigKey(CateGoryConst.CONFIG_PWD_POLICY, SysConfigConst.PWD_DEFAULT_PASSWORD)).ConfigValue;
  892. return isSm4 ? CryptogramUtil.Sm4Encrypt(defaultPassword) : defaultPassword;//判断是否需要加密
  893. }
  894. /// <summary>
  895. /// 检查输入参数
  896. /// </summary>
  897. /// <param name="sysUser"></param>
  898. private async Task CheckInput(SysUser sysUser)
  899. {
  900. var sysOrgList = await _sysOrgService.GetListAsync();//获取组织列表
  901. var userOrg = sysOrgList.FirstOrDefault(it => it.Id == sysUser.OrgId);
  902. if (userOrg == null)
  903. throw Oops.Bah($"组织机构不存在");
  904. //获取多租户配置
  905. var isTenant = await _configService.IsTenant();
  906. long? tenantId = null;
  907. if (isTenant)
  908. tenantId = await _sysOrgService.GetTenantIdByOrgId(sysUser.OrgId, sysOrgList);
  909. //判断账号重复,直接从缓存拿
  910. var accountId = await GetIdByAccount(sysUser.Account, tenantId);
  911. if (accountId > 0 && accountId != sysUser.Id)
  912. throw Oops.Bah($"存在重复的账号:{sysUser.Account}");
  913. //如果手机号不是空
  914. if (!string.IsNullOrEmpty(sysUser.Phone))
  915. {
  916. if (!sysUser.Phone.MatchPhoneNumber())//验证手机格式
  917. throw Oops.Bah($"手机号码:{sysUser.Phone} 格式错误");
  918. var phoneId = await GetIdByPhone(sysUser.Phone, tenantId);
  919. if (phoneId > 0 && sysUser.Id != phoneId)//判断重复
  920. throw Oops.Bah($"存在重复的手机号:{sysUser.Phone}");
  921. sysUser.Phone = CryptogramUtil.Sm4Encrypt(sysUser.Phone);
  922. }
  923. //如果邮箱不是空
  924. if (!string.IsNullOrEmpty(sysUser.Email))
  925. {
  926. var (isMatch, match) = sysUser.Email.MatchEmail();//验证邮箱格式
  927. if (!isMatch)
  928. throw Oops.Bah($"邮箱:{sysUser.Email} 格式错误");
  929. if (await IsAnyAsync(it => it.Email == sysUser.Email && it.Id != sysUser.Id))
  930. throw Oops.Bah($"存在重复的邮箱:{sysUser.Email}");
  931. }
  932. if (sysUser.DirectorId != null)
  933. {
  934. if (sysUser.DirectorId.Value == UserManager.UserId) throw Oops.Bah($"不能设置自己为主管");
  935. }
  936. }
  937. /// <summary>
  938. /// 检查是否为自己
  939. /// </summary>
  940. /// <param name="id"></param>
  941. /// <param name="operate">操作名称</param>
  942. private void CheckSelf(long id, string operate)
  943. {
  944. if (id == UserManager.UserId)//如果是自己
  945. {
  946. throw Oops.Bah($"禁止{operate}自己");
  947. }
  948. }
  949. /// <summary>
  950. /// 根据日期计算年龄
  951. /// </summary>
  952. /// <param name="birthdate"></param>
  953. /// <returns></returns>
  954. public int GetAgeByBirthdate(DateTime birthdate)
  955. {
  956. var now = DateTime.Now;
  957. var age = now.Year - birthdate.Year;
  958. if (now.Month < birthdate.Month || now.Month == birthdate.Month && now.Day < birthdate.Day)
  959. {
  960. age--;
  961. }
  962. return age < 0 ? 0 : age;
  963. }
  964. /// <summary>
  965. /// 获取SqlSugar的ISugarQueryable
  966. /// </summary>
  967. /// <param name="input"></param>
  968. /// <returns></returns>
  969. private async Task<ISugarQueryable<SysUser>> GetQuery(UserPageInput input)
  970. {
  971. var orgIds = await _sysOrgService.GetOrgChildIds(input.OrgId);//获取下级机构
  972. var query = Context.Queryable<SysUser>().LeftJoin<SysOrg>((u, o) => u.OrgId == o.Id).LeftJoin<SysPosition>((u, o, p) => u.PositionId == p.Id)
  973. .WhereIF(input.OrgId > 0, u => orgIds.Contains(u.OrgId))//根据组织
  974. .WhereIF(input.Expression != null, input.Expression?.ToExpression())//动态查询
  975. .WhereIF(!string.IsNullOrEmpty(input.Status), u => u.Status == input.Status)//根据状态查询
  976. .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u => u.Name.Contains(input.SearchKey) || u.Account.Contains(input.SearchKey))//根据关键字查询
  977. .OrderByIF(!string.IsNullOrEmpty(input.SortField), $"u.{input.SortField} {input.SortOrder}").OrderBy(u => u.Id)//排序
  978. .OrderBy((u, o) => u.CreateTime)//排序
  979. .Select((u, o, p) => new SysUser
  980. {
  981. Id = u.Id.SelectAll(),
  982. OrgName = o.Name,
  983. PositionName = p.Name,
  984. OrgNames = o.Names
  985. }).Mapper(u =>
  986. {
  987. u.Password = null;//密码清空
  988. u.Phone = CryptogramUtil.Sm4Decrypt(u.Phone);//手机号解密
  989. });
  990. return query;
  991. }
  992. /// <summary>
  993. /// 数据库获取用户信息
  994. /// </summary>
  995. /// <param name="userId">用户ID</param>
  996. /// <returns></returns>
  997. private async Task<SysUser> GetUserFromDb(long userId)
  998. {
  999. var sysUser = await Context.Queryable<SysUser>().LeftJoin<SysOrg>((u, o) => u.OrgId == o.Id)//连表
  1000. .LeftJoin<SysPosition>((u, o, p) => u.PositionId == p.Id)//连表
  1001. .Where(u => u.Id == userId)
  1002. .Select((u, o, p) => new SysUser
  1003. {
  1004. Id = u.Id.SelectAll(),
  1005. OrgName = o.Name,
  1006. OrgNames = o.Names,
  1007. PositionName = p.Name,
  1008. OrgAndPosIdList = o.ParentIdList
  1009. }).FirstAsync();
  1010. if (sysUser != null)
  1011. {
  1012. sysUser.Password = CryptogramUtil.Sm4Decrypt(sysUser.Password);//解密密码
  1013. sysUser.Phone = CryptogramUtil.Sm4Decrypt(sysUser.Phone);//解密手机号
  1014. sysUser.OrgAndPosIdList.AddRange(sysUser.OrgId, sysUser.PositionId);//添加组织和职位Id
  1015. if (sysUser.DirectorId != null)
  1016. {
  1017. sysUser.DirectorInfo = await GetUserById<UserSelectorOutPut>(sysUser.DirectorId.Value);//获取主管信息
  1018. }
  1019. //获取按钮码
  1020. var buttonCodeList = await GetButtonCodeList(sysUser.Id);
  1021. //获取数据权限
  1022. var dataScopeList = await GetPermissionListByUserId(sysUser.Id, sysUser.OrgId);
  1023. //获取权限码
  1024. var permissionCodeList = dataScopeList.Select(it => it.ApiUrl).ToList();
  1025. //获取角色码
  1026. var roleCodeList = await _sysRoleService.GetRoleListByUserId(sysUser.Id);
  1027. //权限码赋值
  1028. sysUser.ButtonCodeList = buttonCodeList;
  1029. sysUser.RoleCodeList = roleCodeList.Select(it => it.Code).ToList();
  1030. sysUser.RoleIdList = roleCodeList.Select(it => it.Id).ToList();
  1031. sysUser.PermissionCodeList = permissionCodeList;
  1032. sysUser.DataScopeList = dataScopeList;
  1033. var sysOrgList = await _sysOrgService.GetListAsync();
  1034. var scopeOrgChildList =
  1035. (await _sysOrgService.GetChildListById(sysUser.OrgId, true, sysOrgList)).Select(it => it.Id).ToList();//获取所属机构的下级机构Id列表
  1036. sysUser.ScopeOrgChildList = scopeOrgChildList;
  1037. if (await _configService.IsTenant())//如果是多租户就获取用户的租户Id
  1038. {
  1039. var tenantId = await _sysOrgService.GetTenantIdByOrgId(sysUser.OrgId, sysOrgList);
  1040. sysUser.TenantId = tenantId;
  1041. }
  1042. var moduleIds = await _relationService.GetUserModuleId(sysUser.RoleIdList, sysUser.Id);//获取模块ID列表
  1043. var modules = await _resourceService.GetResourcesByIds(moduleIds, CateGoryConst.RESOURCE_MODULE);//获取模块列表
  1044. sysUser.ModuleList = modules;//模块列表赋值给用户
  1045. //插入缓存
  1046. _simpleCacheService.HashAdd(SystemConst.CACHE_SYS_USER_AVATAR, sysUser.Id.ToString(), sysUser.Avatar);
  1047. sysUser.Avatar = null;//头像清空,减少CACHE_SYS_USER的大小
  1048. _simpleCacheService.HashAdd(SystemConst.CACHE_SYS_USER, sysUser.Id.ToString(), sysUser);
  1049. return sysUser;
  1050. }
  1051. return null;
  1052. }
  1053. #endregion 方法
  1054. }