using Berufsschule_HAM.Services; using Microsoft.AspNetCore.Mvc; using Novell.Directory.Ldap; using Berufsschule_HAM.Models; using System.Text.Json; [Route("[controller]")] public class GroupsController : Controller { private readonly LdapService _ldap; private readonly ILogger _logger; public GroupsController(LdapService ldap, ILogger logger) { _ldap = ldap; _logger = logger; } [HttpGet("Index")] public async Task> Index(GroupsIndexRequestModel requestModel) { string? cn = requestModel.Cn; List attributes = [.. _ldap.GroupsAttributes]; if (!requestModel.GidNumber) attributes.Remove("gidNumber"); if (!requestModel.Permissions) attributes.Remove("description"); IEnumerable groups; if (cn is null) { groups = await _ldap.ListGroupsAsync([.. attributes]); } else { try { groups = [await _ldap.GetGroupByCnAsync(cn, [.. attributes])]; } catch (InvalidOperationException) { groups = []; } } return groups; } [HttpGet("Delete")] public async Task Delete(string uid) { return await Task.Run(() => { try { _ldap.DeleteGroup(uid); return true; } catch (Exception) { return false; } }); } [HttpGet("Create")] public async Task Create(string cn, string gidNumber, GroupPermission[] permissions, string description) { try { description ??= JsonSerializer.Serialize(new GroupPermissions() {Permissions = []}); LdapAttributeSet attributeSet = [ new LdapAttribute("objectClass", "posixGroup"), new LdapAttribute("objectClass", "top"), new LdapAttribute("cn", cn), new LdapAttribute("gidNumber", gidNumber), new LdapAttribute( "description", JsonSerializer.Serialize(new GroupPermissions() { Permissions = [.. permissions] })) ]; await _ldap.CreateGroup(cn, attributeSet); return true; } catch (Exception ex) { _logger.LogError("Unable to create user: {ex.Message} - {ex.StackTrace}", [ex.Message, ex.StackTrace]); return false; } } [HttpPost("Update")] public async Task Update([FromBody]GroupsModifyRequestModel requestModel) { if (requestModel is null) { _logger.LogError("Unable to update a group because the GroupsModifyRequestModel is null"); return false; } string cn = requestModel.Cn; if (requestModel.NewCn is not null) { await _ldap.UpdateGroup(cn, "cn", requestModel.NewCn); cn = requestModel.NewCn; } if (requestModel.GidNumber is not null) { await _ldap.UpdateGroup(cn, "gidNumber", requestModel.GidNumber); } if (requestModel.Permissions is not null) { await _ldap.UpdateGroup(cn, "description", JsonSerializer.Serialize(requestModel.Permissions)); } return true; } }