### Environment Configuration for Robust Source: https://context7.com/pablo-peek/robust/llms.txt Specifies the essential environment variables required for the Robust project, including the server port, MongoDB connection URI, and JWT secret key. Also includes instructions for starting the development server. ```bash # .env file PORT=3000 ROBUST_MONGODB_URI=mongodb://localhost:27017/robust KEY_SECRET=your-jwt-secret-key-here # Start development server npm run start:dev ``` -------------------------------- ### GET /api/user/all-users-races - Get Race Leaderboard Source: https://context7.com/pablo-peek/robust/llms.txt Retrieves a paginated leaderboard for a specific race, sorted by best lap times in ascending order. ```APIDOC ## GET /api/user/all-users-races ### Description Retrieves a paginated leaderboard for a specific race, sorted by best lap times in ascending order. ### Method GET ### Endpoint /api/user/all-users-races ### Parameters #### Headers - **Authorization** (string) - Required - The JWT token for authentication. #### Query Parameters - **raceNumber** (integer) - Required - The number of the race to get the leaderboard for. - **page** (integer) - Optional - The page number for pagination. Defaults to 1. - **limit** (integer) - Optional - The number of results per page. Defaults to 10. ### Request Example ```bash curl -X GET "http://localhost:3000/api/user/all-users-races?raceNumber=1&page=1&limit=10" \ -H "Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` ### Response #### Success Response (200) - **status** (integer) - The HTTP status code, 200 for OK. - **data** (array) - An array of user leaderboard entries. - **_id** (string) - The user's unique identifier. - **username** (string) - The user's username. - **isCurrentUser** (boolean) - Indicates if this entry represents the currently authenticated user. - **races** (array) - An array of race data for the user. - **raceNumber** (integer) - The number of the race. - **bestTime** (number) - The user's best lap time for this race. - **formattedBestTime** (string) - The user's best lap time formatted as a string (e.g., "01:32.543"). #### Response Example ```json { "status": 200, "data": [ { "_id": "507f1f77bcf86cd799439011", "username": "SpeedRacer", "isCurrentUser": true, "races": [{ "raceNumber": 1, "bestTime": 92.543, "formattedBestTime": "01:32.543" }] }, { "_id": "507f1f77bcf86cd799439012", "username": "FastDriver", "isCurrentUser": false, "races": [{ "raceNumber": 1, "bestTime": 93.127, "formattedBestTime": "01:33.127" }] } ] } ``` ``` -------------------------------- ### GET /api/user/user-get-profile - Get User Profile Source: https://context7.com/pablo-peek/robust/llms.txt Retrieves the complete profile for the authenticated user, including all race statistics and customization settings. ```APIDOC ## GET /api/user/user-get-profile ### Description Retrieves the complete profile for the authenticated user, including all race statistics and customization settings. ### Method GET ### Endpoint /api/user/user-get-profile ### Parameters #### Headers - **Authorization** (string) - Required - The JWT token for authentication. ### Response #### Success Response (200) - **status** (integer) - The HTTP status code, 200 for OK. - **data** (object) - The user's profile information. - **_id** (string) - The user's unique identifier. - **username** (string) - The user's username. - **email** (string) - The user's email address. - **avatar** (string) - The user's selected avatar. - **variant** (string) - The user's selected avatar variant. - **races** (array) - An array of race data for the user. - **raceNumber** (integer) - The number of the race. - **bestTime** (number) - The user's best lap time for this race. - **created_at** (string) - The timestamp when the user was created. - **updated_at** (string) - The timestamp when the user profile was last updated. #### Response Example ```json { "status": 200, "data": { "_id": "507f1f77bcf86cd799439011", "username": "SpeedRacer", "email": "racer@example.com", "avatar": "Margaret", "variant": "marble", "races": [ { "raceNumber": 1, "bestTime": 92.543 }, { "raceNumber": 2, "bestTime": 105.221 } ], "created_at": "2024-01-15T10:30:00.000Z", "updated_at": "2024-01-20T14:22:00.000Z" } } ``` ``` -------------------------------- ### Get User Profile API Endpoint (Bash) Source: https://context7.com/pablo-peek/robust/llms.txt Fetches the complete profile of the authenticated user, including their username, email, avatar, variant settings, and all recorded race statistics. Requires JWT authentication. ```bash curl -X GET http://localhost:3000/api/user/user-get-profile \ -H "Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### Get Race Leaderboard API Endpoint (Bash) Source: https://context7.com/pablo-peek/robust/llms.txt Retrieves a paginated leaderboard for a specific race. The results are sorted by best lap times in ascending order and require user authentication. Useful for displaying competitive rankings. ```bash curl -X GET "http://localhost:3000/api/user/all-users-races?raceNumber=1&page=1&limit=10" \ -H "Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### Untitled No description -------------------------------- ### Register User API Endpoint (Bash) Source: https://context7.com/pablo-peek/robust/llms.txt Registers a new user by sending their email, password, and username to the API. Passwords are encrypted using bcrypt, and a JWT token is returned upon successful registration. This endpoint is crucial for new user onboarding. ```bash curl -X POST http://localhost:3000/api/auth/register \ -H "Content-Type: application/json" \ -d '{ \ "email": "racer@example.com", \ "password": "SecurePass123!", \ "username": "SpeedRacer" \ }' ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### POST /api/auth/register - User Registration Source: https://context7.com/pablo-peek/robust/llms.txt Registers a new user with email, password, and username. Returns a JWT token upon successful registration. Passwords are encrypted using bcrypt. ```APIDOC ## POST /api/auth/register ### Description Registers a new user with email, password, and username. Returns a JWT token upon successful registration. Passwords are encrypted using bcrypt. ### Method POST ### Endpoint /api/auth/register ### Parameters #### Request Body - **email** (string) - Required - The email address of the user. - **password** (string) - Required - The user's password. - **username** (string) - Required - The desired username for the user. ### Request Example ```json { "email": "racer@example.com", "password": "SecurePass123!", "username": "SpeedRacer" } ``` ### Response #### Success Response (201) - **status** (integer) - The HTTP status code, 201 for created. - **message** (string) - A success message. - **data** (object) - Contains authentication details. - **auth** (boolean) - Indicates if authentication was successful. - **token** (string) - The JWT token for the authenticated user. - **username** (string) - The username of the registered user. #### Response Example ```json { "status": 201, "message": "User created successfully", "data": { "auth": true, "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "username": "SpeedRacer" } } ``` ``` -------------------------------- ### POST /api/auth/login - User Login Source: https://context7.com/pablo-peek/robust/llms.txt Authenticates an existing user and returns a JWT token valid for 365 days. ```APIDOC ## POST /api/auth/login ### Description Authenticates an existing user and returns a JWT token valid for 365 days. ### Method POST ### Endpoint /api/auth/login ### Parameters #### Request Body - **email** (string) - Required - The email address of the user. - **password** (string) - Required - The user's password. ### Request Example ```json { "email": "racer@example.com", "password": "SecurePass123!" } ``` ### Response #### Success Response (200) - **status** (integer) - The HTTP status code, 200 for OK. - **message** (string) - A success message. - **data** (object) - Contains authentication details. - **auth** (boolean) - Indicates if authentication was successful. - **token** (string) - The JWT token for the authenticated user. - **username** (string) - The username of the logged-in user. #### Response Example ```json { "status": 200, "message": "Login successful", "data": { "auth": true, "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "username": "SpeedRacer" } } ``` ``` -------------------------------- ### Controller Handler Middleware for Robust Source: https://context7.com/pablo-peek/robust/llms.txt A middleware function that wraps controller actions to standardize request handling, error management, and response formatting for the Robust application. ```javascript const { to } = require('await-to-js'); function controllerHandler(controllerAction) { return async (req, res, next) => { const httpRequest = { body: req.body, query: req.query, params: req.params, headers: { authorization: req.headers.authorization, }, }; const [err, result] = await to(controllerAction(httpRequest)); if(err) return next(err); return res.status(result?.status || 200).send(result); } } // Usage in router: const controllerHandler = require('../middlewares/controller-handler'); const AuthController = require('../controllers/auth.controller'); authRouter.route('/login').post(controllerHandler(AuthController.login)); ``` -------------------------------- ### Login User API Endpoint (Bash) Source: https://context7.com/pablo-peek/robust/llms.txt Authenticates an existing user by providing their email and password. Upon successful authentication, the API returns a JWT token valid for 365 days, used for subsequent authorized requests. This is the primary method for user access. ```bash curl -X POST http://localhost:3000/api/auth/login \ -H "Content-Type: application/json" \ -d '{ \ "email": "racer@example.com", \ "password": "SecurePass123!" \ }' ``` -------------------------------- ### Input Validation with Joi Source: https://context7.com/pablo-peek/robust/llms.txt Provides Joi validation schemas for user registration and race data submissions. These functions ensure data integrity by defining required fields, formats, and constraints. ```javascript const Joi = require('joi'); function validateRegisterData(data) { const schema = Joi.object({ email: Joi.string().email().required(), password: Joi.string() .min(8) .pattern(new RegExp('^(?=.*[A-Z])(?=.*[!@#$&*])')) .required().messages({ 'string.pattern.base': 'Password must have at least one uppercase letter and one special character' }), username: Joi.string().required().min(4).max(20).messages({ 'string.min': 'Username must have at least 4 characters', 'string.max': 'Username must have at most 20 characters' }), }); return schema.validate(data); } function validatePutFastLapInRace(data) { const schema = Joi.object({ raceId: Joi.number().required(), lapTime: Joi.number().min(0).required() }); return schema.validate(data); } // Usage in controller: const { error } = validateRegisterData(requestBody); if (error) { throw new CustomError({ message: error.details[0].message }); } ``` -------------------------------- ### PUT /api/user/user-update-profile - Update User Profile Source: https://context7.com/pablo-peek/robust/llms.txt Updates the user's avatar and variant customization settings. ```APIDOC ## PUT /api/user/user-update-profile ### Description Updates the user's avatar and variant customization settings. ### Method PUT ### Endpoint /api/user/user-update-profile ### Parameters #### Headers - **Authorization** (string) - Required - The JWT token for authentication. - **Content-Type** (string) - Required - Should be `application/json`. #### Request Body - **avatar** (string) - Optional - The new avatar name to set. - **variant** (string) - Optional - The new variant name to set. ### Request Example ```json { "avatar": "Sarah", "variant": "sunset" } ``` ### Response #### Success Response (200) - **status** (integer) - The HTTP status code, 200 for OK. - **data** (object) - The updated user profile information. - **_id** (string) - The user's unique identifier. - **username** (string) - The user's username. - **email** (string) - The user's email address. - **avatar** (string) - The updated avatar. - **variant** (string) - The updated variant. #### Response Example ```json { "status": 200, "data": { "_id": "507f1f77bcf86cd799439011", "username": "SpeedRacer", "email": "racer@example.com", "avatar": "Sarah", "variant": "sunset" } } ``` ``` -------------------------------- ### User Model Schema with Mongoose Source: https://context7.com/pablo-peek/robust/llms.txt Defines the MongoDB user schema using Mongoose, including fields for username, email, password, race data, and timestamps. It also includes methods for password encryption and validation. ```javascript const { Schema, model } = require("mongoose"); const { hash, compare, genSalt } = require("bcrypt"); const userSchema = new Schema({ username: { type: String, require: true, unique: true }, email: { type: String, require: true, unique: true }, password: { type: String, require: true }, races: [{ raceNumber: { type: Number, require: true }, bestTime: { type: Number, require: true } }], avatar: { type: String, require: false, default: 'Margaret' }, variant: { type: String, require: false, default: 'marble' }, created_at: { type: Date, require: true, default: Date.now }, updated_at: { type: Date, require: true, default: Date.now } }, { versionKey: false }); userSchema.methods.encryptPassword = async (password) => { const salt = await genSalt(10); return hash(password, salt); }; userSchema.methods.validatePassword = function (password) { return compare(password, this.password); } const User = model('User', userSchema); module.exports = User; ``` -------------------------------- ### Submit Fastest Lap Time API Endpoint (Bash) Source: https://context7.com/pablo-peek/robust/llms.txt Records a lap time for a specific race. If the new lap time is faster than the current best time for that race, the system updates the user's record. Requires authentication via JWT. ```bash curl -X PUT http://localhost:3000/api/user/fast-lap-in-race \ -H "Content-Type: application/json" \ -H "Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -d '{ \ "raceId": 1, \ "lapTime": 92.543 \ }' ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Update User Profile API Endpoint (Bash) Source: https://context7.com/pablo-peek/robust/llms.txt Allows the authenticated user to update their profile, specifically their avatar and variant customization settings. This endpoint uses the PUT method and requires JWT authentication. ```bash curl -X PUT http://localhost:3000/api/user/user-update-profile \ -H "Content-Type: application/json" \ -H "Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \ -d '{ \ "avatar": "Sarah", \ "variant": "sunset" \ }' ``` -------------------------------- ### JWT Token Verification Middleware Source: https://context7.com/pablo-peek/robust/llms.txt Middleware designed to authenticate requests by verifying JWT tokens present in the Authorization header. It ensures that only authenticated users can access protected routes. ```javascript const jwt = require('jsonwebtoken'); function verifyToken(req, res, next) { const token = req.headers["authorization"]; if(!token || token === null){ return res.status(401).json({ auth: false, message: "No token provided" }); } try { const decoded = jwt.verify(token, process.env.KEY_SECRET); req.userId = decoded.id; return res.status(200).json({ auth: true, message: "Token is valid", user: decoded.id, token: token }); } catch (error) { return res.status(401).json({ auth: false, message: "Failed to authenticate token" }); } } module.exports = verifyToken; ``` -------------------------------- ### PUT /api/user/fast-lap-in-race - Submit Fastest Lap Time Source: https://context7.com/pablo-peek/robust/llms.txt Records a lap time for a specific race. The system automatically updates the best time if the new lap is faster. ```APIDOC ## PUT /api/user/fast-lap-in-race ### Description Records a lap time for a specific race. The system automatically updates the best time if the new lap is faster. ### Method PUT ### Endpoint /api/user/fast-lap-in-race ### Parameters #### Headers - **Authorization** (string) - Required - The JWT token for authentication. - **Content-Type** (string) - Required - Should be `application/json`. #### Request Body - **raceId** (integer) - Required - The ID of the race. - **lapTime** (number) - Required - The recorded lap time in seconds. ### Request Example ```json { "raceId": 1, "lapTime": 92.543 } ``` ### Response #### Success Response (200) - **status** (integer) - The HTTP status code, 200 for OK. - **data** (array) - An array containing the updated race best time. - **raceNumber** (integer) - The number of the race. - **bestTime** (number) - The fastest lap time recorded for the race. #### Response Example ```json { "status": 200, "data": [ { "raceNumber": 1, "bestTime": 92.543 } ] } ``` ``` -------------------------------- ### Untitled No description -------------------------------- ### POST /api/auth/validate-token - Validate Token Source: https://context7.com/pablo-peek/robust/llms.txt Verifies the validity of a JWT token and returns the associated user ID. ```APIDOC ## POST /api/auth/validate-token ### Description Verifies the validity of a JWT token and returns the associated user ID. ### Method POST ### Endpoint /api/auth/validate-token ### Parameters #### Headers - **Authorization** (string) - Required - The JWT token to validate. ### Request Example ```bash curl -X POST http://localhost:3000/api/auth/validate-token \ -H "Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` ### Response #### Success Response (200) - **auth** (boolean) - Indicates if the token is valid. - **message** (string) - A message indicating the token status. - **user** (string) - The user ID associated with the token. - **token** (string) - The validated JWT token. #### Response Example ```json { "auth": true, "message": "Token is valid", "user": "507f1f77bcf86cd799439011", "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` ``` -------------------------------- ### Validate JWT Token API Endpoint (Bash) Source: https://context7.com/pablo-peek/robust/llms.txt Verifies the validity of a provided JWT token. It returns an authentication status and the associated user ID if the token is valid. This endpoint is essential for securing other API resources. ```bash curl -X POST http://localhost:3000/api/auth/validate-token \ -H "Authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.