đ 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
- Overview & Purpose
- Dependencies & Technologies
- Class & Data Models
- Key Functional Areas
4.1. GetEmployeePermissions
4.2. HasPermission
4.3. ExportRole
4.4. AddPermissions
4.5. ImportRole - Helper Methods & Utilities
- Error Handling & Return Types
- Third-Party Integrations
- Sample Code Blocks & Usage Examples
- UML Diagrams
- 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
- Query
LinkUserRoles&LinkRolePermissionsfor extra roles. - Query
Employees& their primaryRole. - 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
- Load role by
id(ignore softâdeleted). - Fetch active
PermissionsviaLinkRolePermissions. - Output
role.Descriptionviaout string name. - 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:
- Individual actions for a specified controller.
- 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
Permissionsrecord with audit fields.
- Build
- 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
- Deserialize JSON into
Roleobject, overrideRoleId = id. - Upsert each
PermissioninRole.Permissions. - Upsert the
Role(preserve existing description if already set). - Link each permission to the role, add missing, update existing, mark excluded as
IsDeleted=true. - Return the resulting
Roleentity.
đ Helper Methods & Utilities
- Reflection Query (in
AddPermissions) to enumerate controllers and public action methods viaAssembly.GetExecutingAssembly()andBindingFlags. - 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.SerializeObjectfor exporting roles.JsonConvert.DeserializeObject<Role>for importing roles.
- ASP.NET Core MVC
- Reflection of
Controllerbase class and action methods for permission seeding.
- Reflection of
đĄ 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! đĄď¸â¨