Request/Response Flow
Relevant source files
The following files were used as context for generating this wiki page:
The Request/Response Flow in the Smart Absen system is designed for consistency, security, and maintainability. It standardizes how the Flask backend processes incoming requests and formats outgoing responses, particularly for its API endpoints. The architecture leverages helper functions for uniform JSON responses, validation decorators to secure endpoints, and a combination of synchronous and asynchronous patterns to handle features like real-time QR code synchronization.
This document outlines the primary flows, from standard API calls to the more complex cross-device authentication mechanism. The system handles both traditional HTML page rendering for user navigation and standardized JSON responses for API interactions, which are consumed by the frontend JavaScript.
Standard API Response
All API endpoints in the application adhere to a standardized JSON response format. This is managed by a central api_response helper function, ensuring that the frontend can reliably handle both successful and failed operations.
Sources: SECURITY.md, CLEANUP_REPORT.md
Response Structure
The JSON response object contains a consistent set of keys to provide clear feedback on the API call's outcome.
The table below details each field in the standard response object.
| Field | Type | Description | Example |
|---|---|---|---|
success | boolean | true for a successful operation, false for an error. | true |
status | string | A string keyword for the status, e.g., "success" or "error". | "success" |
message | string | A human-readable message describing the result. | "Operation completed" |
data | object/array | The payload of the response. Contains the requested data on success. | {"employee_id": 1, "name": "John"} |
timestamp | string | An ISO 8601 timestamp for when the response was generated. | "2025-12-07T17:45:00" |
Sources: SECURITY.md
Example Usage
The following snippet from the project's documentation illustrates how the api_response helper is used within a Flask route to generate a standard response.
from helpers import api_response
@app.route('/api/test')
def test():
try:
data = {'message': 'Hello'}
return api_response(True, 'Success', data)
except Exception as e:
return api_response(False, str(e), status_code=500)
Sources: SECURITY.md
Input Validation Flow
To enhance security and prevent invalid data from being processed, the application uses Python decorators to validate incoming requests. These decorators are defined in validators.py and are applied to Flask routes.
Sources: SECURITY.md, CLEANUP_REPORT.md
The general request lifecycle, including the validation step, is as follows:
This diagram shows how a request is intercepted by validation decorators before the main function logic is executed.
Sources: SECURITY.md
Key Validators
| Decorator | Description |
|---|---|
@validate_json | Ensures the request has the Content-Type: application/json header. |
@validate_employee_data | Validates the fields required for adding or updating an employee. |
@validate_attendance_data | Validates the data submitted for marking attendance. |
Sources: SECURITY.md
API Endpoints Overview
The system exposes several RESTful API endpoints for frontend interaction, admin operations, and core functionalities like attendance and QR sync. The endpoints are formally defined in static/openapi.yaml.
| Method | Endpoint | Description |
|---|---|---|
GET | /api/qr_sync_status | Polling endpoint to check if a QR code has been scanned. |
POST | /api/accept_qr_sync | Accepts a sync request from a mobile device to authenticate a session. |
GET | /api/refresh_qr | Generates a new QR code and associated unit code. |
POST | /mark_attendance_mobile | Submits attendance data from a mobile device, including a facial image. |
GET | /api/get_attendance_data | Retrieves attendance records with optional filters. |
GET | /api/employees | Retrieves a list of all employees. |
POST | /api/employees | Adds a new employee to the system. |
POST | /api/train_model | Triggers the retraining of the face recognition model. |
GET | /health | A health check endpoint to monitor system status. |
Sources: static/openapi.yaml, README.md
Detailed Flows
QR Code Authentication Flow
The QR code authentication is a multi-step, asynchronous process designed to link a desktop session with a mobile device for face capture.
This sequence diagram illustrates the interactions between the user's devices and the server.
Flow Description:
- The user's laptop requests the
/authpage, and the server returnsqr_auth.html. - The JavaScript on
qr_auth.htmlbegins polling the/api/qr_sync_statusendpoint every 5 seconds. - The user scans the QR code with their mobile device, which opens a verification URL.
- The mobile device is used to capture a face and submit attendance via
POST /mark_attendance_mobile. - Upon successful attendance, the server sets a flag indicating a completed sync for that session.
- The laptop's next poll to
/api/qr_sync_statusreceives ahas_pending_sync: trueresponse. - The laptop then calls
POST /api/accept_qr_syncto confirm the sync and receives a redirect URL. - The laptop navigates to the attendance page, completing the flow.
Sources: templates/qr_auth.html, static/openapi.yaml
Admin Dashboard Data Flow
The admin dashboard is a single-page application (SPA) that dynamically loads data and content into iframes or via API calls. The main dashboard page fetches real-time statistics to populate its widgets and charts.
This diagram shows the flow for loading initial dashboard stats.
Flow Description:
- The
admin_dashboard.htmlpage loads and its JavaScript executes afetchrequest to the/admin/api/statsendpoint. - The server receives the request and queries the database for multiple statistics: total employees, today's attendance count, absent count, and recent activity.
- The server aggregates this data into a single JSON object.
- The JSON response is sent back to the admin dashboard.
- The frontend JavaScript parses the JSON and updates the DOM to display the new numbers in the stat cards and refresh the charts. This process repeats every 5 seconds to keep the data fresh.
Sources: templates/admin_dashboard.html:1000-1015, templates/admin_dashboard_new.html:437-453
Error Handling Flow
The system provides user-friendly error responses. For API requests, it uses the standardized JSON error format. For direct browser requests that result in an error (e.g., 404 Not Found), it renders a dedicated HTML error page.
Sources: SECURITY.md
This diagram shows the two distinct paths for handling errors depending on the request type.
Sources: SECURITY.md