API Endpoints
Relevant source files
The following files were used as context for generating this wiki page:The backend of the CDIO4 project is a Node.js application using the Express framework to provide a RESTful API. This API is the central point for data management, handling authentication, user accounts, and device information. It connects to a MongoDB database and serves data to the frontend application.
All primary API routes are prefixed with /api. The main server entry point registers these routes and configures essential middleware for handling requests, such as JSON body parsing and Cross-Origin Resource Sharing (CORS).
Sources: backend/src/server.js:82-84
Server Configuration and Request Flow
The main server file, server.js, initializes the Express application, connects to MongoDB, and configures middleware before mounting the API routes.
Sources: backend/src/server.js
Middleware
The application uses several key middleware:
express.json(): Parses incoming requests with JSON payloads.express.urlencoded(): Parses incoming requests with URL-encoded payloads.cors(): Enables Cross-Origin Resource Sharing for specified origins, allowing the frontend application to communicate with the API.
The CORS configuration is set to allow requests from http://localhost:3000, http://localhost:3001, and the URL specified in the FRONTEND_URL environment variable.
Sources: backend/src/server.js:43-54
Request Lifecycle
This diagram illustrates the flow of an incoming API request through the server.
Sources: backend/src/server.js:41-54, 82-84
Authentication API (/api/auth)
This module handles user registration and login. It uses JSON Web Tokens (JWT) for session management.
Sources: backend/src/routes/auth.js, backend/src/controllers/authController.js
Endpoints
| Method | Path | Description |
|---|---|---|
POST | /api/auth/register | Registers a new user account. It validates input, checks for existing emails, and creates a new TaiKhoan document. |
POST | /api/auth/login | Authenticates a user with an email and password. On success, it returns a JWT and user data. It checks if the account is active before allowing login. |
POST | /api/auth/logout | A placeholder endpoint that logs the logout request on the server and returns a success message. Actual token invalidation is handled client-side by deleting the token. |
Sources: backend/src/routes/auth.js:15-151
Login Sequence Diagram
The following diagram shows the sequence of events during a successful user login.
Sources: backend/src/routes/auth.js:93-142
JWT Generation
A JWT is created upon successful login using the signToken function. The token payload contains the user's ID (_id). It is signed with a secret from process.env.JWT_SECRET and has an expiration defined by process.env.JWT_EXPIRES_IN (defaulting to '7d').
Sources: backend/src/routes/auth.js:9-13
Account Management API (/api/taikhoan)
This is the primary API for managing user accounts (TaiKhoan model). It provides full CRUD (Create, Read, Update, Delete) functionality.
Sources: backend/src/routes/taiKhoan.js
Endpoints
| Method | Path | Description - |
|---|---|---|
GET | / | Retrieves a list of all user accounts. Selects a specific set of fields to return (_id, TenDangNhap, HoTen, Email, VaiTro, TrangThai). - |
POST | / | Creates a new user account. It performs validation, checks for duplicate TenDangNhap and Email, generates a custom _id (e.g., TK01), hashes the password, and saves the new user. - |
DELETE|/:id| Deletes a user by their ID. Includes a safeguard to prevent the deletion of the last 'Admin' user. - |PATCH|/:id/status| Updates the status of a user account (e.g., 'active', 'locked'). It prevents the last active 'Admin' from being locked. - |PATCH|/:id| Updates general user information likeHoTen,Email,VaiTro, andTrangThai. Includes validation for email format and uniqueness. - |
Sources: backend/src/routes/taiKhoan.js:5-214
Account Creation Flow (POST /api/taikhoan)
The process for creating a new account involves several steps, including custom ID generation and password hashing.
Sources: backend/src/routes/taiKhoan.js:16-80
Device API (/api/thietbi)
This API endpoint is responsible for retrieving a list of devices (ThietBi) and their associated sensor (CamBien) data.
Sources: backend/src/routes/thietBi.js
Endpoints
| Method | Path | Description - |
|---|---|---|
GET | / | Retrieves a paginated list of devices. It supports searching by device name (TenThietBi) and filtering by sensor status (TrangThai). The endpoint uses a MongoDB aggregation pipeline to join ThietBi and CamBien collections. |
Sources: backend/src/routes/thietBi.js:5-75
Query Parameters
| Parameter | Type | Default | Description - |
|---|---|---|---|
search | string | "" | A search term to filter devices by name (TenThietBi), case-insensitive. - |
status | string | "all" | Filters devices based on the associated sensor's status. Can be any status string or 'all' to disable filtering. - |
page | number | 1 | The page number for pagination. - |
limit | number | 10 | The number of results per page. |
Sources: backend/src/routes/thietBi.js:6-7
Aggregation Pipeline Visualization
The GET / endpoint uses a multi-stage aggregation pipeline to fetch and filter data.
Sources: backend/src/routes/thietBi.js:10-53
User Management API (/api/users)
This module provides a more structured approach to user management, intended for administrative purposes. It uses controllers and middleware for authorization and validation, which differs from the more direct approach in /api/taikhoan.
Sources: backend/src/routes/users.js, backend/src/controllers/userController.js
Key Features
- Role-Based Access Control (RBAC): Endpoints are protected using
protect(authentication) andauthorize('admin')(authorization) middleware. For example, getting all users or deleting a user requires admin privileges. - Input Validation: Uses
express-validatorto validate request bodies and parameters (e.g., ensuring a user ID is a valid MongoDB ID). - Controller-Service Pattern: Logic is separated into controller functions (
userController.js), promoting cleaner code.
Sources: backend/src/routes/users.js:12-13, 21-40, 50
Endpoints
| Method | Path | Access | Description - |
|---|---|---|---|
GET | / | Admin | Get a paginated list of all users. Supports filtering by role, isActive, and search (name/email). - |
GET | /:id | Private/Admin | Get a single user by ID. An admin can get any user, while a regular user can only get their own profile. - |
PUT | /:id | Private/Admin | Update a user's details (name, email, avatar). An admin can update any user, while a regular user can only update their own profile. - |
DELETE | /:id | Admin | Deletes a user by ID. This is a soft delete, setting the user's isActive property to false. A user cannot delete their own account via this endpoint. |
Sources: backend/src/routes/users.js:47-65, backend/src/controllers/userController.js:13-255