Compare commits

...

15 Commits

Author SHA1 Message Date
zhangpeihang 4f9f101607 feat: 添加 Role 服务 2022-04-30 17:07:24 +08:00
zhangpeihang 32eb9734cd feat: 添加 Group 服务 2022-04-29 15:09:14 +08:00
zhangpeihang 203b3fd37f feat: 添加中间表 2022-04-29 15:07:16 +08:00
zhangpeihang d1067558e3 feat: 添加 ID 属性 2022-04-29 15:06:54 +08:00
zhangpeihang 35f0f3513a refactor: 配置用户服务 2022-04-29 13:55:34 +08:00
zhangpeihang 8925c77ff2 feat: 添加登录日志服务 2022-04-29 13:54:53 +08:00
zhangpeihang dfb7dc0f50 feat: 添加服务 2022-04-29 11:24:09 +08:00
zhangpeihang 82ef72365d feat: 添加 Trace 服务 2022-04-29 11:23:51 +08:00
zhangpeihang 608ca9c429 refactor: 重构服务 2022-04-29 11:23:10 +08:00
zhangpeihang 831bf2a7f6 feat: 添加菜单服务 2022-04-29 11:22:49 +08:00
zhangpeihang 16449151d5 refactor: 重构服务 2022-04-26 14:38:13 +08:00
zhangpeihang a290a63267 feat: 完善用户服务 2022-04-26 11:17:47 +08:00
zhangpeihang 21253a1ea0 feat: 添加中间表 2022-04-26 11:17:17 +08:00
zhangpeihang 6decc7723d feat: 添加 sqlsugar 引用 2022-04-25 19:48:06 +08:00
zhangpeihang 103bcc7032 feat: 完善 sqlsugar 2022-04-25 17:51:20 +08:00
17 changed files with 1807 additions and 18 deletions

View File

@ -6,6 +6,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BootstrapAdmin.Caching\BootstrapAdmin.Caching.csproj" />
<ProjectReference Include="..\BootstrapAdmin.Web.Core\BootstrapAdmin.Web.Core.csproj" />
</ItemGroup>

View File

@ -1,8 +1,6 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
using BootStarpAdmin.DataAccess.SqlSugar.Service;
using BootStarpAdmin.DataAccess.SqlSugar.Service;
using BootstrapAdmin.DataAccess.SqlSugar.Services;
using BootstrapAdmin.Web.Core;
using BootstrapBlazor.Components;
using Microsoft.Extensions.DependencyInjection.Extensions;
using SqlSugar;
@ -22,26 +20,27 @@ public static class ServiceCollectionExtensions
/// <returns></returns>
public static IServiceCollection AddSqlSugar(this IServiceCollection services, Action<IServiceProvider, ConnectionConfig> sqlSugarBuilder)
{
services.TryAddSingleton<ISqlSugarClient>(provider =>
services.AddSingleton<ISqlSugarClient>(provider =>
{
var builder = new ConnectionConfig();
builder.IsAutoCloseConnection = true;
sqlSugarBuilder(provider, builder);
return new SqlSugarClient(builder);
return new SqlSugarScope(builder);
});
// 增加数据服务
services.AddSingleton(typeof(IDataService<>), typeof(DefaultDataService<>));
services.AddCacheManager();
// 增加业务服务
//services.AddSingleton<IApp, AppService>();
//services.AddSingleton<IDict, DictService>();
services.AddSingleton<IApp, AppService>();
services.AddSingleton<IDict, DictService>();
//services.AddSingleton<IException, ExceptionService>();
//services.AddSingleton<IGroup, GroupService>();
//services.AddSingleton<ILogin, LoginService>();
//services.AddSingleton<INavigation, NavigationService>();
//services.AddSingleton<IRole, RoleService>();
//services.AddSingleton<IUser, UserService>();
services.AddSingleton<IGroup, GroupService>();
services.AddSingleton<ILogin, LoginService>();
services.AddSingleton<INavigation, NavigationService>();
services.AddSingleton<IRole, RoleService>();
services.AddSingleton<IUser, UserService>();
services.AddSingleton<ITrace, TraceService>();
return services;
}
}

View File

@ -0,0 +1,33 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BootStarpAdmin.DataAccess.SqlSugar.Models;
/// <summary>
///
/// </summary>
public class NavigationRole
{
/// <summary>
///
/// </summary>
public string? ID { get; set; }
/// <summary>
///
/// </summary>
public string? NavigationID { get; set; }
/// <summary>
///
/// </summary>
public string? RoleID { get; set; }
}

View File

@ -0,0 +1,22 @@
namespace BootStarpAdmin.DataAccess.SqlSugar.Models;
/// <summary>
///
/// </summary>
public class RoleApp
{
/// <summary>
///
/// </summary>
public string? ID { get; set; }
/// <summary>
///
/// </summary>
public string? RoleID { get; set; }
/// <summary>
///
/// </summary>
public string? AppID { get; set; }
}

View File

@ -0,0 +1,26 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
namespace BootStarpAdmin.DataAccess.SqlSugar.Models;
/// <summary>
///
/// </summary>
public class RoleGroup
{
/// <summary>
///
/// </summary>
public string? ID { get; set; }
/// <summary>
///
/// </summary>
public string? RoleID { get; set; }
/// <summary>
///
/// </summary>
public string? GroupID { get; set; }
}

View File

@ -0,0 +1,26 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
namespace BootStarpAdmin.DataAccess.SqlSugar.Models;
/// <summary>
///
/// </summary>
public class UserGroup
{
/// <summary>
///
/// </summary>
public string? ID { get; set; }
/// <summary>
///
/// </summary>
public string? UserId { get; set; }
/// <summary>
///
/// </summary>
public string? GroupId { get; set; }
}

View File

@ -0,0 +1,26 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
namespace BootStarpAdmin.DataAccess.SqlSugar.Models;
/// <summary>
///
/// </summary>
public class UserRole
{
/// <summary>
///
/// </summary>
public string? ID { get; set; }
/// <summary>
///
/// </summary>
public string? RoleId { get; set; }
/// <summary>
///
/// </summary>
public string? UserId { get; set; }
}

View File

@ -0,0 +1,54 @@
using BootStarpAdmin.DataAccess.SqlSugar.Models;
using BootstrapAdmin.Web.Core;
using SqlSugar;
namespace BootStarpAdmin.DataAccess.SqlSugar.Service;
/// <summary>
///
/// </summary>
public class AppService : IApp
{
private ISqlSugarClient Client { get; }
/// <summary>
///
/// </summary>
/// <param name="client"></param>
public AppService(ISqlSugarClient client) => Client = client;
/// <summary>
///
/// </summary>
/// <param name="roleId"></param>
/// <returns></returns>
public List<string> GetAppsByRoleId(string? roleId)
{
return Client.Ado.SqlQuery<string>("select AppID from RoleApp where RoleID = @roleId", new { roleId = roleId });
}
/// <summary>
///
/// </summary>
/// <param name="roleId"></param>
/// <param name="appIds"></param>
/// <returns></returns>
public bool SaveAppsByRoleId(string? roleId, IEnumerable<string> appIds)
{
var ret = false;
try
{
Client.Ado.BeginTran();
Client.Ado.ExecuteCommand("delete from RoleApp where RoleID = @roleId", new { roleId = roleId });
Client.Insertable(appIds.Select(g => new RoleApp { AppID = g, RoleID = roleId }).ToList()).ExecuteCommand();
Client.Ado.CommitTran();
ret = true;
}
catch (Exception)
{
Client.Ado.RollbackTran();
throw;
}
return ret;
}
}

View File

@ -0,0 +1,813 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
using BootstrapAdmin.Caching;
using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.Web.Core;
using Longbow.Security.Cryptography;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BootStarpAdmin.DataAccess.SqlSugar.Service;
/// <summary>
///
/// </summary>
public class DictService : IDict
{
private const string DictServiceCacheKey = "DictService-GetAll";
private ISqlSugarClient Client { get; }
private string AppId { get; set; }
/// <summary>
///
/// </summary>
/// <param name="client"></param>
/// <param name="configuration"></param>
public DictService(ISqlSugarClient client, IConfiguration configuration)
{
Client = client;
AppId = configuration.GetValue("AppId", "BA");
}
/// <summary>
///
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool AuthenticateDemo(string code)
{
var ret = false;
if (!string.IsNullOrEmpty(code))
{
var dicts = GetAll();
var salt = dicts.FirstOrDefault(d => d.Category == "网站设置" && d.Name == "授权盐值" && d.Define == EnumDictDefine.System)?.Code;
var authCode = dicts.FirstOrDefault(d => d.Category == "网站设置" && d.Name == "哈希结果" && d.Define == EnumDictDefine.System)?.Code;
if (!string.IsNullOrEmpty(salt))
{
ret = LgbCryptography.ComputeHash(code, salt) == authCode;
}
}
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="appId"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool DeleteClient(string appId)
{
bool ret;
try
{
Client.Ado.BeginTran();
Client.Ado.ExecuteCommand("delete Dicts where Category=@Category and Name=@Name and Define=@Define", new { Category = "应用首页", Name = appId, Define = EnumDictDefine.System });
Client.Ado.ExecuteCommand("delete Dicts where Category=@Category and Code=@Code and Define=@Define", new { Category = "应用程序", Code = appId, Define = EnumDictDefine.System });
Client.Ado.ExecuteCommand("delete Dicts where Category=@Category and Name in (@Names)", new
{
Category = appId,
Names = new List<string>
{
"网站标题",
"网站页脚",
"favicon",
"网站图标",
"个人中心地址",
"系统设置地址",
"系统通知地址"
}
});
Client.Ado.CommitTran();
ret = true;
}
catch (Exception)
{
Client.Ado.RollbackTran();
throw;
}
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="appId"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool ExistsAppId(string appId)
{
var dicts = GetAll();
return dicts.Exists(s => s.Category == "应用程序" && s.Code == appId);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
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; ;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public List<Dict> GetAll() => CacheManager.GetOrAdd(DictServiceCacheKey, entry => Client.Queryable<Dict>().AS("Dicts").ToList());
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool GetAppFixHeader()
{
var dicts = GetAll();
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "固定表头" && s.Define == EnumDictDefine.System)?.Code == "1";
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool GetAppHealthCheck()
{
var dicts = GetAll();
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "健康检查" && s.Define == EnumDictDefine.System)?.Code == "1";
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool GetAppMobileLogin()
{
var dicts = GetAll();
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "短信验证码登录" && s.Define == EnumDictDefine.System)?.Code == "1";
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool GetAppOAuthLogin()
{
var dicts = GetAll();
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "OAuth 认证登录" && s.Define == EnumDictDefine.System)?.Code == "1";
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public Dictionary<string, string> GetApps()
{
var dicts = GetAll();
return dicts.Where(d => d.Category == "应用程序").Select(d => new KeyValuePair<string, string>(d.Code, d.Name)).ToDictionary(i => i.Key, i => i.Value);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool GetAppSiderbar()
{
var dicts = GetAll();
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "侧边栏状态" && s.Define == EnumDictDefine.System)?.Code == "1";
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool GetAppTitle()
{
var dicts = GetAll();
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "卡片标题状态" && s.Define == EnumDictDefine.System)?.Code == "1";
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool GetAutoLockScreen()
{
var dicts = GetAll();
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "自动锁屏" && s.Define == EnumDictDefine.System)?.Code == "1";
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
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;
}
/// <summary>
///
/// </summary>
/// <param name="appId"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
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,
};
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Dictionary<string, string>? GetClients()
{
var dicts = GetAll();
return dicts.Where(s => s.Category == "应用程序" && s.Code != "BA").ToDictionary(s => s.Name, s => s.Code);
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public string GetClientUrl(string name)
{
var dicts = GetAll();
return dicts.Where(s => s.Category == "应用首页" && s.Name == name).FirstOrDefault()?.Code ?? "";
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
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;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public int GetCookieExpiresPeriod()
{
var dicts = GetAll();
var code = dicts.FirstOrDefault(d => d.Category == "网站设置" && d.Name == "Cookie保留时长" && d.Define == EnumDictDefine.System)?.Code ?? "0";
_ = int.TryParse(code, out var ret);
return ret;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public string GetCurrentLogin()
{
var dicts = GetAll();
return dicts.FirstOrDefault(d => d.Category == "网站设置" && d.Name == "登录界面" && d.Define == EnumDictDefine.System)?.Code ?? "Login";
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public string GetDefaultIcon()
{
var dicts = GetAll();
return dicts.FirstOrDefault(d => d.Name == "头像文件" && d.Category == "头像地址" && d.Define == EnumDictDefine.System)?.Code ?? "default.jpg";
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool GetEnableDefaultApp()
{
var dicts = GetAll();
var code = dicts.FirstOrDefault(d => d.Category == "网站设置" && d.Name == "默认应用程序")?.Code ?? "0";
return code == "1";
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
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;
}
/// <summary>
///
/// </summary>
/// <param name="appId"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public string? GetHomeUrlByAppId(string appId)
{
var dicts = GetAll();
return dicts.FirstOrDefault(d => d.Category == "应用首页" && d.Name.Equals(appId, StringComparison.OrdinalIgnoreCase) && d.Define == EnumDictDefine.System)?.Code;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public string GetIconFolderPath()
{
var dicts = GetAll();
return dicts.FirstOrDefault(d => d.Name == "头像路径" && d.Category == "头像地址" && d.Define == EnumDictDefine.System)?.Code ?? "/images/uploder/";
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
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; ;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public string? GetIpLocator()
{
var dicts = GetAll();
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "IP地理位置接口" && s.Define == EnumDictDefine.System)?.Code;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public string? GetIpLocatorName()
{
var dicts = GetAll();
return dicts.FirstOrDefault(s => s.Category == "网站设置" && s.Name == "IP地理位置接口" && s.Define == EnumDictDefine.System)?.Code;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
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);
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public string? GetIpLocatorUrl(string? name)
{
var dicts = GetAll();
return string.IsNullOrWhiteSpace(name) ? null : dicts.FirstOrDefault(s => s.Category == "地理位置" && s.Name == name && s.Define == EnumDictDefine.System)?.Code;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
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;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public Dictionary<string, string> GetLogins()
{
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);
}
/// <summary>
///
/// </summary>
/// <param name="appId"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public string? GetNotificationUrl(string appId) => GetUrlByName(appId, "系统通知地址");
/// <summary>
///
/// </summary>
/// <returns></returns>
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;
}
/// <summary>
///
/// </summary>
/// <param name="appId"></param>
/// <returns></returns>
public string? GetProfileUrl(string appId) => GetUrlByName(appId, "个人中心地址");
/// <summary>
///
/// </summary>
/// <param name="appId"></param>
/// <returns></returns>
public string? GetSettingsUrl(string appId) => GetUrlByName(appId, "系统设置地址");
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public Dictionary<string, string> GetThemes()
{
var dicts = GetAll();
return dicts.Where(d => d.Category == "网站样式").Select(d => new KeyValuePair<string, string>(d.Code, d.Name)).ToDictionary(i => i.Key, i => i.Value);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public string GetWebFooter()
{
var dicts = GetAll();
var title = "网站页脚";
var name = dicts.FirstOrDefault(d => d.Category == "应用程序" && d.Code == AppId)?.Name;
if (!string.IsNullOrEmpty(name))
{
var dict = dicts.FirstOrDefault(d => d.Category == name && d.Name == "网站页脚") ?? dicts.FirstOrDefault(d => d.Category == "网站设置" && d.Name == "网站页脚");
title = dict?.Code ?? "网站标题";
}
return title;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public string GetWebTitle()
{
var dicts = GetAll();
var title = "网站标题";
var name = dicts.FirstOrDefault(d => d.Category == "应用程序" && d.Code == AppId)?.Name;
if (!string.IsNullOrEmpty(name))
{
var dict = dicts.FirstOrDefault(d => d.Category == name && d.Name == "网站标题") ?? dicts.FirstOrDefault(d => d.Category == "网站设置" && d.Name == "网站标题");
title = dict?.Code ?? "网站标题";
}
return title;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool IsDemo()
{
var dicts = GetAll();
var code = dicts.FirstOrDefault(d => d.Category == "网站设置" && d.Name == "演示系统" && d.Define == EnumDictDefine.System)?.Code ?? "0";
return code == "1";
}
/// <summary>
///
/// </summary>
/// <param name="enabled"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SavDefaultApp(bool enabled) => SaveDict(new Dict
{
Category = "网站设置",
Name = "默认应用程序",
Code = enabled ? "1" : "0",
Define = EnumDictDefine.System
});
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveAccessExpired(int value) => SaveDict(new Dict { Category = "网站设置", Name = "访问日志保留时长", Code = value.ToString() });
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveAppFixHeader(bool value) => SaveDict(new Dict { Category = "网站设置", Name = "固定表头", Code = value ? "1" : "0" });
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveAppHealthCheck(bool value) => SaveDict(new Dict { Category = "网站设置", Name = "健康检查", Code = value ? "1" : "0" });
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveAppMobileLogin(bool value) => SaveDict(new Dict { Category = "网站设置", Name = "短信验证码登录", Code = value ? "1" : "0" });
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveAppOAuthLogin(bool value) => SaveDict(new Dict { Category = "网站设置", Name = "OAuth 认证登录", Code = value ? "1" : "0" });
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveAppSiderbar(bool value) => SaveDict(new Dict { Category = "网站设置", Name = "侧边栏状态", Code = value ? "1" : "0" });
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveAppTitle(bool value) => SaveDict(new Dict { Category = "网站设置", Name = "卡片标题状态", Code = value ? "1" : "0" });
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveAutoLockScreen(bool value) => SaveDict(new Dict { Category = "网站设置", Name = "自动锁屏", Code = value ? "1" : "0" });
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveAutoLockScreenInterval(int value) => SaveDict(new Dict { Category = "网站设置", Name = "自动锁屏时长", Code = value.ToString() });
/// <summary>
///
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveClient(ClientApp client)
{
var ret = false;
if (!string.IsNullOrEmpty(client.AppId))
{
DeleteClient(client.AppId);
try
{
Client.Ado.BeginTran();
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 }
};
Client.Insertable(items).AS("Dicts").ExecuteCommand();
Client.Ado.CommitTran();
ret = true;
}
catch (DbException)
{
Client.Ado.RollbackTran();
throw;
}
}
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveCookieExpired(int value) => SaveDict(new Dict { Category = "网站设置", Name = "Cookie保留时长", Code = value.ToString() });
/// <summary>
///
/// </summary>
/// <param name="expiresPeriod"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveCookieExpiresPeriod(int expiresPeriod) => SaveDict(new Dict { Category = "网站设置", Name = "Cookie保留时长", Code = expiresPeriod.ToString() });
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveCurrentIp(string value) => SaveDict(new Dict { Category = "网站设置", Name = "IP地理位置接口", Code = value });
/// <summary>
///
/// </summary>
/// <param name="isDemo"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveDemo(bool isDemo) => SaveDict(new Dict
{
Category = "网站设置",
Name = "演示系统",
Code = isDemo ? "1" : "0",
Define = EnumDictDefine.System
});
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveExceptionExpired(int value) => SaveDict(new Dict { Category = "网站设置", Name = "程序异常保留时长", Code = value.ToString() });
/// <summary>
///
/// </summary>
/// <param name="enable"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveHealthCheck(bool enable = true) => SaveDict(new Dict
{
Category = "网站设置",
Name = "健康检查",
Code = enable ? "1" : "0",
Define = EnumDictDefine.System
});
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveIPCacheExpired(int value) => SaveDict(new Dict { Category = "网站设置", Name = "IP请求缓存时长", Code = value.ToString() });
/// <summary>
///
/// </summary>
/// <param name="login"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveLogin(string login) => SaveDict(new Dict { Category = "网站设置", Name = "登录界面", Code = login });
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveLoginExpired(int value) => SaveDict(new Dict { Category = "网站设置", Name = "登录日志保留时长", Code = value.ToString() });
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveOperateExpired(int value) => SaveDict(new Dict { Category = "网站设置", Name = "操作日志保留时长", Code = value.ToString() });
/// <summary>
///
/// </summary>
/// <param name="theme"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveTheme(string theme) => SaveDict(new Dict { Category = "网站设置", Name = "使用样式", Code = theme });
/// <summary>
///
/// </summary>
/// <param name="footer"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveWebFooter(string footer) => SaveDict(new Dict { Category = "网站设置", Name = "网站页脚", Code = footer });
/// <summary>
///
/// </summary>
/// <param name="title"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveWebTitle(string title) => SaveDict(new Dict { Category = "网站设置", Name = "网站标题", Code = title });
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;
}
private bool SaveDict(Dict dict)
{
var ret = Client.Updateable(dict).AS("Dicts").Where(s => s.Category == dict.Category && s.Name == dict.Name).UpdateColumns(s => s.Code).ExecuteCommand() > 0;
if (ret)
{
// 更新缓存
CacheManager.Clear(DictServiceCacheKey);
}
return ret;
}
}

View File

@ -0,0 +1,107 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
using BootStarpAdmin.DataAccess.SqlSugar.Models;
using BootstrapAdmin.Caching;
using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.Web.Core;
using SqlSugar;
namespace BootstrapAdmin.DataAccess.SqlSugar.Services;
class GroupService : IGroup
{
private const string GroupServiceGetAllCacheKey = "GroupService-GetAll";
private const string GroupServiceGetGroupsByUserIdCacheKey = "GroupService-GetGroupsByUserId";
private const string GroupServiceGetGroupsByRoleIdCacheKey = "GroupService-GetGroupsByRoleId";
private ISqlSugarClient Client { get; }
/// <summary>
///
/// </summary>
/// <param name="client"></param>
public GroupService(ISqlSugarClient client) => Client = client;
/// <summary>
///
/// </summary>
/// <returns></returns>
public List<Group> GetAll() => CacheManager.GetOrAdd(GroupServiceGetAllCacheKey, entry => Client.Queryable<Group>().AS("Groups").ToList());
/// <summary>
///
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
public List<string> GetGroupsByUserId(string? userId) => CacheManager.GetOrAdd($"{GroupServiceGetGroupsByUserIdCacheKey}-{userId}", entry => Client.Ado.SqlQuery<string>("select GroupID from UserGroup where UserID = @UserID", new { UserID = userId }));
/// <summary>
///
/// </summary>
/// <param name="userId"></param>
/// <param name="groupIds"></param>
/// <returns></returns>
public bool SaveGroupsByUserId(string? userId, IEnumerable<string> groupIds)
{
var ret = false;
try
{
Client.Ado.BeginTran();
Client.Ado.ExecuteCommand("delete from UserGroup where UserID = @UserID", new { UserID = userId });
Client.Insertable<UserGroup>(groupIds.Select(g => new { GroupID = g, UserID = userId })).ExecuteCommand();
Client.Ado.CommitTran();
ret = true;
}
catch (Exception)
{
Client.Ado.RollbackTran();
throw;
}
if (ret)
{
CacheManager.Clear();
}
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="roleId"></param>
/// <returns></returns>
public List<string> GetGroupsByRoleId(string? roleId) => CacheManager.GetOrAdd($"{GroupServiceGetGroupsByRoleIdCacheKey}-{roleId}", entry => Client.Ado.SqlQuery<string>("select GroupID from RoleGroup where RoleID = @RoleID", new { RoleID = roleId }));
/// <summary>
///
/// </summary>
/// <param name="roleId"></param>
/// <param name="groupIds"></param>
/// <returns></returns>
public bool SaveGroupsByRoleId(string? roleId, IEnumerable<string> groupIds)
{
var ret = false;
try
{
Client.Ado.BeginTran();
Client.Ado.ExecuteCommand("delete from RoleGroup where RoleID = @RoleID", new { RoleID = roleId });
Client.Insertable<RoleGroup>(groupIds.Select(g => new { GroupID = g, RoleID = roleId }));
Client.Ado.CommitTran();
ret = true;
}
catch (Exception)
{
Client.Ado.RollbackTran();
throw;
}
if (ret)
{
CacheManager.Clear();
}
return ret;
}
}

View File

@ -0,0 +1,44 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.Web.Core;
using SqlSugar;
namespace BootstrapAdmin.DataAccess.SqlSugar.Services;
class LoginService : ILogin
{
private ISqlSugarClient Client { get; }
public LoginService(ISqlSugarClient client) => Client = client;
/// <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>
public bool Log(string userName, string? IP, string? OS, string? browser, string? address, string? userAgent, bool result)
{
var loginUser = new LoginLog()
{
UserName = userName,
LoginTime = DateTime.Now,
Ip = IP,
City = address,
OS = OS,
Browser = browser,
UserAgent = userAgent,
Result = result ? "登录成功" : "登录失败"
};
Client.Insertable(loginUser).AS("LoginLogs").ExecuteCommand();
return true;
}
}

View File

@ -0,0 +1,43 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
using BootStarpAdmin.DataAccess.SqlSugar.Models;
using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.Web.Core;
using SqlSugar;
namespace BootStarpAdmin.DataAccess.SqlSugar.Service;
class NavigationService : INavigation
{
private ISqlSugarClient Client { get; }
public NavigationService(ISqlSugarClient client) => Client = client;
public List<Navigation> GetAllMenus(string userName)
{
return Client.Ado.SqlQuery<Navigation>($"select n.ID, n.ParentId, n.Name, n.[order], n.Icon, n.Url, n.Category, n.Target, n.IsResource, n.Application, ln.Name as ParentName from Navigations n inner join Dicts d on n.Category = d.Code and d.Category = @Category and d.Define = @Define left join Navigations ln on n.ParentId = ln.ID 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 = @UserName 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 = @UserName 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 = @UserName and r.RoleName = @RoleName)) nav on n.ID = nav.NavigationID ORDER BY n.Application, n.[order]", new { UserName = userName, Category = "菜单", RoleName = "Administrators", Define = EnumDictDefine.System });
}
public List<string> GetMenusByRoleId(string? roleId) => Client.Ado.SqlQuery<string>("select NavigationID from NavigationRole where RoleID = @RoleId", new { RoleId = roleId });
public bool SaveMenusByRoleId(string? roleId, List<string> menuIds)
{
var ret = false;
try
{
Client.Ado.BeginTran();
Client.Ado.ExecuteCommand("delete from NavigationRole where RoleID = @RoleId", new { RoleId = roleId });
Client.Insertable<NavigationRole>(menuIds.Select(g => new NavigationRole { NavigationID = g, RoleID = roleId })).ExecuteCommand();
ret = true;
Client.Ado.CommitTran();
}
catch (Exception)
{
Client.Ado.RollbackTran();
throw;
}
return ret;
}
}

View File

@ -0,0 +1,123 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
using BootStarpAdmin.DataAccess.SqlSugar.Models;
using BootstrapAdmin.Caching;
using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.Web.Core;
using SqlSugar;
namespace BootstrapAdmin.DataAccess.SqlSugar.Services;
class RoleService : IRole
{
private const string RoleServiceGetAllCacheKey = "RoleService-GetAll";
private const string RoleServiceGetRolesByUserIdCacheKey = "RoleService-GetRolesByUserId";
private const string RoleServiceGetRolesByGroupIdCacheKey = "RoleService-GetRolesByGroupId";
private const string RoleServiceGetRolesByMenuIdCacheKey = "RoleService-GetRolesByMenusId";
private ISqlSugarClient Client { get; }
/// <summary>
///
/// </summary>
/// <param name="client"></param>
public RoleService(ISqlSugarClient client) => Client = client;
/// <summary>
///
/// </summary>
/// <returns></returns>
public List<Role> GetAll() => CacheManager.GetOrAdd(RoleServiceGetAllCacheKey, entry => CacheManager.GetOrAdd(RoleServiceGetAllCacheKey, entry => Client.Queryable<Role>().AS("Roles").ToList()));
public List<string> GetRolesByGroupId(string? groupId) => CacheManager.GetOrAdd($"{RoleServiceGetRolesByGroupIdCacheKey}-{groupId}", entry => Client.Ado.SqlQuery<string>("select RoleID from RoleGroup where GroupID = @GroupID", new { GroupID = groupId }));
public List<string> GetRolesByUserId(string? userId) => CacheManager.GetOrAdd($"{RoleServiceGetRolesByUserIdCacheKey}-{userId}", entry => Client.Ado.SqlQuery<string>("select RoleID from UserRole where UserID = @UserID", new { UserID = userId }));
public List<string> GetRolesByMenuId(string? menuId) => CacheManager.GetOrAdd($"{RoleServiceGetRolesByMenuIdCacheKey}-{menuId}", entry => Client.Ado.SqlQuery<string>("select RoleID from NavigationRole where NavigationID = @NavigationID", new { NavigationID = menuId }));
/// <summary>
///
/// </summary>
/// <param name="groupId"></param>
/// <param name="roleIds"></param>
/// <returns></returns>
public bool SaveRolesByGroupId(string? groupId, IEnumerable<string> roleIds)
{
var ret = false;
try
{
Client.Ado.BeginTran();
Client.Ado.ExecuteCommand("delete from RoleGroup where GroupID = @GroupID", new { GroupID = groupId });
Client.Insertable<RoleGroup>(roleIds.Select(g => new { RoleID = g, GroupID = groupId })).ExecuteCommand();
Client.Ado.CommitTran();
ret = true;
}
catch (Exception)
{
Client.Ado.RollbackTran();
throw;
}
if (ret)
{
CacheManager.Clear();
}
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="userId"></param>
/// <param name="roleIds"></param>
/// <returns></returns>
public bool SaveRolesByUserId(string? userId, IEnumerable<string> roleIds)
{
var ret = false;
try
{
Client.Ado.BeginTran();
Client.Ado.ExecuteCommand("delete from UserRole where UserID = @UserID", new { UserID = userId });
Client.Insertable<UserRole>(roleIds.Select(g => new { RoleID = g, UserID = userId })).ExecuteCommand();
Client.Ado.CommitTran();
ret = true;
}
catch (Exception)
{
Client.Ado.RollbackTran();
throw;
}
if (ret)
{
CacheManager.Clear();
}
return ret;
}
public bool SaveRolesByMenuId(string? menuId, IEnumerable<string> roleIds)
{
var ret = false;
try
{
Client.Ado.BeginTran();
Client.Ado.ExecuteCommand("delete from NavigationRole where NavigationID = @NavigationID", new { NavigationID = menuId });
Client.Insertable<NavigationRole>(roleIds.Select(g => new { RoleID = g, NavigationID = menuId }));
Client.Ado.CommitTran();
ret = true;
}
catch (Exception)
{
Client.Ado.RollbackTran();
throw;
}
if (ret)
{
CacheManager.Clear();
}
return ret;
}
}

View File

@ -0,0 +1,78 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.Web.Core;
using SqlSugar;
namespace BootstrapAdmin.DataAccess.SqlSugar.Services;
class TraceService : ITrace
{
private ISqlSugarClient Client { get; }
/// <summary>
///
/// </summary>
/// <param name="client"></param>
public TraceService(ISqlSugarClient client) => Client = client;
/// <summary>
///
/// </summary>
/// <param name="trace"></param>
public void Log(Trace trace)
{
Client.Insertable(trace).ExecuteCommand();
}
/// <summary>
///
/// </summary>
/// <param name="searchText"></param>
/// <param name="filter"></param>
/// <param name="pageIndex"></param>
/// <param name="pageItems"></param>
/// <param name="sortList"></param>
/// <returns></returns>
public (IEnumerable<Trace> Items, int ItemsCount) GetAll(string? searchText, TraceFilter filter, int pageIndex, int pageItems, List<string> sortList)
{
//var sql = new Sql();
//if (!string.IsNullOrEmpty(searchText))
//{
// sql.Where("UserName Like @0 or Ip Like @0 or RequestUrl Like @0", $"%{searchText}%");
//}
//if (!string.IsNullOrEmpty(filter.UserName))
//{
// sql.Where("UserName Like @0", $"%{filter.UserName}%");
//}
//if (!string.IsNullOrEmpty(filter.Ip))
//{
// sql.Where("Ip Like @0", $"%{filter.Ip}%");
//}
//if (!string.IsNullOrEmpty(filter.RequestUrl))
//{
// sql.Where("ErrorPage Like @0", $"%{filter.RequestUrl}%");
//}
//sql.Where("LogTime >= @0 and LogTime <= @1", filter.Star, filter.End);
//if (sortList.Any())
//{
// sql.OrderBy(string.Join(", ", sortList));
//}
//else
//{
// sql.OrderBy("Logtime desc");
//}
//var data = Database.Page<Trace>(pageIndex, pageItems, sql);
//return (data.Items, Convert.ToInt32(data.TotalItems));
return (new List<Trace>(), 100);
}
}

View File

@ -0,0 +1,376 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
using BootStarpAdmin.DataAccess.SqlSugar.Models;
using BootstrapAdmin.Caching;
using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.Web.Core;
using Longbow.Security.Cryptography;
using SqlSugar;
namespace BootStarpAdmin.DataAccess.SqlSugar.Service;
/// <summary>
///
/// </summary>
public class UserService : IUser
{
private ISqlSugarClient Client;
/// <summary>
///
/// </summary>
/// <param name="client"></param>
public UserService(ISqlSugarClient client) => Client = client;
/// <summary>
///
/// </summary>
/// <returns></returns>
public List<User> GetAll()
{
return Client.Queryable<User>().IgnoreColumns("NewPassword", "ConfirmPassword", "Period", "IsReset").AS("Users").ToList();
}
/// <summary>
///
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
public bool Authenticate(string userName, string password)
{
var user = Client.Ado.SqlQuery<User>("select DisplayName, Password, PassSalt from Users where ApprovedTime is not null and UserName = @UserName", new { UserName = userName }).First();
var isAuth = false;
if (user != null && !string.IsNullOrEmpty(user.PassSalt))
{
isAuth = user.Password == LgbCryptography.ComputeHash(password, user.PassSalt);
}
return isAuth;
}
/// <summary>
///
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <param name="newPassword"></param>
/// <returns></returns>
public bool ChangePassword(string userName, string password, string newPassword)
{
var ret = false;
if (Authenticate(userName, password))
{
var passSalt = LgbCryptography.GenerateSalt();
password = LgbCryptography.ComputeHash(newPassword, passSalt);
string sql = "update users set Password = @Password, PassSalt = @PassSalt where UserName = @UserName";
ret = Client.Ado.ExecuteCommand(sql, new { Password = password, PassSalt = passSalt, UserName = userName }) == 1;
}
return ret;
}
private const string UserServiceGetAppIdByUserNameCacheKey = "UserService-GetAppIdByUserName";
/// <summary>
///
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public string? GetAppIdByUserName(string userName) => CacheManager.GetOrAdd($"{UserServiceGetAppIdByUserNameCacheKey}-{userName}", entry => Client.Queryable<User>().IgnoreColumns("NewPassword", "ConfirmPassword", "Period", "IsReset").AS("Users").Where(s => s.UserName == userName).First()?.App);
private const string UserServiceGetAppsByUserNameCacheKey = "UserService-GetAppsByUserName";
/// <summary>
///
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public List<string> GetApps(string userName) => CacheManager.GetOrAdd($"{UserServiceGetAppsByUserNameCacheKey}-{userName}", entry => Client.Ado.SqlQuery<string>($"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 = @UserName 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 = @UserName) r on ra.RoleId = r.ID union select Code from Dicts where Category = @Category 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 = @UserName and r.RoleName = @RoleName 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 = @UserName and r.RoleName = @RoleName)", new { UserName = userName, Category = "应用程序", RoleName = "Administrators" }));
private const string UserServiceGetRolesByUserNameCacheKey = "UserService-GetRolesByUserName";
/// <summary>
///
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public List<string> GetRoles(string userName) => CacheManager.GetOrAdd($"{UserServiceGetRolesByUserNameCacheKey}-{userName}", entry => Client.Ado.SqlQuery<string>($"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 = @UserName 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=@UserName", new { UserName = userName }));
private const string UserServiceGetUserByUserNameCacheKey = "UserService-GetUserByUserName";
/// <summary>
///
/// </summary>
/// <param name="userName"></param>
/// <returns></returns>
public User? GetUserByUserName(string? userName) => CacheManager.GetOrAdd($"{UserServiceGetUserByUserNameCacheKey}-{userName}", entry => string.IsNullOrEmpty(userName) ? null : Client.Queryable<User>().IgnoreColumns("NewPassword", "ConfirmPassword", "Period", "IsReset").AS("Users").Where(s => s.UserName == userName).First());
private const string UserServiceGetUsersByGroupIdCacheKey = "UserService-GetUsersByGroupId";
/// <summary>
///
/// </summary>
/// <param name="groupId"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public List<string> GetUsersByGroupId(string? groupId) => CacheManager.GetOrAdd($"{UserServiceGetUsersByGroupIdCacheKey}-{groupId}", entry => Client.Ado.SqlQuery<string>("select UserID from UserGroup where GroupID = @GroupID", new { GroupID = groupId }));
private const string UserServiceGetUsersByRoleIdCacheKey = "UserService-GetUsersByRoleId";
/// <summary>
///
/// </summary>
/// <param name="roleId"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public List<string> GetUsersByRoleId(string? roleId) => CacheManager.GetOrAdd($"{UserServiceGetUsersByRoleIdCacheKey}-{roleId}", entry => Client.Ado.SqlQuery<string>("select UserID from UserRole where RoleID = @RoleID", new { RoleID = roleId }));
/// <summary>
///
/// </summary>
/// <param name="userName"></param>
/// <param name="app"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveApp(string userName, string app)
{
var ret = Client.Ado.ExecuteCommand("update users set App = @App Where UserName = @UserName", new { App = app, UserName = userName }) == 1;
if (ret)
{
CacheManager.Clear();
}
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)
{
var ret = Client.Ado.ExecuteCommand("update users set DisplayName = @DisplayName where UserName = @UserName", new { UserName = userName, DisplayName = displayName }) == 1;
if (ret)
{
CacheManager.Clear();
}
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="userName"></param>
/// <param name="logo"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveLogo(string userName, string? logo)
{
var ret = Client.Ado.ExecuteCommand("update users set Icon = @Icon where UserName = @UserName", new { UserName = userName, Icon = logo }) == 1;
if (ret)
{
CacheManager.Clear();
}
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="userName"></param>
/// <param name="theme"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveTheme(string userName, string theme)
{
var ret = Client.Ado.ExecuteCommand("update users set Css = @Css where UserName = @UserName", new { UserName = userName, Css = theme }) == 1;
if (ret)
{
CacheManager.Clear();
}
return ret;
}
/// <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)
{
var salt = LgbCryptography.GenerateSalt();
var pwd = LgbCryptography.ComputeHash(password, salt);
var user = Client.Queryable<User>().IgnoreColumns("NewPassword", "ConfirmPassword", "Period", "IsReset").AS("Users").First(s => s.UserName == userName);
bool ret;
if (user == null)
{
try
{
// 开始事务
Client.Ado.BeginTran();
user = new User()
{
ApprovedBy = "System",
ApprovedTime = DateTime.Now,
DisplayName = "手机用户",
UserName = userName,
Icon = "default.jpg",
Description = "系统默认创建",
PassSalt = salt,
Password = pwd
};
Client.Insertable(user).IgnoreColumns("NewPassword", "ConfirmPassword", "Period", "IsReset").AS("Users").ExecuteCommand();
// 授权 Default 角色
Client.Ado.ExecuteCommand("insert into UserRole (UserID, RoleID) select ID, (select ID from Roles where RoleName = 'Default') RoleId from Users where UserName = @userName", new { UserName = userName });
// 结束事务
Client.Ado.CommitTran();
ret = true;
}
catch (Exception)
{
Client.Ado.RollbackTran();
throw;
}
}
else
{
user.DisplayName = displayName;
user.PassSalt = salt;
user.Password = pwd;
Client.Updateable(user).IgnoreColumns("NewPassword", "ConfirmPassword", "Period", "IsReset").AS("Users").ExecuteCommand();
ret = true;
}
if (ret)
{
CacheManager.Clear();
}
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="groupId"></param>
/// <param name="userIds"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveUsersByGroupId(string? groupId, IEnumerable<string> userIds)
{
var ret = false;
try
{
Client.Ado.BeginTran();
Client.Ado.ExecuteCommand("delete from UserGroup where GroupId = @GroupId", new { GroupId = groupId });
Client.Insertable<UserGroup>(userIds.Select(g => new { UserID = g, GroupID = groupId })).ExecuteCommand();
Client.Ado.CommitTran();
ret = true;
}
catch (Exception)
{
Client.Ado.RollbackTran();
throw;
}
if (ret)
{
CacheManager.Clear();
}
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="roleId"></param>
/// <param name="userIds"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool SaveUsersByRoleId(string? roleId, IEnumerable<string> userIds)
{
var ret = false;
try
{
Client.Ado.BeginTran();
Client.Ado.ExecuteCommand("delete from UserRole where RoleID = @RoleID", new { RoleID = roleId });
Client.Insertable<UserRole>(userIds.Select(g => new { UserID = g, RoleID = roleId })).ExecuteCommand();
Client.Ado.CommitTran();
ret = true;
}
catch (Exception)
{
Client.Ado.RollbackTran();
throw;
}
if (ret)
{
CacheManager.Clear();
}
return ret;
}
/// <summary>
///
/// </summary>
/// <param name="phone"></param>
/// <param name="code"></param>
/// <param name="appId"></param>
/// <param name="roles"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public bool TryCreateUserByPhone(string phone, string code, string appId, ICollection<string> roles)
{
var ret = false;
try
{
var salt = LgbCryptography.GenerateSalt();
var pwd = LgbCryptography.ComputeHash(code, salt);
var user = Client.Queryable<User>().IgnoreColumns("NewPassword", "ConfirmPassword", "Period", "IsReset").AS("Users").First(s => s.UserName == phone);
if (user == null)
{
Client.Ado.BeginTran();
// 插入用户
user = new User()
{
ApprovedBy = "Mobile",
ApprovedTime = DateTime.Now,
DisplayName = "手机用户",
UserName = phone,
Icon = "default.jpg",
Description = "手机用户",
PassSalt = salt,
Password = LgbCryptography.ComputeHash(code, salt),
App = appId
};
Client.Insertable(user).IgnoreColumns("NewPassword", "ConfirmPassword", "Period", "IsReset").AS("Users").ExecuteCommand();
// Authorization
var roleIds = Client.Ado.SqlQuery<string>("select ID from Roles where RoleName in (@roles)", new { roles = roles });
Client.Insertable<UserRole>(roleIds.Select(g => new { RoleID = g, UserID = user.Id })).ExecuteCommand();
Client.Ado.CommitTran();
}
else
{
user.PassSalt = salt;
user.Password = pwd;
Client.Updateable(user).IgnoreColumns("NewPassword", "ConfirmPassword", "Period", "IsReset").AS("Users").ExecuteCommand();
}
ret = true;
}
catch (Exception)
{
Client.Ado.RollbackTran();
throw;
}
if (ret)
{
CacheManager.Clear();
}
return ret;
}
}

View File

@ -11,6 +11,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BootStarpAdmin.DataAccess.SqlSugar\BootStarpAdmin.DataAccess.SqlSugar.csproj" />
<ProjectReference Include="..\BootstrapAdmin.DataAccess.PetaPoco\BootstrapAdmin.DataAccess.PetaPoco.csproj" />
</ItemGroup>

View File

@ -2,6 +2,7 @@
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.Web;
using BootstrapAdmin.Web.Core.Services;
using BootstrapAdmin.Web.HealthChecks;
@ -73,12 +74,28 @@ namespace Microsoft.Extensions.DependencyInjection
// });
// 增加 PetaPoco 数据服务
services.AddPetaPocoDataAccessServices((provider, builder) =>
//services.AddPetaPocoDataAccessServices((provider, builder) =>
//{
// var configuration = provider.GetRequiredService<IConfiguration>();
// var connString = configuration.GetConnectionString("bb");
// builder.UsingProvider<SQLiteDatabaseProvider>()
// .UsingConnectionString(connString);
//});
services.AddSqlSugar((provider, config) =>
{
var configuration = provider.GetRequiredService<IConfiguration>();
var connString = configuration.GetConnectionString("bb");
builder.UsingProvider<SQLiteDatabaseProvider>()
.UsingConnectionString(connString);
config.DbType = SqlSugar.DbType.Sqlite;
config.ConnectionString = connString;
config.InitKeyType = SqlSugar.InitKeyType.SystemTable;
config.ConfigureExternalServices = new SqlSugar.ConfigureExternalServices()
{
EntityNameService = (type, entity) =>
{
entity.DbTableName = entity.DbTableName + "s";
}
};
});
return services;