@page "/FirstTimeSetup/Administrator" @using LANCommander.Server.Services.Exceptions @layout FirstTimeSetupLayout @inject SetupService SetupService @inject RoleService RoleService @inject UserService UserService @inject NavigationManager NavigationManager @inject IMessageService MessageService @inject ILogger Logger Create Administrator User - First Time Setup
To get started, you will need to create an administrator user.
@code { [CascadingParameter] FirstTimeSetupLayout Layout { get; set; } FirstTimeSetupModel Model = new(); bool Loading; protected override async Task OnInitializedAsync() { await Layout.ChangeCurrentStep(FirstTimeSetupStep.Administrator); var isSetupInitialized = await SetupService.IsSetupInitialized(); if (isSetupInitialized) NavigationManager.NavigateTo("/"); } async Task CreateAdministratorUser() { Loading = true; StateHasChanged(); await Task.Yield(); if (Model.Password != Model.PasswordConfirm) { MessageService.Error("Passwords do not match"); Loading = false; StateHasChanged(); await Task.Yield(); return; } try { var role = await RoleService.GetAsync(RoleService.AdministratorRoleName); try { if (role == null) role = await RoleService.AddAsync(new Role { Name = RoleService.AdministratorRoleName, }); } catch (AddRoleException ex) { foreach (var error in ex.IdentityResult.Errors) { MessageService.Error(error.Description); } Loading = false; StateHasChanged(); await Task.Yield(); return; } var administrators = await RoleService.GetUsersAsync(RoleService.AdministratorRoleName); if (administrators != null && administrators.Any()) NavigationManager.NavigateTo("/"); else { var user = Activator.CreateInstance(); user.Approved = true; user.ApprovedOn = DateTime.UtcNow; user.UserName = Model.Username; try { await UserService.AddAsync(user, bypassPasswordPolicy: true, Model.Password); await UserService.AddToRolesAsync(user.UserName, [RoleService.AdministratorRoleName]); Logger?.LogInformation("Administrator created a new account with password."); await MessageService.SuccessAsync("Setup completed! Redirecting...", 3); Loading = false; NavigationManager.NavigateTo("/"); } catch (UserRegistrationException ex) { foreach (var error in ex.IdentityResult.Errors) { MessageService.Error(error.Description); } Loading = false; StateHasChanged(); await Task.Yield(); } catch (AddRoleException ex) { foreach (var error in ex.IdentityResult.Errors) { MessageService.Error(error.Description); } Loading = false; StateHasChanged(); await Task.Yield(); } } } catch (Exception ex) { Logger?.LogError(ex, "Could not create administrator"); MessageService.Error($"Could not create administrator: {ex.Message}", 10); } Loading = false; } }