🍒 feat: 增强session功能
This commit is contained in:
parent
c4f3295409
commit
ef5852ea89
@ -171,8 +171,6 @@ public class AppAuthService : IDynamicApiController, ITransient
|
||||
.LeftJoin<SysRole>((u, a) => u.RoleId == a.Id)
|
||||
.Where(u => u.UserId == user.Id)
|
||||
.Select((u, a) => new RoleDto { Id = a.Id, Name = a.Name, Code = a.Code }).ToListAsync();
|
||||
// 接口集合
|
||||
var apis = (await _sysRoleService.GetUserApiList())[0];
|
||||
|
||||
return new LoginUserOutput
|
||||
{
|
||||
@ -190,8 +188,8 @@ public class AppAuthService : IDynamicApiController, ITransient
|
||||
OrgName = org?.Name,
|
||||
OrgType = org?.Type,
|
||||
PosName = pos?.Name,
|
||||
Apis = apis,
|
||||
Roles = roles
|
||||
Roles = roles,
|
||||
Apis = _appUserManager.Permissions,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@ -221,16 +221,15 @@ public class SysAuthService : IDynamicApiController, ITransient
|
||||
/// </summary>
|
||||
/// <param name="user"></param>
|
||||
/// <param name="loginMode"></param>
|
||||
/// <param name="isRefresh"></param>
|
||||
/// <returns></returns>
|
||||
[NonAction]
|
||||
public async Task<LoginOutput> CreateToken(SysUser user, LoginModeEnum loginMode = LoginModeEnum.PC, bool isRefresh = false)
|
||||
public async Task<LoginOutput> CreateToken(SysUser user, LoginModeEnum loginMode = LoginModeEnum.PC)
|
||||
{
|
||||
// 单用户登录
|
||||
await App.GetRequiredService<SysOnlineUserService>().SingleLogin(user.Id, loginMode);
|
||||
|
||||
// 生成Token令牌
|
||||
if(!isRefresh) user.TokenVersion += 1;
|
||||
user.TokenVersion += 1;
|
||||
var tokenExpire = await _sysConfigService.GetTokenExpire();
|
||||
var accessToken = JWTEncryption.Encrypt(new Dictionary<string, object>
|
||||
{
|
||||
@ -238,24 +237,6 @@ public class SysAuthService : IDynamicApiController, ITransient
|
||||
{ ClaimConst.TokenVersion, user.TokenVersion },
|
||||
}, tokenExpire);
|
||||
|
||||
// 缓存用户Session
|
||||
_userManager.SetSession(new()
|
||||
{
|
||||
UserId = user.Id,
|
||||
TenantId = user.TenantId,
|
||||
Account = user.Account,
|
||||
RealName = user.RealName,
|
||||
AccountType = user.AccountType,
|
||||
OrgId = user.OrgId,
|
||||
OrgCode = user.SysOrg?.Code,
|
||||
OrgName = user.SysOrg?.Name,
|
||||
OrgType = user.SysOrg?.Type,
|
||||
OrgLevel = user.SysOrg?.Level,
|
||||
LoginMode = loginMode,
|
||||
TokenVersion = user.TokenVersion,
|
||||
ExtProps = App.GetServices<IUserSessionExtProps>().SelectMany(u => u.GetInitExtProps(user)).ToDictionary(u => u.Key, u => u.Value)
|
||||
}, TimeSpan.FromMinutes(tokenExpire));
|
||||
|
||||
// 生成刷新Token令牌
|
||||
var refreshTokenExpire = await _sysConfigService.GetRefreshTokenExpire();
|
||||
var refreshToken = JWTEncryption.GenerateRefreshToken(accessToken, refreshTokenExpire);
|
||||
@ -267,27 +248,27 @@ public class SysAuthService : IDynamicApiController, ITransient
|
||||
// ke.global.setAllHeader('Authorization', 'Bearer ' + ke.response.headers['access-token']);
|
||||
|
||||
// 更新用户登录信息
|
||||
if (!isRefresh)
|
||||
user.LastLoginIp = _httpContextAccessor.HttpContext.GetRemoteIpAddressToIPv4(true);
|
||||
(user.LastLoginAddress, double? longitude, double? latitude) = CommonHelper.GetIpAddress(user.LastLoginIp);
|
||||
user.LastLoginTime = DateTime.Now;
|
||||
user.LastLoginDevice = CommonHelper.GetClientDeviceInfo(_httpContextAccessor.HttpContext?.Request?.Headers?.UserAgent);
|
||||
await _sysUserRep.AsUpdateable(user).UpdateColumns(u => new
|
||||
{
|
||||
user.LastLoginIp = _httpContextAccessor.HttpContext.GetRemoteIpAddressToIPv4(true);
|
||||
(user.LastLoginAddress, double? longitude, double? latitude) = CommonHelper.GetIpAddress(user.LastLoginIp);
|
||||
user.LastLoginTime = DateTime.Now;
|
||||
user.LastLoginDevice = CommonHelper.GetClientDeviceInfo(_httpContextAccessor.HttpContext?.Request?.Headers?.UserAgent);
|
||||
await _sysUserRep.AsUpdateable(user).UpdateColumns(u => new
|
||||
{
|
||||
u.TokenVersion,
|
||||
u.LastLoginIp,
|
||||
u.LastLoginAddress,
|
||||
u.LastLoginTime,
|
||||
u.LastLoginDevice,
|
||||
}).ExecuteCommandAsync();
|
||||
u.TokenVersion,
|
||||
u.LastLoginIp,
|
||||
u.LastLoginAddress,
|
||||
u.LastLoginTime,
|
||||
u.LastLoginDevice,
|
||||
}).ExecuteCommandAsync();
|
||||
|
||||
// 缓存用户Token版本
|
||||
_sysCacheService.Set($"{CacheConst.KeyUserToken}{user.Id}", $"{user.TokenVersion}");
|
||||
// 缓存用户Token版本
|
||||
_sysCacheService.Set($"{CacheConst.KeyUserToken}{user.Id}", $"{user.TokenVersion}");
|
||||
|
||||
// 发布系统登录事件
|
||||
await _eventPublisher.PublishAsync(UserEventTypeEnum.Login, user);
|
||||
}
|
||||
// 发布系统登录事件
|
||||
await _eventPublisher.PublishAsync(UserEventTypeEnum.Login, user);
|
||||
|
||||
// 缓存用户Session
|
||||
await SetUserSession(user, loginMode);
|
||||
|
||||
return new LoginOutput
|
||||
{
|
||||
@ -296,6 +277,56 @@ public class SysAuthService : IDynamicApiController, ITransient
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置用户Session
|
||||
/// </summary>
|
||||
/// <param name="user"></param>
|
||||
/// <param name="loginMode"></param>
|
||||
private async Task SetUserSession(SysUser user, LoginModeEnum loginMode = LoginModeEnum.PC)
|
||||
{
|
||||
var db = _sysUserRep.Context.CopyNew();
|
||||
user.SysPos ??= await db.Queryable<SysPos>().FirstAsync(u => u.Id == user.PosId);
|
||||
user.SysOrg ??= await db.Queryable<SysOrg>().FirstAsync(u => u.Id == user.OrgId);
|
||||
|
||||
var permissions = await LazyHelper.GetService<SysRoleService>().GetUserApiList(user.Id);
|
||||
var unauthorizedPermissions = await LazyHelper.GetService<SysRoleService>().GetUnAuthApiList(user.Id);
|
||||
var orgIds = await LazyHelper.GetService<SysOrgService>().GetUserOrgIdList(user.Id, user.OrgId);
|
||||
var roleIds = await db.Queryable<SysUserRole>().Where(u => u.UserId == user.Id).Select(u => u.RoleId).ToListAsync();
|
||||
var postIds = await db.Queryable<SysUserExtOrg>().Where(u => u.UserId == user.Id).Select(u => u.PosId).ToListAsync() ?? [];
|
||||
var maxDataScope = await db.Queryable<SysRole>().Where(u => roleIds.Contains(u.Id)).MinAsync(u => u.DataScope);
|
||||
if (maxDataScope == 0) maxDataScope = DataScopeEnum.Self;
|
||||
postIds.Add(user.PosId);
|
||||
|
||||
// 缓存用户Session
|
||||
_userManager.SetSession(new()
|
||||
{
|
||||
UserId = user.Id,
|
||||
TenantId = user.TenantId,
|
||||
Account = user.Account,
|
||||
RealName = user.RealName,
|
||||
NickName = user.NickName,
|
||||
AccountType = user.AccountType,
|
||||
OrgId = user.OrgId,
|
||||
OrgCode = user.SysOrg?.Code,
|
||||
OrgName = user.SysOrg?.Name,
|
||||
OrgType = user.SysOrg?.Type,
|
||||
OrgLevel = user.SysOrg?.Level,
|
||||
PosId = user.PosId,
|
||||
PosName = user.SysPos?.Name,
|
||||
PosCode = user.SysPos?.Code,
|
||||
LoginMode = loginMode,
|
||||
TokenVersion = user.TokenVersion,
|
||||
OrgIds = orgIds,
|
||||
PosIds = postIds,
|
||||
RoleIds = roleIds,
|
||||
Permissions = permissions,
|
||||
UnauthorizedPermissions = unauthorizedPermissions,
|
||||
AppPermissions = loginMode == LoginModeEnum.APP ? LazyHelper.GetService<SysCommonService>().GetAppApiList() : null,
|
||||
MaxDataScope = user.AccountType == AccountTypeEnum.SuperAdmin ? DataScopeEnum.All : maxDataScope,
|
||||
ExtProps = App.GetServices<IUserSessionExtProps>().SelectMany(u => u.GetInitExtProps(user)).ToDictionary(u => u.Key, u => u.Value)
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前登陆用户信息 🔖
|
||||
/// </summary>
|
||||
@ -313,8 +344,6 @@ public class SysAuthService : IDynamicApiController, ITransient
|
||||
.LeftJoin<SysRole>((u, a) => u.RoleId == a.Id)
|
||||
.Where(u => u.UserId == user.Id)
|
||||
.Select((u, a) => new RoleDto { Id = a.Id, Name = a.Name, Code = a.Code }).ToListAsync();
|
||||
// 接口集合
|
||||
var apis = (await App.GetRequiredService<SysRoleService>().GetUserApiList())[0];
|
||||
// 个性化水印文字(若系统水印为空则不显示)
|
||||
var watermarkText = await _sysUserRep.ChangeRepository<SqlSugarRepository<SysTenant>>().AsQueryable().Where(u => u.Id == user.TenantId).Select(u => u.Watermark).FirstAsync();
|
||||
if (!string.IsNullOrWhiteSpace(watermarkText))
|
||||
@ -337,7 +366,7 @@ public class SysAuthService : IDynamicApiController, ITransient
|
||||
OrgName = org?.Name,
|
||||
OrgType = org?.Type,
|
||||
PosName = pos?.Name,
|
||||
Apis = apis,
|
||||
Apis = _userManager.Permissions,
|
||||
Roles = roles,
|
||||
WatermarkText = watermarkText,
|
||||
LastChangePasswordTime = user.LastChangePasswordTime
|
||||
@ -447,13 +476,13 @@ public class SysAuthService : IDynamicApiController, ITransient
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 刷新token
|
||||
/// 刷新Session
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
[NonAction]
|
||||
public async Task RefreshToken(long userId)
|
||||
public async Task RefreshSession(long userId)
|
||||
{
|
||||
var user = await _sysUserRep.AsQueryable().IgnoreTenant().Includes(u => u.SysOrg).FirstAsync(u => u.Id == userId);
|
||||
await CreateToken(user, CommonHelper.IsMobile(_httpContextAccessor.HttpContext?.Request.Headers.UserAgent ?? "") ? LoginModeEnum.APP : LoginModeEnum.PC, true);
|
||||
await SetUserSession(user, CommonHelper.IsMobile(_httpContextAccessor.HttpContext?.Request.Headers.UserAgent ?? "") ? LoginModeEnum.APP : LoginModeEnum.PC);
|
||||
}
|
||||
}
|
||||
@ -17,6 +17,7 @@ public class SysCodeGenService : IDynamicApiController, ITransient
|
||||
{
|
||||
private readonly ISqlSugarClient _db;
|
||||
private readonly CodeGenOptions _codeGenOptions;
|
||||
private readonly SysCacheService _sysCacheService;
|
||||
private readonly DbConnectionOptions _dbConnectionOptions;
|
||||
private readonly SysCodeGenConfigService _codeGenConfigService;
|
||||
private readonly IViewEngine _viewEngine;
|
||||
@ -25,12 +26,14 @@ public class SysCodeGenService : IDynamicApiController, ITransient
|
||||
IOptions<CodeGenOptions> codeGenOptions,
|
||||
IOptions<DbConnectionOptions> dbConnectionOptions,
|
||||
SysCodeGenConfigService codeGenConfigService,
|
||||
SysCacheService sysCacheService,
|
||||
IViewEngine viewEngine)
|
||||
{
|
||||
_db = db;
|
||||
_dbConnectionOptions = dbConnectionOptions.Value;
|
||||
_codeGenOptions = codeGenOptions.Value;
|
||||
_codeGenConfigService = codeGenConfigService;
|
||||
_sysCacheService = sysCacheService;
|
||||
_viewEngine = viewEngine;
|
||||
}
|
||||
|
||||
@ -600,7 +603,7 @@ public class SysCodeGenService : IDynamicApiController, ITransient
|
||||
await _db.Insertable(menus).ExecuteCommandAsync();
|
||||
|
||||
// 删除角色菜单按钮缓存
|
||||
App.GetRequiredService<SysCacheService>().RemoveByPrefixKey(CacheConst.KeyUserApi);
|
||||
_sysCacheService.RemoveByPrefixKey(CacheConst.KeyUserSession);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@ -395,56 +395,67 @@ public class SysRoleService : IDynamicApiController, ITransient
|
||||
//return roleApis.Union(roleButtons).ToList();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取用户接口集合 🔖
|
||||
/// 获取用户接口集合
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <returns></returns>
|
||||
[DisplayName("获取用户接口集合")]
|
||||
public async Task<List<List<string>>> GetUserApiList()
|
||||
[NonAction]
|
||||
public async Task<List<string>> GetUserApiList(long userId)
|
||||
{
|
||||
var userId = _userManager.UserId;
|
||||
var apiList = _sysCacheService.Get<List<List<string>>>(CacheConst.KeyUserApi + userId);
|
||||
if (apiList != null) return apiList;
|
||||
|
||||
apiList = [[], []];
|
||||
// 所有按钮权限集合
|
||||
var allButtonList = await GetButtonList();
|
||||
List<string> apiList = [];
|
||||
// 超管账号获取所有接口
|
||||
if (_userManager.SuperAdmin)
|
||||
if (await _sysRoleRep.Context.Queryable<SysUser>().IgnoreTenant().AnyAsync(u => u.Id == userId && u.AccountType == AccountTypeEnum.SuperAdmin))
|
||||
{
|
||||
var allApiList = _sysCommonService.GetApiList();
|
||||
foreach (var apiOutput in allApiList)
|
||||
// 获取所有接口
|
||||
var queue = new Queue<ApiOutput>(_sysCommonService.GetApiList());
|
||||
var item = queue.Dequeue();
|
||||
while (item != null)
|
||||
{
|
||||
foreach (var controller in apiOutput.Children)
|
||||
apiList[0].AddRange(controller.Children.Select(u => u.Route));
|
||||
if (item.Children is { Count: > 0 }) queue.EnqueueRange(item.Children);
|
||||
else apiList.Add(item.Route);
|
||||
item = queue.Count > 0 ? queue.Dequeue() : null;
|
||||
}
|
||||
|
||||
// 接口没有对应的按钮权限集合
|
||||
var diffButtonList = allButtonList.Except(apiList[0]).ToList(); // 差集
|
||||
apiList[0].AddRange(diffButtonList);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 当前账号所有角色集合
|
||||
var roleIdList = await _sysUserRoleService.GetUserRoleIdList(_userManager.UserId);
|
||||
// 已有按钮权限集合
|
||||
var menuIdList = await _sysRoleMenuService.GetRoleMenuIdList(roleIdList);
|
||||
apiList[0] = await GetButtonList(menuIdList, false);
|
||||
|
||||
// 未有按钮权限集合(放到接口黑名单里面)
|
||||
apiList[1] = allButtonList.Except(apiList[0]).ToList(); // 差集
|
||||
// 接口黑名单集合
|
||||
var roleApiList = await _sysRoleApiService.GetRoleApiList(roleIdList);
|
||||
apiList[1].AddRange(roleApiList);
|
||||
// 获取账号所有权限集
|
||||
var menuIdList = await _sysRoleMenuService.GetRoleMenuIdList(await _sysUserRoleService.GetUserRoleIdList(userId));
|
||||
apiList = await GetButtonList(menuIdList, false);
|
||||
}
|
||||
|
||||
// 排序接口名称
|
||||
apiList[0].Sort();
|
||||
apiList[1].Sort();
|
||||
_sysCacheService.Set(CacheConst.KeyUserApi + userId, apiList, TimeSpan.FromDays(7)); // 缓存7天
|
||||
apiList = apiList.Distinct().ToList();
|
||||
apiList.Sort();
|
||||
return apiList;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取无权访问接口集合 🔖
|
||||
/// </summary>
|
||||
[NonAction]
|
||||
public async Task<List<string>> GetUnAuthApiList(long userId)
|
||||
{
|
||||
if (await _sysRoleRep.Context.Queryable<SysUser>().IgnoreTenant().AnyAsync(u => u.Id == userId && u.AccountType == AccountTypeEnum.SuperAdmin)) return [];
|
||||
|
||||
// 所有按钮权限集合
|
||||
var allButtonList = await GetButtonList();
|
||||
|
||||
// 当前账号所有角色集合
|
||||
var roleIds = await _sysUserRoleService.GetUserRoleIdList(userId);
|
||||
|
||||
// 菜单中已有的权限集与当前用户的权限集差集,就是无权访问的权限集
|
||||
var menuIdList = await _sysRoleMenuService.GetRoleMenuIdList(roleIds);
|
||||
var apiList = await GetButtonList(menuIdList, false);
|
||||
var blackList = allButtonList.Except(apiList).ToList(); // 差集
|
||||
|
||||
// 角色接口黑名单集合
|
||||
blackList.AddRange(await _sysRoleApiService.GetRoleApiList(roleIds));
|
||||
blackList = blackList.Distinct().ToList();
|
||||
|
||||
blackList.Sort();
|
||||
return blackList;
|
||||
}
|
||||
|
||||
///// <summary>
|
||||
///// 获取用户按钮权限集合
|
||||
///// </summary>
|
||||
@ -485,7 +496,8 @@ public class SysRoleService : IDynamicApiController, ITransient
|
||||
.WhereIF(menuIds != null && menuIds.Count > 0, u => menuIds.Contains(u.Id))
|
||||
.WhereIF(!isAll, u => u.Status == StatusEnum.Enable)
|
||||
.Where(u => u.Type == MenuTypeEnum.Btn)
|
||||
.Select(u => u.Permission).ToListAsync();
|
||||
.Select(u => u.Permission)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -497,9 +509,6 @@ public class SysRoleService : IDynamicApiController, ITransient
|
||||
public async Task ClearUserApiCache(long roleId)
|
||||
{
|
||||
var userIdList = await _sysUserRoleService.GetUserIdList(roleId);
|
||||
foreach (var userId in userIdList)
|
||||
{
|
||||
_sysCacheService.Remove(CacheConst.KeyUserApi + userId);
|
||||
}
|
||||
foreach (var userId in userIdList) _sysCacheService.Remove(CacheConst.KeyUserSession + userId);
|
||||
}
|
||||
}
|
||||
@ -39,7 +39,7 @@ public class SysUserRoleService : ITransient
|
||||
await _sysUserRoleRep.InsertRangeAsync(userRoles);
|
||||
|
||||
// 清除缓存
|
||||
_sysCacheService.Remove(CacheConst.KeyUserApi + input.UserId);
|
||||
_sysCacheService.Remove(CacheConst.KeyUserSession + input.UserId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -61,7 +61,7 @@ public class SysUserRoleService : ITransient
|
||||
// 清除缓存
|
||||
foreach (var userId in input.UserIdList)
|
||||
{
|
||||
_sysCacheService.Remove(CacheConst.KeyUserApi + userId);
|
||||
_sysCacheService.Remove(CacheConst.KeyUserSession + userId);
|
||||
}
|
||||
}
|
||||
|
||||
@ -80,7 +80,7 @@ public class SysUserRoleService : ITransient
|
||||
// 清除缓存
|
||||
foreach (var userId in userIdList)
|
||||
{
|
||||
_sysCacheService.Remove(CacheConst.KeyUserApi + userId);
|
||||
_sysCacheService.Remove(CacheConst.KeyUserSession + userId);
|
||||
}
|
||||
|
||||
await _sysUserRoleRep.DeleteAsync(u => u.RoleId == roleId);
|
||||
@ -96,7 +96,7 @@ public class SysUserRoleService : ITransient
|
||||
await _sysUserRoleRep.DeleteAsync(u => u.UserId == userId);
|
||||
|
||||
// 清除缓存
|
||||
_sysCacheService.Remove(CacheConst.KeyUserApi + userId);
|
||||
_sysCacheService.Remove(CacheConst.KeyUserSession + userId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@ -43,6 +43,13 @@ public class UserManager(
|
||||
[Newtonsoft.Json.JsonIgnore]
|
||||
public override long UserId => (httpContextAccessor.HttpContext?.User.FindFirst(nameof(UserId))?.Value).ToLong();
|
||||
|
||||
/// <summary>
|
||||
/// Token版本号
|
||||
/// </summary>
|
||||
[System.Text.Json.Serialization.JsonIgnore]
|
||||
[Newtonsoft.Json.JsonIgnore]
|
||||
public override int TokenVersion => (httpContextAccessor.HttpContext?.User.FindFirst(nameof(UserId))?.Value).ToInt();
|
||||
|
||||
/// <summary>
|
||||
/// 应用Id
|
||||
/// </summary>
|
||||
@ -88,6 +95,21 @@ public class UserManager(
|
||||
/// </summary>
|
||||
public override string OrgType => Session?.OrgType;
|
||||
|
||||
/// <summary>
|
||||
/// 职位Id
|
||||
/// </summary>
|
||||
public override long? PosId => Session?.PosId;
|
||||
|
||||
/// <summary>
|
||||
/// 职位名称
|
||||
/// </summary>
|
||||
public override string PosName => Session?.PosName;
|
||||
|
||||
/// <summary>
|
||||
/// 职位编码
|
||||
/// </summary>
|
||||
public override string PosCode => Session?.PosCode;
|
||||
|
||||
/// <summary>
|
||||
/// 组织机构级别
|
||||
/// </summary>
|
||||
@ -103,6 +125,41 @@ public class UserManager(
|
||||
/// </summary>
|
||||
public override string OpenId => Session?.OpenId;
|
||||
|
||||
/// <summary>
|
||||
/// 最大数据范围权限
|
||||
/// </summary>
|
||||
public override DataScopeEnum? MaxDataScope => Session?.MaxDataScope;
|
||||
|
||||
/// <summary>
|
||||
/// 角色Id集
|
||||
/// </summary>
|
||||
public override List<long> RoleIds => Session?.RoleIds;
|
||||
|
||||
/// <summary>
|
||||
/// 机构Id集
|
||||
/// </summary>
|
||||
public override List<long> OrgIds => Session?.OrgIds;
|
||||
|
||||
/// <summary>
|
||||
/// 职位Id集
|
||||
/// </summary>
|
||||
public override List<long> PosIds => Session?.PosIds;
|
||||
|
||||
/// <summary>
|
||||
/// 权限集
|
||||
/// </summary>
|
||||
public override List<string> Permissions => Session?.Permissions;
|
||||
|
||||
/// <summary>
|
||||
/// App权限集
|
||||
/// </summary>
|
||||
public override List<string> AppPermissions => Session?.AppPermissions;
|
||||
|
||||
/// <summary>
|
||||
/// 无权权限集
|
||||
/// </summary>
|
||||
public override List<string> UnauthorizedPermissions => Session?.UnauthorizedPermissions;
|
||||
|
||||
/// <summary>
|
||||
/// 扩展属性
|
||||
/// </summary>
|
||||
@ -119,9 +176,9 @@ public class UserManager(
|
||||
/// <summary>
|
||||
/// 设置用户Session
|
||||
/// </summary>
|
||||
public void SetSession(UserSessionDao userSession, TimeSpan expire)
|
||||
public void SetSession(UserSessionDao userSession)
|
||||
{
|
||||
sysCacheService.Set(CacheConst.KeyUserSession + userSession.UserId, userSession, expire);
|
||||
sysCacheService.Set(CacheConst.KeyUserSession + userSession.UserId, userSession);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -140,6 +197,25 @@ public class UserManager(
|
||||
return sysCacheService.Get<UserSessionDao>(CacheConst.KeyUserSession + userId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定用户Session,如果不存在则刷新
|
||||
/// </summary>
|
||||
public UserSessionDao GetSessionOrRefresh(dynamic userId = null)
|
||||
{
|
||||
userId ??= UserId;
|
||||
var session = sysCacheService.Get<UserSessionDao>(CacheConst.KeyUserSession + userId);
|
||||
if (session == null)
|
||||
{
|
||||
if ((Nullable.GetUnderlyingType(userId.GetType()) ?? userId.GetType()) != typeof(long))
|
||||
{
|
||||
if (long.TryParse(userId.ToString(), out long tempId)) userId = tempId;
|
||||
else return null;
|
||||
}
|
||||
LazyHelper.GetService<SysAuthService>().RefreshSession(userId).GetAwaiter().GetResult();
|
||||
}
|
||||
return sysCacheService.Get<UserSessionDao>(CacheConst.KeyUserSession + userId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取扩展属性
|
||||
/// </summary>
|
||||
|
||||
@ -9,13 +9,20 @@ namespace Admin.NET.Core;
|
||||
/// <summary>
|
||||
/// 用户会话信息
|
||||
/// </summary>
|
||||
public partial class UserSessionDao
|
||||
public class UserSessionDao
|
||||
{
|
||||
/// <summary>
|
||||
/// 用户Id
|
||||
/// </summary>
|
||||
public virtual long UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// token版本
|
||||
/// </summary>
|
||||
[System.Text.Json.Serialization.JsonIgnore]
|
||||
[Newtonsoft.Json.JsonIgnore]
|
||||
public virtual int TokenVersion { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 平台应用Id
|
||||
/// </summary>
|
||||
@ -60,6 +67,11 @@ public partial class UserSessionDao
|
||||
[Newtonsoft.Json.JsonIgnore]
|
||||
public bool SysAdmin => AccountType == AccountTypeEnum.SysAdmin;
|
||||
|
||||
/// <summary>
|
||||
/// 最大数据范围权限
|
||||
/// </summary>
|
||||
public virtual DataScopeEnum? MaxDataScope { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 组织机构Id
|
||||
/// </summary>
|
||||
@ -85,6 +97,51 @@ public partial class UserSessionDao
|
||||
/// </summary>
|
||||
public virtual int? OrgLevel { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 职位Id
|
||||
/// </summary>
|
||||
public virtual long? PosId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 职位名称
|
||||
/// </summary>
|
||||
public virtual string PosName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 职位编码
|
||||
/// </summary>
|
||||
public virtual string PosCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 角色Id集
|
||||
/// </summary>
|
||||
public virtual List<long> RoleIds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 机构Id集
|
||||
/// </summary>
|
||||
public virtual List<long> OrgIds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 职位Id集
|
||||
/// </summary>
|
||||
public virtual List<long> PosIds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 移动端权限集
|
||||
/// </summary>
|
||||
public virtual List<string> AppPermissions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 权限集
|
||||
/// </summary>
|
||||
public virtual List<string> Permissions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 无权-权限集
|
||||
/// </summary>
|
||||
public virtual List<string> UnauthorizedPermissions { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 登录模式
|
||||
/// </summary>
|
||||
@ -95,11 +152,6 @@ public partial class UserSessionDao
|
||||
/// </summary>
|
||||
public virtual string OpenId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// token版本
|
||||
/// </summary>
|
||||
public virtual long TokenVersion { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 扩展属性
|
||||
/// </summary>
|
||||
|
||||
@ -28,6 +28,10 @@ public static class SqlSugarFilter
|
||||
sysCacheService.Remove($"{CacheConst.KeyRoleMaxDataScope}{userId}");
|
||||
// 用户权限缓存(接口集合)
|
||||
sysCacheService.Remove($"{CacheConst.KeyUserApi}{userId}");
|
||||
|
||||
// 清除用户session
|
||||
sysCacheService.Remove($"{CacheConst.KeyUserSession}{userId}");
|
||||
|
||||
// 删除用户机构(数据范围)缓存——过滤器
|
||||
_cache.Remove($"db:{dbConfigId}:orgList:{userId}");
|
||||
}
|
||||
@ -54,6 +58,10 @@ public static class SqlSugarFilter
|
||||
var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
|
||||
if (string.IsNullOrWhiteSpace(userId)) return;
|
||||
|
||||
// 获取用户session
|
||||
var session = LazyHelper.GetService<UserManager>().GetSessionOrRefresh(userId);
|
||||
if (session == null) return;
|
||||
|
||||
// 配置用户机构集合缓存
|
||||
var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:orgList:{userId}";
|
||||
var orgFilter = _cache.Get<ConcurrentDictionary<Type, LambdaExpression>>(cacheKey);
|
||||
@ -63,12 +71,7 @@ public static class SqlSugarFilter
|
||||
if (maxDataScope == (int)DataScopeEnum.All) return;
|
||||
|
||||
// 获取用户所属机构,保证同一作用域
|
||||
var orgIds = new List<long>();
|
||||
Scoped.Create((factory, scope) =>
|
||||
{
|
||||
var services = scope.ServiceProvider;
|
||||
orgIds = services.GetRequiredService<SysOrgService>().GetUserOrgIdList().GetAwaiter().GetResult();
|
||||
});
|
||||
var orgIds = session.OrgIds;
|
||||
if (orgIds == null || orgIds.Count == 0) return;
|
||||
|
||||
// 获取业务实体数据表
|
||||
@ -109,19 +112,12 @@ public static class SqlSugarFilter
|
||||
var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
|
||||
if (string.IsNullOrWhiteSpace(userId)) return maxDataScope;
|
||||
|
||||
// 获取用户session
|
||||
var session = LazyHelper.GetService<UserManager>().GetSessionOrRefresh(userId);
|
||||
if (session == null) return (int)DataScopeEnum.Self;
|
||||
|
||||
// 获取用户最大数据范围---仅本人数据
|
||||
maxDataScope = App.GetRequiredService<SysCacheService>().Get<int>(CacheConst.KeyRoleMaxDataScope + userId);
|
||||
// 若为0则获取用户机构组织集合建立缓存
|
||||
if (maxDataScope == 0)
|
||||
{
|
||||
// 获取用户所属机构,保证同一作用域
|
||||
Scoped.Create((factory, scope) =>
|
||||
{
|
||||
var services = scope.ServiceProvider;
|
||||
services.GetRequiredService<SysOrgService>().GetUserOrgIdList().GetAwaiter().GetResult();
|
||||
maxDataScope = services.GetRequiredService<SysCacheService>().Get<int>(CacheConst.KeyRoleMaxDataScope + userId);
|
||||
});
|
||||
}
|
||||
maxDataScope = (int)session.MaxDataScope!;
|
||||
if (maxDataScope != (int)DataScopeEnum.Self) return maxDataScope;
|
||||
|
||||
// 配置用户数据范围缓存
|
||||
@ -130,8 +126,7 @@ public static class SqlSugarFilter
|
||||
if (dataScopeFilter == null)
|
||||
{
|
||||
// 获取业务实体数据表
|
||||
var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
|
||||
&& u.IsSubclassOf(typeof(EntityBaseData)));
|
||||
var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsSubclassOf(typeof(EntityBaseData))).ToList();
|
||||
if (!entityTypes.Any()) return maxDataScope;
|
||||
|
||||
dataScopeFilter = new ConcurrentDictionary<Type, LambdaExpression>();
|
||||
@ -139,8 +134,7 @@ public static class SqlSugarFilter
|
||||
{
|
||||
// 排除非当前数据库实体
|
||||
var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
|
||||
if ((tAtt != null && db.CurrentConnectionConfig.ConfigId.ToString() != tAtt.configId.ToString()))
|
||||
continue;
|
||||
if ((tAtt != null && db.CurrentConnectionConfig.ConfigId.ToString() != tAtt.configId.ToString())) continue;
|
||||
|
||||
//var lambda = DynamicExpressionParser.ParseLambda(new[] {
|
||||
// Expression.Parameter(entityType, "u") }, typeof(bool), $"u.{nameof(EntityBaseData.CreateUserId)}=@0", userId);
|
||||
@ -172,7 +166,8 @@ public static class SqlSugarFilter
|
||||
{
|
||||
// 获取自定义实体过滤器
|
||||
var entityFilterTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
|
||||
&& u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(IEntityFilter))));
|
||||
&& u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(IEntityFilter))))
|
||||
.ToList();
|
||||
if (!entityFilterTypes.Any()) return;
|
||||
|
||||
var tableFilterItems = new List<TableFilterItem<object>>();
|
||||
@ -186,9 +181,9 @@ public static class SqlSugarFilter
|
||||
foreach (var u in entityFilters)
|
||||
{
|
||||
var tableFilterItem = (TableFilterItem<object>)u;
|
||||
var entityType = tableFilterItem.GetType().GetProperty("type", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(tableFilterItem, null) as Type;
|
||||
var entityType = tableFilterItem.GetType().GetProperty("type", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(tableFilterItem, null) as Type;
|
||||
// 排除非当前数据库实体
|
||||
var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
|
||||
var tAtt = entityType?.GetCustomAttribute<TenantAttribute>();
|
||||
if ((tAtt != null && db.CurrentConnectionConfig.ConfigId.ToString() != tAtt.configId.ToString()) ||
|
||||
(tAtt == null && db.CurrentConnectionConfig.ConfigId.ToString() != SqlSugarConst.MainConfigId))
|
||||
continue;
|
||||
|
||||
@ -73,7 +73,7 @@ namespace Admin.NET.Web.Core
|
||||
if (sysCacheService.NotExistKey($"{CacheConst.KeyUserSession}{userId}"))
|
||||
{
|
||||
var sysAuthService = serviceScope.ServiceProvider.GetRequiredService<SysAuthService>();
|
||||
await sysAuthService.RefreshToken(long.Parse(userId!));
|
||||
await sysAuthService.RefreshSession(long.Parse(userId!));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user