Skip to content

Commit 853990c

Browse files
authored
Merge pull request #64 from akordavid373/feature/user-authentication
feat: Implement comprehensive user authentication and authorization s…
2 parents e8ed0df + 9c11000 commit 853990c

15 files changed

Lines changed: 2856 additions & 19 deletions

AUTHENTICATION_IMPLEMENTATION.md

Lines changed: 321 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,321 @@
1+
# User Authentication and Authorization Implementation
2+
3+
This document describes the comprehensive user authentication and authorization system implemented for the NEPA project to address issue #56.
4+
5+
## Overview
6+
7+
The NEPA application now supports multiple authentication methods and provides a complete user management system with role-based access control, session management, and optional two-factor authentication.
8+
9+
## Features Implemented
10+
11+
### ✅ User Registration and Profile System
12+
- Email-based user registration with password hashing
13+
- User profiles with customizable preferences
14+
- Username support with uniqueness validation
15+
- Phone number support for 2FA
16+
- Avatar and profile customization
17+
18+
### ✅ Role-Based Access Control (RBAC)
19+
- Three user roles: USER, ADMIN, SUPER_ADMIN
20+
- Hierarchical permission system
21+
- Role-based route protection
22+
- Admin user management endpoints
23+
24+
### ✅ Secure Session Management
25+
- JWT-based authentication with refresh tokens
26+
- Session tracking with device information
27+
- Automatic token refresh
28+
- Session revocation capabilities
29+
- Secure session storage
30+
31+
### ✅ Two-Factor Authentication (2FA)
32+
- Support for TOTP (Authenticator App)
33+
- Email and SMS 2FA methods (framework ready)
34+
- QR code generation for easy setup
35+
- Backup codes for account recovery
36+
37+
### ✅ Wallet Authentication
38+
- Stellar wallet integration (Freighter)
39+
- Automatic user creation for wallet users
40+
- Hybrid authentication (wallet + traditional)
41+
42+
### ✅ Enhanced Security Features
43+
- Account lockout after failed attempts
44+
- Password strength requirements
45+
- Audit logging for all actions
46+
- Rate limiting on auth endpoints
47+
- Secure password hashing with bcrypt
48+
49+
## Architecture
50+
51+
### Backend Components
52+
53+
#### Database Schema Updates
54+
- Enhanced User model with authentication fields
55+
- UserSession model for session management
56+
- UserProfile model for user preferences
57+
- AuditLog model for security auditing
58+
- Role and status enums for access control
59+
60+
#### Services
61+
- `AuthenticationService`: Core authentication logic
62+
- Password hashing and verification
63+
- JWT token generation and validation
64+
- 2FA setup and verification
65+
- Session management
66+
67+
#### Controllers
68+
- `AuthenticationController`: Auth endpoints
69+
- `UserController`: User management
70+
- Input validation with Joi
71+
- Error handling and response formatting
72+
73+
#### Middleware
74+
- `authentication.ts`: JWT verification and role checking
75+
- Rate limiting for auth endpoints
76+
- Request logging and audit trails
77+
78+
### Frontend Components
79+
80+
#### Services
81+
- `authService.ts`: API communication
82+
- Token management and refresh
83+
- Automatic retry on token expiration
84+
85+
#### Context
86+
- `AuthContext.tsx`: Global auth state
87+
- User session management
88+
- Authentication methods
89+
90+
#### Components
91+
- `LoginForm.tsx`: Email/password login
92+
- `RegisterForm.tsx`: User registration
93+
- `AuthPage.tsx`: Unified auth interface
94+
- Wallet integration with Freighter
95+
96+
## API Endpoints
97+
98+
### Authentication
99+
- `POST /api/auth/register` - User registration
100+
- `POST /api/auth/login` - Email/password login
101+
- `POST /api/auth/wallet` - Wallet authentication
102+
- `POST /api/auth/refresh` - Token refresh
103+
- `POST /api/auth/logout` - User logout
104+
105+
### User Management
106+
- `GET /api/user/profile` - Get user profile
107+
- `PUT /api/user/profile` - Update profile
108+
- `GET /api/user/preferences` - Get preferences
109+
- `PUT /api/user/preferences` - Update preferences
110+
- `POST /api/user/change-password` - Change password
111+
112+
### Two-Factor Authentication
113+
- `POST /api/user/2fa/enable` - Enable 2FA
114+
- `POST /api/user/2fa/verify` - Verify 2FA code
115+
116+
### Session Management
117+
- `GET /api/user/sessions` - List active sessions
118+
- `DELETE /api/user/sessions/:id` - Revoke session
119+
120+
### Admin Endpoints
121+
- `GET /api/admin/users` - List all users
122+
- `GET /api/admin/users/:id` - Get user details
123+
- `PUT /api/admin/users/:id/role` - Update user role
124+
- `DELETE /api/admin/users/:id` - Delete user
125+
126+
## Security Considerations
127+
128+
### Password Security
129+
- Minimum 8 characters requirement
130+
- bcrypt hashing with 12 rounds
131+
- Password change functionality
132+
- Secure password reset (to be implemented)
133+
134+
### Session Security
135+
- Short-lived access tokens (15 minutes)
136+
- Long-lived refresh tokens (7 days)
137+
- Automatic token refresh
138+
- Session invalidation on logout
139+
140+
### Rate Limiting
141+
- Stricter limits on auth endpoints
142+
- Account lockout after 5 failed attempts
143+
- IP-based rate limiting
144+
- DDoS protection integration
145+
146+
### Audit Trail
147+
- All authentication events logged
148+
- User action tracking
149+
- IP and user agent logging
150+
- Security event monitoring
151+
152+
## Setup Instructions
153+
154+
### Backend Setup
155+
156+
1. **Install Dependencies**
157+
```bash
158+
cd nepa
159+
npm install bcryptjs jsonwebtoken speakeasy qrcode nodemailer express-session connect-redis joi uuid
160+
npm install -D @types/bcryptjs @types/jsonwebtoken @types/speakeasy @types/qrcode @types/nodemailer @types/express-session @types/uuid
161+
```
162+
163+
2. **Environment Variables**
164+
```env
165+
# JWT Configuration
166+
JWT_SECRET=your-super-secret-jwt-key
167+
JWT_REFRESH_SECRET=your-super-secret-refresh-key
168+
169+
# Database
170+
DATABASE_URL=postgresql://username:password@localhost:5432/nepa
171+
172+
# Email (for 2FA)
173+
SMTP_HOST=smtp.gmail.com
174+
SMTP_PORT=587
175+
SMTP_USER=your-email@gmail.com
176+
SMTP_PASS=your-app-password
177+
178+
# Redis (for sessions)
179+
REDIS_URL=redis://localhost:6379
180+
```
181+
182+
3. **Database Migration**
183+
```bash
184+
npx prisma migrate dev
185+
npx prisma generate
186+
```
187+
188+
4. **Start Development Server**
189+
```bash
190+
npm run dev
191+
```
192+
193+
### Frontend Setup
194+
195+
1. **Install Dependencies**
196+
```bash
197+
cd nepa-frontend
198+
npm install
199+
```
200+
201+
2. **Environment Variables**
202+
```env
203+
REACT_APP_API_URL=http://localhost:3000/api
204+
```
205+
206+
3. **Start Development Server**
207+
```bash
208+
npm run dev
209+
```
210+
211+
## Usage Examples
212+
213+
### User Registration
214+
```javascript
215+
const registerData = {
216+
email: 'user@example.com',
217+
password: 'securePassword123',
218+
username: 'johndoe',
219+
name: 'John Doe'
220+
};
221+
222+
const result = await authService.register(registerData);
223+
```
224+
225+
### Email Login
226+
```javascript
227+
const loginData = {
228+
email: 'user@example.com',
229+
password: 'securePassword123'
230+
};
231+
232+
const result = await authService.login(loginData);
233+
```
234+
235+
### Wallet Login
236+
```javascript
237+
const result = await authService.loginWithWallet();
238+
```
239+
240+
### Enabling 2FA
241+
```javascript
242+
const result = await authService.enableTwoFactor('AUTHENTICATOR_APP');
243+
// Returns QR code and secret for user to scan
244+
```
245+
246+
## Testing
247+
248+
### Authentication Flow Tests
249+
1. User registration
250+
2. Email verification
251+
3. Login with correct credentials
252+
4. Login with wrong credentials (should fail)
253+
5. Token refresh
254+
6. Logout and session invalidation
255+
256+
### 2FA Tests
257+
1. Enable 2FA with authenticator app
258+
2. Login with 2FA code
259+
3. Login with wrong 2FA code (should fail)
260+
4. Backup code recovery
261+
262+
### Role-Based Access Tests
263+
1. Admin access to protected endpoints
264+
2. User access denied to admin endpoints
265+
3. Role hierarchy enforcement
266+
267+
## Future Enhancements
268+
269+
### Planned Features
270+
- Email verification system
271+
- Password reset functionality
272+
- SMS 2FA implementation
273+
- OAuth integration (Google, GitHub)
274+
- Advanced audit dashboard
275+
- Biometric authentication support
276+
277+
### Security Improvements
278+
- Advanced threat detection
279+
- Device fingerprinting
280+
- Anomaly detection
281+
- IP whitelisting
282+
- Advanced rate limiting
283+
284+
## Troubleshooting
285+
286+
### Common Issues
287+
288+
1. **Token Not Found**
289+
- Check if token is stored in localStorage
290+
- Verify token is not expired
291+
- Check network connectivity
292+
293+
2. **2FA Verification Failed**
294+
- Ensure time sync on device
295+
- Check backup codes if available
296+
- Verify TOTP secret is correct
297+
298+
3. **Wallet Connection Issues**
299+
- Ensure Freighter is installed
300+
- Check wallet is unlocked
301+
- Verify network settings
302+
303+
### Debug Mode
304+
Enable debug logging by setting:
305+
```env
306+
DEBUG=auth:*
307+
```
308+
309+
## Contributing
310+
311+
When contributing to the authentication system:
312+
313+
1. Follow security best practices
314+
2. Add comprehensive tests
315+
3. Update documentation
316+
4. Consider edge cases
317+
5. Implement proper error handling
318+
319+
## License
320+
321+
This authentication implementation follows the same license as the NEPA project.

0 commit comments

Comments
 (0)