AuthSessionAppService.cs
9.34 KB
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
using FoodLabeling.Application.Contracts.Dtos.AuthSession;
using FoodLabeling.Application.Contracts.IServices;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.Caching;
using FoodLabeling.Application.Services.DbModels;
using Yi.Framework.Rbac.Domain.Entities;
using Yi.Framework.Rbac.Domain.Shared.Caches;
using Yi.Framework.Rbac.Domain.Shared.Consts;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace FoodLabeling.Application.Services;
/// <summary>
/// 当前登录会话:菜单权限与退出
/// </summary>
[Authorize]
public class AuthSessionAppService : ApplicationService, IAuthSessionAppService
{
private readonly IDistributedCache<UserInfoCacheItem, UserInfoCacheKey> _userCache;
private readonly ISqlSugarDbContext _dbContext;
private readonly ISqlSugarRepository<UserAggregateRoot, Guid> _userRepository;
public AuthSessionAppService(
ISqlSugarDbContext dbContext,
ISqlSugarRepository<UserAggregateRoot, Guid> userRepository,
IDistributedCache<UserInfoCacheItem, UserInfoCacheKey> userCache)
{
_dbContext = dbContext;
_userRepository = userRepository;
_userCache = userCache;
}
/// <inheritdoc />
public virtual async Task<CurrentUserMenuPermissionsOutputDto> GetMyMenusAsync()
{
if (!CurrentUser.Id.HasValue)
{
throw new UserFriendlyException("用户未登录");
}
// 避免走 UserManager.GetInfoAsync -> UserRepository.GetUserAllInfoAsync 的导航加载
// 这里直接按 UserRole/RoleMenu/Menu 表关联查询当前用户可见菜单与权限码
var userId = CurrentUser.Id.Value;
var user = await _userRepository.GetByIdAsync(userId);
if (user is null || user.IsDeleted)
{
throw new UserFriendlyException("用户不存在");
}
var userRoleIds = await _dbContext.SqlSugarClient.Queryable<UserRoleEntity>()
.Where(x => x.UserId == userId)
.Select(x => x.RoleId)
.ToListAsync();
var distinctUserRoleIds = userRoleIds.Distinct().ToList();
List<MenuDbEntity> menus;
if (UserConst.Admin.Equals(user.UserName))
{
// MenuAggregateRoot(ParentId 为 Guid) 无法兼容 menu.ParentId=0/字符串:这里统一用 MenuDbEntity
menus = await _dbContext.SqlSugarClient.Queryable<MenuDbEntity>()
.Where(x => x.IsDeleted == false)
.ToListAsync();
}
else
{
var roleIdStrs = distinctUserRoleIds.Select(x => x.ToString()).Distinct().ToList();
if (roleIdStrs.Count == 0)
{
menus = new List<MenuDbEntity>();
}
else
{
var menuIds = await _dbContext.SqlSugarClient.Queryable<RoleMenuDbEntity>()
.Where(x => roleIdStrs.Contains(x.RoleId))
.Select(x => x.MenuId)
.Distinct()
.ToListAsync();
menus = menuIds.Count == 0
? new List<MenuDbEntity>()
: await _dbContext.SqlSugarClient.Queryable<MenuDbEntity>()
.Where(x => x.IsDeleted == false && menuIds.Contains(x.Id))
.ToListAsync();
}
}
var menuNodes = menus
.Select(MapToNode)
.OrderByDescending(x => x.OrderNum)
.ThenBy(x => x.MenuName)
.ToList();
// 注意:经仓储查询 RoleAggregateRoot 会触发 YiRbacDbContext 的 IDataPermission 过滤,
// 其表达式包含 roleInfo.Select(...).Contains(...),在当前 SqlSugar 版本下会报“不支持 Select”。
// 角色展示名使用 RoleDbEntity 直查 Role 表;角色编码列表仍用 JWT(CurrentUser.Roles),与原先 RoleCodes 行为一致。
var roleCodes = CurrentUser.Roles?.ToList() ?? new List<string>();
var roleDisplay = await BuildRoleDisplayAsync(distinctUserRoleIds, roleCodes);
var permissionCodes = menuNodes
.Where(x => !string.IsNullOrWhiteSpace(x.PermissionCode))
.Select(x => x.PermissionCode!.Trim())
.Distinct()
.OrderBy(x => x)
.ToList();
return new CurrentUserMenuPermissionsOutputDto
{
User = new CurrentUserBriefDto
{
Id = user.Id,
UserName = user.UserName,
Nick = user.Nick,
Email = user.Email,
Icon = user.Icon
},
RoleCodes = roleCodes.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim()).Distinct().OrderBy(x => x).ToList(),
PermissionCodes = permissionCodes,
Menus = BuildMenuTree(menuNodes),
LastUpdated = user.LastModificationTime,
Role = roleDisplay,
FullName = BuildFullName(user)
};
}
/// <inheritdoc />
[HttpPost]
public virtual async Task<bool> LogoutAsync()
{
if (!CurrentUser.Id.HasValue)
{
return false;
}
await _userCache.RemoveAsync(new UserInfoCacheKey(CurrentUser.Id.Value));
return true;
}
private static string BuildFullName(UserAggregateRoot user)
{
if (!string.IsNullOrWhiteSpace(user.Name))
{
return user.Name.Trim();
}
if (!string.IsNullOrWhiteSpace(user.Nick))
{
return user.Nick.Trim();
}
return user.UserName ?? string.Empty;
}
private async Task<string> BuildRoleDisplayAsync(
IReadOnlyList<Guid> userRoleIds,
IReadOnlyList<string> jwtRoleCodes)
{
var names = new List<string>();
if (userRoleIds.Count > 0)
{
names = await _dbContext.SqlSugarClient.Queryable<RoleDbEntity>()
.Where(r => !r.IsDeleted && userRoleIds.Contains(r.Id))
.OrderBy(r => r.RoleName)
.Select(r => r.RoleName)
.ToListAsync();
}
if (names.Count == 0 && jwtRoleCodes.Count > 0)
{
var codes = jwtRoleCodes
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => x.Trim())
.Distinct()
.ToList();
names = await _dbContext.SqlSugarClient.Queryable<RoleDbEntity>()
.Where(r => !r.IsDeleted && codes.Contains(r.RoleCode))
.OrderBy(r => r.RoleName)
.Select(r => r.RoleName)
.ToListAsync();
}
var distinctNames = names
.Where(n => !string.IsNullOrWhiteSpace(n))
.Select(n => n.Trim())
.Distinct()
.ToList();
if (distinctNames.Count > 0)
{
return string.Join(", ", distinctNames);
}
var fallbackCodes = jwtRoleCodes
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => x.Trim())
.Distinct()
.ToList();
return fallbackCodes.Count > 0 ? string.Join(", ", fallbackCodes) : string.Empty;
}
private static List<CurrentUserMenuNodeDto> BuildMenuTree(List<CurrentUserMenuNodeDto> flat)
{
var nodes = flat
.GroupBy(x => x.Id)
.Select(g => g.First())
.ToList();
var byId = nodes.ToDictionary(n => n.Id, n => n);
foreach (var n in nodes)
{
n.Children = new List<CurrentUserMenuNodeDto>();
}
var roots = new List<CurrentUserMenuNodeDto>();
foreach (var n in nodes)
{
var pid = string.IsNullOrWhiteSpace(n.ParentId) ? "0" : n.ParentId.Trim();
if (pid == "0" || pid == "00000000-0000-0000-0000-000000000000")
{
roots.Add(n);
continue;
}
if (byId.TryGetValue(pid, out var parent))
{
parent.Children.Add(n);
}
else
{
roots.Add(n);
}
}
SortMenuTree(roots);
return roots;
}
private static CurrentUserMenuNodeDto MapToNode(MenuDbEntity m)
{
return new CurrentUserMenuNodeDto
{
Id = m.Id,
ParentId = string.IsNullOrWhiteSpace(m.ParentId) ? "0" : m.ParentId.Trim(),
MenuName = m.MenuName ?? string.Empty,
RouterName = m.RouterName,
Router = m.Router,
PermissionCode = m.PermissionCode,
MenuType = m.MenuType,
MenuSource = m.MenuSource,
OrderNum = m.OrderNum,
State = m.State,
MenuIcon = m.MenuIcon,
Component = m.Component,
IsLink = m.IsLink,
IsCache = m.IsCache,
IsShow = m.IsShow,
Query = m.Query,
Remark = m.Remark
};
}
private static void SortMenuTree(List<CurrentUserMenuNodeDto> level)
{
level.Sort((a, b) =>
{
var o = b.OrderNum.CompareTo(a.OrderNum);
return o != 0 ? o : string.Compare(a.MenuName, b.MenuName, StringComparison.Ordinal);
});
foreach (var n in level)
{
if (n.Children.Count > 0)
{
SortMenuTree(n.Children);
}
}
}
}