UserService.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. using Microsoft.Extensions.Caching.Distributed;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using XYY.Common.Standard;
  7. using XYY.Core.Standard;
  8. using XYY.Data.Standard;
  9. using XYY.Model.Standard;
  10. using XYY.Service.Standard.UserService.Model;
  11. namespace XYY.Service.Standard.UserService
  12. {
  13. public interface IUserService
  14. {
  15. Task<UserContent> GetUserContentAtApi(string token);
  16. Task<User_Info> Login(string account, string password);
  17. Task<LoginDto> LoginV2(string account, string password);
  18. Task<List<string>> GetUserRoleNames(int userId);
  19. }
  20. public class UserService : IUserService
  21. {
  22. private readonly IUserInfoRepository _userInfoRepository;
  23. private readonly IUserApiRepository _userApiRepository;
  24. private readonly IUserRoleRepository _userRoleRepository;
  25. private readonly IUserPermissionRepository _userPermissionRepository;
  26. private readonly IDistributedCache _cache;
  27. public UserService(
  28. IUserInfoRepository userInfoRepository,
  29. IUserApiRepository userApiRepository,
  30. IUserRoleRepository userRoleRepository,
  31. IDistributedCache cache,
  32. IUserPermissionRepository userPermissionRepository
  33. )
  34. {
  35. _userInfoRepository = userInfoRepository;
  36. _userApiRepository = userApiRepository;
  37. _userRoleRepository = userRoleRepository;
  38. _cache = cache;
  39. _userPermissionRepository = userPermissionRepository;
  40. }
  41. string keyBase = "userinfo";
  42. /// <summary>
  43. /// 用户登录
  44. /// </summary>
  45. /// <param name="account">账号</param>
  46. /// <param name="password">密码</param>
  47. /// <returns></returns>
  48. public async Task<User_Info> Login(string account, string password)
  49. {
  50. Ensure.NotNullOrEmpty(account, "account");
  51. Ensure.NotNullOrEmpty(password, "password");
  52. var user = await _userInfoRepository.QueryAsync(x => (x.LoginAccount == account || x.Email == account) && x.LoginPassword == password);
  53. return user.FirstOrDefault();
  54. }
  55. public async Task<LoginDto> LoginV2(string account, string password)
  56. {
  57. Ensure.NotNullOrEmpty(account, "account");
  58. Ensure.NotNullOrEmpty(password, "password");
  59. password = MD5Util.Get(password);
  60. var user =await this.Login(account, password);
  61. if (user == null)
  62. {
  63. throw new Exception("用户名或密码错误");
  64. }
  65. if (!user.IsActive)
  66. {
  67. throw new Exception("该账号未激活或已被管理员关闭");
  68. }
  69. return await GetDto(user);
  70. }
  71. public async Task<List<string>> GetUserRoleNames(int userId)
  72. {
  73. var roles = await _userRoleRepository.GetUserRoles(userId);
  74. var roleNames = roles.Select(i => i.RoleName)?.ToList();
  75. return roleNames;
  76. }
  77. private async Task<LoginDto> GetDto(User_Info user)
  78. {
  79. var roles = await _userRoleRepository.GetUserRoles(user.Id);
  80. bool isAdmin = false;
  81. if (roles.Any(x => x.RoleName == "系统管理员"))
  82. {
  83. isAdmin = true;
  84. }
  85. var roleNames = roles.Select(i => i.RoleName)?.ToArray();
  86. int userId = user.Id;
  87. var result = await _userApiRepository.QueryAsync(i => i.UserId == userId);
  88. var api = result?.FirstOrDefault();
  89. if (api == null)
  90. {
  91. throw new Exception("User Token Not Found");
  92. }
  93. return new LoginDto()
  94. {
  95. Id = user.Id,
  96. Name = user.NickName,
  97. CustomerId = user.CustomerId,
  98. LoginAccount = user.LoginAccount,
  99. IsSuccess = true,
  100. IsAdmin = isAdmin,
  101. IsCustomer = user.CustomerId > 0,
  102. RoleNames = roleNames,
  103. Token = api.Token
  104. };
  105. }
  106. public async Task<UserContent> GetUserContentAtApi(string token)
  107. {
  108. string key = getTokenKey(token);
  109. string cacheData = await _cache.GetStringAsync(key);
  110. if (string.IsNullOrEmpty(cacheData))
  111. {
  112. var userInfo = await GetUserAtApi(token);
  113. var uc = await GetUserContent(userInfo);
  114. cacheData = Newtonsoft.Json.JsonConvert.SerializeObject(uc);
  115. await _cache.SetStringAsync(key, cacheData);
  116. }
  117. return Newtonsoft.Json.JsonConvert.DeserializeObject<UserContent>(cacheData);
  118. }
  119. private async Task<UserContent> GetUserContent(User_Info userInfo)
  120. {
  121. if (userInfo == null)
  122. return new UserContent { IsAuthorization = false };
  123. else
  124. {
  125. UserContent userContent = new UserContent
  126. {
  127. IsAuthorization = true,
  128. NiceName = userInfo.NickName,
  129. CustomerId = userInfo.CustomerId,
  130. Id = userInfo.Id
  131. };
  132. var roles = await GetUserRoles(userContent.Id);
  133. userContent.Roles = roles.Select(x => x.RoleName).ToList();
  134. var permissionTask = await GetPermissionByUserId(userContent.Id);
  135. userContent.PrivilegeUrl = permissionTask.Select(x => x.Href).Distinct().ToList();
  136. return userContent;
  137. }
  138. }
  139. public async Task<IEnumerable<User_Permission>> GetPermissionByUserId(int userId)
  140. {
  141. string sql = $@"SELECT c.* FROM dbo.User_UserRole(NOLOCK) a
  142. INNER JOIN dbo.User_RolePermission(NOLOCK) b ON a.RoleId=b.RoleId
  143. INNER JOIN dbo.User_Permission(NOLOCK) c ON b.PermissionId = c.Id
  144. WHERE c.IsEnable=1 AND a.UserId={userId}";
  145. return await _userPermissionRepository.QueryBySqlAsync(sql);
  146. }
  147. public async Task<User_Info> GetUserAtApi(string token)
  148. {
  149. token = token.Trim();
  150. string sql = @"select info.* from User_Info as info join User_API as api on info.Id = api.UserId and token=@token";
  151. var obj = await _userInfoRepository.QueryAsync(sql, new { token = token });
  152. return obj.FirstOrDefault();
  153. }
  154. /// <summary>
  155. /// 获取用户对应的角色
  156. /// </summary>
  157. /// <returns></returns>
  158. public async Task<List<User_Role>> GetUserRoles(int userId)
  159. {
  160. string sql = "Select UR.* from User_Role UR Join User_UserRole URR on URR.UserId=" + userId + " and URR.RoleId = UR.Id";
  161. var r = await _userRoleRepository.QueryBySqlAsync(sql);
  162. return r.ToList();
  163. }
  164. private string getUserKey(int id)
  165. {
  166. return string.Concat(keyBase, "_", id.ToString());
  167. }
  168. /// <summary>
  169. /// 清除指定用户的Cache
  170. /// </summary>
  171. /// <param name="usreId"></param>
  172. public async Task ClareUserCache(int userId)
  173. {
  174. await _cache.RemoveAsync(getUserKey(userId));
  175. }
  176. private string getTokenKey(string token)
  177. {
  178. return string.Concat(keyBase, "_", token);
  179. }
  180. public async Task ClareUserCacheAsToken(string token)
  181. {
  182. await _cache.RemoveAsync(getTokenKey(token));
  183. }
  184. public async Task ClareUserCache()
  185. {
  186. await _cache.RemoveAsync(keyBase);
  187. }
  188. }
  189. }