# Backend Setup Guide

## Prerequisites

- Node.js v18+ and npm v9+
- PostgreSQL 13+ (or MongoDB as alternative)
- Docker (optional, for containerized database)

## Installation

### 1. Install Dependencies

```bash
cd backend
npm install
```

### 2. Setup Environment

Copy `.env.example` to `.env.local` and fill in your values:

```bash
cp .env.example .env.local
```

**Key configurations to update:**
- `DB_HOST`, `DB_PORT`, `DB_USER`, `DB_PASSWORD`, `DB_NAME` - Database connection
- `JWT_SECRET` - Change to a random 32+ character string
- `JWT_REFRESH_SECRET` - Change to a random 32+ character string
- `SESSION_SECRET` - Change to a random string
- `BCRYPT_ROUNDS` - Set to minimum 12 (higher = more secure but slower)
- `FRONTEND_URL` - Your React frontend URL
- `TWILIO_*` - If using SMS 2FA (optional)
- `STRIPE_*` - If using Stripe payments (optional)

### 3. Setup Database

```bash
# Create PostgreSQL database
createdb serdark_db

# Run migrations (creates tables)
npm run db:migrate

# Optional: Seed admin user
npm run db:migrate -- --seed-admin
```

### 4. Start Development Server

```bash
npm run dev
```

Server will start on `http://localhost:5000`

## API Endpoints

Base URL: `http://localhost:5000/api/v1`

### Authentication Endpoints

- `POST /auth/register` - Register new user
- `POST /auth/login` - Login user
- `POST /auth/logout` - Logout user
- `POST /auth/refresh` - Refresh access token
- `POST /auth/password-reset` - Request password reset
- `POST /auth/password-reset-confirm` - Confirm password reset
- `POST /auth/change-password` - Change password (authenticated)

### 2FA Endpoints

- `POST /auth/2fa/generate` - Generate 2FA secret and QR code
- `POST /auth/2fa/enable` - Enable 2FA
- `POST /auth/2fa/disable` - Disable 2FA
- `POST /auth/2fa/verify` - Verify 2FA code
- `POST /auth/2fa/backup-verify` - Verify backup code
- `GET /auth/2fa/status` - Get 2FA status

### User Endpoints

- `GET /users/me` - Get own profile
- `GET /users/:userId` - Get user profile
- `PATCH /users/me/profile` - Update profile
- `GET /users/me/sessions` - Get all sessions
- `POST /users/me/sessions/:sessionId/logout` - Logout from specific session
- `DELETE /users/me/account` - Delete account

### Audit Endpoints

- `GET /audit/my` - Get own audit logs
- `GET /audit` - Get all audit logs (admin only)
- `GET /audit/statistics` - Get statistics (admin only)
- `GET /audit/export` - Export audit logs (admin only)

## Security Features

### ✅ Implemented

- [x] Password hashing with bcryptjs (minimum 12 rounds)
- [x] JWT token authentication with refresh tokens
- [x] Rate limiting on sensitive endpoints
- [x] CSRF token protection
- [x] Input validation and sanitization
- [x] Comprehensive audit logging
- [x] 2FA framework (TOTP + backup codes)
- [x] SQL injection prevention (parameterized queries)
- [x] Session management with timeout
- [x] Helmet.js security headers
- [x] CORS configuration

### 🔲 To Implement

- [ ] HTTPS/TLS enforcement
- [ ] API key management
- [ ] Webhook signing
- [ ] Database encryption at rest
- [ ] Secrets management (Vault)
- [ ] DDoS protection
- [ ] Web Application Firewall (WAF)

## Testing

```bash
# Run all tests
npm test

# Run tests in watch mode
npm test -- --watch

# Generate coverage report
npm test -- --coverage
```

## Development Tips

### Enable Debug Mode

```bash
NODE_ENV=development DEBUG=* npm run dev
```

### Check Database

```bash
# Connect to psql
psql -U postgres -d serdark_db

# View tables
\dt

# Check users table
SELECT id, email, role, is_active FROM users;

# Check audit logs
SELECT event_type, action, user_id, severity, created_at FROM audit_logs ORDER BY created_at DESC LIMIT 10;
```

### Test Authentication

```bash
# Register
curl -X POST http://localhost:5000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "firstName": "John",
    "lastName": "Doe",
    "email": "test@example.com",
    "password": "TestPassword123!@#"
  }'

# Login
curl -X POST http://localhost:5000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "TestPassword123!@#"
  }'

# Use returned accessToken for authenticated requests
curl -X GET http://localhost:5000/api/v1/users/me \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
```

## Production Deployment

### Pre-Deployment Checklist

- [ ] All `.env` variables set correctly
- [ ] JWT secrets are strong (32+ chars, random)
- [ ] HTTPS/TLS configured
- [ ] Database backups configured
- [ ] Rate limiting configured appropriately
- [ ] CORS origin set to production domain
- [ ] `NODE_ENV=production`
- [ ] Helmet CSP configured for production
- [ ] Error logging configured (Sentry)
- [ ] Database indexes verified

### Build for Production

```bash
npm run build
npm run prod
```

### Using PM2 for Process Management

```bash
# Install PM2 globally
npm install -g pm2

# Start application
pm2 start src/server.js --name "serdark-backend"

# Monitor
pm2 monit

# View logs
pm2 logs serdark-backend

# Setup auto-restart on reboot
pm2 startup
pm2 save
```

### Docker Deployment

```dockerfile
# Dockerfile (create in backend root)
FROM node:18-alpine

WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

COPY src ./src

EXPOSE 5000
CMD ["node", "src/server.js"]
```

```bash
# Build and run
docker build -t serdark-backend .
docker run -p 5000:5000 --env-file .env.local serdark-backend
```

## Troubleshooting

### CORS Issues

If frontend can't access backend, check CORS_ORIGIN in `.env.local`:
```env
CORS_ORIGIN=http://localhost:3000
```

### Database Connection Fails

Check PostgreSQL is running:
```bash
# macOS
brew services list

# Linux
sudo systemctl status postgresql

# Windows
sc query postgresql-x64-13
```

### JWT Errors

Ensure JWT_SECRET is at least 32 characters and identical across restarts.

### Rate Limiting Too Strict

Adjust rate limit values in `.env.local`:
```env
RATE_LIMIT_API_REQUESTS=100
RATE_LIMIT_API_WINDOW=60000
```

## Support

For issues or questions:
- Check logs: `logs/app.log`
- Check errors: `logs/error.log`
- Enable debug: `DEBUG=* npm run dev`
- Review: [Backend Architecture Docs](./ARCHITECTURE.md)
