# 🔧 Server Error Fix Instructions

## Problem Analysis

Your server **already has** refresh token functionality, but it's failing because:

1. ❌ **Missing/Invalid JWT_REFRESH_SECRET** in `.env` file
2. ❌ **Missing `refresh_tokens` table** in MySQL database
3. ⚠️ **Invalid MySQL2 connection options** causing warnings

## Error Details

```
Token refresh error: TokenExpiredError: jwt expired
expiredAt: 2025-11-14T08:27:57.000Z
```

The refresh token expired on **November 14, 2025** (8 days ago), and when trying to verify it, the JWT_REFRESH_SECRET is either missing or wrong.

---

## 🚀 Fix Steps

### Step 1: Update Environment Variables

SSH into your server and edit the `.env` file:

```bash
cd /home/hrbackendtest/public_html
nano .env
```

**Add or update these variables:**

```env
# JWT Configuration
JWT_SECRET=your_existing_secret_here
JWT_EXPIRES_IN=7d
JWT_REFRESH_SECRET=your_refresh_secret_key_here_make_it_different_from_jwt_secret
JWT_REFRESH_EXPIRES_IN=30d

# Database Configuration (verify these are correct)
DB_HOST=localhost
DB_PORT=3306
DB_USER=your_mysql_user
DB_PASSWORD=your_mysql_password
DB_NAME=project_management
```

**Important:**
- `JWT_REFRESH_SECRET` must be **different** from `JWT_SECRET`
- Make it a long, random string (e.g., `openssl rand -base64 64`)

Save and exit (Ctrl+X, then Y, then Enter)

---

### Step 2: Create the `refresh_tokens` Table in MySQL

Run this SQL command to create the missing table:

```bash
# Connect to MySQL
mysql -u your_mysql_user -p

# Select your database
USE project_management;

# Create the refresh_tokens table
CREATE TABLE IF NOT EXISTS refresh_tokens (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  token TEXT NOT NULL,
  expires_at DATETIME NOT NULL,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  INDEX idx_user_id (user_id),
  INDEX idx_expires_at (expires_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

# Verify the table was created
SHOW TABLES LIKE 'refresh_tokens';

# Exit MySQL
EXIT;
```

**Or use this one-liner:**

```bash
mysql -u your_mysql_user -p project_management -e "CREATE TABLE IF NOT EXISTS refresh_tokens (id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, token TEXT NOT NULL, expires_at DATETIME NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, INDEX idx_user_id (user_id), INDEX idx_expires_at (expires_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;"
```

---

### Step 3: Update Database Configuration (Optional - Remove Warnings)

The MySQL2 warnings about invalid options can be fixed by updating the config file:

```bash
cd /home/hrbackendtest/public_html/config
nano database.js
```

**Find this section:**

```javascript
const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 3306,
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'project_management',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
};
```

**Add these options to prevent connection issues:**

```javascript
const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  port: process.env.DB_PORT || 3306,
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'project_management',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
  connectTimeout: 60000,        // Add this
  enableKeepAlive: true,         // Add this
  keepAliveInitialDelay: 0,      // Add this
  charset: 'utf8mb4'             // Add this
};
```

Save and exit.

---

### Step 4: Restart PM2

```bash
cd /home/hrbackendtest/public_html
pm2 restart server
pm2 logs server --lines 50
```

---

## 🧪 Testing the Fix

### Test 1: Check Environment Variables

```bash
cd /home/hrbackendtest/public_html
grep JWT .env
```

You should see:
```
JWT_SECRET=...
JWT_EXPIRES_IN=7d
JWT_REFRESH_SECRET=...
JWT_REFRESH_EXPIRES_IN=30d
```

### Test 2: Verify Database Table

```bash
mysql -u your_mysql_user -p -e "USE project_management; DESCRIBE refresh_tokens;"
```

You should see the table structure.

### Test 3: Check Server Logs

```bash
pm2 logs server --lines 100
```

Look for:
- ✅ "MySQL database connected successfully"
- ✅ No more "Token refresh error: TokenExpiredError"
- ✅ No more "Ignoring invalid configuration option"

### Test 4: Test Login API

```bash
curl -X POST http://your-server-domain/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "phone_number": "1234567890",
    "otp": "123456"
  }'
```

Response should include both tokens:
```json
{
  "success": true,
  "data": {
    "tokens": {
      "access_token": "...",
      "refresh_token": "..."
    }
  }
}
```

### Test 5: Test Refresh Token API

```bash
curl -X POST http://your-server-domain/api/auth/refresh-token \
  -H "Content-Type: application/json" \
  -d '{
    "refresh_token": "your_refresh_token_here"
  }'
```

---

## 📋 Quick Fix Script

Save this as `fix_server.sh` and run it:

```bash
#!/bin/bash

echo "🔧 Fixing server errors..."

# Navigate to project directory
cd /home/hrbackendtest/public_html || exit

# Backup .env file
cp .env .env.backup.$(date +%Y%m%d_%H%M%S)
echo "✅ Backed up .env file"

# Check if JWT_REFRESH_SECRET exists
if ! grep -q "JWT_REFRESH_SECRET" .env; then
    echo "⚠️  JWT_REFRESH_SECRET not found in .env"
    echo "Please add it manually:"
    echo "JWT_REFRESH_SECRET=$(openssl rand -base64 64 | tr -d '\n')"
    echo ""
fi

# Create refresh_tokens table
echo "📊 Creating refresh_tokens table..."
mysql -u $DB_USER -p$DB_PASSWORD $DB_NAME << EOF
CREATE TABLE IF NOT EXISTS refresh_tokens (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  token TEXT NOT NULL,
  expires_at DATETIME NOT NULL,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
  INDEX idx_user_id (user_id),
  INDEX idx_expires_at (expires_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
EOF

if [ $? -eq 0 ]; then
    echo "✅ Database table created/verified"
else
    echo "❌ Failed to create database table"
fi

# Restart PM2
echo "🔄 Restarting PM2..."
pm2 restart server

echo ""
echo "✅ Fix complete!"
echo ""
echo "Next steps:"
echo "1. Verify JWT_REFRESH_SECRET is in .env file"
echo "2. Check logs: pm2 logs server"
echo "3. Test the API endpoints"
```

---

## 🎯 Summary

The fixes are simple:

1. ✅ **Add `JWT_REFRESH_SECRET` to `.env`** - This is the main issue
2. ✅ **Create `refresh_tokens` table in MySQL** - Required for token storage
3. ✅ **Update database config** (optional) - Removes warnings
4. ✅ **Restart PM2** - Apply changes

After these steps, the token refresh errors should be completely resolved! 🎉

---

## 🆘 If Issues Persist

If you still see errors after following these steps:

1. **Check the exact error message:**
   ```bash
   pm2 logs server --err --lines 50
   ```

2. **Verify database connection:**
   ```bash
   node -e "require('./config/database').testConnection()"
   ```

3. **Check if users table exists:**
   ```bash
   mysql -u your_user -p -e "USE project_management; SHOW TABLES;"
   ```

4. **Send me the output** and I'll help debug further!
