aboutsummaryrefslogtreecommitdiff
path: root/AUTHENTICATION.md
blob: 86b9cf45806f26de87e03241ff305adc9ea91e3a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
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.