refactor: 重构 EFCore
This commit is contained in:
parent
8c102946d7
commit
1de338c6b7
|
@ -28,13 +28,13 @@ namespace BootstrapAdmin.DataAccess.EFCore
|
|||
///
|
||||
/// </summary>
|
||||
[NotNull]
|
||||
public DbSet<EFUser>? Users { get; set; }
|
||||
public DbSet<User>? Users { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
[NotNull]
|
||||
public DbSet<EFRole>? Roles { get; set; }
|
||||
public DbSet<Role>? Roles { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
|
@ -46,7 +46,7 @@ namespace BootstrapAdmin.DataAccess.EFCore
|
|||
///
|
||||
/// </summary>
|
||||
[NotNull]
|
||||
public DbSet<EFNavigation>? Navigations { get; set; }
|
||||
public DbSet<Navigation>? Navigations { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
|
@ -58,7 +58,7 @@ namespace BootstrapAdmin.DataAccess.EFCore
|
|||
///
|
||||
/// </summary>
|
||||
[NotNull]
|
||||
public DbSet<EFGroup>? Groups { get; set; }
|
||||
public DbSet<Group>? Groups { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
|
|
|
@ -7,6 +7,9 @@ using Microsoft.EntityFrameworkCore.ValueGeneration;
|
|||
|
||||
namespace BootstrapAdmin.DataAccess.EFCore;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public static class EntityConfiguration
|
||||
{
|
||||
/// <summary>
|
||||
|
@ -26,31 +29,11 @@ public static class EntityConfiguration
|
|||
builder.Entity<User>().Ignore(u => u.ConfirmPassword);
|
||||
builder.Entity<User>().Ignore(u => u.IsReset);
|
||||
builder.Entity<User>().Property(s => s.Id).HasConversion(converter).ValueGeneratedOnAdd();
|
||||
builder.Entity<User>().HasMany(s => s.Roles).WithMany(s => s.Users).UsingEntity<UserRole>(s =>
|
||||
{
|
||||
s.HasOne(s => s.User).WithMany(s => s.UserRoles).HasForeignKey(s => s.UserId);
|
||||
s.HasOne(s => s.Role).WithMany(s => s.UserRoles).HasForeignKey(s => s.RoleId);
|
||||
});
|
||||
builder.Entity<User>().HasMany(s => s.Groups).WithMany(s => s.Users).UsingEntity<UserGroup>(s =>
|
||||
{
|
||||
s.HasOne(s => s.User).WithMany(s => s.UserGroup).HasForeignKey(s => s.UserId);
|
||||
s.HasOne(s => s.Group).WithMany(s => s.UserGroup).HasForeignKey(s => s.GroupId);
|
||||
});
|
||||
|
||||
builder.Entity<UserRole>().Property(s => s.Id).HasConversion(converter).ValueGeneratedOnAdd();
|
||||
|
||||
builder.Entity<Role>().ToTable("Roles");
|
||||
builder.Entity<Role>().Property(s => s.Id).HasConversion(converter).ValueGeneratedOnAdd();
|
||||
builder.Entity<Role>().HasMany(s => s.Navigations).WithMany(s => s.Roles).UsingEntity<NavigationRole>(s =>
|
||||
{
|
||||
s.HasOne(s => s.Navigation).WithMany(s => s.NavigationRoles).HasForeignKey(s => s.NavigationId);
|
||||
s.HasOne(s => s.Role).WithMany(s => s.NavigationRoles).HasForeignKey(s => s.RoleId);
|
||||
});
|
||||
builder.Entity<Role>().HasMany(s => s.Groups).WithMany(s => s.Roles).UsingEntity<RoleGroup>(s =>
|
||||
{
|
||||
s.HasOne(s => s.Group).WithMany(s => s.RoleGroup).HasForeignKey(s => s.GroupId);
|
||||
s.HasOne(s => s.Role).WithMany(s => s.RoleGroup).HasForeignKey(s => s.RoleId);
|
||||
});
|
||||
|
||||
builder.Entity<Navigation>().ToTable("Navigations");
|
||||
builder.Entity<Navigation>().Property(s => s.Id).HasConversion(converter).ValueGeneratedOnAdd();
|
||||
|
|
|
@ -45,7 +45,7 @@ public static class ServicesExtensions
|
|||
// 增加数据服务
|
||||
services.AddSingleton(typeof(IDataService<>), typeof(DefaultDataService<>));
|
||||
|
||||
services.AddSingleton<INavigation, NavigationsService>();
|
||||
services.AddSingleton<INavigation, NavigationService>();
|
||||
services.AddSingleton<IDict, DictService>();
|
||||
services.AddSingleton<IUser, UserService>();
|
||||
services.AddSingleton<IRole, RoleService>();
|
||||
|
|
|
@ -1,26 +0,0 @@
|
|||
using BootstrapAdmin.DataAccess.Models;
|
||||
|
||||
namespace BootstrapAdmin.DataAccess.EFCore.Models;
|
||||
|
||||
public class EFGroup : Group
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ICollection<User>? Users { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ICollection<UserGroup>? UserGroup { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ICollection<Role>? Roles { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public List<RoleGroup>? RoleGroup { get; set; }
|
||||
}
|
|
@ -1,16 +0,0 @@
|
|||
using BootstrapAdmin.DataAccess.Models;
|
||||
|
||||
namespace BootstrapAdmin.DataAccess.EFCore.Models;
|
||||
|
||||
public class EFNavigation : Navigation
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ICollection<Role>? Roles { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public List<NavigationRole>? NavigationRoles { get; set; }
|
||||
}
|
|
@ -1,37 +0,0 @@
|
|||
using BootstrapAdmin.DataAccess.Models;
|
||||
|
||||
namespace BootstrapAdmin.DataAccess.EFCore.Models;
|
||||
|
||||
public class EFRole : Role
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ICollection<User>? Users { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public List<UserRole>? UserRoles { get; set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ICollection<Navigation>? Navigations { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public List<NavigationRole>? NavigationRoles { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ICollection<Group>? Groups { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public List<RoleGroup>? RoleGroup { get; set; }
|
||||
}
|
|
@ -1,26 +0,0 @@
|
|||
using BootstrapAdmin.DataAccess.Models;
|
||||
|
||||
namespace BootstrapAdmin.DataAccess.EFCore.Models;
|
||||
|
||||
public class EFUser : User
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ICollection<Role>? Roles { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public List<UserRole>? UserRoles { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ICollection<Group>? Groups { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public ICollection<UserGroup>? UserGroup { get; set; }
|
||||
}
|
|
@ -1,14 +1,18 @@
|
|||
using BootstrapAdmin.DataAccess.Models;
|
||||
using BootstrapAdmin.Caching;
|
||||
using BootstrapAdmin.DataAccess.Models;
|
||||
using BootstrapAdmin.Web.Core;
|
||||
using BootstrapBlazor.Components;
|
||||
using Longbow.Security.Cryptography;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using System.Data.Common;
|
||||
|
||||
namespace BootstrapAdmin.DataAccess.EFCore.Services;
|
||||
|
||||
class DictService : IDict
|
||||
{
|
||||
private const string DictServiceCacheKey = "DictService-GetAll";
|
||||
|
||||
private IDbContextFactory<BootstrapAdminContext> DbFactory { get; set; }
|
||||
|
||||
private string AppId { get; set; }
|
||||
|
@ -27,7 +31,7 @@ class DictService : IDict
|
|||
public List<Dict> GetAll()
|
||||
{
|
||||
using var context = DbFactory.CreateDbContext();
|
||||
return context.Dicts.ToList();
|
||||
return CacheManager.GetOrAdd(DictServiceCacheKey, entry => context.Dicts.ToList());
|
||||
}
|
||||
|
||||
public Dictionary<string, string> GetApps()
|
||||
|
@ -81,10 +85,13 @@ class DictService : IDict
|
|||
return code == "1";
|
||||
}
|
||||
|
||||
public bool SaveDemo(bool isDemo)
|
||||
public bool SaveDemo(bool isDemo) => SaveDict(new Dict
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
Category = "网站设置",
|
||||
Name = "演示系统",
|
||||
Code = isDemo ? "1" : "0",
|
||||
Define = EnumDictDefine.System
|
||||
});
|
||||
|
||||
public bool AuthenticateDemo(string code)
|
||||
{
|
||||
|
@ -102,10 +109,13 @@ class DictService : IDict
|
|||
return ret;
|
||||
}
|
||||
|
||||
public bool SaveHealthCheck(bool enable = true)
|
||||
public bool SaveHealthCheck(bool enable = true) => SaveDict(new Dict
|
||||
{
|
||||
return true;
|
||||
}
|
||||
Category = "网站设置",
|
||||
Name = "健康检查",
|
||||
Code = enable ? "1" : "0",
|
||||
Define = EnumDictDefine.System
|
||||
});
|
||||
|
||||
public int GetCookieExpiresPeriod()
|
||||
{
|
||||
|
@ -117,46 +127,335 @@ class DictService : IDict
|
|||
|
||||
public string GetCurrentLogin()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
var dicts = GetAll();
|
||||
return dicts.FirstOrDefault(d => d.Category == "网站设置" && d.Name == "登录界面" && d.Define == EnumDictDefine.System)?.Code ?? "Login";
|
||||
}
|
||||
|
||||
public bool SaveLogin(string login)
|
||||
public bool SaveLogin(string login) => SaveDict(new Dict { Category = "网站设置", Name = "登录界面", Code = login });
|
||||
|
||||
public bool SaveTheme(string theme) => SaveDict(new Dict { Category = "网站设置", Name = "使用样式", Code = theme });
|
||||
|
||||
public bool SaveWebTitle(string title) => SaveDict(new Dict { Category = "网站设置", Name = "网站标题", Code = title });
|
||||
|
||||
public bool SaveWebFooter(string footer) => SaveDict(new Dict { Category = "网站设置", Name = "网站页脚", Code = footer });
|
||||
|
||||
public bool SaveCookieExpiresPeriod(int expiresPeriod) => SaveDict(new Dict { Category = "网站设置", Name = "Cookie保留时长", Code = expiresPeriod.ToString() });
|
||||
|
||||
public string? GetProfileUrl(string appId) => GetUrlByName(appId, "个人中心地址");
|
||||
|
||||
public string? GetSettingsUrl(string appId) => GetUrlByName(appId, "系统设置地址");
|
||||
|
||||
public string? GetNotificationUrl(string appId) => GetUrlByName(appId, "系统通知地址");
|
||||
|
||||
public string? GetIpLocatorName()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
var dicts = GetAll();
|
||||
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "IP地理位置接口" && s.Define == EnumDictDefine.System)?.Code;
|
||||
}
|
||||
|
||||
public bool SaveTheme(string theme)
|
||||
public string? GetIpLocatorUrl(string? name)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
var dicts = GetAll();
|
||||
return string.IsNullOrWhiteSpace(name) ? null : dicts.FirstOrDefault(s => s.Category == "地理位置" && s.Name == name && s.Define == EnumDictDefine.System)?.Code;
|
||||
}
|
||||
|
||||
public bool SaveWebTitle(string title)
|
||||
public bool SavDefaultApp(bool enabled) => SaveDict(new Dict
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
Category = "网站设置",
|
||||
Name = "默认应用程序",
|
||||
Code = enabled ? "1" : "0",
|
||||
Define = EnumDictDefine.System
|
||||
});
|
||||
|
||||
public string GetIconFolderPath()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
return dicts.FirstOrDefault(d => d.Name == "头像路径" && d.Category == "头像地址" && d.Define == EnumDictDefine.System)?.Code ?? "/images/uploder/";
|
||||
}
|
||||
|
||||
public bool SaveWebFooter(string footer)
|
||||
public string GetDefaultIcon()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
var dicts = GetAll();
|
||||
return dicts.FirstOrDefault(d => d.Name == "头像文件" && d.Category == "头像地址" && d.Define == EnumDictDefine.System)?.Code ?? "default.jpg";
|
||||
}
|
||||
|
||||
public bool SaveCookieExpiresPeriod(int expiresPeriod)
|
||||
public string? GetHomeUrlByAppId(string appId)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
var dicts = GetAll();
|
||||
return dicts.FirstOrDefault(d => d.Category == "应用首页" && d.Name.Equals(appId, StringComparison.OrdinalIgnoreCase) && d.Define == EnumDictDefine.System)?.Code;
|
||||
}
|
||||
|
||||
public string? GetProfileUrl(string appId)
|
||||
public bool GetEnableDefaultApp()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
var dicts = GetAll();
|
||||
var code = dicts.FirstOrDefault(d => d.Category == "网站设置" && d.Name == "默认应用程序")?.Code ?? "0";
|
||||
return code == "1";
|
||||
}
|
||||
|
||||
public string? GetSettingsUrl(string appId)
|
||||
public bool GetAppSiderbar()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
var dicts = GetAll();
|
||||
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "侧边栏状态" && s.Define == EnumDictDefine.System)?.Code == "1";
|
||||
}
|
||||
|
||||
public string? GetNotificationUrl(string appId)
|
||||
public bool SaveAppSiderbar(bool value) => SaveDict(new Dict { Category = "网站设置", Name = "侧边栏状态", Code = value ? "1" : "0" });
|
||||
|
||||
public bool GetAppTitle()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
var dicts = GetAll();
|
||||
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "卡片标题状态" && s.Define == EnumDictDefine.System)?.Code == "1";
|
||||
}
|
||||
|
||||
public bool SaveAppTitle(bool value) => SaveDict(new Dict { Category = "网站设置", Name = "卡片标题状态", Code = value ? "1" : "0" });
|
||||
|
||||
public bool GetAppFixHeader()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "固定表头" && s.Define == EnumDictDefine.System)?.Code == "1";
|
||||
}
|
||||
|
||||
public bool SaveAppFixHeader(bool value) => SaveDict(new Dict { Category = "网站设置", Name = "固定表头", Code = value ? "1" : "0" });
|
||||
|
||||
public bool GetAppHealthCheck()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "健康检查" && s.Define == EnumDictDefine.System)?.Code == "1";
|
||||
}
|
||||
|
||||
public bool SaveAppHealthCheck(bool value) => SaveDict(new Dict { Category = "网站设置", Name = "健康检查", Code = value ? "1" : "0" });
|
||||
|
||||
public bool GetAppMobileLogin()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "短信验证码登录" && s.Define == EnumDictDefine.System)?.Code == "1";
|
||||
}
|
||||
|
||||
public bool SaveAppMobileLogin(bool value) => SaveDict(new Dict { Category = "网站设置", Name = "短信验证码登录", Code = value ? "1" : "0" });
|
||||
|
||||
public bool GetAppOAuthLogin()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "OAuth 认证登录" && s.Define == EnumDictDefine.System)?.Code == "1";
|
||||
}
|
||||
|
||||
public bool SaveAppOAuthLogin(bool value) => SaveDict(new Dict { Category = "网站设置", Name = "OAuth 认证登录", Code = value ? "1" : "0" });
|
||||
|
||||
public bool GetAutoLockScreen()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "自动锁屏" && s.Define == EnumDictDefine.System)?.Code == "1";
|
||||
}
|
||||
|
||||
public bool SaveAutoLockScreen(bool value) => SaveDict(new Dict { Category = "网站设置", Name = "自动锁屏", Code = value ? "1" : "0" });
|
||||
|
||||
public int GetAutoLockScreenInterval()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
var value = dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "自动锁屏时长" && s.Define == EnumDictDefine.System)?.Code ?? "0";
|
||||
_ = int.TryParse(value, out var ret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
public bool SaveAutoLockScreenInterval(int value) => SaveDict(new Dict { Category = "网站设置", Name = "自动锁屏时长", Code = value.ToString() });
|
||||
|
||||
public Dictionary<string, string> GetIpLocators()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
return dicts.Where(d => d.Category == "地理位置服务").Select(d => new KeyValuePair<string, string>(d.Code, d.Name)).OrderBy(i => i.Value).ToDictionary(i => i.Key, i => i.Value);
|
||||
}
|
||||
|
||||
public string? GetIpLocator()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "IP地理位置接口" && s.Define == EnumDictDefine.System)?.Code;
|
||||
}
|
||||
|
||||
public bool SaveCurrentIp(string value) => SaveDict(new Dict { Category = "网站设置", Name = "IP地理位置接口", Code = value });
|
||||
|
||||
public int GetCookieExpired()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
var value = dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "Cookie保留时长" && s.Define == EnumDictDefine.System)?.Code ?? "0";
|
||||
_ = int.TryParse(value, out var ret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
public bool SaveCookieExpired(int value) => SaveDict(new Dict { Category = "网站设置", Name = "Cookie保留时长", Code = value.ToString() });
|
||||
|
||||
public int GetExceptionExpired()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
var value = dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "程序异常保留时长" && s.Define == EnumDictDefine.System)?.Code ?? "0";
|
||||
_ = int.TryParse(value, out var ret);
|
||||
return ret; ;
|
||||
}
|
||||
|
||||
public bool SaveExceptionExpired(int value) => SaveDict(new Dict { Category = "网站设置", Name = "程序异常保留时长", Code = value.ToString() });
|
||||
|
||||
public int GetOperateExpired()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
var value = dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "操作日志保留时长" && s.Define == EnumDictDefine.System)?.Code ?? "0";
|
||||
_ = int.TryParse(value, out var ret);
|
||||
return ret; ;
|
||||
}
|
||||
|
||||
public bool SaveOperateExpired(int value) => SaveDict(new Dict { Category = "网站设置", Name = "操作日志保留时长", Code = value.ToString() });
|
||||
|
||||
public int GetLoginExpired()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
var value = dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "登录日志保留时长" && s.Define == EnumDictDefine.System)?.Code ?? "0";
|
||||
_ = int.TryParse(value, out var ret);
|
||||
return ret; ;
|
||||
}
|
||||
|
||||
public bool SaveLoginExpired(int value) => SaveDict(new Dict { Category = "网站设置", Name = "登录日志保留时长", Code = value.ToString() });
|
||||
|
||||
public int GetAccessExpired()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
var value = dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "访问日志保留时长" && s.Define == EnumDictDefine.System)?.Code ?? "0";
|
||||
_ = int.TryParse(value, out var ret);
|
||||
return ret; ;
|
||||
}
|
||||
|
||||
public bool SaveAccessExpired(int value) => SaveDict(new Dict { Category = "网站设置", Name = "访问日志保留时长", Code = value.ToString() });
|
||||
|
||||
public int GetIPCacheExpired()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
var value = dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "IP请求缓存时长" && s.Define == EnumDictDefine.System)?.Code ?? "0";
|
||||
_ = int.TryParse(value, out var ret);
|
||||
return ret; ;
|
||||
}
|
||||
|
||||
public bool SaveIPCacheExpired(int value) => SaveDict(new Dict { Category = "网站设置", Name = "IP请求缓存时长", Code = value.ToString() });
|
||||
|
||||
public Dictionary<string, string>? GetClients()
|
||||
{
|
||||
var dicts = GetAll();
|
||||
return dicts.Where(s => s.Category == "应用程序" && s.Code != "BA").ToDictionary(s => s.Name, s => s.Code);
|
||||
}
|
||||
|
||||
public string GetClientUrl(string name)
|
||||
{
|
||||
var dicts = GetAll();
|
||||
return dicts.Where(s => s.Category == "应用首页" && s.Name == name).FirstOrDefault()?.Code ?? "";
|
||||
}
|
||||
|
||||
public bool ExistsAppId(string appId)
|
||||
{
|
||||
var dicts = GetAll();
|
||||
return dicts.Exists(s => s.Category == "应用程序" && s.Code == appId);
|
||||
}
|
||||
|
||||
public bool SaveClient(ClientApp client)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
var ret = false;
|
||||
if (!string.IsNullOrEmpty(client.AppId))
|
||||
{
|
||||
DeleteClient(client.AppId);
|
||||
try
|
||||
{
|
||||
var items = new List<Dict>()
|
||||
{
|
||||
new Dict { Category = "应用程序", Name = client.AppName, Code = client.AppId, Define = EnumDictDefine.System },
|
||||
new Dict { Category = "应用首页", Name = client.AppId, Code = client.HomeUrl, Define = EnumDictDefine.System },
|
||||
new Dict { Category = client.AppId, Name = "网站页脚", Code = client.Footer, Define = EnumDictDefine.Customer },
|
||||
new Dict { Category = client.AppId, Name = "网站标题", Code = client.Title, Define = EnumDictDefine.Customer },
|
||||
new Dict { Category = client.AppId, Name = "favicon", Code = client.Favicon, Define = EnumDictDefine.Customer },
|
||||
new Dict { Category = client.AppId, Name = "网站图标", Code = client.Icon, Define = EnumDictDefine.Customer },
|
||||
new Dict { Category = client.AppId, Name = "个人中心地址", Code = client.ProfileUrl, Define = EnumDictDefine.Customer },
|
||||
new Dict { Category = client.AppId, Name = "系统设置地址", Code = client.SettingsUrl, Define = EnumDictDefine.Customer },
|
||||
new Dict { Category = client.AppId, Name = "系统通知地址", Code = client.NotificationUrl, Define = EnumDictDefine.Customer }
|
||||
};
|
||||
dbcontext.AddRange(items);
|
||||
dbcontext.SaveChanges();
|
||||
ret = true;
|
||||
}
|
||||
catch (DbException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
public ClientApp GetClient(string appId)
|
||||
{
|
||||
var dicts = GetAll();
|
||||
return new ClientApp()
|
||||
{
|
||||
AppId = appId,
|
||||
AppName = dicts.FirstOrDefault(s => s.Category == "应用程序" && s.Code == appId)?.Name,
|
||||
HomeUrl = dicts.FirstOrDefault(s => s.Category == "应用首页" && s.Name == appId)?.Code,
|
||||
ProfileUrl = dicts.FirstOrDefault(s => s.Category == appId && s.Name == "个人中心地址")?.Code,
|
||||
SettingsUrl = dicts.FirstOrDefault(s => s.Category == appId && s.Name == "系统设置地址")?.Code,
|
||||
NotificationUrl = dicts.FirstOrDefault(s => s.Category == appId && s.Name == "系统通知地址")?.Code,
|
||||
Title = dicts.FirstOrDefault(s => s.Category == appId && s.Name == "网站标题")?.Code,
|
||||
Footer = dicts.FirstOrDefault(s => s.Category == appId && s.Name == "网站页脚")?.Code,
|
||||
Icon = dicts.FirstOrDefault(s => s.Category == appId && s.Name == "网站图标")?.Code,
|
||||
Favicon = dicts.FirstOrDefault(s => s.Category == appId && s.Name == "favicon")?.Code,
|
||||
};
|
||||
}
|
||||
|
||||
public bool DeleteClient(string appId)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
bool ret;
|
||||
try
|
||||
{
|
||||
dbcontext.Database.BeginTransaction();
|
||||
dbcontext.Database.ExecuteSqlRaw("delete Dicts where Category={0} and Name={1} and Define={2}", "应用首页", appId, EnumDictDefine.System);
|
||||
dbcontext.Database.ExecuteSqlRaw("delete Dicts where Category={0} and Name={1} and Define={2}", "应用程序", appId, EnumDictDefine.System);
|
||||
dbcontext.Database.ExecuteSqlRaw("delete Dicts where Category=@{0} and Name in ({1})", new
|
||||
{
|
||||
Category = appId,
|
||||
Names = new List<string>
|
||||
{
|
||||
"网站标题",
|
||||
"网站页脚",
|
||||
"favicon",
|
||||
"网站图标",
|
||||
"个人中心地址",
|
||||
"系统设置地址",
|
||||
"系统通知地址"
|
||||
}
|
||||
});
|
||||
dbcontext.Database.CommitTransaction();
|
||||
ret = true;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
dbcontext.Database.RollbackTransaction();
|
||||
throw;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
private bool SaveDict(Dict dict)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
var ret = dbcontext.Database.ExecuteSqlRaw("update dicts set Code = @Code where Category = @Category and Name = {0}", dict) == 1;
|
||||
if (ret)
|
||||
{
|
||||
// 更新缓存
|
||||
CacheManager.Clear(DictServiceCacheKey);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
private string? GetUrlByName(string appId, string dictName)
|
||||
{
|
||||
string? url = null;
|
||||
var dicts = GetAll();
|
||||
var appName = dicts.FirstOrDefault(d => d.Category == "应用程序" && d.Code == appId && d.Define == EnumDictDefine.System)?.Name;
|
||||
if (!string.IsNullOrEmpty(appName))
|
||||
{
|
||||
url = dicts.FirstOrDefault(d => d.Category == appName && d.Name == dictName && d.Define == EnumDictDefine.Customer)?.Code;
|
||||
}
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,9 @@
|
|||
using BootstrapAdmin.DataAccess.Models;
|
||||
using BootstrapAdmin.Caching;
|
||||
using BootstrapAdmin.DataAccess.EFCore.Models;
|
||||
using BootstrapAdmin.DataAccess.Models;
|
||||
using BootstrapAdmin.Web.Core;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
@ -9,60 +12,146 @@ using System.Threading.Tasks;
|
|||
|
||||
namespace BootstrapAdmin.DataAccess.EFCore.Services;
|
||||
|
||||
public class GroupService : IGroup
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class GroupService : IGroup, IDisposable
|
||||
{
|
||||
|
||||
private const string GroupServiceGetAllCacheKey = "GroupService-GetAll";
|
||||
|
||||
private const string GroupServiceGetGroupsByUserIdCacheKey = "GroupService-GetGroupsByUserId";
|
||||
|
||||
private const string GroupServiceGetGroupsByRoleIdCacheKey = "GroupService-GetGroupsByRoleId";
|
||||
|
||||
private CancellationTokenSource? GetGroupsByUserIdCancellationTokenSource { get; set; }
|
||||
|
||||
private CancellationTokenSource? GetGroupsByRoleIdCancellationTokenSource { get; set; }
|
||||
|
||||
private IDbContextFactory<BootstrapAdminContext> DbFactory;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="dbFactory"></param>
|
||||
public GroupService(IDbContextFactory<BootstrapAdminContext> dbFactory) => DbFactory = dbFactory;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public List<Group> GetAll()
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
|
||||
return dbcontext.Groups.ToList();
|
||||
return CacheManager.GetOrAdd(GroupServiceGetAllCacheKey, entry => dbcontext.Groups.ToList());
|
||||
|
||||
}
|
||||
|
||||
public List<string> GetGroupsByRoleId(string? roleId)
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="roleId"></param>
|
||||
/// <returns></returns>
|
||||
public List<string> GetGroupsByRoleId(string? roleId) => CacheManager.GetOrAdd($"{GroupServiceGetGroupsByRoleIdCacheKey}-{roleId}", entry =>
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
|
||||
GetGroupsByRoleIdCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(10));
|
||||
var token = new CancellationChangeToken(GetGroupsByRoleIdCancellationTokenSource.Token);
|
||||
entry.ExpirationTokens.Add(token);
|
||||
return dbcontext.RoleGroup.Where(s => s.RoleId == roleId).Select(s => s.GroupId!).ToList();
|
||||
}
|
||||
});
|
||||
|
||||
public List<string> GetGroupsByUserId(string? userId)
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <returns></returns>
|
||||
public List<string> GetGroupsByUserId(string? userId) => CacheManager.GetOrAdd($"{GroupServiceGetGroupsByUserIdCacheKey}-{userId}", entry =>
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
GetGroupsByUserIdCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(10));
|
||||
var token = new CancellationChangeToken(GetGroupsByUserIdCancellationTokenSource.Token);
|
||||
entry.ExpirationTokens.Add(token);
|
||||
return dbcontext.Set<UserGroup>().FromSqlRaw("select GroupID from UserGroup where UserID = {0}", userId!).Select(s => s.GroupId!).ToList();
|
||||
});
|
||||
|
||||
return dbcontext.UserGroup.Where(s => s.UserId == userId).Select(s => s.GroupId!).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="roleId"></param>
|
||||
/// <param name="groupIds"></param>
|
||||
/// <returns></returns>
|
||||
public bool SaveGroupsByRoleId(string? roleId, IEnumerable<string> groupIds)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
var role = dbcontext.Roles.Include(s => s.Groups).Where(s => s.Id == roleId).FirstOrDefault();
|
||||
if (role != null)
|
||||
var ret = false;
|
||||
try
|
||||
{
|
||||
role.Groups = dbcontext.Groups.Where(s => groupIds.Contains(s.Id)).ToList();
|
||||
return dbcontext.SaveChanges() > 0;
|
||||
dbcontext.Database.ExecuteSqlRaw("delete from RoleGroup where RoleID = {0}", roleId!);
|
||||
dbcontext.AddRange(groupIds.Select(g => new RoleGroup { GroupId = g, RoleId = roleId }));
|
||||
dbcontext.SaveChanges();
|
||||
ret = true;
|
||||
}
|
||||
else
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
throw;
|
||||
}
|
||||
|
||||
if (ret)
|
||||
{
|
||||
// reset cache
|
||||
GetGroupsByRoleIdCancellationTokenSource?.Cancel();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="groupIds"></param>
|
||||
/// <returns></returns>
|
||||
public bool SaveGroupsByUserId(string? userId, IEnumerable<string> groupIds)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
var user = dbcontext.Users.Include(s => s.Groups).Where(s => s.Id == userId).FirstOrDefault();
|
||||
if (user != null)
|
||||
var ret = false;
|
||||
try
|
||||
{
|
||||
user.Groups = dbcontext.Groups.Where(s => groupIds.Contains(s.Id)).ToList();
|
||||
return dbcontext.SaveChanges() > 0;
|
||||
dbcontext.Database.ExecuteSqlRaw("delete from UserGroup where UserID = {0}", userId!);
|
||||
dbcontext.AddRange(groupIds.Select(g => new UserGroup { GroupId = g, UserId = userId }));
|
||||
dbcontext.SaveChanges();
|
||||
ret = true;
|
||||
}
|
||||
else
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
throw;
|
||||
}
|
||||
|
||||
if (ret)
|
||||
{
|
||||
GetGroupsByUserIdCancellationTokenSource?.Cancel();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
private void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
GetGroupsByRoleIdCancellationTokenSource?.Cancel();
|
||||
GetGroupsByRoleIdCancellationTokenSource?.Dispose();
|
||||
|
||||
GetGroupsByUserIdCancellationTokenSource?.Cancel();
|
||||
GetGroupsByUserIdCancellationTokenSource?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,6 @@
|
|||
using BootstrapAdmin.Web.Core;
|
||||
using BootstrapAdmin.DataAccess.Models;
|
||||
using BootstrapAdmin.Web.Core;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
@ -7,10 +9,46 @@ using System.Threading.Tasks;
|
|||
|
||||
namespace BootstrapAdmin.DataAccess.EFCore.Services;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class LoginService : ILogin
|
||||
{
|
||||
public Task<bool> Log(string userName, bool result)
|
||||
private IDbContextFactory<BootstrapAdminContext> DbFactory;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public LoginService(IDbContextFactory<BootstrapAdminContext> dbFactory) => DbFactory = dbFactory;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userName"></param>
|
||||
/// <param name="IP"></param>
|
||||
/// <param name="OS"></param>
|
||||
/// <param name="browser"></param>
|
||||
/// <param name="address"></param>
|
||||
/// <param name="userAgent"></param>
|
||||
/// <param name="result"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotImplementedException"></exception>
|
||||
public bool Log(string userName, string? IP, string? OS, string? browser, string? address, string? userAgent, bool result)
|
||||
{
|
||||
return Task.FromResult(true);
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
|
||||
var loginUser = new LoginLog()
|
||||
{
|
||||
UserName = userName,
|
||||
LoginTime = DateTime.Now,
|
||||
Ip = IP,
|
||||
City = address,
|
||||
OS = OS,
|
||||
Browser = browser,
|
||||
UserAgent = userAgent,
|
||||
Result = result ? "登录成功" : "登录失败"
|
||||
};
|
||||
dbcontext.Add(loginUser);
|
||||
return dbcontext.SaveChanges() > 0;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,64 @@
|
|||
using BootstrapAdmin.Web.Core;
|
||||
using BootstrapAdmin.DataAccess.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using BootstrapAdmin.Caching;
|
||||
using BootstrapAdmin.DataAccess.EFCore.Models;
|
||||
|
||||
namespace BootstrapAdmin.DataAccess.EFCore.Services
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
class NavigationService : INavigation
|
||||
{
|
||||
private IDbContextFactory<BootstrapAdminContext> DbFactory { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="factory"></param>
|
||||
public NavigationService(IDbContextFactory<BootstrapAdminContext> factory) => DbFactory = factory;
|
||||
|
||||
/// <summary>
|
||||
/// 获得指定用户名可访问的所有菜单集合
|
||||
/// </summary>
|
||||
/// <param name="userName">当前用户名</param>
|
||||
/// <returns>未层次化的菜单集合</returns>
|
||||
public List<Navigation> GetAllMenus(string userName)
|
||||
{
|
||||
return CacheManager.GetOrAdd($"{nameof(NavigationService)}-{nameof(GetAllMenus)}-{userName}", entry =>
|
||||
{
|
||||
using var context = DbFactory.CreateDbContext();
|
||||
return context.Set<Navigation>().FromSqlRaw("select n.ID, n.ParentId, n.Name, n.[order], n.Icon, n.Url, n.Category, n.Target, n.IsResource, n.Application from Navigations n inner join (select nr.NavigationID from Users u inner join UserRole ur on ur.UserID = u.ID inner join NavigationRole nr on nr.RoleID = ur.RoleID where u.UserName = {0} union select nr.NavigationID from Users u inner join UserGroup ug on u.ID = ug.UserID inner join RoleGroup rg on rg.GroupID = ug.GroupID inner join NavigationRole nr on nr.RoleID = rg.RoleID where u.UserName = {0} union select n.ID from Navigations n where EXISTS (select UserName from Users u inner join UserRole ur on u.ID = ur.UserID inner join Roles r on ur.RoleID = r.ID where u.UserName = {0} and r.RoleName = {1})) nav on n.ID = nav.NavigationID ORDER BY n.Application, n.[order]", new[] { userName, "Administrators" }).ToList();
|
||||
});
|
||||
}
|
||||
|
||||
public List<string> GetMenusByRoleId(string? roleId)
|
||||
{
|
||||
using var context = DbFactory.CreateDbContext();
|
||||
|
||||
return context.NavigationRole.Where(s => s.RoleId == roleId).Select(s => s.NavigationId!).ToList();
|
||||
}
|
||||
|
||||
public bool SaveMenusByRoleId(string? roleId, List<string> menuIds)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
var ret = false;
|
||||
try
|
||||
{
|
||||
dbcontext.Database.ExecuteSqlRaw("delete from NavigationRole where RoleID = {0}", roleId!);
|
||||
dbcontext.Set<NavigationRole>().AddRange(menuIds.Select(g => new NavigationRole { NavigationId = g, RoleId = roleId }));
|
||||
dbcontext.SaveChanges();
|
||||
ret = true;
|
||||
CacheManager.Clear($"{nameof(NavigationService)}-{nameof(GetAllMenus)}-*");
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,58 +0,0 @@
|
|||
using BootstrapAdmin.Web.Core;
|
||||
using BootstrapAdmin.DataAccess.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace BootstrapAdmin.DataAccess.EFCore.Services
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
class NavigationsService : INavigation
|
||||
{
|
||||
private IDbContextFactory<BootstrapAdminContext> DbFactory { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="factory"></param>
|
||||
public NavigationsService(IDbContextFactory<BootstrapAdminContext> factory) => DbFactory = factory;
|
||||
|
||||
/// <summary>
|
||||
/// 获得指定用户名可访问的所有菜单集合
|
||||
/// </summary>
|
||||
/// <param name="userName">当前用户名</param>
|
||||
/// <returns>未层次化的菜单集合</returns>
|
||||
public List<Navigation> GetAllMenus(string userName)
|
||||
{
|
||||
using var context = DbFactory.CreateDbContext();
|
||||
|
||||
var user = context.Set<User>().Include(s => s.Roles!).ThenInclude(s => s.Navigations!.Where(s => s.IsResource == EnumResource.Navigation)).AsSplitQuery().FirstOrDefault(s => s.UserName == userName);
|
||||
|
||||
if (user == null)
|
||||
return new List<Navigation>();
|
||||
return user.Roles!.SelectMany(s => s.Navigations!).ToList();
|
||||
}
|
||||
|
||||
public List<string> GetMenusByRoleId(string? roleId)
|
||||
{
|
||||
using var context = DbFactory.CreateDbContext();
|
||||
|
||||
return context.NavigationRole.Where(s => s.RoleId == roleId).Select(s => s.NavigationId!).ToList();
|
||||
}
|
||||
|
||||
public bool SaveMenusByRoleId(string? roleId, List<string> menuIds)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
var currentrole = dbcontext.Roles.Include(s => s.Navigations).Where(s => s.Id == roleId).FirstOrDefault();
|
||||
if (currentrole != null)
|
||||
{
|
||||
currentrole.Navigations = dbcontext.Navigations.Where(s => menuIds.Contains(s.Id!)).ToList();
|
||||
return dbcontext.SaveChanges() > 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,4 +1,6 @@
|
|||
using BootstrapAdmin.DataAccess.Models;
|
||||
using BootstrapAdmin.Caching;
|
||||
using BootstrapAdmin.DataAccess.EFCore.Models;
|
||||
using BootstrapAdmin.DataAccess.Models;
|
||||
using BootstrapAdmin.Web.Core;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
|
@ -9,26 +11,65 @@ using System.Threading.Tasks;
|
|||
|
||||
namespace BootstrapAdmin.DataAccess.EFCore.Services;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class RoleService : IRole
|
||||
{
|
||||
private const string RoleServiceGetAllCacheKey = "RoleService-GetAll";
|
||||
|
||||
private const string RoleServiceGetRolesByUserIdCacheKey = "RoleService-GetRolesByUserId";
|
||||
|
||||
private const string RoleServiceGetRolesByGroupIdCacheKey = "RoleService-GetRolesByGroupId";
|
||||
|
||||
private CancellationTokenSource? GetRolesByUserIdCancellationTokenSource { get; set; }
|
||||
|
||||
private CancellationTokenSource? GetRolesByGroupIdCancellationTokenSource { get; set; }
|
||||
|
||||
private IDbContextFactory<BootstrapAdminContext> DbFactory;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="dbFactory"></param>
|
||||
public RoleService(IDbContextFactory<BootstrapAdminContext> dbFactory) => DbFactory = dbFactory;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public List<Role> GetAll()
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
return CacheManager.GetOrAdd(RoleServiceGetAllCacheKey, entry =>
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
|
||||
return dbcontext.Roles.ToList();
|
||||
});
|
||||
|
||||
return dbcontext.Roles.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="groupId"></param>
|
||||
/// <returns></returns>
|
||||
|
||||
public List<string> GetRolesByGroupId(string? groupId)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
return CacheManager.GetOrAdd($"{RoleServiceGetRolesByGroupIdCacheKey}-{groupId}", entry =>
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
|
||||
return dbcontext.RoleGroup.Where(s => s.GroupId == groupId).Select(s => s.RoleId!).ToList();
|
||||
return dbcontext.RoleGroup.Where(s => s.GroupId == groupId).Select(s => s.RoleId!).ToList();
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="menuId"></param>
|
||||
/// <returns></returns>
|
||||
public List<string> GetRolesByMenuId(string? menuId)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
|
@ -36,55 +77,92 @@ public class RoleService : IRole
|
|||
return dbcontext.NavigationRole.Where(s => s.NavigationId == menuId).Select(s => s.RoleId!).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <returns></returns>
|
||||
public List<string> GetRolesByUserId(string? userId)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
return CacheManager.GetOrAdd($"{RoleServiceGetRolesByUserIdCacheKey}-{userId}", entry =>
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
|
||||
return dbcontext.UserRole.Where(s => s.UserId == userId).Select(s => s.RoleId!).ToList();
|
||||
});
|
||||
|
||||
|
||||
return dbcontext.UserRole.Where(s => s.UserId == userId).Select(s => s.RoleId!).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="groupId"></param>
|
||||
/// <param name="roleIds"></param>
|
||||
/// <returns></returns>
|
||||
public bool SaveRolesByGroupId(string? groupId, IEnumerable<string> roleIds)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
var group = dbcontext.Groups.Include(s => s.Roles).Where(s => s.Id == groupId).FirstOrDefault();
|
||||
if (group != null)
|
||||
var ret = false;
|
||||
try
|
||||
{
|
||||
group.Roles = dbcontext.Roles.Where(s => roleIds.Contains(s.Id)).ToList();
|
||||
return dbcontext.SaveChanges() > 0;
|
||||
dbcontext.Database.ExecuteSqlRaw("delete from RoleGroup where GroupID = {0}", groupId!);
|
||||
dbcontext.AddRange(roleIds.Select(g => new RoleGroup { RoleId = g, GroupId = groupId }));
|
||||
dbcontext.SaveChanges();
|
||||
ret = true;
|
||||
}
|
||||
else
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
throw;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="menuId"></param>
|
||||
/// <param name="roleIds"></param>
|
||||
/// <returns></returns>
|
||||
public bool SaveRolesByMenuId(string? menuId, IEnumerable<string> roleIds)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
var menu = dbcontext.Navigations.Include(s => s.Roles).Where(s => s.Id == menuId).FirstOrDefault();
|
||||
if (menu != null)
|
||||
var ret = false;
|
||||
try
|
||||
{
|
||||
menu.Roles = dbcontext.Roles.Where(s => roleIds.Contains(s.Id)).ToList();
|
||||
return dbcontext.SaveChanges() > 0;
|
||||
dbcontext.Database.ExecuteSqlRaw("delete from NavigationRole where NavigationID = {0}", menuId!);
|
||||
dbcontext.AddRange(roleIds.Select(g => new NavigationRole { RoleId = g, NavigationId = menuId }));
|
||||
dbcontext.SaveChanges();
|
||||
ret = true;
|
||||
}
|
||||
else
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
throw;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userId"></param>
|
||||
/// <param name="roleIds"></param>
|
||||
/// <returns></returns>
|
||||
public bool SaveRolesByUserId(string? userId, IEnumerable<string> roleIds)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
var user = dbcontext.Users.Include(s => s.Roles).Where(s => s.Id == userId).FirstOrDefault();
|
||||
if (user != null)
|
||||
var ret = false;
|
||||
try
|
||||
{
|
||||
user.Roles = dbcontext.Roles.Where(s => roleIds.Contains(s.Id)).ToList();
|
||||
return dbcontext.SaveChanges() > 0;
|
||||
dbcontext.Database.ExecuteSqlRaw("delete from RoleGroup where GroupID = {0}", userId!);
|
||||
dbcontext.AddRange(roleIds.Select(g => new UserRole { RoleId = g, UserId = userId }));
|
||||
dbcontext.SaveChanges();
|
||||
ret = true;
|
||||
}
|
||||
else
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
throw;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
using BootstrapAdmin.DataAccess.Models;
|
||||
using BootstrapAdmin.DataAccess.EFCore.Models;
|
||||
using BootstrapAdmin.DataAccess.Models;
|
||||
using BootstrapAdmin.Web.Core;
|
||||
using Longbow.Security.Cryptography;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
@ -10,18 +11,35 @@ using System.Threading.Tasks;
|
|||
|
||||
namespace BootstrapAdmin.DataAccess.EFCore.Services;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public class UserService : IUser
|
||||
{
|
||||
private IDbContextFactory<BootstrapAdminContext> DbFactory { get; set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="factory"></param>
|
||||
public UserService(IDbContextFactory<BootstrapAdminContext> factory) => DbFactory = factory;
|
||||
|
||||
public IEnumerable<User> GetAll()
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public List<User> GetAll()
|
||||
{
|
||||
using var context = DbFactory.CreateDbContext();
|
||||
return context.Users.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userName"></param>
|
||||
/// <param name="password"></param>
|
||||
/// <returns></returns>
|
||||
public bool Authenticate(string userName, string password)
|
||||
{
|
||||
using var context = DbFactory.CreateDbContext();
|
||||
|
@ -36,26 +54,46 @@ public class UserService : IUser
|
|||
return isAuth;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userName"></param>
|
||||
/// <returns></returns>
|
||||
public List<string> GetApps(string userName)
|
||||
{
|
||||
return new List<string> { "BA" };
|
||||
using var context = DbFactory.CreateDbContext();
|
||||
return context.Dicts.FromSqlRaw("select d.Code from Dicts d inner join RoleApp ra on d.Code = ra.AppId inner join (select r.Id from Roles r inner join UserRole ur on r.ID = ur.RoleID inner join Users u on ur.UserID = u.ID where u.UserName = {0} union select r.Id from Roles r inner join RoleGroup rg on r.ID = rg.RoleID inner join [Groups] g on rg.GroupID = g.ID inner join UserGroup ug on ug.GroupID = g.ID inner join Users u on ug.UserID = u.ID where u.UserName = {0}) r on ra.RoleId = r.ID union select Code from Dicts where Category = {1} and exists(select r.ID from Roles r inner join UserRole ur on r.ID = ur.RoleID inner join Users u on ur.UserID = u.ID where u.UserName = {0} and r.RoleName = {2} union select r.ID from Roles r inner join RoleGroup rg on r.ID = rg.RoleID inner join [Groups] g on rg.GroupID = g.ID inner join UserGroup ug on ug.GroupID = g.ID inner join Users u on ug.UserID = u.ID where u.UserName = {0} and r.RoleName = {2})", new[] { userName, "应用程序", "Administrators" }).Select(s => s.Code).ToList();
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userName"></param>
|
||||
/// <returns></returns>
|
||||
public string? GetDisplayName(string? userName)
|
||||
{
|
||||
using var context = DbFactory.CreateDbContext();
|
||||
return string.IsNullOrEmpty(userName) ? "" : context.Users.FirstOrDefault(s => s.UserName == userName)?.DisplayName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userName"></param>
|
||||
/// <returns></returns>
|
||||
public List<string> GetRoles(string userName)
|
||||
{
|
||||
using var context = DbFactory.CreateDbContext();
|
||||
|
||||
var user = context.Users.Include(s => s.Roles).FirstOrDefault(s => s.UserName == userName);
|
||||
|
||||
return user != null ? user.Roles!.Select(s => s.RoleName).ToList() : new List<string>();
|
||||
return context.UserRole.FromSqlRaw("select r.RoleName from Roles r inner join UserRole ur on r.ID=ur.RoleID inner join Users u on ur.UserID = u.ID and u.UserName = {0} union select r.RoleName from Roles r inner join RoleGroup rg on r.ID = rg.RoleID inner join [Groups] g on rg.GroupID = g.ID inner join UserGroup ug on ug.GroupID = g.ID inner join Users u on ug.UserID = u.ID and u.UserName = {0}", userName).Select(s => s.RoleId!).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="groupId"></param>
|
||||
/// <returns></returns>
|
||||
public List<string> GetUsersByGroupId(string? groupId)
|
||||
{
|
||||
using var context = DbFactory.CreateDbContext();
|
||||
|
@ -63,6 +101,11 @@ public class UserService : IUser
|
|||
return context.UserGroup.Where(s => s.GroupId == groupId).Select(s => s.UserId!).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="roleId"></param>
|
||||
/// <returns></returns>
|
||||
public List<string> GetUsersByRoleId(string? roleId)
|
||||
{
|
||||
using var context = DbFactory.CreateDbContext();
|
||||
|
@ -70,46 +113,73 @@ public class UserService : IUser
|
|||
return context.UserRole.Where(s => s.RoleId == roleId).Select(s => s.UserId!).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="groupId"></param>
|
||||
/// <param name="userIds"></param>
|
||||
/// <returns></returns>
|
||||
public bool SaveUsersByGroupId(string? groupId, IEnumerable<string> userIds)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
var group = dbcontext.Groups.Include(s => s.Users).Where(s => s.Id == groupId).FirstOrDefault();
|
||||
if (group != null)
|
||||
var ret = false;
|
||||
try
|
||||
{
|
||||
group.Users = dbcontext.Users.Where(s => userIds.Contains(s.Id));
|
||||
return dbcontext.SaveChanges() > 0;
|
||||
dbcontext.Database.ExecuteSqlRaw("delete from UserGroup where GroupId = {0}", groupId!);
|
||||
dbcontext.AddRange(userIds.Select(g => new UserGroup { UserId = g, GroupId = groupId }));
|
||||
dbcontext.SaveChanges();
|
||||
ret = true;
|
||||
}
|
||||
else
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
throw;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="roleId"></param>
|
||||
/// <param name="userIds"></param>
|
||||
/// <returns></returns>
|
||||
public bool SaveUsersByRoleId(string? roleId, IEnumerable<string> userIds)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
var currentrole = dbcontext.Roles.Include(s => s.Users).Where(s => s.Id == roleId).FirstOrDefault();
|
||||
if (currentrole != null)
|
||||
var ret = false;
|
||||
try
|
||||
{
|
||||
currentrole.Users = dbcontext.Users.Where(s => userIds.Contains(s.Id)).ToList();
|
||||
return dbcontext.SaveChanges() > 0;
|
||||
dbcontext.Database.ExecuteSqlRaw("delete from UserRole where RoleID = {0}", roleId!);
|
||||
dbcontext.AddRange(userIds.Select(g => new UserRole { UserId = g, RoleId = roleId }));
|
||||
dbcontext.SaveChanges();
|
||||
ret = true;
|
||||
}
|
||||
else
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
throw;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
public bool TryCreateUserByPhone(string phone, string appId, ICollection<string> roles)
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="phone"></param>
|
||||
/// <param name="code"></param>
|
||||
/// <param name="appId"></param>
|
||||
/// <param name="roles"></param>
|
||||
/// <returns></returns>
|
||||
public bool TryCreateUserByPhone(string phone, string code, string appId, ICollection<string> roles)
|
||||
{
|
||||
var ret = false;
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
try
|
||||
{
|
||||
var salt = LgbCryptography.GenerateSalt();
|
||||
var pwd = LgbCryptography.ComputeHash(code, salt);
|
||||
var user = GetAll().FirstOrDefault(user => user.UserName == phone);
|
||||
if (user == null)
|
||||
{
|
||||
dbcontext.Database.BeginTransaction();
|
||||
user = new User()
|
||||
{
|
||||
ApprovedBy = "Mobile",
|
||||
|
@ -137,13 +207,162 @@ public class UserService : IUser
|
|||
return ret;
|
||||
}
|
||||
|
||||
List<User> IUser.GetAll()
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userName"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotImplementedException"></exception>
|
||||
public User? GetUserByUserName(string? userName)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
if (userName != null)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
|
||||
return dbcontext.Set<User>().FirstOrDefault(s => s.UserName == userName);
|
||||
}
|
||||
else
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryCreateUserByPhone(string phone, string code, string appId, ICollection<string> roles)
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userName"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotImplementedException"></exception>
|
||||
|
||||
public string? GetAppIdByUserName(string userName)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
|
||||
return dbcontext.Set<User>().FirstOrDefault(s => s.UserName == userName)?.App;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userName"></param>
|
||||
/// <param name="password"></param>
|
||||
/// <param name="newPassword"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotImplementedException"></exception>
|
||||
public bool ChangePassword(string userName, string password, string newPassword)
|
||||
{
|
||||
var ret = false;
|
||||
if (Authenticate(userName, password))
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
var passSalt = LgbCryptography.GenerateSalt();
|
||||
password = LgbCryptography.ComputeHash(newPassword, passSalt);
|
||||
string sql = "update user set Password = {0}, PassSalt = {1} where UserName = {2}";
|
||||
ret = dbcontext.Database.ExecuteSqlRaw(sql, new[] { password, passSalt, userName }) > 0;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userName"></param>
|
||||
/// <param name="displayName"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotImplementedException"></exception>
|
||||
public bool SaveDisplayName(string userName, string displayName)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
return dbcontext.Database.ExecuteSqlRaw("update User set DisplayName = {1} where UserName = {0}", userName, displayName!) > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userName"></param>
|
||||
/// <param name="theme"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotImplementedException"></exception>
|
||||
public bool SaveTheme(string userName, string theme)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
return dbcontext.Database.ExecuteSqlRaw("update User set Css = {1} where UserName = {0}", userName, theme!) > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userName"></param>
|
||||
/// <param name="logo"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotImplementedException"></exception>
|
||||
public bool SaveLogo(string userName, string? logo)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
return dbcontext.Database.ExecuteSqlRaw("update User set Icon = {1} where UserName = {0}", userName, logo!) > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userName"></param>
|
||||
/// <param name="app"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotImplementedException"></exception>
|
||||
public bool SaveApp(string userName, string app)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
return dbcontext.Database.ExecuteSqlRaw("update User Set App = {1} Where UserName = {0}", userName, app) > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="userName"></param>
|
||||
/// <param name="displayName"></param>
|
||||
/// <param name="password"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotImplementedException"></exception>
|
||||
public bool SaveUser(string userName, string displayName, string password)
|
||||
{
|
||||
using var dbcontext = DbFactory.CreateDbContext();
|
||||
var salt = LgbCryptography.GenerateSalt();
|
||||
var pwd = LgbCryptography.ComputeHash(password, salt);
|
||||
var user = GetAll().FirstOrDefault(s => s.UserName == userName);
|
||||
bool ret;
|
||||
if (user == null)
|
||||
{
|
||||
try
|
||||
{
|
||||
user = new User()
|
||||
{
|
||||
ApprovedBy = "System",
|
||||
ApprovedTime = DateTime.Now,
|
||||
DisplayName = "手机用户",
|
||||
UserName = userName,
|
||||
Icon = "default.jpg",
|
||||
Description = "系统默认创建",
|
||||
PassSalt = salt,
|
||||
Password = pwd
|
||||
};
|
||||
dbcontext.Add(user);
|
||||
// 授权 Default 角色
|
||||
dbcontext.Database.ExecuteSqlRaw("insert into UserRole (UserID, RoleID) select ID, (select ID from Roles where RoleName = 'Default') RoleId from Users where UserName = {0}", userName);
|
||||
ret = dbcontext.SaveChanges() > 0;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
user.DisplayName = displayName;
|
||||
user.PassSalt = salt;
|
||||
user.Password = pwd;
|
||||
dbcontext.Update(user);
|
||||
ret = true;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue