# Traccar GPS Tracking Setup Guide

This guide explains how to set up Traccar GPS tracking with Auth0 OpenID Connect authentication for the VIP Coordinator application.

## Overview

Traccar integrates with Auth0 for Single Sign-On (SSO), using the same authentication as VIP Coordinator. Users are granted access based on their Auth0 roles:
- **ADMINISTRATOR** - Full admin access to Traccar
- **COORDINATOR** - Standard user access to Traccar
- Users without these roles cannot access Traccar

## How Access Control Works

```
┌─────────────────────────────────────────────────────────────────┐
│                        Auth0 Tenant                              │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────┐  │
│  │    Roles     │  │   Action     │  │       Users          │  │
│  │ ADMINISTRATOR│  │ Adds roles   │  │ john@company.com     │  │
│  │ COORDINATOR  │  │ to tokens    │  │   └─ ADMINISTRATOR   │  │
│  └──────────────┘  └──────────────┘  │ jane@company.com     │  │
│                                       │   └─ COORDINATOR     │  │
│                                       │ guest@example.com    │  │
│                                       │   └─ (no role)       │  │
│                                       └──────────────────────┘  │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                         Traccar                                  │
│  Checks token for roles:                                        │
│  - john@company.com → ADMINISTRATOR → Admin access ✓            │
│  - jane@company.com → COORDINATOR → Standard access ✓           │
│  - guest@example.com → No role → Access denied ✗                │
└─────────────────────────────────────────────────────────────────┘
```

## Prerequisites

1. Auth0 tenant with Management API access
2. Digital Ocean droplet or server with Docker
3. Domain with SSL certificate (e.g., `traccar.yourdomain.com`)
4. VIP Coordinator already deployed (sharing the same Auth0 tenant)

## Step 1: Configure Auth0

### Automatic Setup (Recommended)

Run the setup script with your configuration:

```bash
# Get a Management API token from Auth0 Dashboard:
# Applications → APIs → Auth0 Management API → API Explorer → Copy Token

cd vip-coordinator
node scripts/setup-auth0-traccar.js \
  --token=<AUTH0_MANAGEMENT_TOKEN> \
  --domain=<your-tenant.us.auth0.com> \
  --traccar-url=<https://traccar.yourdomain.com> \
  --admins=<admin@example.com,other-admin@example.com>
```

**Example for a new deployment:**
```bash
node scripts/setup-auth0-traccar.js \
  --token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9... \
  --domain=acme-corp.us.auth0.com \
  --traccar-url=https://traccar.acme.com \
  --admins=john@acme.com,jane@acme.com
```

This script will:
1. Create ADMINISTRATOR and COORDINATOR roles in your Auth0 tenant
2. Create a Post Login Action that adds roles to tokens as a "groups" claim
3. Deploy the action to the Login flow
4. Assign ADMINISTRATOR role to the specified admin emails (if they exist in Auth0)

### Manual Setup

If you prefer manual setup:

1. **Create Roles** in Auth0 Dashboard → User Management → Roles:
   - Name: `ADMINISTRATOR`, Description: "Full admin access"
   - Name: `COORDINATOR`, Description: "Standard access"

2. **Create Action** in Auth0 Dashboard → Actions → Library → Build Custom:
   - Name: `Add Roles to Traccar Groups`
   - Trigger: `Login / Post Login`
   - Code:
   ```javascript
   exports.onExecutePostLogin = async (event, api) => {
     const namespace = 'https://traccar.vip.madeamess.online';
     if (event.authorization && event.authorization.roles) {
       api.idToken.setCustomClaim(namespace + '/groups', event.authorization.roles);
       api.accessToken.setCustomClaim(namespace + '/groups', event.authorization.roles);
     }
   };
   ```

3. **Deploy Action** to Login Flow in Auth0 Dashboard → Actions → Flows → Login

4. **Assign Roles** to admin users in Auth0 Dashboard → User Management → Users

## Step 2: Configure Auth0 Application URLs

In Auth0 Dashboard → Applications → BSA VIP Track (your app), add:

**Allowed Callback URLs:**
```
https://traccar.vip.madeamess.online/api/session/openid/callback
```

**Allowed Logout URLs:**
```
https://traccar.vip.madeamess.online
```

**Allowed Web Origins:**
```
https://traccar.vip.madeamess.online
```

## Step 3: Deploy Traccar

### Docker Compose Configuration

Add to your `docker-compose.yml`:

```yaml
traccar:
  image: traccar/traccar:6.4
  container_name: vip-traccar
  ports:
    - "127.0.0.1:8082:8082"  # Web UI (proxied through nginx)
    - "5055:5055"            # GPS device protocol (OsmAnd)
  volumes:
    - ./traccar.xml:/opt/traccar/conf/traccar.xml:ro
    - traccar_data:/opt/traccar/data
  restart: unless-stopped

volumes:
  traccar_data:
```

### Traccar Configuration

Create `traccar.xml` on the server:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <!-- Database -->
    <entry key="database.driver">org.h2.Driver</entry>
    <entry key="database.url">jdbc:h2:./data/database</entry>
    <entry key="database.user">sa</entry>
    <entry key="database.password"></entry>

    <!-- Auth0 OpenID Connect -->
    <entry key="openid.clientId">YOUR_AUTH0_CLIENT_ID</entry>
    <entry key="openid.clientSecret">YOUR_AUTH0_CLIENT_SECRET</entry>
    <entry key="openid.issuerUrl">https://YOUR_AUTH0_DOMAIN</entry>
    <entry key="openid.force">true</entry>
    <entry key="web.url">https://traccar.your-domain.com</entry>

    <!-- Role-based Access Control -->
    <entry key="openid.group">https://traccar.your-domain.com/groups</entry>
    <entry key="openid.adminGroup">ADMINISTRATOR</entry>
    <entry key="openid.allowGroup">ADMINISTRATOR,COORDINATOR</entry>

    <!-- Logging -->
    <entry key="logger.level">info</entry>
</properties>
```

### Nginx Configuration

Add to your nginx config:

```nginx
server {
    listen 443 ssl http2;
    server_name traccar.vip.madeamess.online;

    ssl_certificate /etc/letsencrypt/live/vip.madeamess.online/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/vip.madeamess.online/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:8082;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
```

## Step 4: Bootstrap First User

Traccar 6.x requires at least one user before OpenID authentication works. Create a bootstrap user via API:

```bash
curl -X POST "https://traccar.your-domain.com/api/users" \
  -H "Content-Type: application/json" \
  -d '{"name":"Bootstrap Admin","email":"bootstrap@your-domain.com","password":"TEMP_PASSWORD"}'
```

This user will become admin. After OpenID is working, you can delete this user from Traccar settings.

## Step 5: Start Traccar

```bash
cd /opt/vip-coordinator
docker-compose up -d traccar
docker-compose logs -f traccar  # Watch logs
```

## Step 6: Test Authentication

1. Open `https://traccar.your-domain.com` in an incognito browser
2. Should redirect to Auth0 login
3. Log in with an admin user email
4. Should land in Traccar dashboard as admin

## Managing Users After Deployment

Once Traccar is deployed, manage user access through Auth0:

### Adding a New Admin

1. Go to Auth0 Dashboard → User Management → Users
2. Find the user (or wait for them to log in once to create their account)
3. Click on the user → Roles tab
4. Click "Assign Roles" → Select "ADMINISTRATOR"

### Adding a Coordinator

1. Go to Auth0 Dashboard → User Management → Users
2. Find the user
3. Click on the user → Roles tab
4. Click "Assign Roles" → Select "COORDINATOR"

### Removing Access

1. Go to Auth0 Dashboard → User Management → Users
2. Find the user → Roles tab
3. Remove both ADMINISTRATOR and COORDINATOR roles
4. User will be denied access on next login

### Bulk User Management

You can also use the Auth0 Management API:
```bash
# Assign role to user
curl -X POST "https://YOUR_DOMAIN/api/v2/users/USER_ID/roles" \
  -H "Authorization: Bearer MGMT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"roles": ["ROLE_ID"]}'
```

## Troubleshooting

### "Registration form appears instead of Auth0"
- Check that `newServer: false` in `/api/server` response
- If `newServer: true`, bootstrap a user first (Step 4)

### "User logged in but not admin"
- Verify user has ADMINISTRATOR role in Auth0
- Check that the Action is deployed to Login flow
- Test with a fresh incognito window

### "Access denied"
- User doesn't have ADMINISTRATOR or COORDINATOR Auth0 role
- Assign role in Auth0 Dashboard → User Management → Users

### "OpenID not working at all"
- Check Auth0 callback URL is correct
- Verify `openid.issuerUrl` has NO trailing slash
- Check Traccar logs: `docker-compose logs traccar`

## Security Notes

1. The `openid.clientSecret` should be kept secure
2. Only users with specific Auth0 roles can access Traccar
3. The bootstrap user can be deleted once OpenID is working
4. Consider using PostgreSQL instead of H2 for production

## Files Reference

- `scripts/setup-auth0-traccar.js` - Auth0 setup automation
- `deployment/traccar-production.xml` - Production Traccar config
- `deployment/TRACCAR-SETUP.md` - This guide
