From 9bf129f1ad06f7cfe2df3279e051364dfe7cc354 Mon Sep 17 00:00:00 2001 From: Marcel Baumgartner Date: Tue, 19 Mar 2024 17:31:15 +0100 Subject: [PATCH] Added automatic user creation on first start --- Moonlight/Core/CoreFeature.cs | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/Moonlight/Core/CoreFeature.cs b/Moonlight/Core/CoreFeature.cs index f1607b1c..a2d8a635 100644 --- a/Moonlight/Core/CoreFeature.cs +++ b/Moonlight/Core/CoreFeature.cs @@ -6,6 +6,7 @@ using MoonCore.Services; using MoonCoreUI.Services; using Moonlight.Core.Configuration; using Moonlight.Core.Database; +using Moonlight.Core.Database.Entities; using Moonlight.Core.Implementations.Diagnose; using Moonlight.Core.Interfaces; using Moonlight.Core.Models; @@ -136,6 +137,45 @@ public class CoreFeature : MoonlightFeature await pluginService.RegisterImplementation(new PluginsDiagnoseAction()); await pluginService.RegisterImplementation(new FeatureDiagnoseAction()); await pluginService.RegisterImplementation(new LogDiagnoseAction()); + + // Startup job services + var startupJobService = app.Services.GetRequiredService(); + + await startupJobService.AddJob("Default user creation", TimeSpan.FromSeconds(3), async provider => + { + using var scope = provider.CreateScope(); + + var configService = scope.ServiceProvider.GetRequiredService>(); + var userRepo = scope.ServiceProvider.GetRequiredService>(); + var authenticationProvider = scope.ServiceProvider.GetRequiredService(); + + if(!configService.Get().Authentication.UseDefaultAuthentication) + return; + + if(userRepo.Get().Any()) + return; + + // Define credentials + var password = Formatter.GenerateString(32); + var username = "adminowo"; + var email = "adminowo@example.com"; + + // Register user + var registeredUser = await authenticationProvider.Register(username, email, password); + + if (registeredUser == null) + { + Logger.Warn("Unable to create default user. Register function returned null"); + return; + } + + // Give user admin permissions + var user = userRepo.Get().First(x => x.Username == username); + user.Permissions = 9999; + userRepo.Update(user); + + Logger.Info($"Default login: Email: '{email}' Password: '{password}'"); + }); } public override Task OnUiInitialized(UiInitContext context)