Overview
The inspir API uses JWT (JSON Web Token) authentication. Tokens are issued upon signup or login and remain valid for 7 days. Authentication flow:- User signs up or logs in
- Server returns a JWT token
- Client includes token in
Authorizationheader for subsequent requests - Server validates token and identifies user
Authentication Types
The API supports three authentication patterns:Public
No authentication required. Anyone can access.
Optional Auth
Works for guests, enhanced for authenticated users.
Required Auth
Must be authenticated. Returns 401 if not logged in.
Getting a Token
Sign Up
Create a new account and receive a JWT token:Username (alphanumeric, underscores, hyphens only)
Password (minimum 6 characters)
Password confirmation (must match password)
JWT authentication token (valid for 7 days)
| Status | Error | Cause |
|---|---|---|
400 | "Username and password are required" | Missing required fields |
400 | "Passwords do not match" | Password confirmation doesn’t match |
400 | "Password must be at least 6 characters" | Password too short |
400 | "Username already exists" | Username taken |
400 | "Username can only contain..." | Invalid username format |
429 | "Too many authentication attempts" | Rate limit exceeded (5 attempts per 15 minutes) |
Usernames are sanitized to allow only alphanumeric characters, underscores, and hyphens. The username is case-sensitive.
Log In
Authenticate with existing credentials:Your username
Your password
JWT authentication token (valid for 7 days)
| Status | Error | Cause |
|---|---|---|
400 | "Username and password are required" | Missing required fields |
401 | "Invalid username or password" | Incorrect credentials |
429 | "Too many authentication attempts" | Rate limit exceeded |
Using Your Token
Authorization Header
Include the JWT token in theAuthorization header using the Bearer scheme:
Token Structure
JWT tokens contain encoded user information:User’s unique identifier (UUID)
User’s username
Issued at (Unix timestamp)
Expiration time (Unix timestamp, 7 days from issuance)
Token Validation
The server validates tokens using the middleware inbackend/middleware/auth.js:7:
- Checks for
Authorizationheader withBearerprefix - Extracts and verifies JWT signature
- Decodes user ID from token payload
- Queries database to ensure user still exists
- Attaches user object to request:
req.user
Authentication Errors
When authentication fails, the API returns401 Unauthorized:
Missing Token
Request without Authorization header:Invalid Token Format
Malformed or corrupted JWT:Expired Token
Token older than 7 days:User Not Found
Valid token but user deleted from database: Response (401):Token Refresh
Tokens are valid for 7 days. There is currently no token refresh endpoint. To get a new token:- Log in again with username and password
- Replace the old token with the new one in your client
Best practice: Store tokens securely (e.g., in httpOnly cookies or secure storage). Never expose tokens in URLs or client-side JavaScript logs.
Optional Authentication
Some endpoints work for both guests and authenticated users. These use theoptionalAuth middleware (backend/middleware/auth.js:59):
Endpoints with optional authentication:
POST /api/quiz/generate- Generate quizzesPOST /api/quiz/submit- Submit quiz answersGET /api/quiz/:id- View specific quizPOST /api/quiz/shared/:shareToken/submit- Submit shared quiz
- Without token: Request proceeds as guest user
- With valid token:
req.useris populated with user data - With invalid token: Request proceeds as guest (no error)
Required Authentication
Endpoints that require authentication will return401 if no valid token is provided:
Protected endpoints:
GET /api/auth/me- Get current userGET /api/quiz/history- Get quiz historyPOST /api/quiz/:quizId/share- Share a quizGET /api/quiz/:quizId/attempts- View quiz statisticsGET /api/streaks- View study streaks- User profile and settings endpoints
Get Current User
Verify authentication and retrieve current user information:Bearer token
| Status | Error | Cause |
|---|---|---|
401 | "No authorization token provided" | Missing Authorization header |
401 | "Invalid token" | Malformed JWT |
401 | "Token expired" | Token older than 7 days |
401 | "Invalid or expired token" | User not found in database |
401 | "Not authenticated" | Generic authentication failure |
Logout
Log out from the current session:Since authentication is JWT-based and stateless, logout is primarily handled client-side by removing the stored token. The server endpoint exists for consistency but doesn’t invalidate the token server-side. The token remains technically valid until expiration (7 days).
Security Best Practices
Store tokens securely
Store tokens securely
- Use httpOnly cookies for web applications
- Use secure storage mechanisms in mobile apps
- Never store tokens in localStorage if XSS is a concern
- Never expose tokens in URLs or logs
Handle token expiration gracefully
Handle token expiration gracefully
- Monitor for 401 responses indicating expired tokens
- Prompt users to re-authenticate when tokens expire
- Consider implementing token refresh before implementing auto-re-login
Use HTTPS in production
Use HTTPS in production
- Always use HTTPS to prevent token interception
- The production API enforces HTTPS
- Development environments (localhost) can use HTTP
Respect rate limits
Respect rate limits
- Authentication endpoints are limited to 5 attempts per 15 minutes
- Implement exponential backoff for retry logic
- Cache tokens instead of requesting new ones on every API call
Example: Complete Authentication Flow
Here’s a complete example of signing up, authenticating, and making authenticated requests:Next Steps
Quiz API
Generate and manage quizzes with authentication
Study Tools
Access AI-powered study tools