📘 AccessControl Class Documentation

Welcome to the comprehensive documentation for the AccessControl class in the IrbyImaging.BusinessLogic namespace. This utility class provides core permission-management features—retrieving, verifying, exporting, importing, and seeding role‐ and user‐based permissions.


📑 Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Class & Data Models
  4. Key Functional Areas
    4.1. GetEmployeePermissions
    4.2. HasPermission
    4.3. ExportRole
    4.4. AddPermissions
    4.5. ImportRole
  5. Helper Methods & Utilities
  6. Error Handling & Return Types
  7. Third-Party Integrations
  8. Sample Code Blocks & Usage Examples
  9. UML Diagrams
  10. Conclusion

🎯 Overview & Purpose

The AccessControl class centralizes permission logic for IrbyImaging, including:

  • Fetching an employee’s effective permissions (GetEmployeePermissions).
  • Validating whether a user can access a given controller/action (HasPermission).
  • Exporting a role (with its permissions) to a JSON payload (ExportRole).
  • Adding new permissions dynamically based on discovered controller/actions (AddPermissions).
  • Importing a role JSON back into the database, reconciling changes (ImportRole).

This avoids repetition across controllers and services, providing a single source of truth for all permission-related operations.


🧰 Dependencies & Technologies

Dependency Purpose
IrbyImaging.DomainClasses Domain entities: Employee, Role, Permissions, links.
Microsoft.AspNetCore.Mvc Reflection helpers to enumerate controllers.
Newtonsoft.Json JSON (de)serialization for export/import.
System.Linq Query syntax over EF Core DbSet<T>.
System.Reflection Discover controllers & actions dynamically.
Entity Framework Core (via IrbyContext) Database context for CRUD.

🗂️ Class & Data Models

AccessControl (static class)

A static utility that does not hold state. All methods accept a Guid, Employee, or JSON string plus the IrbyContext.

Domain Entities (from IrbyImaging.DomainClasses)

Entity Key Properties
Employee EmployeeId (Guid), RoleId (Guid), Permissions (HashSet<string>), etc.
Role RoleId (Guid), Description (string), IsDeleted (bool), Permissions (List<Permissions>)
Permissions PermissionId (Guid), PermissionName (string), IsDeleted (bool), timestamps
LinkRolePermissions join table: RoleId, PermissionId, IsDeleted
LinkUserRoles join table: EmployeeId, RoleId, IsDeleted

🔑 Key Functional Areas

1. GetEmployeePermissions

Signature

public static HashSet<string> GetEmployeePermissions(Guid id, IrbyContext db)

Purpose
Fetch all effective permissions for an employee:

  • Permissions granted via additional roles (LinkUserRoles → LinkRolePermissions).
  • Permissions granted via their primary role (Employees → Roles → LinkRolePermissions).

All permission names are lower‐cased for uniform comparison.

Workflow

  1. Query LinkUserRoles & LinkRolePermissions for extra roles.
  2. Query Employees & their primary Role.
  3. Merge both lists, convert to lower‐case, remove duplicates.

Returns
HashSet<string> of lower‐cased permission strings, e.g.

{ "orders - get", "orders - create", "users - *" }

2. HasPermission

Signature

public static bool HasPermission(Employee employee, string controller, string action)

Purpose
Check if an employee’s in-memory Permissions set includes:

  • A developer wildcard: *
  • A controller wildcard: "Controller - *"
  • A named permission: "Controller - Action"

Usage

if (AccessControl.HasPermission(currentUser, "Orders", "Create")) {
    // proceed
}

3. ExportRole

Signature

public static string ExportRole(Guid id, IrbyContext db, out string name)

Purpose
Serialize a Role (and its active permissions) into a pretty‐printed JSON string for backup or transfer.

Workflow

  1. Load role by id (ignore soft‐deleted).
  2. Fetch active Permissions via LinkRolePermissions.
  3. Output role.Description via out string name.
  4. Return JSON (Formatting.Indented).

Returns

  • JSON string representation of the role
  • Sets name = role description

Example Output

{
  "RoleId": "d290f1ee-6c54-4b01-90e6-d701748f0851",
  "Description": "Administrator",
  "Permissions": [
    { "PermissionId": "...", "PermissionName": "Users - *", ... },
    { "PermissionId": "...", "PermissionName": "Orders - Get", ... }
  ]
}

4. AddPermissions

Signature

public static void AddPermissions(
    IrbyContext context,
    Employee employee,
    string Controller,
    List<string> Actions
)

Purpose
Dynamically seed new permissions into the database:

  1. Individual actions for a specified controller.
  2. A controller‐wide wildcard permission ("Controller - *").

Workflow

  • Reflect on all MVC controllers/actions (currently unused except grouping).
  • For each action:
    • Build PermissionName = "Controller - Action".
    • If missing, insert new Permissions record with audit fields.
  • Finally, ensure "Controller - *" exists.

5. ImportRole

Signature

public static Role ImportRole(
    string json,
    IrbyContext db,
    Guid id
)

Purpose
Deserialize a role JSON (produced by ExportRole) and reconcile against the database:

  • Inserts or updates permissions.
  • Inserts or updates the role itself.
  • Inserts or updates link table entries (LinkRolePermissions).
  • Soft‐deletes any permissions no longer included.

Workflow

  1. Deserialize JSON into Role object, override RoleId = id.
  2. Upsert each Permission in Role.Permissions.
  3. Upsert the Role (preserve existing description if already set).
  4. Link each permission to the role, add missing, update existing, mark excluded as IsDeleted=true.
  5. Return the resulting Role entity.

🛠 Helper Methods & Utilities

  • Reflection Query (in AddPermissions) to enumerate controllers and public action methods via Assembly.GetExecutingAssembly() and BindingFlags.
  • Lower‑casing normalization for permission strings.
  • LINQ join operations to map many‐to‐many relationships (LinkUserRoles, LinkRolePermissions).

🚨 Error Handling & Return Types

Method Error Handling Return Type
GetEmployeePermissions Returns empty HashSet if no roles/permissions found HashSet<string>
HasPermission Null‐safe: returns false if employee or Permissions is null bool
ExportRole Returns String.Empty if role not found string (JSON)
AddPermissions No explicit error handling; exceptions bubble up void
ImportRole Returns null if JSON empty; otherwise returns Role Role

🔌 Third-Party Integrations

  • Newtonsoft.Json
    • JsonConvert.SerializeObject for exporting roles.
    • JsonConvert.DeserializeObject<Role> for importing roles.
  • ASP.NET Core MVC
    • Reflection of Controller base class and action methods for permission seeding.

💡 Sample Code Blocks & Usage Examples

Fetching and Validating a Permission

// 1. Load from DB
var permissions = AccessControl.GetEmployeePermissions(currentUserId, _db);
currentUser.Permissions = permissions;

// 2. Check if user can call OrdersController.Create
if (!AccessControl.HasPermission(currentUser, "Orders", "Create")) {
    return Forbid(); // or custom 403
}

Export a Role to JSON

string roleName;
string jsonPayload = AccessControl.ExportRole(adminRoleId, _db, out roleName);
Console.WriteLine($"Exported '{roleName}':\n{jsonPayload}");

Importing a Role from JSON

Guid newRoleId = Guid.NewGuid();
string inputJson = File.ReadAllText("exported-admin.json");
Role imported = AccessControl.ImportRole(inputJson, _db, newRoleId);
Console.WriteLine($"Imported Role: {imported.Description} ({imported.RoleId})");

Seeding New Permissions

var actions = new List<string> { "Index", "Create", "Delete" };
AccessControl.AddPermissions(_db, currentUser, "Products", actions);
// This ensures "Products - Index", "Products - Create", ..., "Products - *" exist

📊 UML Diagrams

classDiagram
    AccessControl <.. IrbyContext : uses
    AccessControl <-- Employee : checks
    AccessControl <-- Role : export/import
    IrbyContext "*" --> "1" DbSet~Employee~
    IrbyContext "*" --> "1" DbSet~Role~
    IrbyContext "*" --> "1" DbSet~Permissions~
    IrbyContext "*" --> "1" DbSet~LinkRolePermissions~
    IrbyContext "*" --> "1" DbSet~LinkUserRoles~

Sequence: HasPermission

sequenceDiagram
    participant C as Controller
    participant AC as AccessControl
    participant E as Employee

    C->>AC: HasPermission(E, "Orders", "Delete")
    AC->>E: E.Permissions.Contains(...)
    alt has match
        AC-->>C: true
    else no match
        AC-->>C: false
    end

🏁 Conclusion

The AccessControl class is a centralized, robust, and extensible solution for role‐based access control in IrbyImaging. By providing both in‑memory checks and database‐driven export/import, it simplifies:

  • Permission retrieval (GetEmployeePermissions)
  • Permission enforcement (HasPermission)
  • Role backup & restore (ExportRole/ImportRole)
  • Dynamic seeding of new controller/action pairs (AddPermissions)

With this in place, adding new controllers/actions or seeding roles becomes a breeze—ensuring your application remains secure, maintainable, and consistent across environments.

Happy coding! 🛡️✨