/* * EXAMPLE: How to Apply Permission Checks to UserAccessManagementController * * This file shows how to add permission authorization to your existing controller. * Copy the pattern and apply it to your other controllers. */ using MiCash360.Api.Classes; using MiCash360.Api.Models; using MiCash360.Api.Helpers; // ← ADD THIS IMPORT using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web.Mvc; namespace MiCash360.Api.Controllers { public class UserAccessManagementController : Controller { Business business = null; // ==================== ROLES ==================== // BEFORE: No permission check // public ActionResult Roles(string search) // AFTER: With permission check [PermissionAuthorization("/UserAccessManagement/Roles", "GET")] public ActionResult Roles(string search) { User user = GetLoggedInUser(); if (user == null) return RedirectToAction("Login", "Site"); MICASHEntities db = new MICASHEntities(); var roles = db.Roles.AsQueryable(); if (!string.IsNullOrWhiteSpace(search)) { search = search.ToLower(); roles = roles.Where(r => r.Name.ToLower().Contains(search) || r.Code.ToLower().Contains(search) || (r.Description != null && r.Description.ToLower().Contains(search)) ); } var orderedRoles = roles.OrderBy(r => r.Name).ToList(); return View(orderedRoles); } // GET: Create Role [PermissionAuthorization("/UserAccessManagement/Create", "GET")] public ActionResult Create() { User user = GetLoggedInUser(); if (user == null) return RedirectToAction("Login", "Site"); return View(); } // POST: Create Role [PermissionAuthorization("/UserAccessManagement/Create", "POST")] [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Role role) { User user = GetLoggedInUser(); if (user == null) return RedirectToAction("Login", "Site"); try { if (ModelState.IsValid) { MICASHEntities db = new MICASHEntities(); var existingRole = db.Roles.FirstOrDefault(r => r.Code == role.Code); if (existingRole != null) { ViewBag.AlertTitle = "Creation Error"; ViewBag.AlertMessage = "A role with this code already exists."; ViewBag.AlertShow = true; return View(role); } role.CreatedAt = DateTime.Now; role.UpdatedAt = DateTime.Now; role.IsDeleted = false; db.Roles.Add(role); db.SaveChanges(); TempData["SuccessMessage"] = "Role created successfully!"; return RedirectToAction("Roles"); } ViewBag.AlertTitle = "Validation Error"; ViewBag.AlertMessage = "Please fill in all required fields."; ViewBag.AlertShow = true; return View(role); } catch (Exception ex) { LogError logError = new LogError(); logError.LogErrors(ex.Message + " Create Role method from UserAccessManagementController", user?.E_ID); ViewBag.AlertTitle = "Creation Error"; ViewBag.AlertMessage = "An error occurred while creating the role."; ViewBag.AlertShow = true; return View(role); } } // GET: Edit Role [PermissionAuthorization("/UserAccessManagement/Edit", "GET")] public ActionResult Edit(int id) { User user = GetLoggedInUser(); if (user == null) return RedirectToAction("Login", "Site"); try { MICASHEntities db = new MICASHEntities(); var role = db.Roles.Find(id); if (role == null) { TempData["ErrorMessage"] = "Role not found."; return RedirectToAction("Roles"); } return View(role); } catch (Exception ex) { LogError logError = new LogError(); logError.LogErrors(ex.Message + " Edit Role GET method from UserAccessManagementController", user?.E_ID); TempData["ErrorMessage"] = "An error occurred while loading the role."; return RedirectToAction("Roles"); } } // POST: Edit Role [PermissionAuthorization("/UserAccessManagement/Edit", "POST")] [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(Role role) { User user = GetLoggedInUser(); if (user == null) return RedirectToAction("Login", "Site"); try { if (ModelState.IsValid) { MICASHEntities db = new MICASHEntities(); var existingRole = db.Roles.FirstOrDefault(r => r.Code == role.Code && r.Id != role.Id); if (existingRole != null) { ViewBag.AlertTitle = "Update Error"; ViewBag.AlertMessage = "A role with this code already exists."; ViewBag.AlertShow = true; return View(role); } var roleToUpdate = db.Roles.Find(role.Id); if (roleToUpdate == null) { TempData["ErrorMessage"] = "Role not found."; return RedirectToAction("Roles"); } roleToUpdate.Name = role.Name; roleToUpdate.Code = role.Code; roleToUpdate.Description = role.Description; roleToUpdate.UpdatedAt = DateTime.Now; db.Entry(roleToUpdate).State = EntityState.Modified; db.SaveChanges(); TempData["SuccessMessage"] = "Role updated successfully!"; return RedirectToAction("Roles"); } ViewBag.AlertTitle = "Validation Error"; ViewBag.AlertMessage = "Please fill in all required fields."; ViewBag.AlertShow = true; return View(role); } catch (Exception ex) { LogError logError = new LogError(); logError.LogErrors(ex.Message + " Edit Role POST method from UserAccessManagementController", user?.E_ID); ViewBag.AlertTitle = "Update Error"; ViewBag.AlertMessage = "An error occurred while updating the role."; ViewBag.AlertShow = true; return View(role); } } // GET: View Role Details [PermissionAuthorization("/UserAccessManagement/Details", "GET")] public ActionResult Details(int id) { User user = GetLoggedInUser(); if (user == null) return RedirectToAction("Login", "Site"); try { MICASHEntities db = new MICASHEntities(); var role = db.Roles.Find(id); if (role == null) { TempData["ErrorMessage"] = "Role not found."; return RedirectToAction("Roles"); } return View(role); } catch (Exception ex) { LogError logError = new LogError(); logError.LogErrors(ex.Message + " Details Role method from UserAccessManagementController", user?.E_ID); TempData["ErrorMessage"] = "An error occurred while loading the role details."; return RedirectToAction("Roles"); } } // GET: Delete Role [PermissionAuthorization("/UserAccessManagement/Delete", "GET")] public ActionResult Delete(int id) { User user = GetLoggedInUser(); if (user == null) return RedirectToAction("Login", "Site"); try { MICASHEntities db = new MICASHEntities(); var role = db.Roles.Find(id); if (role == null) { TempData["ErrorMessage"] = "Role not found."; return RedirectToAction("Roles"); } return View(role); } catch (Exception ex) { LogError logError = new LogError(); logError.LogErrors(ex.Message + " Delete Role GET method from UserAccessManagementController", user?.E_ID); TempData["ErrorMessage"] = "An error occurred while loading the role."; return RedirectToAction("Roles"); } } // POST: Delete Role Confirmed [PermissionAuthorization("/UserAccessManagement/Delete", "POST")] [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { User user = GetLoggedInUser(); if (user == null) return RedirectToAction("Login", "Site"); try { MICASHEntities db = new MICASHEntities(); var role = db.Roles.Find(id); if (role == null) { TempData["ErrorMessage"] = "Role not found."; return RedirectToAction("Roles"); } var businessUsersWithRole = db.BusinessUsers.Where(bu => bu.RoleId == id && bu.IsActive).ToList(); if (businessUsersWithRole.Any()) { TempData["ErrorMessage"] = $"Cannot delete this role. It is currently assigned to {businessUsersWithRole.Count} active user(s)."; return RedirectToAction("Roles"); } role.IsDeleted = true; role.UpdatedAt = DateTime.Now; db.Entry(role).State = EntityState.Modified; db.SaveChanges(); TempData["SuccessMessage"] = "Role deleted successfully!"; return RedirectToAction("Roles"); } catch (Exception ex) { LogError logError = new LogError(); logError.LogErrors(ex.Message + " Delete Role POST method from UserAccessManagementController", user?.E_ID); TempData["ErrorMessage"] = "An error occurred while deleting the role."; return RedirectToAction("Roles"); } } // ==================== PERMISSION MODULES ==================== [PermissionAuthorization("/UserAccessManagement/PermissionModules", "GET")] public ActionResult PermissionModules(string search) { // ... implementation } [PermissionAuthorization("/UserAccessManagement/CreatePermissionModule", "GET")] public ActionResult CreatePermissionModule() { // ... implementation } [PermissionAuthorization("/UserAccessManagement/CreatePermissionModule", "POST")] [HttpPost] [ValidateAntiForgeryToken] public ActionResult CreatePermissionModule(PermissionModule module) { // ... implementation } // Continue with all other actions... private User GetLoggedInUser() { MICASHEntities db = new MICASHEntities(); User user = Session["user"] as User; int businessId = int.Parse(Session["selectBusiness"].ToString() ?? "0"); if (user != null) { business = db.Businesses.Where(i => i.Id == businessId).FirstOrDefault(); if (business != null) { Session["business"] = business; ViewBag.Business = business; Pocket wallet = db.Pockets.Where(i => i.UserID == business.Business_id && i.isMain == 1).First(); ViewBag.user = user; ViewBag.walletAmount = wallet.PocketAmount?.ToString("0.00"); var messages = db.Messages.Where(i => i.E_ID == business.Business_id && i.IsRead == 0).OrderByDescending(i => i.Id).ToList(); ViewBag.notificationAlerts = messages; ViewBag.IslightMode = user.DisplayMode == 1; return user; } } return null; } } } /* * KEY POINTS: * * 1. Add "using MiCash360.Api.Helpers;" at the top * * 2. Add [PermissionAuthorization] attribute to each action: * [PermissionAuthorization("/Controller/Action", "METHOD")] * * 3. URL format must match permissions in database: * - Always start with / * - Follow pattern: /ControllerName/ActionName * - Case-sensitive match * * 4. HTTP Method must match: * - GET, POST, PUT, DELETE * - Must match what's in the Permissions table * * 5. Apply to both GET and POST versions of the same action * * 6. If user doesn't have permission: * - They'll be redirected to /Site/NoAccess * - See a professional error page * - Can navigate back or go to dashboard */