Added user add modal and converted to dark mode

This commit is contained in:
2024-08-02 20:53:43 +02:00
parent 69c58e61fc
commit b57e1ca8cf
11 changed files with 197 additions and 26 deletions

View File

@@ -30,6 +30,6 @@ public class AuthMiddleware(IAuthService auth, IPermissionService perms) : IMidd
context.User.AddIdentity(new ClaimsIdentity(claims, HopFrameAuthentication<HopDbContextBase>.SchemeName)); context.User.AddIdentity(new ClaimsIdentity(claims, HopFrameAuthentication<HopDbContextBase>.SchemeName));
} }
await next.Invoke(context); await next?.Invoke(context);
} }
} }

View File

@@ -4,4 +4,8 @@ namespace HopFrame.Web.Model;
public class RegisterData : UserRegister { public class RegisterData : UserRegister {
public string RepeatedPassword { get; set; } public string RepeatedPassword { get; set; }
public bool PasswordsMatch => Password == RepeatedPassword;
public bool PasswordIsValid => Password.Length >= 8;
public bool EmailIsValid => Email.Contains('@') && Email.Contains('.') && !Email.EndsWith('.');
} }

View File

@@ -0,0 +1,5 @@
namespace HopFrame.Web.Model;
public class UserAdd : RegisterData {
public string Group { get; set; }
}

View File

@@ -0,0 +1,69 @@
@rendermode InteractiveServer
@using BlazorStrap
@using static Microsoft.AspNetCore.Components.Web.RenderMode
@using BlazorStrap.Shared.Components.Modal
@using BlazorStrap.V5
@using HopFrame.Database.Models
@using HopFrame.Security.Services
@using HopFrame.Web.Model
<BSModal DataId="add-user-modal" HideOnValidSubmit="true" IsStaticBackdrop="true" OnShow="() => _user = new()" @ref="_modal" ModalColor="BSColor.Dark">
<BSForm Model="_user" OnValidSubmit="Submit">
<BSModalHeader style="color: white">Add user</BSModalHeader>
<BSModalContent>
<div class="mb-3">
<BSLabel style="color: white">E-Mail</BSLabel>
<BSInput InputType="InputType.Email" @bind-Value="_user.Email" />
</div>
<div class="mb-3">
<BSLabel style="color: white">Username</BSLabel>
<BSInput InputType="InputType.Text" @bind-Value="_user.Username" />
</div>
<div class="mb-3">
<BSLabel style="color: white">Password</BSLabel>
<BSInput InputType="InputType.Password" @bind-Value="_user.Password" />
</div>
<div class="mb-3">
<BSLabel style="color: white">Primary group</BSLabel>
<BSInput InputType="InputType.Select" @bind-Value="_user.Group">
<option value="">Select group</option>
@foreach (var group in _allGroups) {
<option value="@group.Name">@group.Name.Replace("group.", "")</option>
}
</BSInput>
</div>
</BSModalContent>
<BSModalFooter>
<BSButton Target="add-user-modal" Color="BSColor.Dark">Cancel</BSButton>
<BSButton IsSubmit="true" Color="BSColor.Primary">Save</BSButton>
</BSModalFooter>
</BSForm>
</BSModal>
@inject IPermissionService Permissions
@code {
[Parameter] public Action<UserAdd> OnSubmit { get; set; }
private IList<PermissionGroup> _allGroups = new List<PermissionGroup>();
private UserAdd _user;
private BSModalBase _modal;
protected override async Task OnInitializedAsync() {
_allGroups = await Permissions.GetPermissionGroups();
}
public Task ShowAsync() {
return _modal.ShowAsync();
}
private void Submit() {
OnSubmit.Invoke(_user);
}
}

View File

@@ -6,12 +6,12 @@
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<div class="page"> <div class="page" style="background-color: #2c3034; position: relative; min-height: 100vh">
<nav> <nav>
<AdminMenu/> <AdminMenu/>
</nav> </nav>
<main> <main style="padding-top: 60px">
<article class="content px-4"> <article class="content px-4">
@Body @Body
<BSCore/> <BSCore/>

View File

@@ -1,11 +1,17 @@
@using BlazorStrap @rendermode InteractiveServer
@using BlazorStrap
@using BlazorStrap.V5 @using BlazorStrap.V5
@using HopFrame.Security.Claims
@using HopFrame.Web.Pages.Administration.Components
@using HopFrame.Web.Services
@using static Microsoft.AspNetCore.Components.Web.RenderMode
<BSNavbar Color="BSColor.Light"> <BSNavbar Color="BSColor.Dark" IsDark="true" IsFixedTop="true">
<BSContainer Container="Container.Fluid"> <BSContainer Container="Container.Fluid">
<BSNavbarBrand> <BSNavbarBrand>
@*<img src="logo.svg" alt="logo" width="30" class="d-inline-block align-text-top"/>*@ <img src="/favicon.png" alt="logo" width="30" class="d-inline-block align-text-top"/>
HopFrame HopFrame
</BSNavbarBrand> </BSNavbarBrand>
<BSCollapse IsInNavbar="true"> <BSCollapse IsInNavbar="true">
@@ -18,6 +24,14 @@
<BSNavItem IsActive="IsNavItemActive(nav.Key)" Url="@nav.Key">@nav.Value</BSNavItem> <BSNavItem IsActive="IsNavItemActive(nav.Key)" Url="@nav.Key">@nav.Value</BSNavItem>
} }
</BSNav> </BSNav>
<span style="margin-left: auto; line-height: 100%; color: white">
logged in as @Context?.User.Username
</span>
<BSButton DataId="logout" Size="Size.ExtraSmall" OnClick="Logout" Color="BSColor.Dark">
<HopIconDisplay Type="HopIconDisplay.HopIcon.Logout"/>
</BSButton>
<BSTooltip Placement="Placement.Bottom" Target="logout" ContentAlwaysRendered="false">logout</BSTooltip>
</Content> </Content>
</BSCollapse> </BSCollapse>
</BSContainer> </BSContainer>
@@ -25,6 +39,8 @@
@inject NavigationManager Navigator @inject NavigationManager Navigator
@inject ITokenContext Context
@inject IAuthService Auth
@code { @code {
public static IDictionary<string, string> Subpages = new Dictionary<string, string> { public static IDictionary<string, string> Subpages = new Dictionary<string, string> {
@@ -35,4 +51,8 @@
public bool IsNavItemActive(string element) { public bool IsNavItemActive(string element) {
return Navigator.Uri.Contains(element); return Navigator.Uri.Contains(element);
} }
private async void Logout() {
Navigator.NavigateTo("login?redirect=/administration", true);
}
} }

View File

@@ -16,32 +16,32 @@
<PageTitle>Edit @User.Username</PageTitle> <PageTitle>Edit @User.Username</PageTitle>
<AuthorizedView Permission="@AdminPermissions.EditUsers" RedirectIfUnauthorized="@ConstructRedirectUrl()"/> <AuthorizedView Permission="@AdminPermissions.EditUsers" RedirectIfUnauthorized="@ConstructRedirectUrl()"/>
<h3>Edit @User.Username (@User.Id)</h3> <h3 style="color: white">Edit @User.Username (@User.Id)</h3>
<EditForm EditContext="_context" OnValidSubmit="OnEdit" FormName="register-form" class="edit-form"> <EditForm EditContext="_context" OnValidSubmit="OnEdit" FormName="register-form" class="edit-form">
@*<AntiforgeryToken />*@ @*<AntiforgeryToken />*@
<div class="field-wrapper" style="max-width: 750px"> <div class="field-wrapper" style="max-width: 750px">
<div class="mb-3"> <div class="mb-3">
<label for="id" class="form-label">Registered At</label> <label for="id" class="form-label" style="color: white">Registered At</label>
<input type="text" class="form-control" id="id" disabled value="@User.CreatedAt"/> <input type="text" class="form-control" id="id" disabled value="@User.CreatedAt"/>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="email" class="form-label">Email address</label> <label for="email" class="form-label" style="color: white">Email address</label>
<InputText type="email" class="form-control" id="email" required @bind-Value="User.Email"/> <InputText type="email" class="form-control" id="email" required @bind-Value="User.Email"/>
<ValidationMessage For="() => User.Email"/> <ValidationMessage For="() => User.Email"/>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="username" class="form-label">Username</label> <label for="username" class="form-label" style="color: white">Username</label>
<InputText type="text" class="form-control" id="username" required @bind-Value="User.Username"/> <InputText type="text" class="form-control" id="username" required @bind-Value="User.Username"/>
<ValidationMessage For="() => User.Username"/> <ValidationMessage For="() => User.Username"/>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="password" class="form-label">Password</label> <label for="password" class="form-label" style="color: white">Password</label>
<InputText type="password" class="form-control" id="password" required @bind-Value="_password"/> <InputText type="password" class="form-control" id="password" required @bind-Value="_password"/>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="groups" class="form-label">Groups</label> <label for="groups" class="form-label" style="color: white">Groups</label>
<ul class="list-group" id="groups"> <ul class="list-group" id="groups">
<li class="list-group-item"> <li class="list-group-item">
<ul class="list-group list-group-flush"> <ul class="list-group list-group-flush">
@@ -74,7 +74,7 @@
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label for="permissions" class="form-label">Permissions</label> <label for="permissions" class="form-label" style="color: white">Permissions</label>
<ul class="list-group" id="permissions"> <ul class="list-group" id="permissions">
<li class="list-group-item"> <li class="list-group-item">
<ul class="list-group list-group-flush"> <ul class="list-group list-group-flush">

View File

@@ -13,11 +13,14 @@
@using Microsoft.AspNetCore.Components.Web @using Microsoft.AspNetCore.Components.Web
@using HopFrame.Web.Components @using HopFrame.Web.Components
@using BlazorStrap.V5 @using BlazorStrap.V5
@using HopFrame.Web.Model
@using HopFrame.Web.Pages.Administration.Components @using HopFrame.Web.Pages.Administration.Components
<PageTitle>Users</PageTitle> <PageTitle>Users</PageTitle>
<AuthorizedView Permission="@AdminPermissions.ViewUsers" RedirectIfUnauthorized="login?redirect=/administration/users"/> <AuthorizedView Permission="@AdminPermissions.ViewUsers" RedirectIfUnauthorized="login?redirect=/administration/users"/>
<UserAddModal @ref="_userAddModal" OnSubmit="CreateUser"/>
<div class="title"> <div class="title">
<h3> <h3>
Users administration Users administration
@@ -26,13 +29,14 @@
</span> </span>
</h3> </h3>
<form class="d-flex" role="search" @onsubmit="Search"> <form class="d-flex" role="search" @onsubmit="Search" id="search">
<input class="form-control me-2 input-dark" type="search" placeholder="Search" aria-label="Search" @bind="_searchText"> <input class="form-control me-2 input-dark" type="search" placeholder="Search" aria-label="Search" @bind="_searchText">
<BSButton Color="BSColor.Success" IsOutlined="true" type="submit">Search</BSButton> <BSButton Color="BSColor.Success" IsOutlined="true" type="submit">Search</BSButton>
</form> </form>
<BSButton IsSubmit="false" Color="BSColor.Success" Target="add-user" OnClick="() => _userAddModal.ShowAsync()">Add User</BSButton>
</div> </div>
<BSTable IsStriped="true" IsHoverable="true"> <BSTable IsStriped="true" IsHoverable="true" IsDark="true" Color="BSColor.Dark">
<BSTHead> <BSTHead>
<BSTR> <BSTR>
<BSTD>#</BSTD> <BSTD>#</BSTD>
@@ -97,7 +101,7 @@
@code { @code {
private IList<User> _users = new List<User>(); private IList<User> _users = new List<User>();
private readonly IDictionary<Guid, PermissionGroup> _userGroups = new Dictionary<Guid, PermissionGroup>(); private IDictionary<Guid, PermissionGroup> _userGroups = new Dictionary<Guid, PermissionGroup>();
private OrderType _currentOrder = OrderType.None; private OrderType _currentOrder = OrderType.None;
private OrderDirection _currentOrderDirection = OrderDirection.Asc; private OrderDirection _currentOrderDirection = OrderDirection.Asc;
@@ -107,6 +111,8 @@
private bool _hasEditPrivileges = false; private bool _hasEditPrivileges = false;
private bool _hasDeletePrivileges = false; private bool _hasDeletePrivileges = false;
private UserAddModal _userAddModal;
protected override async Task OnInitializedAsync() { protected override async Task OnInitializedAsync() {
_users = await UserService.GetUsers(); _users = await UserService.GetUsers();
@@ -119,8 +125,16 @@
_hasDeletePrivileges = await PermissionsService.HasPermission(AdminPermissions.DeleteUsers, Auth.User.Id); _hasDeletePrivileges = await PermissionsService.HasPermission(AdminPermissions.DeleteUsers, Auth.User.Id);
} }
private void Reload() { private async Task Reload() {
Navigator.Refresh(true); _users = new List<User>();
_userGroups = new Dictionary<Guid, PermissionGroup>();
_users = await UserService.GetUsers();
foreach (var user in _users) {
var groups = await PermissionsService.GetUserPermissionGroups(user);
_userGroups.Add(user.Id, groups.FirstOrDefault());
}
} }
private async Task Search() { private async Task Search() {
@@ -176,6 +190,9 @@
if (result.IsConfirmed) { if (result.IsConfirmed) {
await UserService.DeleteUser(user); await UserService.DeleteUser(user);
await Reload();
StateHasChanged();
await Alerts.FireAsync(new SweetAlertOptions { await Alerts.FireAsync(new SweetAlertOptions {
Title = "Deleted!", Title = "Deleted!",
@@ -183,8 +200,6 @@
Timer = 1500, Timer = 1500,
ShowConfirmButton = false ShowConfirmButton = false
}); });
Reload();
} }
} }
@@ -204,4 +219,51 @@
Desc = 1 Desc = 1
} }
private async void CreateUser(UserAdd newUser) {
string errorMessage = null;
if (_users.Any(user => user.Username == newUser.Username)) {
errorMessage = "Username is already taken!";
}
else if (_users.Any(user => user.Email == newUser.Email)) {
errorMessage = "E-Mail is already taken!";
}
else if (!newUser.PasswordIsValid) {
errorMessage = "The password needs to be at least 8 characters long!";
}
else if (!newUser.EmailIsValid) {
errorMessage = "Invalid E-Mail address!";
}
if (!string.IsNullOrWhiteSpace(errorMessage)) {
await Alerts.FireAsync(new SweetAlertOptions {
Title = "Something went wrong!",
Text = errorMessage,
Icon = SweetAlertIcon.Error,
ShowConfirmButton = false,
Timer = 1500
});
return;
}
var user = await UserService.AddUser(newUser);
if (!string.IsNullOrWhiteSpace(newUser.Group)) {
await PermissionsService.AddPermission(user, newUser.Group);
}
await Reload();
StateHasChanged();
await Alerts.FireAsync(new SweetAlertOptions {
Title = "New user added!",
Icon = SweetAlertIcon.Success,
ShowConfirmButton = false,
Timer = 1500
});
}
} }

View File

@@ -1,13 +1,22 @@
.title { .title {
display: flex; display: flex;
flex-direction: row; flex-direction: row;
justify-content: space-between; gap: 10px;
margin-bottom: 10px;
}
#search {
margin-left: auto;
} }
th, h3 { th, h3 {
user-select: none; user-select: none;
} }
h3 {
color: white;
}
.reload, .sorter { .reload, .sorter {
cursor: pointer; cursor: pointer;
} }

View File

@@ -87,15 +87,15 @@
private void ValidateForm(object sender, ValidationRequestedEventArgs e) { private void ValidateForm(object sender, ValidationRequestedEventArgs e) {
_messages.Clear(); _messages.Clear();
if (RegisterData.Password != RegisterData.RepeatedPassword) { if (!RegisterData.PasswordsMatch) {
_messages.Add(() => RegisterData.RepeatedPassword, "Passwords doesn't mach"); _messages.Add(() => RegisterData.RepeatedPassword, "Passwords doesn't mach");
} }
if (RegisterData.Password.Length < 8) { if (!RegisterData.PasswordIsValid) {
_messages.Add(() => RegisterData.Password, "Password needs to be at least 8 characters long"); _messages.Add(() => RegisterData.Password, "Password needs to be at least 8 characters long");
} }
if (!RegisterData.Email.Contains("@") || !RegisterData.Email.Contains(".") || RegisterData.Email.EndsWith(".")) { if (!RegisterData.EmailIsValid) {
_messages.Add(() => RegisterData.Email, "Please enter a valid email address"); _messages.Add(() => RegisterData.Email, "Please enter a valid email address");
} }
} }

View File

@@ -116,6 +116,7 @@ public class AuthService<TDbContext>(
old.UserId == token.UserId && old.UserId == token.UserId &&
old.CreatedAt + HopFrameAuthentication<TDbContext>.AccessTokenTime < DateTime.Now) old.CreatedAt + HopFrameAuthentication<TDbContext>.AccessTokenTime < DateTime.Now)
.ToList(); .ToList();
if (oldAccessTokens.Count != 0)
context.Tokens.RemoveRange(oldAccessTokens); context.Tokens.RemoveRange(oldAccessTokens);
var oldRefreshTokens = context.Tokens var oldRefreshTokens = context.Tokens
@@ -125,6 +126,7 @@ public class AuthService<TDbContext>(
old.UserId == token.UserId && old.UserId == token.UserId &&
old.CreatedAt + HopFrameAuthentication<TDbContext>.RefreshTokenTime < DateTime.Now) old.CreatedAt + HopFrameAuthentication<TDbContext>.RefreshTokenTime < DateTime.Now)
.ToList(); .ToList();
if (oldRefreshTokens.Count != 0)
context.Tokens.RemoveRange(oldRefreshTokens); context.Tokens.RemoveRange(oldRefreshTokens);
await context.SaveChangesAsync(); await context.SaveChangesAsync();