aboutsummaryrefslogtreecommitdiff
path: root/AUTHENTICATION.md
diff options
context:
space:
mode:
Diffstat (limited to 'AUTHENTICATION.md')
-rw-r--r--AUTHENTICATION.md287
1 files changed, 287 insertions, 0 deletions
diff --git a/AUTHENTICATION.md b/AUTHENTICATION.md
new file mode 100644
index 0000000..86b9cf4
--- /dev/null
+++ b/AUTHENTICATION.md
@@ -0,0 +1,287 @@
+# Authentication System Implementation
+
+**Date:** August 15, 2025
+**Feature:** User Authentication with Registration Prompts
+
+## Overview
+
+I've implemented a comprehensive authentication system for JCHAT that automatically prompts users to register an account if they're not logged in. The system includes both server-side authentication using JWT tokens and bcrypt password hashing, plus a client-side interface with login and registration modals.
+
+## Server-Side Implementation
+
+### 1. Authentication Module (`jchat_auth.erl`)
+
+**Core Features:**
+- JWT token generation and validation
+- Bcrypt password hashing and verification
+- User registration and login
+- Token-based session management
+
+**Key Functions:**
+```erlang
+authenticate_request/1 % Main auth entry point
+register_user/3 % Register new user
+login_user/2 % Login existing user
+validate_token/1 % Validate JWT token
+generate_jwt/2 % Create JWT token
+hash_password/1 % Hash passwords with bcrypt
+verify_password/2 % Verify password against hash
+```
+
+**Security Features:**
+- Password hashing with bcrypt salt
+- JWT tokens with expiration (24 hours)
+- Input validation (email format, password length, etc.)
+- Account status checking (active/disabled)
+
+### 2. HTTP Authentication Endpoints (`jchat_http_auth.erl`)
+
+**Endpoints Added:**
+```
+POST /auth/register - Create new user account
+POST /auth/login - Login existing user
+POST /auth/logout - Logout (token invalidation)
+GET /auth/me - Get current user info
+```
+
+**Features:**
+- Proper JSON request/response handling
+- Comprehensive error responses
+- CORS support
+- Input validation and sanitization
+
+### 3. Database Schema Updates
+
+**New User Record:**
+```erlang
+-record(user, {
+ id, % UUID
+ email, % Unique email address
+ password_hash, % Bcrypt hashed password
+ display_name, % Display name for UI
+ created_at, % ISO8601 timestamp
+ last_login_at, % Last login time
+ is_active, % Account status
+ auth_provider, % 'local' | 'google' | etc
+ auth_provider_id % External provider ID
+}).
+```
+
+**Database Functions:**
+- `get_user_by_id/1` - Find user by ID
+- `get_user_by_email/1` - Find user by email
+- `create_user/1` - Create new user record
+- `update_user/1` - Update user record
+
+### 4. JMAP Integration
+
+**Updated Session Endpoint:**
+- Now requires authentication
+- Returns proper 401 errors with registration prompts
+- Dynamic session objects based on authenticated user
+
+**Updated API Endpoint:**
+- JWT token validation on all requests
+- User-specific account IDs
+- Proper error responses for auth failures
+
+## Client-Side Implementation
+
+### 1. Authentication UI
+
+**New Modals:**
+- **Login Modal**: Email/password login form
+- **Register Modal**: Email/display name/password registration form
+- **Error Handling**: Inline error messages for validation failures
+
+**Features:**
+- Auto-switching between login and register
+- Password confirmation validation
+- Responsive error messaging
+- Clean, modern UI design
+
+### 2. Token Management
+
+**Client Storage:**
+```javascript
+// Token stored in localStorage
+localStorage.setItem('jchat_auth_token', token);
+
+// Automatic token validation on startup
+async verifyAuthentication() {
+ // Validates token with /auth/me endpoint
+}
+```
+
+**Authentication Flow:**
+1. App checks for stored token on startup
+2. Validates token with server
+3. If invalid/missing, shows registration prompt
+4. On successful auth, initializes JMAP session
+5. Stores token and user info locally
+
+### 3. JMAP Client Updates
+
+**Token Support:**
+```javascript
+// Updated to include Authorization header
+headers: {
+ 'Authorization': `Bearer ${this.authToken}`,
+ 'Content-Type': 'application/json; charset=utf-8'
+}
+```
+
+**Error Handling:**
+- Automatic detection of 401 responses
+- Graceful fallback to authentication prompts
+- Token refresh on auth errors
+
+## User Experience Flow
+
+### New User Registration
+1. **First Visit**: App detects no auth token
+2. **Registration Prompt**: Shows register modal automatically
+3. **Form Completion**: User enters email, display name, password
+4. **Validation**: Client validates password confirmation, server validates email format
+5. **Account Creation**: Server creates user with hashed password
+6. **JWT Generation**: Server returns JWT token and user info
+7. **Auto-Login**: Client stores token and initializes chat
+
+### Returning User Login
+1. **Token Check**: App validates stored token
+2. **If Valid**: Direct access to chat
+3. **If Invalid**: Shows login modal
+4. **Login Form**: User enters email/password
+5. **Authentication**: Server validates credentials
+6. **JWT Response**: New token issued and stored
+7. **Chat Access**: Full chat functionality enabled
+
+### Error Scenarios
+- **Invalid Credentials**: Clear error message, stay on login form
+- **Email Already Exists**: Registration error with suggestion to login
+- **Weak Password**: Password requirements shown
+- **Network Issues**: Graceful error handling with retry options
+
+## Security Considerations
+
+### Password Security
+- **Minimum Length**: 8 characters required
+- **Bcrypt Hashing**: Industry-standard with salt
+- **No Plain Text**: Passwords never stored in plain text
+
+### Token Security
+- **JWT Standard**: Industry-standard JSON Web Tokens
+- **Expiration**: 24-hour token lifetime
+- **Bearer Format**: Proper Authorization header format
+- **Secure Storage**: localStorage with automatic cleanup
+
+### Input Validation
+- **Email Format**: Regex validation for proper email format
+- **Password Strength**: Length and character requirements
+- **SQL Injection**: Parameterized Mnesia queries
+- **XSS Prevention**: HTML escaping in client
+
+### Session Management
+- **Stateless**: JWT tokens eliminate server-side session storage
+- **Auto-Expiry**: Tokens automatically expire
+- **Logout**: Client-side token clearing
+- **Account Status**: Server checks if account is active
+
+## Dependencies Added
+
+**Server Dependencies:**
+```erlang
+{deps, [
+ {jsx, "3.1.0"}, % JSON encoding/decoding
+ {cowboy, "2.10.0"}, % HTTP server
+ {bcrypt, "1.2.0"}, % Password hashing
+ {jwt, "0.1.11"} % JWT token handling
+]}.
+```
+
+## Testing the Implementation
+
+### Manual Testing
+
+**1. Test Registration:**
+```bash
+curl -X POST http://localhost:8080/auth/register \
+ -H "Content-Type: application/json" \
+ -d '{
+ "email": "user@example.com",
+ "displayName": "Test User",
+ "password": "testpassword123"
+ }'
+```
+
+**2. Test Login:**
+```bash
+curl -X POST http://localhost:8080/auth/login \
+ -H "Content-Type: application/json" \
+ -d '{
+ "email": "user@example.com",
+ "password": "testpassword123"
+ }'
+```
+
+**3. Test Session Access:**
+```bash
+curl -X GET http://localhost:8080/jmap/session \
+ -H "Authorization: Bearer <token>"
+```
+
+### Expected Responses
+
+**Successful Registration:**
+```json
+{
+ "user": {
+ "id": "uuid-here",
+ "email": "user@example.com",
+ "displayName": "Test User",
+ "createdAt": "2025-08-15T...",
+ "isActive": true
+ },
+ "token": "jwt-token-here",
+ "tokenType": "Bearer",
+ "expiresIn": 86400
+}
+```
+
+**Authentication Error:**
+```json
+{
+ "type": "unauthorized",
+ "detail": "Authentication required. Please log in or register.",
+ "status": 401,
+ "prompt": "register"
+}
+```
+
+## Next Steps
+
+### Immediate Enhancements
+1. **Password Reset**: Add forgot password functionality
+2. **Email Verification**: Verify email addresses on registration
+3. **Token Refresh**: Implement refresh token mechanism
+4. **Rate Limiting**: Add rate limiting to auth endpoints
+
+### Advanced Features
+1. **OAuth Integration**: Google/GitHub login options
+2. **Two-Factor Auth**: TOTP-based 2FA
+3. **Session Management**: Track active sessions
+4. **Account Settings**: Change password, email, etc.
+
+### Production Readiness
+1. **HTTPS Enforcement**: Require TLS for all auth operations
+2. **Secure Headers**: Add security headers (HSTS, CSP, etc.)
+3. **Audit Logging**: Log authentication events
+4. **Monitoring**: Track login failures, suspicious activity
+
+## Conclusion
+
+The authentication system is now fully functional and provides a seamless user experience. Users are automatically prompted to create an account if not logged in, and the system handles both new user registration and returning user login gracefully.
+
+The implementation follows security best practices with bcrypt password hashing, JWT tokens, and proper input validation. The client-side experience is smooth with automatic token management and clear error messaging.
+
+This foundation supports the planned RBAC system and provides a solid base for additional authentication features like OAuth integration and two-factor authentication.