using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using PSTW_CentralSystem.DBContext; using PSTW_CentralSystem.Models; using System.Reflection; using static System.Runtime.InteropServices.JavaScript.JSType; using System.Security.Cryptography; using System.Text; using System.Text.Json; namespace PSTW_CentralSystem.Controllers.API { [ApiController] [Route("[controller]")] public class AdminAPI : Controller { private readonly ILogger _logger; private readonly IdentityDBContext _authDbContext; private readonly UserManager _userManager; private readonly SignInManager _signInManager; // Communication Key for API. Not API authentication key private readonly string _commKey = "LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUF4NW42anlkNlpTYzZNSE1Zem9qaApUbldpYTIra2pud2ZNbVhpSWlyK0RadjM2cEVGMGhRUWFLaWpaMWtyMGNiT25Ha2d2QnNwTzNiYkFua0E3SWwzCk4zM3NNYWdQV0JOQzZyVm1jT04zNEhDSWJCM0hvQXFYQUtkSHFUOGZneklMRzFhRzdxK2h4RDZhZzZsemhTMnEKdDA1bHdNc0hONWpOdmVNNnFWalRnTVB4aEFOMUhnUTkrd1lRWFh5bnZYYUo5OUNySHBqS21WdUt2VUh6WXdlRwp6SnBtYXZOclc4bE9oM1lMeVNuUVU5bjRrdURubGc1OWNHeUtKbzJ2YUxZbll4MkR1ZDNabzBXMHRMWGd0dlQyCjVXdVFsY0NVbldvaVpBV1JBTGI3anRpcTF0MGY5eVBiV2gxYXpMMjFoL3QvckJUMXNCL2FQd2kzRCt3MnBUR00KeVFJREFRQUIKLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg=="; public AdminAPI(ILogger logger, IdentityDBContext authDbContext, UserManager userManager, SignInManager signInManager) { _logger = logger; _authDbContext = authDbContext; _userManager = userManager; _signInManager = signInManager; } [HttpPost("GetClassAndMethodInformation")] public async Task GetClassAndMethodInformation(string moduleName) { var controllerAndMethodList = new object(); // Get the assembly containing the controllers var assembly = Assembly.GetExecutingAssembly(); // Get all types in the assembly (controllers will typically be in the "Controllers" namespace) //var controllerTypes = await Task.Run(() => assembly.GetTypes().Where(type => typeof(ControllerBase).IsAssignableFrom(type) && type.IsClass && type.CompanyName.Contains("Controller") && type.CompanyName != "AdminController") .ToList()); var controllerTypes = await Task.Run(() => assembly.GetTypes().Where(type => typeof(ControllerBase).IsAssignableFrom(type) && !type.Name.Contains("API") && type.IsClass && type.Name.Contains(moduleName)).FirstOrDefault()); // Iterate over the controller types and get their methods var methods = controllerTypes?.GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(m => m.DeclaringType == controllerTypes) // Filter methods declared directly in the controller (ignoring inherited ones) .Select(m => m.Name) // Get the method names .ToList(); controllerAndMethodList = (new { Controller = controllerTypes?.Name, Methods = methods }); // Return the list as JSON return Json(controllerAndMethodList); } [HttpPost("GetListClassAndMethodInformation")] public async Task GetListClassAndMethodInformation() { var controllerAndMethodList = new List(); // Get the assembly containing the controllers var assembly = Assembly.GetExecutingAssembly(); // Get all types in the assembly (controllers will typically be in the "Controllers" namespace) //var controllerTypes = await Task.Run(() => assembly.GetTypes().Where(type => typeof(ControllerBase).IsAssignableFrom(type) && type.IsClass && type.CompanyName.Contains("Controller") && type.CompanyName != "AdminController") .ToList()); var controllerTypes = await Task.Run(() => assembly.GetTypes().Where(type => typeof(ControllerBase).IsAssignableFrom(type) && type.IsClass && !type.Name.Contains("API") && !type.Name.Contains("Admin")).ToList()); // Iterate over the controller types and get their methods foreach (var controllerType in controllerTypes) { var methods = controllerType?.GetMethods(BindingFlags.Public | BindingFlags.Instance) .Where(m => m.DeclaringType == controllerType) // Filter methods declared directly in the controller (ignoring inherited ones) .Select(m => m.Name) // Get the method names .ToList(); controllerAndMethodList.Add(new { Controller = controllerType?.Name.Replace("Controller", string.Empty), Methods = methods }); } // Return the list as JSON return Json(controllerAndMethodList); } [HttpPost("GetUserList")] public async Task GetUserList() { try { var user = await _userManager.GetUserAsync(User); var userRole = await _userManager.GetRolesAsync(user??new UserModel()); List userInfo = new List(); if (userRole == null || userRole.Count == 0) { // Fetch all users excluding those with roles SuperAdmin or SystemAdmin var allUsers = await _authDbContext.Users .Include(u => u.Department) .ToListAsync(); foreach (var u in allUsers) { var roles = await _userManager.GetRolesAsync(u); if (!roles.Contains("SuperAdmin") && !roles.Contains("SystemAdmin")) { userInfo.Add(u); } } } else { userInfo = await _authDbContext.Users.Include(u => u.Department).ToListAsync(); } return Ok(new { UserInfo = userInfo }); } catch (Exception ex) { return StatusCode(500, $"An error occurred: {ex.Message}"); } } public class LdapLoginCredential { public required string username { get; set; } public required string password { get; set; } } [HttpPost("LdapLogin")] public async Task LdapLogin([FromBody] LdapLoginCredential ldapLoginInfo) { if (!ModelState.IsValid) { return BadRequest(ModelState); } byte[] noFormatString = Convert.FromBase64String(_commKey); string initUrlKey = Encoding.UTF8.GetString(noFormatString); string jsonData = JsonSerializer.Serialize(ldapLoginInfo); RSA rsaBase = RSA.Create(); rsaBase.ImportFromPem(initUrlKey.ToCharArray()); byte[] rsaData = rsaBase.Encrypt(Encoding.UTF8.GetBytes(jsonData), RSAEncryptionPadding.Pkcs1); string rsaDataBase64 = Convert.ToBase64String(rsaData); string ldapUrl = "http://192.168.11.231/api/ldap/"; string ldapUrlResult = ""; using (HttpClient httpClient = new HttpClient()) { try { StringContent rsaDataB64HttpContent = new(rsaDataBase64, Encoding.UTF8); HttpResponseMessage ldapUrlResponse = await httpClient.PostAsync(ldapUrl, rsaDataB64HttpContent); ldapUrlResponse.EnsureSuccessStatusCode(); if (ldapUrlResponse.IsSuccessStatusCode) { ldapUrlResult = await ldapUrlResponse.Content.ReadAsStringAsync(); } } catch (Exception e) { return BadRequest(new { Message = $"Message: {e.Message}\nException Caught!" }); } } userLdapInfo userLdapInfo = JsonSerializer.Deserialize(ldapUrlResult)!; userInfo userInfo = userLdapInfo.UserInfo; if (!userLdapInfo.Authenticated) { return BadRequest(new { Message = "Login Failed" }); } UserModel ldapuser = new UserModel() { FullName = userInfo.Username, UserName = userInfo.Email, NormalizedUserName = userInfo.Email.ToUpper(), Email = userInfo.Email, NormalizedEmail = userInfo.Email.ToUpper(), EmailConfirmed = true, PhoneNumberConfirmed = false, TwoFactorEnabled = false, LockoutEnabled = false, AccessFailedCount = 0, }; var existUser = await doUserExists(ldapuser.Email); if (existUser == null) { await _userManager.CreateAsync(ldapuser); //await _userManager.SetLockoutEnabledAsync(ldapuser, false); //return RedirectToAction("AssignRoleAfterLdap", "IdentityController"); return Ok(new { RedirectUrl = Url.Action("RoleAssignment", "Identity") }); }; await _signInManager.SignInAsync(existUser, false); //return RedirectToAction("Index", "HomeController"); return Ok(new { RedirectUrl = Url.Action("Index", "Home") }); } public async Task doUserExists(string username) { var user = await _userManager.FindByNameAsync(username); return user != null ? user : null; } class userLdapInfo() { public required bool Authenticated { get; set; } public required userInfo UserInfo { get; set; } } class userInfo() { public required string FirstName { get; set; } public required string LastName { get; set; } public required string DisplayName { get; set; } public required string Description { get; set; } public required string Username { get; set; } public required string Office { get; set; } public required string Email { get; set; } public required string Street { get; set; } public required string City { get; set; } public required string State { get; set; } public required string ZipCode { get; set; } public required string Country { get; set; } public required string Home { get; set; } public required string Mobile { get; set; } } } }