codenuk_frontend_mine/AUTH_IMPLEMENTATION.md

232 lines
6.2 KiB
Markdown

# Authentication Implementation
## Overview
This document describes the authentication system implementation with proper error handling, separate signup/signin routes, and email verification flow.
## Architecture
### Backend (User Auth Service)
- **Port**: 8011
- **Base URL**: `http://localhost:8011`
- **Database**: PostgreSQL
- **Features**: JWT authentication, email verification, session management
### Frontend (Next.js App)
- **Port**: 3001
- **Base URL**: `http://localhost:3001`
- **Framework**: Next.js 15.4.6 with TypeScript
- **UI**: Tailwind CSS + shadcn/ui components
## Routes Structure
### Frontend Routes
```
/signup - User registration page
/signin - User login page
/auth - Redirects to /signin (legacy support)
/verify-email - Email verification page (handled by backend redirect)
```
### Backend API Endpoints
```
POST /api/auth/register - User registration
POST /api/auth/login - User login
GET /api/auth/verify-email - Email verification (redirects to frontend)
POST /api/auth/logout - User logout
POST /api/auth/refresh - Token refresh
GET /api/auth/me - Get user profile
```
## User Flow
### 1. Registration Flow
1. User visits `/signup`
2. Fills out registration form
3. Submits form → `POST /api/auth/register`
4. Backend creates user account and sends verification email
5. Frontend shows success message and redirects to `/signin` after 3 seconds
6. User receives email with verification link
### 2. Email Verification Flow
1. User clicks verification link in email
2. Link points to: `http://localhost:8011/api/auth/verify-email?token=<token>`
3. Backend verifies token and redirects to: `http://localhost:3001/signin?verified=true`
4. Frontend displays success message: "Email verified successfully! You can now sign in to your account."
### 3. Login Flow
1. User visits `/signin`
2. Fills out login form
3. Submits form → `POST /api/auth/login`
4. Backend validates credentials and returns JWT tokens
5. Frontend stores tokens and redirects to dashboard (`/`)
## Error Handling
### Backend Error Responses
All API endpoints return consistent error format:
```json
{
"success": false,
"error": "Error type",
"message": "Detailed error message"
}
```
### Frontend Error Handling
- **Network Errors**: Display user-friendly messages
- **API Errors**: Show specific error messages from backend
- **Validation Errors**: Client-side validation with immediate feedback
- **Authentication Errors**: Clear messaging for login/registration issues
### Common Error Scenarios
#### Registration Errors
- **Email already exists**: "An account with this email already exists"
- **Username taken**: "Username is already taken"
- **Invalid email format**: "Please enter a valid email address"
- **Weak password**: "Password must be at least 8 characters long"
- **Missing fields**: "Please fill in all required fields"
#### Login Errors
- **Invalid credentials**: "Invalid email or password"
- **Email not verified**: "Please verify your email before signing in"
- **Account locked**: "Account is temporarily locked due to multiple failed attempts"
#### Email Verification Errors
- **Invalid token**: "Verification link is invalid or has expired"
- **Already verified**: "Email is already verified"
- **Token expired**: "Verification link has expired. Please request a new one"
## Components Structure
### Signup Flow
```
/signup
├── SignUpPage (main container)
├── SignUpForm (form component)
└── Success State (after registration)
```
### Signin Flow
```
/signin
├── SignInPage (main container)
├── SignInForm (form component)
└── Verification Messages (from URL params)
```
## API Integration
### Authentication Handler (`authenticationHandler.tsx`)
- Handles API calls to backend
- Proper error propagation
- TypeScript interfaces for type safety
### Key Functions
```typescript
registerUser(data: RegisterData): Promise<ApiResponse>
loginUser(email: string, password: string): Promise<ApiResponse>
```
## Security Features
### Backend Security
- JWT token authentication
- Password hashing (bcrypt)
- Rate limiting on auth endpoints
- CORS configuration
- Helmet security headers
- Session management
### Frontend Security
- Token storage in localStorage
- Automatic token refresh
- Secure API communication
- Input validation and sanitization
## Environment Configuration
### Backend (.env)
```env
PORT=8011
FRONTEND_URL=http://localhost:3001
POSTGRES_HOST=localhost
POSTGRES_DB=user_auth
JWT_SECRET=your-secret-key
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASS=your-app-password
```
### Frontend (.env.local)
```env
NEXT_PUBLIC_API_URL=http://localhost:8011
NEXT_PUBLIC_FRONTEND_URL=http://localhost:3001
```
## Testing the Implementation
### 1. Start Services
```bash
# Backend
cd automated-dev-pipeline
docker-compose up user-auth
# Frontend
cd codenuk-frontend-dark-theme
npm run dev
```
### 2. Test Registration
1. Visit `http://localhost:3001/signup`
2. Fill out registration form
3. Submit and check for success message
4. Check email for verification link
### 3. Test Email Verification
1. Click verification link in email
2. Should redirect to `http://localhost:3001/signin?verified=true`
3. Verify success message appears
### 4. Test Login
1. Visit `http://localhost:3001/signin`
2. Enter credentials
3. Should redirect to dashboard on success
## Troubleshooting
### Common Issues
1. **CORS Errors**
- Check backend CORS configuration
- Verify frontend URL in allowed origins
2. **Email Not Sending**
- Check SMTP configuration in backend
- Verify email credentials
3. **Verification Link Not Working**
- Check frontend URL in backend configuration
- Verify token expiration settings
4. **Login Fails After Verification**
- Check if user is properly verified in database
- Verify JWT token generation
### Debug Steps
1. Check browser network tab for API calls
2. Check backend logs for errors
3. Verify database connections
4. Test API endpoints directly with Postman/curl
## Future Enhancements
1. **Password Reset Flow**
2. **Two-Factor Authentication**
3. **Social Login Integration**
4. **Account Lockout Protection**
5. **Session Management Dashboard**
6. **Audit Logging**