Skip to content

Commit

Permalink
Merge pull request #4 from pengqian089/support-mongodb-repository
Browse files Browse the repository at this point in the history
系统初始化优化
  • Loading branch information
pengqian089 authored Dec 27, 2023
2 parents e2f8137 + 85884cf commit 5428e92
Show file tree
Hide file tree
Showing 16 changed files with 166 additions and 104 deletions.
4 changes: 2 additions & 2 deletions src/AgileConfig.Server.Apisite/ConfigureJwtBearerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ namespace AgileConfig.Server.Apisite;

public class ConfigureJwtBearerOptions(
IJwtService jwtService,
ISettingService settingService) : IConfigureNamedOptions<JwtBearerOptions>
ISystemInitializationService systemInitializationService) : IConfigureNamedOptions<JwtBearerOptions>
{
public void Configure(JwtBearerOptions options)
{
settingService.TryInitJwtSecret();
systemInitializationService.TryInitJwtSecret();
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = jwtService.Issuer,
Expand Down
4 changes: 2 additions & 2 deletions src/AgileConfig.Server.Apisite/Controllers/UserController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public async Task<IActionResult> Search(string userName, string team, int curren
}

var users = await _userService.GetAll();
users = users.Where(x => x.Status == UserStatus.Normal && x.Id != SettingService.SuperAdminId).ToList();
users = users.Where(x => x.Status == UserStatus.Normal && x.Id != SystemSettings.SuperAdminId).ToList();
if (!string.IsNullOrEmpty(userName))
{
users = users.Where(x => x.UserName != null && x.UserName.Contains(userName)).ToList();
Expand Down Expand Up @@ -264,7 +264,7 @@ public async Task<IActionResult> adminUsers()
public async Task<IActionResult> AllUsers()
{
var users = await _userService.GetAll();
users = users.Where(x => x.Status == UserStatus.Normal && x.Id != SettingService.SuperAdminId).ToList();
users = users.Where(x => x.Status == UserStatus.Normal && x.Id != SystemSettings.SuperAdminId).ToList();

return Json(new
{
Expand Down
11 changes: 11 additions & 0 deletions src/AgileConfig.Server.Common/SystemSettings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace AgileConfig.Server.Common;

public static class SystemSettings
{
public const string SuperAdminId = "super_admin";
public const string SuperAdminUserName = "admin";

public const string DefaultEnvironment = "DEV,TEST,STAGING,PROD";
public const string DefaultEnvironmentKey = "environment";
public const string DefaultJwtSecretKey = "jwtsecret";
}
18 changes: 18 additions & 0 deletions src/AgileConfig.Server.Data.Abstraction/ISysInitRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using AgileConfig.Server.Data.Entity;

namespace AgileConfig.Server.Data.Abstraction;

public interface ISysInitRepository
{
/// <summary>
/// get jwt token secret from db
/// </summary>
/// <returns></returns>
string? GetJwtTokenSecret();

/// <summary>
/// save initialization setting
/// </summary>
/// <param name="setting"></param>
void SaveInitSetting(Setting setting);
}
6 changes: 3 additions & 3 deletions src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@ public async Task<List<TEntity>> AllAsync()

private Expression<Func<TEntity,bool>> GetIdPropertyFilter(TId id)
{
var expression = _access.MongoQueryable.Where(x => Equals(x.Id, id)).Expression;
return Expression.Lambda<Func<TEntity, bool>>(expression);
Expression<Func<TEntity, bool>> expression = x => Equals(x.Id, id);
return expression;
}

public async Task<TEntity> GetAsync(TId id)
public async Task<TEntity?> GetAsync(TId id)
{
var filter = GetIdPropertyFilter(id);
return await (await _access.Collection.FindAsync(filter)).SingleOrDefaultAsync();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ public static void AddFreeSqlRepository(this IServiceCollection sc)
sc.AddScoped<IUserAppAuthRepository, UserAppAuthRepository>();
sc.AddScoped<IUserRepository, UserRepository>();
sc.AddScoped<IUserRoleRepository, IUserRoleRepository>();

sc.AddSingleton<ISysInitRepository, SysInitRepository>();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using AgileConfig.Server.Common;
using AgileConfig.Server.Data.Abstraction;
using AgileConfig.Server.Data.Entity;
using AgileConfig.Server.Data.Freesql;

namespace AgileConfig.Server.Data.Repository.Freesql;

public class SysInitRepository : ISysInitRepository
{
public string? GetJwtTokenSecret()
{
var setting = FreeSQL.Instance.Select<Setting>().Where(x => x.Id == SystemSettings.DefaultJwtSecretKey)
.ToOne();
return setting?.Value;
}

public void SaveInitSetting(Setting setting)
{
FreeSQL.Instance.Insert(setting);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,7 @@ public static void AddMongodbRepository(this IServiceCollection services)
services.AddScoped<IUserAppAuthRepository, UserAppAuthRepository>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IUserRoleRepository, UserRoleRepository>();

services.AddSingleton<ISysInitRepository, SysInitRepository>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using AgileConfig.Server.Common;

namespace AgileConfig.Server.Data.Repository.Mongodb;

public class SysInitRepository : ISysInitRepository
{
private readonly MongodbAccess<Setting> _access = new(Global.Config["db:conn"]);

public string? GetJwtTokenSecret()
{
var setting = _access.MongoQueryable.FirstOrDefault(x => x.Id == SystemSettings.DefaultJwtSecretKey);
return setting?.Value;
}

public void SaveInitSetting(Setting setting)
{
_access.Collection.InsertOne(setting);
}
}
12 changes: 0 additions & 12 deletions src/AgileConfig.Server.IService/ISettingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,5 @@ public interface ISettingService: IDisposable
/// </summary>
/// <returns></returns>
Task<string[]> GetEnvironmentList();

/// <summary>
/// 如果环境变量没有 JwtSetting:SecurityKey 则尝试生成一个key到数据库
/// </summary>
/// <returns></returns>
bool TryInitJwtSecret();

/// <summary>
/// 从配置表获取 jwt secret key
/// </summary>
/// <returns></returns>
string GetJwtTokenSecret();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace AgileConfig.Server.IService;

public interface ISystemInitializationService
{
bool TryInitJwtSecret();
}
11 changes: 3 additions & 8 deletions src/AgileConfig.Server.Service/JwtService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Security.Claims;
using System.Text;
using AgileConfig.Server.Common;
using AgileConfig.Server.Data.Abstraction;
using AgileConfig.Server.IService;
using Microsoft.IdentityModel.Tokens;

Expand All @@ -11,21 +12,15 @@ namespace AgileConfig.Server.Service;
/// <summary>
/// jwt 相关业务
/// </summary>
public class JwtService : IJwtService
public class JwtService(ISysInitRepository sysInitRepository) : IJwtService
{
private readonly ISettingService _settingService;
// static JwtService()
// {
// // 则尝试生成一个key到数据库
// using var settingService = new SettingService(new FreeSqlContext(FreeSQL.Instance));
// settingService.TryInitJwtSecret();
// }

public JwtService(ISettingService settingService)
{
_settingService = settingService;
}

public string Issuer => Global.Config["JwtSetting:Issuer"];
public string Audience => Global.Config["JwtSetting:Audience"];
public int ExpireSeconds => int.Parse(Global.Config["JwtSetting:ExpireSeconds"]);
Expand All @@ -45,7 +40,7 @@ public string GetSecurityKey()
}

//using var settingService = new SettingService(new FreeSqlContext(FreeSQL.Instance));
_secretKey = _settingService.GetJwtTokenSecret();
_secretKey = sysInitRepository.GetJwtTokenSecret();

if (string.IsNullOrEmpty(_secretKey))
{
Expand Down
11 changes: 6 additions & 5 deletions src/AgileConfig.Server.Service/ServiceCollectionExt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public static class ServiceCollectionExt
{
public static void AddBusinessServices(this IServiceCollection sc)
{
sc.AddSingleton<ISystemInitializationService, SystemInitializationService>();
sc.AddSingleton<IJwtService, JwtService>();

sc.AddScoped<IRemoteServerNodeProxy, RemoteServerNodeProxy>();
Expand Down Expand Up @@ -46,11 +47,11 @@ public static void AddBusinessServices(this IServiceCollection sc)
};
});

sc.AddTransient<EventRegisterTransient<IConfigService>,EventRegisterTransient<ConfigService>>();
sc.AddTransient<EventRegisterTransient<IAppService>,EventRegisterTransient<AppService>>();
sc.AddTransient<EventRegisterTransient<IServerNodeService>,EventRegisterTransient<ServerNodeService>>();
sc.AddTransient<EventRegisterTransient<IServiceInfoService>,EventRegisterTransient<ServiceInfoService>>();
sc.AddTransient<EventRegisterTransient<ISysLogService>,EventRegisterTransient<SysLogService>>();
sc.AddTransient<EventRegisterTransient<IConfigService>>(x => x.GetService<IConfigService>);
sc.AddTransient<EventRegisterTransient<IAppService>>(x => x.GetService<IAppService>);
sc.AddTransient<EventRegisterTransient<IServerNodeService>>(x => x.GetService<IServerNodeService>);
sc.AddTransient<EventRegisterTransient<IServiceInfoService>>(x => x.GetService<IServiceInfoService>);
sc.AddTransient<EventRegisterTransient<ISysLogService>>(x => x.GetService<ISysLogService>);
}
}
}
79 changes: 9 additions & 70 deletions src/AgileConfig.Server.Service/SettingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,6 @@ public class SettingService : ISettingService
private readonly IUserRepository _userRepository;
private readonly IUserRoleRepository _userRoleRepository;

public const string SuperAdminId = "super_admin";
public const string SuperAdminUserName = "admin";

public const string DefaultEnvironment = "DEV,TEST,STAGING,PROD";
public const string DefaultEnvironmentKey = "environment";
public const string DefaultJwtSecretKey = "jwtsecret";

public SettingService(
ISettingRepository settingRepository,
IUserRepository userRepository,
Expand Down Expand Up @@ -84,28 +77,28 @@ public async Task<bool> SetSuperAdminPassword(string password)
password = Encrypt.Md5((password + newSalt));

var su = new User();
su.Id = SuperAdminId;
su.Id = SystemSettings.SuperAdminId;
su.Password = password;
su.Salt = newSalt;
su.Status = UserStatus.Normal;
su.Team = "";
su.CreateTime = DateTime.Now;
su.UserName = SuperAdminUserName;
su.UserName = SystemSettings.SuperAdminUserName;
await _userRepository.InsertAsync(su);

var userRoles = new List<UserRole>();
var ursa = new UserRole()
{
Id = Guid.NewGuid().ToString("N"),
Role = Role.SuperAdmin,
UserId = SuperAdminId
UserId = SystemSettings.SuperAdminId
};
userRoles.Add(ursa);
var ura = new UserRole()
{
Id = Guid.NewGuid().ToString("N"),
Role = Role.Admin,
UserId = SuperAdminId
UserId = SystemSettings.SuperAdminId
};
userRoles.Add(ura);

Expand All @@ -116,20 +109,20 @@ public async Task<bool> SetSuperAdminPassword(string password)

public async Task<bool> HasSuperAdmin()
{
var admin = await _userRepository.GetAsync(SuperAdminId);
var admin = await _userRepository.GetAsync(SystemSettings.SuperAdminId);

return admin != null;
}

public async Task<bool> InitDefaultEnvironment()
{
var env = await _settingRepository.GetAsync(DefaultEnvironmentKey);
var env = await _settingRepository.GetAsync(SystemSettings.DefaultEnvironmentKey);
if (env == null)
{
var setting = new Setting
{
Id = DefaultEnvironmentKey,
Value = DefaultEnvironment,
Id = SystemSettings.DefaultEnvironmentKey,
Value = SystemSettings.DefaultEnvironment,
CreateTime = DateTime.Now
};
await _settingRepository.InsertAsync(setting);
Expand All @@ -149,63 +142,9 @@ public void Dispose()

public async Task<string[]> GetEnvironmentList()
{
var env = await _settingRepository.GetAsync(DefaultEnvironmentKey);
var env = await _settingRepository.GetAsync(SystemSettings.DefaultEnvironmentKey);

return env?.Value?.ToUpper().Split(',') ?? [];
}

/// <summary>
/// 如果 配置文件或者环境变量没配置 JwtSetting:SecurityKey 则生成一个存库
/// </summary>
/// <returns></returns>
public bool TryInitJwtSecret()
{
var jwtSecretFromConfig = Global.Config["JwtSetting:SecurityKey"];
if (string.IsNullOrEmpty(jwtSecretFromConfig))
{
var jwtSecretSetting = _settingRepository.GetAsync(DefaultEnvironmentKey).Result;
if (jwtSecretSetting == null)
{
var setting = new Setting
{
Id = DefaultJwtSecretKey,
Value = GenreateJwtSecretKey(),
CreateTime = DateTime.Now
};

try
{
_ = _settingRepository.InsertAsync(setting).Result;
return true;
}
catch (Exception e)
{
//处理异常,防止多个实例第一次启动的时候,并发生成key值,发生异常,导致服务起不来
Console.WriteLine(e);
}

return false;
}
}
return true;
}

public string GetJwtTokenSecret()
{
var jwtSecretSetting = _settingRepository.GetAsync(DefaultEnvironmentKey).Result;
return jwtSecretSetting?.Value;
}

/// <summary>
/// 生成一个 jwt 加密的 key ,38位
/// </summary>
/// <returns></returns>
private string GenreateJwtSecretKey()
{
var guid1 = Guid.NewGuid().ToString("n");
var guid2 = Guid.NewGuid().ToString("n");

return guid1.Substring(0, 19) + guid2.Substring(0, 19);
}
}
}
Loading

0 comments on commit 5428e92

Please sign in to comment.