Merge pull request #96 from LD-Reborn/95-feature-create-users-table

95 feature create users table
This commit is contained in:
LD50
2025-10-09 11:51:09 +02:00
committed by GitHub
8 changed files with 113 additions and 43 deletions

View File

@@ -60,10 +60,23 @@ public class HomeController : Controller
} }
[HttpGet("Users")] [HttpGet("Users")]
public ActionResult Users() public async Task<ActionResult> UsersAsync()
{ {
return View(); IEnumerable<UserModel> users = await _ldap.ListUsersAsync();
List<UserTableViewModel> UserTableViewModels = [];
foreach (UserModel user in users)
{
UserTableViewModels.Add(new()
{
JpegPhoto = user.JpegPhoto ?? "",
Name = user.Cn ?? "",
Surname = user.Sn ?? "",
Title = user.Title ?? "",
Uid = user.Uid,
Workplace = user.Description?.Workplace ?? ""
});
} }
return View(new UsersIndexViewModel() { UserTableViewModels = UserTableViewModels }); }
[HttpPost("Login")] [HttpPost("Login")]
public async Task<ActionResult> Login(string username, string password) public async Task<ActionResult> Login(string username, string password)

View File

@@ -3,6 +3,7 @@ using Berufsschule_HAM.Services;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Novell.Directory.Ldap; using Novell.Directory.Ldap;
using Berufsschule_HAM.Models; using Berufsschule_HAM.Models;
using Berufsschule_HAM.Helpers;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
@@ -45,20 +46,17 @@ public class UsersController : Controller
} }
[HttpGet("Delete")] [HttpGet("Delete")]
public async Task<bool> Delete(string uid) public async Task<UsersDeleteRequestModel> Delete(string uid)
{
return await Task.Run(async () =>
{ {
try try
{ {
await _ldap.DeleteUserAsync(uid); await _ldap.DeleteUserAsync(uid);
return true; return new UsersDeleteRequestModel(true);
} }
catch (Exception) catch (Exception ex)
{ {
return false; return new UsersDeleteRequestModel(false, ex.Message);
} }
});
} }
[HttpGet("Create")] [HttpGet("Create")]
@@ -66,7 +64,7 @@ public class UsersController : Controller
{ {
try try
{ {
jpegPhoto ??= System.IO.File.ReadAllText("wwwroot/user_default.jpeg"); // TODO: cleanup - make this a config setting jpegPhoto ??= Convert.ToBase64String(System.IO.File.ReadAllBytes("wwwroot/user_default.jpeg")); // TODO: cleanup - make this a config setting
uid ??= sn.ToLower() + cn.ToLower(); uid ??= sn.ToLower() + cn.ToLower();
title ??= ""; title ??= "";
description ??= "{}"; description ??= "{}";

View File

@@ -1,4 +1,5 @@
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Text;
namespace Berufsschule_HAM.Helpers; namespace Berufsschule_HAM.Helpers;
@@ -16,4 +17,9 @@ public static class StringHelpers
input = input.Trim('-'); input = input.Trim('-');
return input; return input;
} }
public static string ToBase64String(string input)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(input));
}
} }

View File

@@ -1,3 +1,5 @@
using System.Text.Json;
namespace Berufsschule_HAM.Models; namespace Berufsschule_HAM.Models;
public class UserModel public class UserModel
@@ -5,7 +7,7 @@ public class UserModel
public required string Uid { get; set; } public required string Uid { get; set; }
public string? Cn { get; set; } public string? Cn { get; set; }
public string? Sn { get; set; } public string? Sn { get; set; }
public string? Description { get; set; } public UserDescription? Description { get; set; }
public string? JpegPhoto { get; set; } public string? JpegPhoto { get; set; }
public string? Title { get; set; } public string? Title { get; set; }
public string? UserPassword { get; set; } public string? UserPassword { get; set; }
@@ -14,13 +16,28 @@ public class UserModel
Uid = ldapData.GetValueOrDefault("uid") ?? throw new ArgumentException("UID is required"); Uid = ldapData.GetValueOrDefault("uid") ?? throw new ArgumentException("UID is required");
Cn = ldapData.GetValueOrDefault("cn"); Cn = ldapData.GetValueOrDefault("cn");
Sn = ldapData.GetValueOrDefault("sn"); Sn = ldapData.GetValueOrDefault("sn");
Description = ldapData.GetValueOrDefault("description"); string? description = ldapData.GetValueOrDefault("description");
Description = description != null ? JsonSerializer.Deserialize<UserDescription>(description) : null;
JpegPhoto = ldapData.GetValueOrDefault("jpegPhoto"); JpegPhoto = ldapData.GetValueOrDefault("jpegPhoto");
Title = ldapData.GetValueOrDefault("title"); Title = ldapData.GetValueOrDefault("title");
UserPassword = ldapData.GetValueOrDefault("userPassword"); UserPassword = ldapData.GetValueOrDefault("userPassword");
} }
} }
public class UserDescription
{
public required string BirthDate { get; set; }
public required UserAddress Address { get; set; }
public required string Workplace { get; set; }
}
public class UserAddress
{
public string? City { get; set; }
public string? Street { get; set; }
public string? StreetNr { get; set; }
}
public class UserAuthenticationResult public class UserAuthenticationResult
{ {
public required bool Success; public required bool Success;
@@ -34,3 +51,13 @@ public enum UserNotAuthenticatedReason
UserNotAuthorized, UserNotAuthorized,
UserLockedOut UserLockedOut
} }
public class UserTableViewModel
{
public required string JpegPhoto { get; set; }
public required string Uid { get; set; }
public required string Title { get; set; }
public required string Name { get; set; }
public required string Surname { get; set; }
public required string Workplace { get; set; }
}

View File

@@ -22,3 +22,10 @@ public class UsersModifyRequestModel
public string? JpegPhoto { get; set; } = null; public string? JpegPhoto { get; set; } = null;
public string? UserPassword { get; set; } = null; public string? UserPassword { get; set; } = null;
} }
public class UsersDeleteRequestModel(bool successful, string exception = "None")
{
public bool Success { get; set; } = successful;
public string? Exception { get; set; } = exception;
}

View File

@@ -0,0 +1,6 @@
namespace Berufsschule_HAM.Models;
public class UsersIndexViewModel
{
public required IEnumerable<UserTableViewModel> UserTableViewModels { get; set; }
}

View File

@@ -1,6 +1,7 @@
@using Microsoft.AspNetCore.Mvc.Localization @using Microsoft.AspNetCore.Mvc.Localization
@using Berufsschule_HAM.Models @using Berufsschule_HAM.Models
@model HomeIndexViewModel @using System.Buffers.Text
@model UsersIndexViewModel
@inject IViewLocalizer T @inject IViewLocalizer T
@{ @{
ViewData["Title"] = T["Users"]; ViewData["Title"] = T["Users"];
@@ -20,27 +21,33 @@
<table class="table table-striped align-middle"> <table class="table table-striped align-middle">
<thead> <thead>
<tr> <tr>
<th>User</th> <th style="width: 2rem;"></th>
<th>Asset ID</th> <th>User ID</th>
<th>Asset Name</th> <th>title</th>
<th>Location</th> <th>Name</th>
<th>Surname</th>
<th>Workplace</th>
<th>Action</th> <th>Action</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@* @{ @{
foreach (AssetsTableViewModel assetsTableViewModel in Model.AssetsTableViewModels) foreach (UserTableViewModel userTableViewModel in Model.UserTableViewModels)
{ {
<tr> <tr>
<td>@assetsTableViewModel.UserUID</td> <td>
<td>@assetsTableViewModel.AssetCn</td> <img class="rounded-circle user-icon" src="data:image/jpeg;base64,@userTableViewModel.JpegPhoto" alt="Photo" style="max-width:300px;" />
<td>@assetsTableViewModel.AssetName</td> </td>
<td>@assetsTableViewModel.LocationName</td> <td>@userTableViewModel.Uid</td>
<td>@userTableViewModel.Title</td>
<td>@userTableViewModel.Name</td>
<td>@userTableViewModel.Surname</td>
<td>@userTableViewModel.Workplace</td>
<td> <td>
<div class="d-flex gap-2"> <div class="d-flex gap-2">
<button class="btn btn-sm btn-primary">Update</button> <button class="btn btn-sm btn-primary">Update</button>
<button class="btn btn-sm btn-danger btn-delete" <button class="btn btn-sm btn-danger btn-delete"
data-asset-id="@assetsTableViewModel.AssetCn" data-user-id="@userTableViewModel.Uid"
data-bs-toggle="modal" data-bs-toggle="modal"
data-bs-target="#deleteModal"> data-bs-target="#deleteModal">
🗑️ Delete 🗑️ Delete
@@ -49,13 +56,13 @@
</td> </td>
</tr> </tr>
} }
} *@ }
</tbody> </tbody>
</table> </table>
</div> </div>
</div> </div>
<!-- Asset Delete Confirmation Modal --> <!-- User Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true"> <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered"> <div class="modal-dialog modal-dialog-centered">
<div class="modal-content"> <div class="modal-content">
@@ -64,7 +71,7 @@
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button> <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div> </div>
<div class="modal-body"> <div class="modal-body">
<p>Are you sure you want to delete the asset <strong id="assetName"></strong> (ID: <span id="assetId"></span>)?</p> <p>Are you sure you want to delete the user <strong id="userName"></strong> (ID: <span id="userId"></span>)?</p>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
@@ -77,21 +84,21 @@
</div> </div>
@* <script> <script>
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
const deleteModal = document.getElementById('deleteModal'); const deleteModal = document.getElementById('deleteModal');
let currentButton = null; // The delete button that opened the modal let currentButton = null; // The delete button that opened the modal
deleteModal.addEventListener('show.bs.modal', event => { deleteModal.addEventListener('show.bs.modal', event => {
currentButton = event.relatedTarget; // Button that triggered the modal currentButton = event.relatedTarget; // Button that triggered the modal
const assetId = currentButton.getAttribute('data-asset-id'); const userId = currentButton.getAttribute('data-user-id');
const assetName = currentButton.getAttribute('data-asset-name'); const userName = currentButton.getAttribute('data-user-name');
deleteModal.querySelector('#assetId').textContent = assetId; deleteModal.querySelector('#userId').textContent = userId;
deleteModal.querySelector('#assetName').textContent = assetName; deleteModal.querySelector('#userName').textContent = userName;
// Store the delete URL for later use // Store the delete URL for later use
deleteModal.querySelector('#deleteForm').dataset.url = `/Assets/Delete?cn=${assetId}`; deleteModal.querySelector('#deleteForm').dataset.url = `/Users/Delete?uid=${userId}`;
}); });
// Handle submit of deleteForm via fetch() // Handle submit of deleteForm via fetch()
@@ -100,7 +107,7 @@
e.preventDefault(); e.preventDefault();
const url = deleteForm.dataset.url; const url = deleteForm.dataset.url;
const assetId = deleteModal.querySelector('#assetId').textContent; const userId = deleteModal.querySelector('#userId').textContent;
try { try {
const response = await fetch(url, { const response = await fetch(url, {
@@ -109,7 +116,7 @@
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'Accept': 'application/json' 'Accept': 'application/json'
}//, }//,
//body: JSON.stringify({ id: assetId }) // Use this for Post requests with [FromBody] parameters like in /Groups/Update //body: JSON.stringify({ id: userId }) // Use this for Post requests with [FromBody] parameters like in /Groups/Update
}); });
const result = await response.json(); const result = await response.json();
@@ -124,7 +131,7 @@
row.classList.add('table-danger'); row.classList.add('table-danger');
setTimeout(() => row.remove(), 300); setTimeout(() => row.remove(), 300);
showToast('Asset deleted successfully', 'success'); showToast('User deleted successfully', 'success');
} else { } else {
showToast(`❌ ${result.reason}: ${result.exception || 'Unknown error'}`, 'danger'); showToast(`❌ ${result.reason}: ${result.exception || 'Unknown error'}`, 'danger');
} }
@@ -160,4 +167,4 @@
return container; return container;
} }
}); });
</script> *@ </script>

View File

@@ -35,3 +35,9 @@ body {
margin: 1rem 0 1rem 0; margin: 1rem 0 1rem 0;
padding: 2rem 4rem 2rem 4rem; padding: 2rem 4rem 2rem 4rem;
} }
.user-icon {
width: 2rem;
height: 2rem;
float: right;
}