update
This commit is contained in:
parent
7cbc870f78
commit
5db84d96a2
@ -136,11 +136,21 @@
|
||||
if (!response.ok) {
|
||||
throw new Error('Name module already exist');
|
||||
}
|
||||
alert('Module information saved successfully');
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
console.log(data);
|
||||
if (data.redirectUrl) {
|
||||
window.location.href = data.redirectUrl;
|
||||
}
|
||||
else
|
||||
{
|
||||
console.error('Login failed:', data);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('There was a problem with the update operation:', error);
|
||||
alert('Failed to save data: ' + error.message);
|
||||
console.error('Error during LDAP login:', error);
|
||||
alert('Failed to login: ' + error.message);
|
||||
});
|
||||
},
|
||||
fetchControllerMethodList() {
|
||||
|
||||
@ -16,17 +16,19 @@ namespace PSTW_CentralSystem.Controllers.API
|
||||
|
||||
public class AdminAPI : Controller
|
||||
{
|
||||
private readonly ILogger<HomeController> _logger;
|
||||
private readonly ILogger<AdminAPI> _logger;
|
||||
private readonly IdentityDBContext _authDbContext;
|
||||
private readonly UserManager<UserModel> _userManager;
|
||||
private readonly SignInManager<UserModel> _signInManager;
|
||||
// Communication Key for API. Not API authentication key
|
||||
private readonly string _commKey = "LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUlJQklqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FROEFNSUlCQ2dLQ0FRRUF4NW42anlkNlpTYzZNSE1Zem9qaApUbldpYTIra2pud2ZNbVhpSWlyK0RadjM2cEVGMGhRUWFLaWpaMWtyMGNiT25Ha2d2QnNwTzNiYkFua0E3SWwzCk4zM3NNYWdQV0JOQzZyVm1jT04zNEhDSWJCM0hvQXFYQUtkSHFUOGZneklMRzFhRzdxK2h4RDZhZzZsemhTMnEKdDA1bHdNc0hONWpOdmVNNnFWalRnTVB4aEFOMUhnUTkrd1lRWFh5bnZYYUo5OUNySHBqS21WdUt2VUh6WXdlRwp6SnBtYXZOclc4bE9oM1lMeVNuUVU5bjRrdURubGc1OWNHeUtKbzJ2YUxZbll4MkR1ZDNabzBXMHRMWGd0dlQyCjVXdVFsY0NVbldvaVpBV1JBTGI3anRpcTF0MGY5eVBiV2gxYXpMMjFoL3QvckJUMXNCL2FQd2kzRCt3MnBUR00KeVFJREFRQUIKLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg==";
|
||||
|
||||
public AdminAPI(ILogger<HomeController> logger, IdentityDBContext authDbContext, UserManager<UserModel> userManager)
|
||||
public AdminAPI(ILogger<AdminAPI> logger, IdentityDBContext authDbContext, UserManager<UserModel> userManager, SignInManager<UserModel> signInManager)
|
||||
{
|
||||
_logger = logger;
|
||||
_authDbContext = authDbContext;
|
||||
_userManager = userManager;
|
||||
_signInManager = signInManager;
|
||||
}
|
||||
|
||||
[HttpPost("GetClassAndMethodInformation")]
|
||||
@ -128,6 +130,7 @@ namespace PSTW_CentralSystem.Controllers.API
|
||||
public required string username { get; set; }
|
||||
public required string password { get; set; }
|
||||
}
|
||||
|
||||
[HttpPost("LdapLogin")]
|
||||
public async Task<IActionResult> LdapLogin([FromBody] LdapLoginCredential ldapLoginInfo)
|
||||
{
|
||||
@ -146,10 +149,6 @@ namespace PSTW_CentralSystem.Controllers.API
|
||||
byte[] rsaData = rsaBase.Encrypt(Encoding.UTF8.GetBytes(jsonData), RSAEncryptionPadding.Pkcs1);
|
||||
string rsaDataBase64 = Convert.ToBase64String(rsaData);
|
||||
|
||||
Console.WriteLine("Sending data (RSA-Encrypted JSON as Base64)");
|
||||
Console.WriteLine(rsaDataBase64);
|
||||
Console.WriteLine("");
|
||||
|
||||
string ldapUrl = "http://192.168.11.231/api/ldap/";
|
||||
string ldapUrlResult = "";
|
||||
|
||||
@ -158,11 +157,11 @@ namespace PSTW_CentralSystem.Controllers.API
|
||||
try
|
||||
{
|
||||
StringContent rsaDataB64HttpContent = new(rsaDataBase64, Encoding.UTF8);
|
||||
HttpResponseMessage ldapUrlResponse = httpClient.PostAsync(ldapUrl, rsaDataB64HttpContent).Result;
|
||||
HttpResponseMessage ldapUrlResponse = await httpClient.PostAsync(ldapUrl, rsaDataB64HttpContent);
|
||||
ldapUrlResponse.EnsureSuccessStatusCode();
|
||||
if (ldapUrlResponse.IsSuccessStatusCode)
|
||||
{
|
||||
ldapUrlResult = ldapUrlResponse.Content.ReadAsStringAsync().Result;
|
||||
ldapUrlResult = await ldapUrlResponse.Content.ReadAsStringAsync();
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
@ -171,26 +170,52 @@ namespace PSTW_CentralSystem.Controllers.API
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
userLdapInfo userInfo = JsonSerializer.Deserialize<userLdapInfo>(ldapUrlResult)!;
|
||||
|
||||
if (userInfo.Authenticated != "True")
|
||||
userLdapInfo userLdapInfo = JsonSerializer.Deserialize<userLdapInfo>(ldapUrlResult)!;
|
||||
userInfo userInfo = userLdapInfo.UserInfo;
|
||||
|
||||
if (!userLdapInfo.Authenticated)
|
||||
{
|
||||
return BadRequest(new { Message = "Login Failed" });
|
||||
}
|
||||
|
||||
UserModel ldapuser = new UserModel()
|
||||
{
|
||||
UserName = userInfo.UserInfo.Email,
|
||||
Email = userInfo.UserInfo.Email,
|
||||
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") });
|
||||
|
||||
};
|
||||
|
||||
return Json(userInfo);
|
||||
await _signInManager.SignInAsync(existUser, false);
|
||||
//return RedirectToAction("Index", "HomeController");
|
||||
return Ok(new { RedirectUrl = Url.Action("Index", "Home") });
|
||||
|
||||
}
|
||||
|
||||
public async Task<UserModel?> doUserExists(string username)
|
||||
{
|
||||
var user = await _userManager.FindByNameAsync(username);
|
||||
return user != null ? user : null;
|
||||
}
|
||||
|
||||
class userLdapInfo()
|
||||
{
|
||||
public required string Authenticated { get; set; }
|
||||
public required bool Authenticated { get; set; }
|
||||
public required userInfo UserInfo { get; set; }
|
||||
}
|
||||
class userInfo()
|
||||
|
||||
29
Controllers/IdentityController.cs
Normal file
29
Controllers/IdentityController.cs
Normal file
@ -0,0 +1,29 @@
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using PSTW_CentralSystem.DBContext;
|
||||
using PSTW_CentralSystem.Models;
|
||||
|
||||
namespace PSTW_CentralSystem.Controllers
|
||||
{
|
||||
|
||||
public class IdentityController: Controller
|
||||
{
|
||||
private readonly ILogger<HomeController> _logger;
|
||||
private readonly IdentityDBContext _authDbContext;
|
||||
private readonly UserManager<UserModel> _userManager;
|
||||
|
||||
public IdentityController(ILogger<HomeController> logger, IdentityDBContext authDbContext, UserManager<UserModel> userManager)
|
||||
{
|
||||
_logger = logger;
|
||||
_authDbContext = authDbContext;
|
||||
_userManager = userManager;
|
||||
}
|
||||
|
||||
public async Task<IActionResult> RoleAssignment()
|
||||
{
|
||||
var thisUser = await _userManager.GetUserAsync(User);
|
||||
return View();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
207
Views/Identity/RoleAssignment.cshtml
Normal file
207
Views/Identity/RoleAssignment.cshtml
Normal file
@ -0,0 +1,207 @@
|
||||
@*
|
||||
For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
|
||||
*@
|
||||
@{
|
||||
ViewData["Title"] = "Role Assignment";
|
||||
Layout = "~/Views/Shared/_Layout.cshtml";
|
||||
}
|
||||
|
||||
<p>
|
||||
@* <a asp-action="UserCreate">Create New</a> *@
|
||||
</p>
|
||||
<div id="app">
|
||||
<div class="row">
|
||||
<div class="col-md-12 col-lg-12">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<h4 class="card-title">Latest Posts</h4>
|
||||
<div class="col-md-12 col-lg-12">
|
||||
<div>
|
||||
<table class="table table-bordered border-primary" id="userDatatable">
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- MODAL -->
|
||||
<div class="modal fade" id="confirm-dialog" tabindex="-1" role="dialog" aria-labelledby="confirm-dialog-title" aria-hidden="true">
|
||||
<div class="modal-dialog modal-dialog-centered" role="document">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="confirm-dialog-title">Confirmation</h5>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close" v-on:click="hideModal">
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="selectedModule">
|
||||
<div class="modal-body">
|
||||
<p>Are you sure you want to delete module {{ selectedModule.moduleName }}?</p>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-dismiss="modal" v-on:click="hideModal">Cancel</button>
|
||||
<input type="hidden" id="delete-id">
|
||||
<a id="confirmButton" href="#" class="btn btn-danger" v-on:click="confirmDelete(selectedModule)">Confirm</a>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else><p>Loading...</p></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@section Scripts {
|
||||
@{
|
||||
await Html.RenderPartialAsync("_ValidationScriptsPartial");
|
||||
}
|
||||
<script>
|
||||
const app = Vue.createApp({
|
||||
data() {
|
||||
return {
|
||||
userList: null,
|
||||
selectedModule: null
|
||||
};
|
||||
},
|
||||
mounted() {
|
||||
this.fetchModule();
|
||||
},
|
||||
methods: {
|
||||
fetchModule() {
|
||||
fetch('/AdminAPI/GetUserList', {
|
||||
method: 'POST'
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.length > 0) {
|
||||
this.userList = data.length ? data : [];
|
||||
}
|
||||
this.initiateTable();
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('There was a problem with the fetch operation:', error);
|
||||
});
|
||||
},
|
||||
editModule(module) {
|
||||
// Check if the user ID exists
|
||||
if (module.settingId) {
|
||||
// Redirect the user to the edit user page
|
||||
window.location.href = 'ModuleSetting/' + module.settingId;
|
||||
} else {
|
||||
console.error('Module ID not found');
|
||||
}
|
||||
},
|
||||
deleteModule(module) {
|
||||
this.selectedModule = module; // Set selected user
|
||||
$('#confirm-dialog').modal('show'); // Show the modal
|
||||
|
||||
// console.log(this.selectedModule);
|
||||
},
|
||||
confirmDelete(module) {
|
||||
fetch(`/ModuleAPI/DeleteModule/${module.settingId}`, {
|
||||
method: 'POST'
|
||||
})
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to delete module');
|
||||
}
|
||||
// Remove the deleted user from the userData array
|
||||
const index = this.moduleData.findIndex(u => u.settingId === module.settingId);
|
||||
if (index !== -1) {
|
||||
alert("Module deleted successfully");
|
||||
this.moduleData.splice(index, 1);
|
||||
}
|
||||
this.hideModal(); // Hide the modal after deletion
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Failed to delete module with status:', error);
|
||||
});
|
||||
},
|
||||
hideModal() {
|
||||
$('#confirm-dialog').modal('hide');
|
||||
},
|
||||
initiateTable() {
|
||||
self = this;
|
||||
this.itemDatatable = $('#userDatatable').DataTable({
|
||||
"data": this.userList,
|
||||
"columns": [
|
||||
{
|
||||
"title": "UID",
|
||||
"data": "id",
|
||||
"createdCell": function (td, cellData, rowData, row, col) {
|
||||
// Assign a unique ID to the <td> element
|
||||
$(td).attr('id', `qr${cellData}`);
|
||||
},
|
||||
},
|
||||
{
|
||||
"title": "Email",
|
||||
"data": "email",
|
||||
},
|
||||
{
|
||||
"title": "Company Name",
|
||||
"data": "company",
|
||||
},
|
||||
{
|
||||
"title": "Department",
|
||||
"data": "department",
|
||||
},
|
||||
{
|
||||
"title": "Role",
|
||||
"data": "role",
|
||||
},
|
||||
{
|
||||
"title": "Delete",
|
||||
"data": "id",
|
||||
"render": function (data) {
|
||||
var deleteButton = `<button type="button" class="btn btn-danger delete-btn" data-id="${data}">Delete</button>`;
|
||||
return deleteButton;
|
||||
},
|
||||
}
|
||||
],
|
||||
responsive: true,
|
||||
drawCallback: function (settings) {
|
||||
// Generate QR codes after rows are rendered
|
||||
const api = this.api();
|
||||
api.rows().every(function () {
|
||||
const data = this.data(); // Row data
|
||||
const containerId = `qr${data.uniqueID}`;
|
||||
const container = $(`#${containerId}`);
|
||||
// console.log(container[0]);
|
||||
if (container) {
|
||||
// Generate QR code only if not already generated
|
||||
new QRCode(container[0], {
|
||||
text: data.qrString,
|
||||
width: 150,
|
||||
height: 150,
|
||||
colorDark: "#000000",
|
||||
colorLight: "#ffffff",
|
||||
correctLevel: QRCode.CorrectLevel.H
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
})
|
||||
|
||||
// Attach click event listener to the delete buttons
|
||||
$('#itemDatatable tbody').on('click', '.delete-btn', function () {
|
||||
const itemId = $(this).data('id');
|
||||
self.deleteItem(itemId);
|
||||
});
|
||||
|
||||
$('#itemDatatable tbody').on('click', '.print-btn', function () {
|
||||
const itemId = $(this).data('id');
|
||||
var $row = $(this).closest('tr'); // get the row containing the button
|
||||
var imageSrc = $row.find('img').attr('src'); // find the img element in the row and get its src
|
||||
// console.log(imageSrc);
|
||||
self.printItem(itemId, imageSrc);
|
||||
});
|
||||
|
||||
this.loading = false;
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
$(function () {
|
||||
app.mount('#app');
|
||||
});
|
||||
</script>
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user