Skip to content

Commit

Permalink
add Admin Pannel Tp manage users
Browse files Browse the repository at this point in the history
  • Loading branch information
Mohammed committed Sep 27, 2024
1 parent e33f70c commit f780ef4
Show file tree
Hide file tree
Showing 11 changed files with 334 additions and 8 deletions.
File renamed without changes.
5 changes: 5 additions & 0 deletions BookStore.DataAccess/Repository/ApplicationUser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,10 @@ public ApplicationUserRepository(ApplicationDbContext db) : base(db)
{
_db = db;
}

public void Update(ApplicationUser applicationUser)
{
_db.ApplicationUsers.Update(applicationUser);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@ namespace BookStore.DataAccess.Repository.IRepository
{
public interface IApplicationUserRepository : IRepository<ApplicationUser>
{
public void Update(ApplicationUser applicationUser);
}
}
2 changes: 2 additions & 0 deletions BookStore.Models/ApplicationUser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,6 @@ public class ApplicationUser:IdentityUser {
[ForeignKey("CompanyId")]
[ValidateNever]
public Company? Company { get; set; }
[NotMapped]
public string Role { get; set; }
}
11 changes: 11 additions & 0 deletions BookStore.Models/ViewModels/RoleManagmentVM.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using Microsoft.AspNetCore.Mvc.Rendering;

namespace BookStore.Models.ViewModels;

public class RoleManagmentVM
{
public ApplicationUser ApplicationUser { get; set; }
public IEnumerable<SelectListItem> RoleList { get; set; }
public IEnumerable<SelectListItem> CompanyList { get; set; }

}
134 changes: 134 additions & 0 deletions BookStore.Web/Areas/Admin/Controllers/UserController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Data;
using BookStore.DataAccess.Repository.IRepository;
using BookStore.Models;
using BookStore.Models.ViewModels;
using BookStore.Utility;

namespace BookStore.Web.Areas.Admin.Controllers
{
[Area("Admin")]
[Authorize(Roles = SD.Role_Admin)]
public class UserController : Controller
{
private readonly UserManager<IdentityUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly IUnitOfWork _unitOfWork;
public UserController(UserManager<IdentityUser> userManager, IUnitOfWork unitOfWork, RoleManager<IdentityRole> roleManager) {
_unitOfWork = unitOfWork;
_roleManager = roleManager;
_userManager = userManager;
}
public IActionResult Index()
{
return View();
}

public IActionResult RoleManagment(string userId) {

RoleManagmentVM RoleVM = new RoleManagmentVM() {
ApplicationUser = _unitOfWork.ApplicationUser.Get(u => u.Id == userId, includeProperties:"Company"),
RoleList = _roleManager.Roles.Select(i => new SelectListItem {
Text = i.Name,
Value = i.Name
}),
CompanyList = _unitOfWork.Company.GetAll().Select(i => new SelectListItem {
Text = i.Name,
Value = i.Id.ToString()
}),
};

RoleVM.ApplicationUser.Role = _userManager.GetRolesAsync(_unitOfWork.ApplicationUser.Get(u=>u.Id==userId))
.GetAwaiter().GetResult().FirstOrDefault();
return View(RoleVM);
}

[HttpPost]
public IActionResult RoleManagment(RoleManagmentVM roleManagmentVM) {

string oldRole = _userManager.GetRolesAsync(_unitOfWork.ApplicationUser.Get(u => u.Id == roleManagmentVM.ApplicationUser.Id))
.GetAwaiter().GetResult().FirstOrDefault();

ApplicationUser applicationUser = _unitOfWork.ApplicationUser.Get(u => u.Id == roleManagmentVM.ApplicationUser.Id);


if (!(roleManagmentVM.ApplicationUser.Role == oldRole)) {
//a role was updated
if (roleManagmentVM.ApplicationUser.Role == SD.Role_Company) {
applicationUser.CompanyId = roleManagmentVM.ApplicationUser.CompanyId;
}
if (oldRole == SD.Role_Company) {
applicationUser.CompanyId = null;
}
_unitOfWork.ApplicationUser.Update(applicationUser);
_unitOfWork.Save();

_userManager.RemoveFromRoleAsync(applicationUser, oldRole).GetAwaiter().GetResult();
_userManager.AddToRoleAsync(applicationUser, roleManagmentVM.ApplicationUser.Role).GetAwaiter().GetResult();

}
else {
if(oldRole==SD.Role_Company && applicationUser.CompanyId != roleManagmentVM.ApplicationUser.CompanyId) {
applicationUser.CompanyId = roleManagmentVM.ApplicationUser.CompanyId;
_unitOfWork.ApplicationUser.Update(applicationUser);
_unitOfWork.Save();
}
}

return RedirectToAction("Index");
}


#region API CALLS

[HttpGet]
public IActionResult GetAll()
{
List<ApplicationUser> objUserList = _unitOfWork.ApplicationUser.GetAll(includeProperties: "Company").ToList();

foreach(var user in objUserList) {

user.Role= _userManager.GetRolesAsync(user).GetAwaiter().GetResult().FirstOrDefault();

if (user.Company == null) {
user.Company = new Company() {
Name = ""
};
}
}

return Json(new { data = objUserList });
}


[HttpPost]
public IActionResult LockUnlock([FromBody]string id)
{

var objFromDb = _unitOfWork.ApplicationUser.Get(u => u.Id == id);
if (objFromDb == null)
{
return Json(new { success = false, message = "Error while Locking/Unlocking" });
}

if(objFromDb.LockoutEnd!=null && objFromDb.LockoutEnd > DateTime.Now) {
//user is currently locked and we need to unlock them
objFromDb.LockoutEnd = DateTime.Now;
}
else {
objFromDb.LockoutEnd = DateTime.Now.AddYears(1000);
}
_unitOfWork.ApplicationUser.Update(objFromDb);
_unitOfWork.Save();
return Json(new { success = true, message = "Operation Successful" });
}

#endregion
}
}
30 changes: 30 additions & 0 deletions BookStore.Web/Areas/Admin/Views/User/Index.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@

<div class="card shadow border-0 my-4">
<div class="card-header bg-secondary bg-gradient ml-0 py-3">
<div class="row">
<div class="col-12 text-center">
<h2 class="text-white py-2">User List</h2>
</div>
</div>
</div>
<div class="card-body p-4">

<table id="tblData" class="table table-bordered table-striped" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Company</th>
<th>Role</th>
<th></th>
</tr>
</thead>
</table>

</div>
</div>

@section Scripts{
<script src="~/js/user.js"></script>
}
70 changes: 70 additions & 0 deletions BookStore.Web/Areas/Admin/Views/User/RoleManagment.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
@using BookStore.Utility
@model RoleManagmentVM

<div class="card shadow border-0 mt-4">
<div class="card-header bg-secondary bg-gradient ml-0 py-3">
<div class="row">
<div class="col-12 text-center">
<h2 class="text-white py-2">Manage User Role</h2>
</div>
</div>
</div>
<div class="card-body p-4">
<form method="post" class="row">
<input asp-for="ApplicationUser.Id" hidden />
<div class="border p-3">
@*<div asp-validation-summary="ModelOnly"></div>*@
<div class="form-floating py-2 col-12">
<input asp-for="ApplicationUser.Name" readonly class="form-control border-0 shadow" />
<label asp-for="ApplicationUser.Name" class="ms-2"></label>
</div>
<div class="form-floating py-2 col-12">
<select asp-for="ApplicationUser.Role" asp-items="@Model.RoleList" class="form-select"></select>
</div>
@{
var companyVisible = "display:none;";
}
@if (Model.ApplicationUser.Role == SD.Role_Company) {
companyVisible = "display:block;";
}
<div class="form-floating py-2 col-12">
<select asp-for="ApplicationUser.CompanyId" style="@companyVisible" asp-items="@Model.CompanyList" class="form-select">
</select>
</div>

<div class="row pt-2">
<div class="col-6 col-md-3">
<button type="submit" class="btn btn-primary form-control">Update Role</button>
</div>
<div class="col-6 col-md-3">
<a asp-action="Index" class="btn btn-outline-primary border form-control">
Back to List
</a>
</div>
</div>
</div>
</form>
</div>
</div>




@section Scripts{
@{
<partial name="_ValidationScriptsPartial"/>
}
<script>
$(document).ready(function () {
$('#ApplicationUser_Role').change(function () {
var selection = $('#ApplicationUser_Role Option:Selected').text();
if (selection == 'Company') {
$('#ApplicationUser_CompanyId').show();
}
else {
$('#ApplicationUser_CompanyId').hide();
}
})
})
</script>
}
18 changes: 11 additions & 7 deletions BookStore.Web/Views/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,13 @@
<li class="nav-item">
<a class="dropdown-item" asp-area="Admin" asp-controller="Company" asp-action="Index">Company</a>
</li>
<li class="nav-item">
<a class="dropdown-item" asp-area="Identity" asp-page="/Account/Register">Create User</a>
</li>

<li><hr class="dropdown-divider"></li>

<li class="nav-item">
<a class="dropdown-item" asp-area="Identity" asp-page="/Account/Register">Create User</a>
</li>
<li class="nav-item">
<a class="dropdown-item" asp-area="Admin" asp-controller="User" asp-action="Index">Manage User</a>
</li>
</ul>
</li>
}
Expand Down Expand Up @@ -92,8 +93,11 @@
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="//cdn.datatables.net/1.13.3/js/jquery.dataTables.min.js" asp-append-version="true"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<script src="//cdn.datatables.net/1.13.3/js/jquery.dataTables.min.js" asp-append-version="true"></script>

<script src="https://cdn.tiny.cloud/1/rg27w56nz0roz1730z00tzjiim1150230pobxdil7qowzjcg/tinymce/7/tinymce.min.js" referrerpolicy="origin"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
Expand Down
69 changes: 69 additions & 0 deletions BookStore.Web/wwwroot/js/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
var dataTable;

$(document).ready(function () {
loadDataTable();
});

function loadDataTable() {
dataTable = $('#tblData').DataTable({
"ajax": { url:'/admin/user/getall'},
"columns": [
{ "data": "name", "width": "15%" },
{ "data": "email", "width": "15%" },
{ "data": "phoneNumber", "width": "15%" },
{ "data": "company.name", "width": "15%" },
{ "data": "role", "width": "15%" },
{
data: { id:"id", lockoutEnd:"lockoutEnd"},
"render": function (data) {
var today = new Date().getTime();
var lockout = new Date(data.lockoutEnd).getTime();

if (lockout > today) {
return `
<div class="text-center">
<a onclick=LockUnlock('${data.id}') class="btn btn-danger text-white" style="cursor:pointer; width:100px;">
<i class="bi bi-lock-fill"></i> Lock
</a>
<a href="/admin/user/RoleManagment?userId=${data.id}" class="btn btn-danger text-white" style="cursor:pointer; width:150px;">
<i class="bi bi-pencil-square"></i> Permission
</a>
</div>
`
}
else {
return `
<div class="text-center">
<a onclick=LockUnlock('${data.id}') class="btn btn-success text-white" style="cursor:pointer; width:100px;">
<i class="bi bi-unlock-fill"></i> UnLock
</a>
<a href="/admin/user/RoleManagment?userId=${data.id}" class="btn btn-danger text-white" style="cursor:pointer; width:150px;">
<i class="bi bi-pencil-square"></i> Permission
</a>
</div>
`
}


},
"width": "25%"
}
]
});
}


function LockUnlock(id) {
$.ajax({
type: "POST",
url: '/Admin/User/LockUnlock',
data: JSON.stringify(id),
contentType: "application/json",
success: function (data) {
if (data.success) {
toastr.success(data.message);
dataTable.ajax.reload();
}
}
});
}
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Manga Store is a comprehensive online platform built with ASP.NET Core 8, follow
- Bootstrap for responsive design
- **Back-End**:
- C#
- ASP.NET Core 7 (MVC)
- ASP.NET Core 8 (MVC)
- Entity Framework Core for database access
- **Database**:
- Microsoft SQL Server
Expand Down

0 comments on commit f780ef4

Please sign in to comment.