← back to Designer Wallcoverings

DW-Agents/dw-agents/global-auth-system/SETUP.md

319 lines

# DW Global Authentication System Setup Guide

## Overview

Complete Google OAuth SSO system with SMS 2FA, session management, and security monitoring for all DW-Agents.

## Features

✅ **Google OAuth 2.0** - Single Sign-On for all agents
✅ **SMS 2FA** - Required after 4 hours of activity
✅ **Session Management** - 4-hour sessions with automatic expiry
✅ **Security Monitoring** - Track all logins, access patterns, and errors
✅ **User Management** - Admin panel for access control
✅ **Legal Compliance** - Terms acceptance and email verification
✅ **Blocked Users** - Automatic blocking of suspicious accounts
✅ **Error Tracking** - Session error logs assigned to appropriate agents

## Setup Instructions

### 1. Google OAuth Configuration

1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Create a new project or select existing one
3. Enable **Google+ API**
4. Go to **Credentials** → **Create Credentials** → **OAuth 2.0 Client ID**
5. Application type: **Web application**
6. Authorized redirect URIs: `http://45.61.58.125:9999/auth/google/callback`
7. Copy **Client ID** and **Client Secret**

### 2. Twilio SMS Configuration (Optional but Recommended)

1. Sign up at [Twilio.com](https://www.twilio.com/)
2. Get a phone number
3. Copy **Account SID**, **Auth Token**, and **Phone Number**

**Note:** If Twilio is not configured, the system will run in development mode with a static code `123456`.

### 3. Environment Configuration

```bash
cd /root/DW-Agents/global-auth-system
cp .env.example .env
nano .env
```

Update these required values:
```
GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=your-google-client-secret
TWILIO_ACCOUNT_SID=your-twilio-sid  # Optional
TWILIO_AUTH_TOKEN=your-twilio-token  # Optional
TWILIO_PHONE_NUMBER=+1234567890  # Optional
ADMIN_EMAILS=admin@designerwallcoverings.com
SESSION_SECRET=generate-random-secret-here
```

### 4. Install Dependencies

```bash
cd /root/DW-Agents/global-auth-system
npm install
```

### 5. Start Authentication Server

```bash
# Development mode (with auto-reload)
npm run dev

# Production mode
npm start

# Or with PM2
pm2 start auth-server.ts --name dw-global-auth --interpreter tsx
```

### 6. Access Points

- **Login Portal**: http://45.61.58.125:9999/login
- **Admin Dashboard**: http://45.61.58.125:9999/admin
- **Security Monitor**: http://45.61.58.125:9892/ (Security Agent)

## How It Works

### Authentication Flow

1. **User visits any agent** → Redirected to http://45.61.58.125:9999/login
2. **Click "Sign in with Google"** → Google OAuth consent screen
3. **Google authentication** → User profile retrieved
4. **Terms acceptance** → Legal terms and email verification notice
5. **Session created** → 4-hour session token issued
6. **Access dashboard** → View all available agents

### Session Management

- **Initial login**: Email authentication via Google OAuth
- **Session duration**: 4 hours maximum
- **After 4 hours**: SMS verification required to extend session
- **Auto-logout**: Sessions expire automatically after timeout
- **Activity tracking**: Every agent access is logged

### SMS Verification (After 4 Hours)

1. User tries to access any agent after 4 hours
2. Redirected to SMS verification page
3. Enter phone number → Verification code sent via SMS
4. Enter 6-digit code → Session extended for 4 more hours
5. Continue working with all agents

### Security Features

#### Session Tracking
- Login/logout times
- IP addresses
- User agents (browser/device)
- Agents accessed
- Error logs from each session

#### Suspicious Activity Detection
- Multiple failed login attempts
- Blocked user access attempts
- Unusual access patterns
- Geographic anomalies

#### Blocked Users
Add blocked emails to `.env`:
```
BLOCKED_USERS=spammer@example.com,badactor@example.com
```

## Admin Features

### Security Dashboard (Port 9892)

View all:
- Active sessions
- Access logs
- Failed login attempts
- Blocked users
- Error summaries per session
- Assign issues to appropriate agents

### User Management

- Grant/revoke access
- View user activity history
- Block/unblock users
- View session history
- Export logs for compliance

## Integration with Existing Agents

### Option 1: Middleware (Recommended)

Create `/root/DW-Agents/shared-global-auth.ts`:

```typescript
import { Request, Response, NextFunction } from 'express';
import fetch from 'node-fetch';

const AUTH_SERVER = 'http://localhost:9999';

export async function requireGlobalAuth(req: Request, res: Response, next: NextFunction) {
  const sessionId = req.cookies.dw_session || req.query.session;

  if (!sessionId) {
    return res.redirect(`${AUTH_SERVER}/login`);
  }

  try {
    const response = await fetch(`${AUTH_SERVER}/api/validate-session?session=${sessionId}`);
    const result = await response.json();

    if (!result.valid) {
      if (result.requiresSMS) {
        return res.redirect(`${AUTH_SERVER}/verify-sms`);
      }
      return res.redirect(`${AUTH_SERVER}/login`);
    }

    req.user = result.user;
    next();
  } catch (error) {
    res.redirect(`${AUTH_SERVER}/login`);
  }
}
```

### Option 2: Direct Redirect

In each agent's main route:

```typescript
app.get('/', (req, res) => {
  const sessionId = req.cookies.dw_session;
  if (!sessionId) {
    return res.redirect('http://45.61.58.125:9999/login');
  }
  // ... rest of your code
});
```

## API Endpoints

### `GET /auth/google`
Initiate Google OAuth flow

### `GET /auth/google/callback`
Handle Google OAuth callback

### `GET /login`
Login page with Google Sign-In button

### `GET /terms`
Terms of Service acceptance page

### `POST /terms/accept`
Accept terms and create session

### `GET /dashboard`
User dashboard with all available agents

### `GET /verify-sms`
SMS verification page (shown after 4 hours)

### `POST /verify-sms/send`
Send SMS verification code

### `POST /verify-sms/verify`
Verify SMS code and extend session

### `GET /logout`
End session and logout

### `GET /api/validate-session?session={sessionId}`
Validate session token (used by agents)

**Response:**
```json
{
  "valid": true,
  "user": {
    "email": "user@example.com",
    "userId": "user_123"
  }
}
```

## Security Best Practices

1. **HTTPS in Production**: Enable HTTPS and set `cookie.secure = true`
2. **Strong Session Secret**: Use a random 32+ character string
3. **Regular Backups**: Backup `data/` directory daily
4. **Monitor Logs**: Check security alerts regularly
5. **Update Blocked List**: Keep blocked users list current
6. **SMS Verification**: Enable Twilio for production use
7. **Admin Emails**: Keep admin email list updated

## Troubleshooting

### Issue: "Google OAuth not configured"
**Solution**: Add GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET to `.env`

### Issue: SMS not sending
**Solution**: Check Twilio credentials or use development mode (static code 123456)

### Issue: Sessions not persisting
**Solution**: Check that `data/sessions.json` has write permissions

### Issue: "Invalid session" errors
**Solution**: Clear browser cookies and login again

## File Structure

```
global-auth-system/
├── auth-server.ts          # Main authentication server
├── session-manager.ts      # Session handling logic
├── sms-verifier.ts        # SMS 2FA system
├── types.ts               # TypeScript type definitions
├── package.json           # Dependencies
├── .env                   # Configuration (create from .env.example)
├── data/                  # Runtime data (auto-created)
│   ├── users.json        # User database
│   ├── sessions.json     # Active sessions
│   ├── access-logs.json  # All access logs
│   └── security-alerts.json # Security incidents
└── SETUP.md              # This file
```

## Monitoring

### View Active Sessions
```bash
curl http://localhost:9999/api/sessions
```

### View Access Logs
```bash
cat /root/DW-Agents/global-auth-system/data/access-logs.json | jq
```

### View Security Alerts
```bash
cat /root/DW-Agents/global-auth-system/data/security-alerts.json | jq
```

## Support

For issues or questions:
1. Check logs: `pm2 logs dw-global-auth`
2. Review data files in `data/` directory
3. Verify `.env` configuration
4. Test with development SMS mode first

## License

Proprietary - Designer Wallcoverings 2025