Authentication API Endpoints
Relevant source files
The following files were used as context for generating this wiki page:
The Authentication API in NEXUS provides a secure framework for user identity management, enabling registration, login, and session validation. It utilizes JSON Web Tokens (JWT) for stateless authentication and bcrypt for secure password hashing, ensuring that sensitive user credentials are never stored in plain text.
This system serves as the gateway to the "Digital Command Center," protecting all downstream resources such as Account Vault, Email Management, and Trial Tracking. The backend is built with FastAPI and integrates with MongoDB for persistent storage, while the frontend leverages React Context and Axios interceptors to manage authentication state across the application.
System Architecture
The authentication architecture follows a client-server model where the backend issues a signed JWT upon successful credential verification. This token is then stored by the client and included in the Authorization header for subsequent requests to protected endpoints.
Authentication Flow
The following diagram illustrates the lifecycle of a user session from registration to accessing protected dashboard statistics.
The sequence shows the transition from public registration to authenticated state management.
Sources: backend/server.py:171-209, frontend/src/App.js:24-60
Backend Implementation
The backend is implemented using FastAPI and utilizes several key security libraries. The SECRET_KEY and ALGORITHM (HS256) are used to sign tokens, with a default expiration of 30 minutes.
Key Security Components
| Component | Implementation | Purpose |
|---|---|---|
| Password Hashing | bcrypt.hashpw | Salts and hashes passwords before DB insertion. |
| Token Generation | jwt.encode | Creates signed access tokens with an expiry claim (exp). |
| Security Scheme | HTTPBearer | Defines the bearer token requirement for FastAPI routes. |
| Validation | jwt.decode | Verifies token integrity and extracts the sub (username) claim. |
Sources: backend/server.py:34-40, backend/server.py:155-170, backend/requirements.txt:3, 50
API Endpoints Summary
| Endpoint | Method | Auth Required | Description |
|---|---|---|---|
/api/register | POST | No | Validates unique username/email and creates a new user. |
/api/login | POST | No | Verifies credentials and returns a JWT access token. |
/api/me | GET | Yes | Returns the currently authenticated user's profile. |
Sources: backend/server.py:172, backend/server.py:194, backend/server.py:206, backend_test.py:73-125
Data Models
The system utilizes Pydantic models to enforce strict schema validation for incoming authentication requests.
class UserCreate(BaseModel):
username: str
email: EmailStr
password: str
class UserLogin(BaseModel):
username: str
password: str
class Token(BaseModel):
access_token: str
token_type: str
Sources: backend/server.py:72-84
Frontend Integration
The NEXUS frontend manages authentication state through an AuthProvider component. This provider wraps the entire application, ensuring that the user's login status is globally accessible via the useAuth hook.
Authentication Context Logic
The AuthProvider handles token persistence using localStorage and configures default Axios headers.
const login = async (username, password) => {
try {
const response = await axios.post(`${API}/login`, { username, password });
const { access_token } = response.data;
localStorage.setItem('token', access_token);
setToken(access_token);
axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}`;
const userResponse = await axios.get(`${API}/me`);
setUser(userResponse.data);
return true;
} catch (error) {
throw error;
}
};
Sources: frontend/src/App.js:37-53
Protected Routes
Access to the main dashboard and CRUD interfaces is restricted using the ProtectedRoute component. If no user is present in the context, the application redirects to the /login route.
The flowchart demonstrates the logic applied by the ProtectedRoute component to secure application views.
Sources: frontend/src/App.js:1010-1037
Testing and Validation
The authentication system is verified through a dedicated Python test suite that performs end-to-end checks on registration, login, and token rejection.
Test Results Overview
Recent testing protocols confirmed the system's reliability:
- Registration: Successfully handles new users and detects existing accounts.
- Login: Validates credentials and verifies token generation.
- Protected Access: Confirms the
/meendpoint correctly identifies users via token. - Invalid Token Handling: Correctly returns a
401 Unauthorizedstatus for malformed or expired tokens.
Sources: backend_test.py:73-125, test_result.md:92-104
Conclusion
The Authentication API Endpoints form the security foundation of NEXUS. By combining FastAPI's dependency injection system (Depends(get_current_user)) with industry-standard JWT and bcrypt implementations, the project ensures user data isolation and protected access to all management modules. The seamless integration with the React frontend provides a responsive experience while maintaining strict server-side security.