Skip to main content

Dynamic Time Restriction System - Developer Documentation

This component provides a robust, MongoDB-backed time restriction system that allows updating API availability (times, days, routes) without any code deployment. It uses a template-based approach to minimize duplication.

Key Features

  • Zero Deployment Updates: Change settings via API or direct DB update (MongoDB).
  • Template-Based: Define reusable time restriction templates and reference them across multiple routes.
  • Distributed Caching (Redis): Uses Redis to share configuration across all server instances.
  • Manual Refresh: Admin API to trigger an immediate update in Redis and all server instances.

Directory Structure

  • models.py: Pydantic models for data validation and structure.
  • service.py: Core logic for caching (Redis), DB syncing (MongoDB), and template-based access checking. Includes a configurable in-memory local cache (Default: 10 minutes) for zero-latency lookups.
  • middleware.py: FastAPI middleware for global enforcement of restrictions.
  • api.py: Admin endpoints for configuration and template management.
  • utils.py: Helper functions for JSON serialization.

API Usage

1. View Current Configuration

Endpoint: GET /api/v1/time-restrictions/ Returns the current active configuration (routes + resolved templates) currently loaded in memory.

2. Manage Templates (Reduced Duplication)

Templates are stored in the time_restriction_templates collection.

Endpoint: POST /api/v1/time-restrictions/templates Body:

{
"name": "standard_school_hours",
"time_slots": [
{
"start_time": "08:00:00",
"end_time": "18:00:00",
"allowed_days": ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]
}
],
"enabled": true,
"message": "API available only during school hours (08:00 - 18:00)",
"status_code": 423,
"user_id": "60d5ecb8b391690015ef5c2a"
}

Endpoint: GET /api/v1/time-restrictions/templates - List all templates. Endpoint: DELETE /api/v1/time-restrictions/templates/{name} - Delete a template.

3. Configure Routes

Routes are stored in the dynamic_time_restrictions collection. Routes can reference templates and override specific fields.

Endpoint: PUT /api/v1/time-restrictions/ Body:

{
"routes": {
"/api/teacher/app/create_student_assessment/": {
"template": "standard_school_hours",
"enabled": true,
"message": "Custom Message: Assessment not available now"
},
"/api/v2/admin/emergency-block/": {
"time_slots": [],
"enabled": true,
"force_block": true,
"message": "Emergency maintenance in progress"
}
},
"user_id": "60d5ecb8b391690015ef5c2a"
}

Updating via this API saves the config as the "active" record in the dynamic_time_restrictions collection and immediately refreshes the server instance's memory cache.

2.3 Partial Update (Merging)

Endpoint: PATCH /api/v1/time-restrictions/ Allows you to update specific routes without providing the full configuration. New routes are added, and existing ones are updated.

Body:

{
"routes": {
"/api/teacher/app/new-feature/": {
"template": "school_hours",
"enabled": true
}
},
"user_id": "60d5ecb8b391690015ef5c2a"
}

Detailed Model Attributes

Template & Route Common Attributes

AttributeTypeDescription
namestring(Template Only) Unique identifier for the template.
templatestring(Route Only) Reference to a template's name. The route will inherit the template's settings.
time_slotsarrayList of allowed time intervals. If defined at the route level, it overrides the template.
enabledbooleanIf false, the restriction is disabled for this route/template (Default: true).
force_blockbooleanIf true, the API is blocked 24/7 regardless of time slots. If either route OR template has this true, it is blocked (Default: false).
messagestringCustom error message shown when blocked.
status_codeintegerHTTP status code returned when blocked (Default: 423).
endpoint_detailstring(Route Only) Optional description of what the API does for documentation purposes.
user_idstringRequired. Must be a valid 24-character hex MongoDB ObjectId.

Time Slot Object

AttributeTypeDescription
start_timestringFormat "HH:MM:SS" (e.g., "08:00:00").
end_timestringFormat "HH:MM:SS" (e.g., "18:00:00").
allowed_daysarrayList of days ("monday", "tuesday", etc.) when access is permitted.
timezonestringTimezone for calculations (Default: "Asia/Kolkata").

Overriding Logic

  1. Field Override: If a route provides its own time_slots, message, or status_code, it completely overrides the values in the referenced template.
  2. force_block Merge: If a template says force_block: true, its routes are blocked unless they disable the restriction via enabled: false.

4. Force Sync from Database

Endpoint: POST /api/v1/time-restrictions/refresh Forces the server to sync with the latest MongoDB state (both templates and routes) immediately.

Integration Details

  • This component is registered in main.py via DynamicTimeRestrictionMiddleware.
  • The router is registered under the prefix /api/v1/time-restrictions.
  • The original logic in app/time_restrictions is preserved but inactive as a backup.