๐Ÿ“š BaseController.cs Documentation


๐Ÿš€ Table of Contents

  1. Overview & Purpose
  2. Dependencies & Technologies
  3. Class: BaseController
  4. Key Functional Areas
  5. View Models & Data Models
  6. Helper Methods & Utilities
  7. Error Handling & Return Types
  8. Thirdโ€‘party Integrations
  9. Sample Usage & Code Examples
  10. UML Class Diagram
  11. Conclusion

๐Ÿง Overview & Purpose

BaseController is an ASP.NET Core MVC base class from which all application controllers inherit common behavior:

  • Audit logging of every incoming request
  • User context initialization, reading Azure AD details & database records
  • ViewBag population for layout components (e.g., Department, Role, DisplayName)
  • Central place to implement permission checks (commented-out stubs)

Location: IrbyImaging.UI/Controllers/BaseController.cs
Author: kvamshi
Created: 05โ€‘17โ€‘2022


โš™๏ธ Dependencies & Technologies

Category Package / Framework
.NET Core / ASP.NET Core Microsoft.AspNetCore.Mvc, EntityFrameworkCore
Configuration Microsoft.Extensions.Configuration
HTTP Context & Filters Microsoft.AspNetCore.Http, Microsoft.AspNetCore.Mvc.Filters
Database Context IrbyContext (EF Core DbContext)
Models & Services IrbyImaging.Models, IrbyImaging.UI.Models
Repositories & Helpers AuditRepository, AzureADRead, ActiveDirectoryService

๐Ÿ› Class: BaseController

namespace IrbyImaging.UI.Controllers
{
    public class BaseController : Controller
    {
        private readonly IrbyContext _context;
        private readonly IConfiguration _configuration;
        
        // 1. Constructor
        public BaseController(IrbyContext context, IConfiguration configuration) { ... }

        // 2. Pre-Action Hook
        public override void OnActionExecuting(ActionExecutingContext filterContext) { ... }

        // 3. Audit Logger
        public void AuditActivity(ActionExecutingContext filterContext, Employee emp) { ... }
    }
}

1. Constructor

public BaseController(IrbyContext context, IConfiguration configuration)
{
    _context = context;
    _configuration = configuration;
}
  • Purpose: Injects the EF Core database context and application configuration.
  • Parameters:
    • IrbyContext context: access to DB sets (Employees, Audit logs, etc.).
    • IConfiguration configuration: access to appsettings.json or environment variables.

2. Override: OnActionExecuting

โœจ Pre-action filter that runs before any derived controller action:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    // 1. Read user claims (Full name, email)
    var fullname = User.Claims.ToList()[1].Value;
    var email = User.Identity.Name;
    
    // 2. Fetch Azure AD user details
    var ad = new AzureADRead(_context, _configuration);
    var res = ad.GetUserADList(email).Result;  // department, title, full name
    
    // 3. Fetch local Employee record
    var username = email.Split("@")[0];
    var employee = _context.Employees
                    .FirstOrDefault(e => e.WorkEmail == email)
                  ?? _context.Employees
                    .FirstOrDefault(e => e.UserName == username);
    
    // 4. Audit the request
    AuditActivity(filterContext, employee);
    
    // 5. Populate ViewBag for shared layout
    ViewBag.Department = res.Department ?? "";
    ViewBag.Role       = res.Title      ?? "";
    ViewBag.DisplayName= res.FullName   ?? "";
    
    base.OnActionExecuting(filterContext);
}

Key actions:

  • Retrieves Azure AD and database user info
  • Calls AuditActivity(...) to persist an audit log
  • Sets ViewBag values for UI rendering in Razor views

Note: Commented-out code stubs exist for employee status checks & dynamic permission assignment.

3. Method: AuditActivity

๐Ÿ“ Logs user interactions in Audit table.

public void AuditActivity(ActionExecutingContext filterContext, Employee emp)
{
    var audit = new AuditModel
    {
        UserEmail      = filterContext.HttpContext.User.Identity.Name,
        ControllerName = /* current controller */,
        ActionName     = /* current action */,
        Area           = /* MVC area if any */,
        PageAccessed   = filterContext.HttpContext.Request.Path,
        IpAddress      = filterContext.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString(),
        SessionId      = filterContext.HttpContext.Session.Id,
        LangId         = filterContext.HttpContext.Session.GetInt32(AllSessionKeys.LangId)?.ToString() ?? "",
        IsFirstLogin   = filterContext.HttpContext.Session.GetString(AllSessionKeys.IsFirstLogin) ?? "",
        Namespace      = filterContext.ActionDescriptor.DisplayName,
        UrlReferrer    = filterContext.HttpContext.Request.GetTypedHeaders().Referer?.AbsoluteUri,
        LoginStatus    = "Active"
    };

    // Persist via repository
    var repo = new AuditRepository(_context);
    repo.InsertAuditLogs(audit, emp);
}

Data Recorded:

  • UserEmail, Controller, Action, Area
  • Session ID, Language, FirstLogin
  • IP Address, Page Accessed, Referrer URL
  • Timestamp (added by repository or DB)

๐Ÿ”‘ Key Functional Areas

  1. Authentication Context
    • Reads the loggedโ€‘in user's claims & identity.
  2. Azure AD Integration
    • Enriches with department, title, full name via AzureADRead.
  3. Database Lookup
    • Finds corresponding Employee record.
  4. Audit Logging
    • Centralized AuditActivity to persist every request.
  5. UI Data Binding
    • Shares user metadata with all Razor views via ViewBag.
  6. Permission Hooks (commented-out)
    • Stubs for dynamic permission enforcement & termination checks.

๐Ÿ–ผ View Models & Data Models

Model Location Purpose
Employee IrbyImaging.Models HR/user details (Username, Email, Status)
AuditModel IrbyImaging.UI.Models Data shape for audit logging
IrbyContext IrbyImaging.BusinessLogic EF Core DB context for Employees, Audits
AllSessionKeys IrbyImaging.UI.Helpers Session key constants (LangId, FirstLogin)

๐Ÿ›  Helper Methods & Utilities

  • AzureADRead
    • Reads Azure AD graph for department/title via _context & _configuration.
  • ActiveDirectoryService
    • Placeholder for further AD operations (unused here).
  • AuditRepository
    • Encapsulates DB write logic for AuditModel.
  • AllSessionKeys
    • Constants for session-based flags (language, first login).

โš ๏ธ Error Handling & Return Types

  • Exceptions bubbling from Azure AD calls or EF Core queries will propagate up; no custom catch blocks in BaseController.
  • Redirect Logic
    • Commented-out redirection to UnAuthorized/Index for terminated employees or insufficient permissions.
  • Return Values
    • OnActionExecuting is void; you may set filterContext.Result to shortโ€‘circuit execution.

๐Ÿ”— Thirdโ€‘party Integrations

  1. Azure Active Directory
    • Via custom AzureADRead service to fetch user metadata.
  2. Entity Framework Core
    • For database connectivity & audit persistence.
  3. ASP.NET Core MVC Filters
    • Utilizes OnActionExecuting for cross-cutting concerns.

๐Ÿ’ก Sample Usage & Code Examples

Deriving from BaseController

public class HomeController : BaseController
{
    public HomeController(IrbyContext ctx, IConfiguration cfg)
        : base(ctx, cfg) { }

    public IActionResult Index()
    {
        // ะ’ัั‘ shared logic runs first (OnActionExecuting)
        return View();
    }
}

Audit Repository Insert (simplified)

public class AuditRepository
{
    private readonly IrbyContext _ctx;

    public AuditRepository(IrbyContext ctx) => _ctx = ctx;

    public void InsertAuditLogs(AuditModel model, Employee emp)
    {
        _ctx.AuditLogs.Add(model);
        _ctx.SaveChanges();
    }
}

๐Ÿ“ UML Class Diagram

@startuml
class BaseController {
  - IrbyContext _context
  - IConfiguration _configuration
  + BaseController(IrbyContext, IConfiguration)
  + OnActionExecuting(ActionExecutingContext)
  + AuditActivity(ActionExecutingContext, Employee)
}

class AzureADRead
class ActiveDirectoryService
class AuditRepository
class Employee
class AuditModel

BaseController --> AzureADRead : uses
BaseController --> ActiveDirectoryService : uses
BaseController --> AuditRepository : uses
AuditRepository --> AuditModel
BaseController ..> Employee : references
@enduml

๐Ÿ Conclusion

BaseController provides a robust foundation for all MVC controllers in the IrbyImaging.UI project by:

  • Centralizing authentication & user context logic
  • Automating audit log creation
  • Preparing UI-specific data (ViewBag) for shared layouts
  • Outlining hooks for advanced permission handling

Controllers inheriting from BaseController gain cross-cutting capabilities without cluttering individual action methods. Enjoy building on this solid base! ๐Ÿš€