qinchulong
2025-03-29 039a4a5433e7f80adc88b491b549e5d9486e4f9a
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
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using WIDESEA_Core.CacheManager;
using WIDESEA_Core.DBManager;
using WIDESEA_Core.Enums;
using WIDESEA_Core.Extensions;
using WIDESEA_Core.Extensions.AutofacManager;
using WIDESEA_Entity;
using WIDESEA_Entity.DomainModels;
 
namespace WIDESEA_Core.ManageUser
{
    public class UserContext
    {
        /// <summary>
        /// 为了尽量减少redis或Memory读取,保证执行效率,将UserContext注入到DI,
        /// 每个UserContext的属性至多读取一次redis或Memory缓存从而提高查询效率
        /// </summary>
        public static UserContext Current
        {
            get
            {
                return Context.RequestServices.GetService(typeof(UserContext)) as UserContext;
            }
        }
 
        private static Microsoft.AspNetCore.Http.HttpContext Context
        {
            get
            {
                return Utilities.HttpContext.Current;
            }
        }
        private static ICacheService CacheService
        {
            get { return GetService<ICacheService>(); }
        }
 
        private static T GetService<T>() where T : class
        {
            return AutofacContainerModule.GetService<T>();
        }
 
        public UserInfo UserInfo
        {
            get
            {
                if (_userInfo != null)
                {
                    return _userInfo;
                }
                return GetUserInfo(UserId);
            }
        }
 
        private UserInfo _userInfo { get; set; }
 
        /// <summary>
        /// 角色ID为1的默认为超级管理员
        /// </summary>
        public bool IsSuperAdmin
        {
            get { return IsRoleIdSuperAdmin(this.RoleId); }
        }
        /// <summary>
        /// 角色ID为1的默认为超级管理员
        /// </summary>
        public static bool IsRoleIdSuperAdmin(int roleId)
        {
            return roleId == 1;
        }
 
        public UserInfo GetUserInfo(int userId)
        {
            if (_userInfo != null) return _userInfo;
            if (userId <= 0)
            {
                _userInfo = new UserInfo();
                return _userInfo;
            }
            string key = userId.GetUserIdKey();
            _userInfo = CacheService.Get<UserInfo>(key);
            if (_userInfo != null && _userInfo.User_Id > 0) return _userInfo;
 
            _userInfo = DBServerProvider.DbContext.Set<Sys_User>()
                .Where(x => x.User_Id == userId).Select(s => new UserInfo()
                {
                    User_Id = userId,
                    Role_Id = s.Role_Id.GetInt(),
                    RoleName = s.RoleName,
                    Token = s.Token,
                    UserName = s.UserName,
                    UserTrueName = s.UserTrueName,
                    Enable = s.Enable
                }).FirstOrDefault();
 
            if (_userInfo != null && _userInfo.User_Id > 0)
            {
                CacheService.AddObject(key, _userInfo);
            }
            return _userInfo ?? new UserInfo();
        }
 
        /// <summary>
        /// 获取角色权限时通过安全字典锁定的角色id
        /// </summary>
        private static ConcurrentDictionary<string, object> objKeyValue = new ConcurrentDictionary<string, object>();
 
        /// <summary>
        /// 角色权限的版本号
        /// </summary>
        private static readonly Dictionary<int, string> rolePermissionsVersion = new Dictionary<int, string>();
 
        /// <summary>
        /// 每个角色ID对应的菜单权限(已做静态化处理)
        /// 每次获取权限时用当前服务器的版本号与redis/memory缓存的版本比较,如果不同会重新刷新缓存
        /// </summary>
        private static readonly Dictionary<int, List<Permissions>> rolePermissions = new Dictionary<int, List<Permissions>>();
 
 
        /// <summary>
        /// 获取用户所有的菜单权限
        /// </summary>
 
        public List<Permissions> Permissions
        {
            get
            {
                return GetPermissions(RoleId);
            }
        }
 
        /// <summary>
        /// 获取单个表的权限
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public Permissions GetPermissions(string tableName)
        {
            return GetPermissions(RoleId).Where(x => x.TableName == tableName).FirstOrDefault();
        }
 
        /// <summary>
        /// 自定条件查询权限
        /// </summary>
        /// <param name="func"></param>
        /// <returns></returns>
        public Permissions GetPermissions(Func<Permissions, bool> func)
        {
            return GetPermissions(RoleId).Where(func).FirstOrDefault();
        }
 
        private List<Permissions> ActionToArray(List<Permissions> permissions)
        {
            permissions.ForEach(x =>
            {
                try
                {
                    x.UserAuthArr = string.IsNullOrEmpty(x.UserAuth)
                    ? new string[0]
                    : x.UserAuth.Split(",");
                }
                catch { }
                finally
                {
                    if (x.UserAuthArr == null)
                    {
                        x.UserAuthArr = new string[0];
                    }
                }
            });
            return permissions;
        }
        private List<Permissions> MenuActionToArray(List<Permissions> permissions)
        {
            permissions.ForEach(x =>
            {
                try
                {
                    x.UserAuthArr = string.IsNullOrEmpty(x.UserAuth)
                    ? new string[0]
                    : x.UserAuth.DeserializeObject<List<Sys_Actions>>().Select(s => s.Value).ToArray();
                }
                catch { }
                finally
                {
                    if (x.UserAuthArr == null)
                    {
                        x.UserAuthArr = new string[0];
                    }
                }
            });
            return permissions;
        }
        public List<Permissions> GetPermissions(int roleId)
        {
            if (IsRoleIdSuperAdmin(roleId))
            {
                var permissions = DBServerProvider.DbContext.Set<Sys_Menu>().Where(x => x.Enable == 1).Select(a => new Permissions
                {
                    Menu_Id = a.Menu_Id,
                    ParentId = a.ParentId,
                    //2020.05.06增加默认将表名转换成小写,权限验证时不再转换
                    TableName = (a.TableName ?? "").ToLower(),
                    //MenuAuth = a.Auth,
                    UserAuth = a.Auth,
                }).ToList();
                return MenuActionToArray(permissions);
            }
            ICacheService cacheService = CacheService;
            string roleKey = roleId.GetRoleIdKey();
 
            //角色有缓存,并且当前服务器的角色版本号与redis/memory缓存角色的版本号相同直接返回静态对象角色权限
            string currnetVeriosn = "";
            if (rolePermissionsVersion.TryGetValue(roleId, out currnetVeriosn)
                && currnetVeriosn == cacheService.Get(roleKey))
            {
                return rolePermissions.ContainsKey(roleId) ? rolePermissions[roleId] : new List<Permissions>();
            }
 
            //锁定每个角色,通过安全字典减少锁粒度,否则多个同时角色获取缓存会导致阻塞
            object objId = objKeyValue.GetOrAdd(roleId.ToString(), new object());
            //锁定每个角色
            lock (objId)
            {
                if (rolePermissionsVersion.TryGetValue(roleId, out currnetVeriosn)
                    && currnetVeriosn == cacheService.Get(roleKey))
                {
                    return rolePermissions.ContainsKey(roleId) ? rolePermissions[roleId] : new List<Permissions>();
                }
 
                //没有redis/memory缓存角色的版本号或与当前服务器的角色版本号不同时,刷新缓存
                var dbContext = DBServerProvider.DbContext;
                List<Permissions> _permissions = (from a in dbContext.Set<Sys_Menu>()
                                                  join b in dbContext.Set<Sys_RoleAuth>()
                                                  on a.Menu_Id equals b.Menu_Id
                                                  where b.Role_Id == roleId //&& a.ParentId > 0
                                                  && b.AuthValue != ""
                                                  orderby a.ParentId
                                                  select new Permissions
                                                  {
                                                      Menu_Id = a.Menu_Id,
                                                      ParentId = a.ParentId,
                                                      //2020.05.06增加默认将表名转换成小写,权限验证时不再转换
                                                      TableName = (a.TableName ?? "").ToLower(),
                                                      MenuAuth = a.Auth,
                                                      UserAuth = b.AuthValue ?? ""
                                                  }).ToList();
                ActionToArray(_permissions);
                string _version = cacheService.Get(roleKey);
                //生成一个唯一版本号标识
                if (_version == null)
                {
                    _version = DateTime.Now.ToString("yyyyMMddHHMMssfff");
                    //将版本号写入缓存
                    cacheService.Add(roleKey, _version);
                }
                //刷新当前服务器角色的权限
                rolePermissions[roleId] = _permissions;
 
                //写入当前服务器的角色最新版本号
                rolePermissionsVersion[roleId] = _version;
                return _permissions;
            }
 
        }
 
        /// <summary>
        /// 判断是否有权限
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="authName"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public bool ExistsPermissions(string tableName, string authName, int roleId = 0)
        {
            if (roleId <= 0) roleId = RoleId;
            tableName = tableName.ToLower();
            authName = authName.ToLower();
            return GetPermissions(roleId).Any(x => x.TableName == tableName && x.UserAuthArr.Contains(authName));
        }
 
        /// <summary>
        /// 判断是否有权限
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="authName"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public bool ExistsPermissions(string tableName, ActionPermissionOptions actionPermission, int roleId = 0)
        {
            return ExistsPermissions(tableName, actionPermission.ToString(),roleId);
        }
        public int UserId
        {
            get
            {
                return (Context.User.FindFirstValue(JwtRegisteredClaimNames.Jti)
                    ?? Context.User.FindFirstValue(ClaimTypes.NameIdentifier)).GetInt();
            }
        }
 
        public string UserName
        {
            get { return UserInfo.UserName; }
        }
 
        public string UserTrueName
        {
            get { return UserInfo.UserTrueName; }
        }
 
        public string Token
        {
            get { return UserInfo.Token; }
        }
 
        public int RoleId
        {
            get { return UserInfo.Role_Id; }
        }
 
        public void LogOut(int userId)
        {
            CacheService.Remove(userId.GetUserIdKey());
        }
    }
}