# Google OAuth Setup Guide

This guide will help you set up Google OAuth using the Node.js Express backend with redirect flow (no popup, no COOP errors).

## 📦 Prerequisites

All required packages have been installed:
- `passport`
- `passport-google-oauth20`
- `express-session`
- `jsonwebtoken`

## 🔐 Environment Variables

Create a `.env` file in the `Backend` directory with the following variables:

```env
# Server Configuration
PORT=4000
NODE_ENV=development

# CORS Configuration
FRONTEND_URL=http://localhost:3000
# OR use CORS_ORIGIN if you prefer
# CORS_ORIGIN=http://localhost:3000

# Database Configuration (if needed)
MONGO_URL=
MONGODB_DB_NAME=

# Google OAuth Configuration
GOOGLE_OAUTH_CLIENT_ID=your_client_id_here
GOOGLE_OAUTH_CLIENT_SECRET=your_client_secret_here
BACKEND_URL=http://localhost:4000
JWT_SECRET=supersecret123

# Session Secret (optional, defaults to "keyboard cat")
SESSION_SECRET=your_session_secret_here
```

## 🌐 Google Console Configuration

1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Select your project (or create a new one)
3. Navigate to **APIs & Services** > **Credentials**
4. Click **Create Credentials** > **OAuth client ID**
5. Configure the OAuth consent screen if you haven't already
6. Set up the OAuth client:

### Authorized JavaScript Origins
```
http://localhost:4000
```

### Authorized Redirect URIs
```
http://localhost:4000/auth/google/callback
```

7. Copy the **Client ID** and **Client Secret** to your `.env` file as `GOOGLE_OAUTH_CLIENT_ID` and `GOOGLE_OAUTH_CLIENT_SECRET`

## 🚀 Running the Server

```bash
cd Backend
npm run dev
```

The server will start on `http://localhost:4000`

## 🔄 OAuth Flow

1. **User clicks "Continue with Google"** → Frontend redirects to `http://localhost:4000/auth/google`
2. **Backend initiates OAuth** → Redirects user to Google login
3. **User authenticates** → Google redirects to `http://localhost:4000/auth/google/callback`
4. **Backend processes callback** → Creates JWT token and redirects to `http://localhost:3000/login-success?token=...`
5. **Frontend receives token** → Decodes JWT and stores user data in localStorage

## 📁 File Structure

```
Backend/
├── src/
│   ├── auth/
│   │   └── google.js          # Passport Google Strategy configuration
│   ├── routes/
│   │   └── auth.routes.js     # OAuth routes (/auth/google, /auth/google/callback)
│   ├── app.js                 # Express app with session & passport middleware
│   └── config/
│       └── index.js           # Configuration (uses FRONTEND_URL for CORS)
└── .env                       # Environment variables

reactwebsite/
└── login-success.php          # Handles JWT token from callback
```

## 🔧 Frontend Integration

The frontend button in `reactwebsite/includes/footer.php` has been updated to use the redirect flow:

```javascript
// Google OAuth - redirect to Node.js backend
if (provider === 'google') {
    const backendUrl = 'http://localhost:4000';
    window.location.href = `${backendUrl}/auth/google`;
    return;
}
```

## 🛡️ Security Notes

1. **JWT Secret**: Use a strong, random secret in production
2. **HTTPS**: Use HTTPS in production (update `BACKEND_URL` and `FRONTEND_URL`)
3. **Session Secret**: Use a strong session secret in production
4. **CORS**: Update `FRONTEND_URL` to match your production frontend URL

## 🐛 Troubleshooting

### "Redirect URI mismatch" error (Error 400)

This is the most common error. The callback URL must match EXACTLY in Google Console.

**Step 1: Check your current configuration**
Visit: `http://localhost:4000/auth/google/debug`

This will show you:
- The exact callback URL being used
- Which environment variables are set
- What needs to be configured in Google Console

**Step 2: Verify Google Console settings**

1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Navigate to **APIs & Services** > **Credentials**
3. Click on your OAuth 2.0 Client ID
4. Under **Authorized redirect URIs**, you MUST have EXACTLY:
   ```
   http://localhost:4000/auth/google/callback
   ```
   
   ⚠️ **Common mistakes:**
   - ❌ `http://localhost:4000/auth/google/callback/` (trailing slash)
   - ❌ `https://localhost:4000/auth/google/callback` (https instead of http)
   - ❌ `http://127.0.0.1:4000/auth/google/callback` (127.0.0.1 instead of localhost)
   - ❌ `http://localhost:4000/api/auth/google/callback` (extra /api)
   - ✅ `http://localhost:4000/auth/google/callback` (CORRECT)

**Step 3: Verify your .env file**

Make sure your `Backend/.env` file has:
```env
BACKEND_URL=http://localhost:4000
```

**Step 4: Restart your server**

After making changes:
```bash
# Stop the server (Ctrl+C)
# Then restart
npm run dev
```

**Step 5: Clear browser cache**

Sometimes Google caches the redirect URI. Try:
- Incognito/Private browsing mode
- Clear browser cache
- Or wait a few minutes for Google's cache to clear

### CORS errors
- Ensure `FRONTEND_URL` in `.env` matches your frontend URL
- Check that credentials are enabled in CORS config

### Token not received
- Check browser console for errors
- Verify `login-success.php` exists and is accessible
- Ensure `FRONTEND_URL` matches where `login-success.php` is hosted

## 📝 Production Checklist

- [ ] Update `BACKEND_URL` to production URL
- [ ] Update `FRONTEND_URL` to production URL
- [ ] Use strong `JWT_SECRET`
- [ ] Use strong `SESSION_SECRET`
- [ ] Enable HTTPS
- [ ] Update Google Console redirect URIs for production
- [ ] Test OAuth flow end-to-end

