mirror of
https://github.com/LD-Reborn/Berufsschule_HAM.git
synced 2025-12-20 06:51:55 +00:00
Added LDAP migrations, made CreateObject async, moved LdapOptions to Models, fixed user password not hashed on user creation
This commit is contained in:
@@ -1,13 +0,0 @@
|
||||
namespace Berufsschule_HAM.Services;
|
||||
public class LdapOptions
|
||||
{
|
||||
public required string Host { get; set; }
|
||||
public int Port { get; set; } = 389;
|
||||
public bool UseSsl { get; set; } = false;
|
||||
public required string BindDn { get; set; }
|
||||
public required string BindPassword { get; set; }
|
||||
public required string BaseDn { get; set; }
|
||||
public string AssetsOu { get; set; } = "ou=assets";
|
||||
public string LocationsOu { get; set; } = "ou=locations";
|
||||
public string UsersOu { get; set; } = "ou=users";
|
||||
}
|
||||
@@ -4,15 +4,16 @@ using Berufsschule_HAM.Models;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Berufsschule_HAM.Services;
|
||||
public partial class LdapService : IDisposable
|
||||
{
|
||||
private readonly LdapOptions _opts;
|
||||
private readonly LdapConfig _opts;
|
||||
private readonly LdapConnection _conn;
|
||||
private ILogger _logger;
|
||||
|
||||
public LdapService(IOptions<LdapOptions> options, ILogger<LdapService> logger)
|
||||
public LdapService(IOptions<LdapConfig> options, ILogger<LdapService> logger)
|
||||
{
|
||||
_opts = options.Value;
|
||||
_conn = new LdapConnection { SecureSocketLayer = _opts.UseSsl };
|
||||
@@ -39,9 +40,11 @@ public partial class LdapService : IDisposable
|
||||
await _conn.BindAsync(_opts.BindDn, _opts.BindPassword);
|
||||
}
|
||||
|
||||
private string AssetsBaseDn => string.IsNullOrEmpty(_opts.AssetsOu) ? _opts.BaseDn : $"{_opts.AssetsOu},{_opts.BaseDn}";
|
||||
private string LocationsBaseDn => string.IsNullOrEmpty(_opts.LocationsOu) ? _opts.BaseDn : $"{_opts.LocationsOu},{_opts.BaseDn}";
|
||||
private string UsersBaseDn => string.IsNullOrEmpty(_opts.UsersOu) ? _opts.BaseDn : $"{_opts.UsersOu},{_opts.BaseDn}";
|
||||
public string AssetsBaseDn => string.IsNullOrEmpty(_opts.AssetsOu) ? _opts.BaseDn : $"{_opts.AssetsOu},{_opts.BaseDn}";
|
||||
public string LocationsBaseDn => string.IsNullOrEmpty(_opts.LocationsOu) ? _opts.BaseDn : $"{_opts.LocationsOu},{_opts.BaseDn}";
|
||||
public string UsersBaseDn => string.IsNullOrEmpty(_opts.UsersOu) ? _opts.BaseDn : $"{_opts.UsersOu},{_opts.BaseDn}";
|
||||
public string GroupsBaseDn => string.IsNullOrEmpty(_opts.GroupsOu) ? _opts.BaseDn : $"{_opts.GroupsOu},{_opts.BaseDn}";
|
||||
public string MigrationsBaseDn => string.IsNullOrEmpty(_opts.MigrationsOu) ? _opts.BaseDn : $"{_opts.MigrationsOu},{_opts.BaseDn}";
|
||||
|
||||
public async Task<IEnumerable<Dictionary<string, string>>> ListLocationsAsync()
|
||||
{
|
||||
@@ -53,6 +56,41 @@ public partial class LdapService : IDisposable
|
||||
return await ListObjectBy(UsersBaseDn, "", ["cn", "sn", "title", "uid", "jpegPhoto", "userPassword", "description"]);
|
||||
}
|
||||
|
||||
public async Task<MigrationModel> GetMigrationVersionAsync()
|
||||
{
|
||||
Dictionary<string, string> objects;
|
||||
try
|
||||
{
|
||||
objects = (await ListObjectBy(_opts.BaseDn, _opts.MigrationsOu, ["description"])).First();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
objects = [];
|
||||
}
|
||||
return new MigrationModel(objects);
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateMigrationVersionAsync(MigrationModel migrationModel)
|
||||
{
|
||||
await ConnectAndBind();
|
||||
try
|
||||
{
|
||||
string dn = MigrationsBaseDn; //PrependRDN($"", MigrationsBaseDn);
|
||||
string targetText = JsonSerializer.Serialize(migrationModel);
|
||||
_logger.LogInformation("Setting the LDAP migration description to {targetText} for {dn}", [targetText, dn]);
|
||||
var modification = new LdapModification(
|
||||
LdapModification.Replace,
|
||||
new LdapAttribute("description", targetText)
|
||||
);
|
||||
await _conn.ModifyAsync(dn, modification);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<UserModel>> ListUsersAsync(string[] attributes)
|
||||
{
|
||||
List<UserModel> returnValue = [];
|
||||
@@ -85,20 +123,20 @@ public partial class LdapService : IDisposable
|
||||
return await ListObjectBy(AssetsBaseDn, "(objectClass=device)", ["CN", "description", "l", "owner", "serialNumber"]);
|
||||
}
|
||||
|
||||
public void CreateUser(string uid, LdapAttributeSet attributeSet)
|
||||
public async Task CreateUser(string uid, LdapAttributeSet attributeSet)
|
||||
{
|
||||
string dn = PrependRDN($"uid={uid}", UsersBaseDn);
|
||||
CreateObject(dn, attributeSet);
|
||||
await CreateObject(dn, attributeSet);
|
||||
}
|
||||
|
||||
public void CreateAsset(LdapAttributeSet attributeSet)
|
||||
public async Task CreateAsset(LdapAttributeSet attributeSet)
|
||||
{
|
||||
CreateObject(AssetsBaseDn, attributeSet);
|
||||
await CreateObject(AssetsBaseDn, attributeSet);
|
||||
}
|
||||
|
||||
public void CreateLocation(LdapAttributeSet attributeSet)
|
||||
public async Task CreateLocation(LdapAttributeSet attributeSet)
|
||||
{
|
||||
CreateObject(LocationsBaseDn, attributeSet);
|
||||
await CreateObject(LocationsBaseDn, attributeSet);
|
||||
}
|
||||
|
||||
public async Task<UserAuthenticationResult> AuthenticateUser(string username, string password)
|
||||
@@ -201,13 +239,12 @@ public partial class LdapService : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public async void DeleteObjectByDn(string dn)
|
||||
{
|
||||
await _conn.DeleteAsync(dn);
|
||||
}
|
||||
|
||||
public async void CreateObject(string dn, LdapAttributeSet attributeSet)
|
||||
public async Task CreateObject(string dn, LdapAttributeSet attributeSet)
|
||||
{
|
||||
await ConnectAndBind();
|
||||
LdapEntry ldapEntry = new(dn, attributeSet);
|
||||
|
||||
115
src/Services/MigrationService.cs
Normal file
115
src/Services/MigrationService.cs
Normal file
@@ -0,0 +1,115 @@
|
||||
using Berufsschule_HAM.Models;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Novell.Directory.Ldap;
|
||||
using System.Reflection;
|
||||
namespace Berufsschule_HAM.Services;
|
||||
|
||||
public class MigrationService
|
||||
{
|
||||
private readonly LdapService _ldapService;
|
||||
private readonly ILogger<MigrationService> _logger;
|
||||
private readonly LdapConfig _ldapConfig;
|
||||
|
||||
public MigrationService(LdapService ldapService, ILogger<MigrationService> logger, IOptions<LdapConfig> ldapConfig)
|
||||
{
|
||||
_ldapService = ldapService;
|
||||
_logger = logger;
|
||||
_ldapConfig = ldapConfig.Value;
|
||||
MigrateAsync().ConfigureAwait(false);
|
||||
}
|
||||
public async Task<MigrationModel> MigrateAsync()
|
||||
{
|
||||
MigrationModel migrationModel = await _ldapService.GetMigrationVersionAsync();
|
||||
int version = migrationModel.Version;
|
||||
string dc = _ldapConfig.BaseDn.Split("=")[1];
|
||||
|
||||
List<MethodInfo> updateMethods = [.. typeof(MigrationService)
|
||||
.GetMethods(BindingFlags.Public | BindingFlags.Static)
|
||||
.Where(m => m.Name.StartsWith("UpdateFrom")
|
||||
&& m.Name.EndsWith("Async")
|
||||
&& m.ReturnType == typeof(Task<int>))
|
||||
.OrderBy(m => int.Parse(m.Name["UpdateFrom".Length..^5]))]; // TODO remove magic number ("5" -> global constant)
|
||||
|
||||
foreach (var method in updateMethods)
|
||||
{
|
||||
int methodVersion = int.Parse(method.Name["UpdateFrom".Length..^5]); // TODO TODO remove magic number ("5" -> global constant)
|
||||
if (methodVersion >= version)
|
||||
{
|
||||
_logger.LogInformation("Migrating LDAP database from version {version} to {methodVersion}", [version, methodVersion + 1]);
|
||||
if (method is null) { continue; }
|
||||
#pragma warning disable CS8605 // Unboxing a possibly null value.
|
||||
version = (int)method.Invoke(null, [_ldapService]);
|
||||
#pragma warning restore CS8605 // Unboxing a possibly null value.
|
||||
}
|
||||
}
|
||||
|
||||
if (version != migrationModel.Version)
|
||||
{
|
||||
migrationModel.Version = version;
|
||||
await _ldapService.UpdateMigrationVersionAsync(migrationModel);
|
||||
}
|
||||
|
||||
return migrationModel;
|
||||
}
|
||||
|
||||
public static async Task<int> UpdateFrom0Async(LdapService ldapService)
|
||||
{
|
||||
LdapAttributeSet usersAttributes =
|
||||
[
|
||||
new("objectClass", "organizationalUnit"),
|
||||
new("objectClass", "top"),
|
||||
new("ou", "users")
|
||||
];
|
||||
await TryCreateObjectIgnoreAlreadyExists(ldapService, ldapService.UsersBaseDn, usersAttributes);
|
||||
LdapAttributeSet locationsAttributes =
|
||||
[
|
||||
new("objectClass", "organizationalUnit"),
|
||||
new("objectClass", "top"),
|
||||
new("ou", "locations")
|
||||
];
|
||||
await TryCreateObjectIgnoreAlreadyExists(ldapService, ldapService.LocationsBaseDn, locationsAttributes);
|
||||
LdapAttributeSet groupsAttributes =
|
||||
[
|
||||
new("objectClass", "organizationalUnit"),
|
||||
new("objectClass", "top"),
|
||||
new("ou", "groups")
|
||||
];
|
||||
await TryCreateObjectIgnoreAlreadyExists(ldapService, ldapService.GroupsBaseDn, groupsAttributes);
|
||||
LdapAttributeSet assetsAttributes =
|
||||
[
|
||||
new("objectClass", "organizationalUnit"),
|
||||
new("objectClass", "top"),
|
||||
new("ou", "assets")
|
||||
];
|
||||
await TryCreateObjectIgnoreAlreadyExists(ldapService, ldapService.AssetsBaseDn, assetsAttributes);
|
||||
LdapAttributeSet migrationsAttributes =
|
||||
[
|
||||
new("objectClass", "organizationalUnit"),
|
||||
new("objectClass", "top"),
|
||||
new("ou", "migrations"),
|
||||
new("description", "{\"Version\": 1}")
|
||||
];
|
||||
await TryCreateObjectIgnoreAlreadyExists(ldapService, ldapService.MigrationsBaseDn, migrationsAttributes);
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static async Task TryCreateObjectIgnoreAlreadyExists(LdapService ldapService, string dn, LdapAttributeSet ldapAttributes)
|
||||
{
|
||||
try
|
||||
{
|
||||
await ldapService.CreateObject(dn, ldapAttributes);
|
||||
}
|
||||
catch (LdapException ex)
|
||||
{
|
||||
if (ex.ResultCode != LdapException.EntryAlreadyExists)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user