Authentication Methods
The Water Quality Backend API supports three authentication methods:- Email/Password Authentication - Traditional email and password login with Firebase Auth
- JWT Token Authentication - Stateless JWT tokens for API requests
- GitHub OAuth - Social authentication via GitHub
Authorization header.
Email/Password Authentication
User Registration
Create a new user account with email and password. Endpoint:POST /auth/register/
Request Body:
Passwords must meet Firebase Auth requirements. The password is validated using the
PasswordStr type from ~/workspace/source/app/share/users/domain/types.py.200 OK):
User Login
Authenticate with email and password to receive a JWT token. Endpoint:POST /auth/login/
Request Body:
200 OK):
404- User not registered401- Invalid credentials
Authentication Flow
The login process follows these steps (from~/workspace/source/app/features/auth/services/services.py:23-48):
Validate Credentials with Firebase
Credentials are validated against Firebase Auth using the Identity Toolkit API:
Generate JWT Token
Upon successful authentication, a JWT token is created with user data and a 30-day expiration.
JWT Token Authentication
Token Structure
JWT tokens are generated using the HS256 algorithm and contain the following payload:uid- Unique user identifieremail- User email addressusername- User’s display namephone- Phone number (optional)rol- User role (client,manager,administrator)exp- Token expiration timestamp (Unix timestamp)
Using Bearer Tokens in Requests
Include the JWT token in theAuthorization header with the Bearer scheme:
Token Validation
Tokens are validated using the shared secret key configured in the JWT configuration. The validation process:- Decodes the token using the HS256 algorithm
- Verifies the signature with the secret key
- Checks the expiration timestamp
- Extracts the user payload
~/workspace/source/app/share/jwt/infrastructure/access_token.py:20-23 for implementation.
Token Expiration and Refresh
Token Expiration: JWT tokens expire after 30 days (2,592,000 seconds) Token Issued At:~/workspace/source/app/features/auth/presentation/routes.py:89
- Catch 401 Unauthorized responses
- Prompt the user to log in again
- Store the new token for subsequent requests
GitHub OAuth Authentication
The API supports GitHub OAuth for social authentication.OAuth Flow
Initiate OAuth Flow
Redirect users to the GitHub login endpoint:
- Web:
GET /auth/github/login/web - Mobile:
GET /auth/github/login/mobile
GitHub Callback
GitHub redirects back to the callback URL with an authorization code:
GET /auth/github/callback?code=...&state=...GitHub OAuth Endpoints
Web Login
FRONTEND_ORIGIN environment variable.
Example:
Mobile Login
OAuth Callback
Users are redirected here after authorizing on GitHub:GitHub OAuth Security
The OAuth implementation includes several security features:- Signed State Parameter - Prevents CSRF attacks using HMAC-SHA256
- State Expiration - State tokens expire after 10 minutes
- Redirect URI Whitelist - Only allowed origins can receive tokens
- Timeout Handling - 10-second timeout for GitHub API requests
~/workspace/source/app/features/auth/presentation/routes.py:48-70 for state signing/verification.
Password Reset Flow
The API provides a secure password reset flow using verification codes.Step 1: Request Password Reset
Endpoint:POST /auth/request-password-reset/
Request Body:
200 OK):
Step 2: Verify Reset Code
Endpoint:POST /auth/verify-reset-code/
Request Body:
200 OK):
Step 3: Reset Password
Endpoint:POST /auth/reset-password/
Query Parameter: token - The temporary reset token from Step 2
Request Body:
200 OK):
Verification codes are stored in Firebase Realtime Database at
/password_reset/{uid} and are automatically deleted after successful password reset.Authentication for WebSocket Connections
WebSocket connections require JWT authentication: Meter Connections (/receive/ namespace):
- Requires a meter-specific JWT token with
MeterPayload - Token contains:
id_workspace,owner,id_meter
/subscribe/ namespace):
- Requires a user JWT token with
UserPayload - Must also provide
id_workspaceandid_meterquery parameters - Access is validated against workspace permissions
~/workspace/source/app/share/socketio/__init__.py for WebSocket authentication implementation.
Best Practices
Store Tokens Securely
- Never store tokens in localStorage if possible (vulnerable to XSS)
- Use httpOnly cookies or secure storage mechanisms
- Never commit tokens to version control
Handle Token Expiration
- Implement automatic re-authentication when tokens expire
- Show user-friendly messages when authentication fails
- Store token expiration time to refresh proactively
Use HTTPS
- Always use HTTPS in production to prevent token interception
- Never send tokens over unencrypted connections
Common Authentication Errors
| Status Code | Error Message | Solution |
|---|---|---|
401 | Credenciales inválidas | Verify email and password are correct |
404 | Usuario no registrado | Register the user first |
401 | Token inválido | Token is expired or malformed - re-authenticate |
401 | Código de verificación inválido | Verification code is incorrect |
401 | Código expirado | Request a new verification code |
500 | STATE_SECRET not configured | Server configuration issue |
504 | Tiempo de espera agotado | GitHub OAuth timeout - retry |
Next Steps
- Explore API endpoints for workspaces, meters, and monitoring
- Learn about WebSocket connections
- Understand workspace permissions and access control