# Google Sign-In Setup Guide

## 🎯 Overview
SunnaGhar now supports **Google Sign-In** authentication, allowing customers to log in and sign up with their Google accounts instantly.

## ✨ Features Implemented

### 1. **Google Sign-In Button**
- Added to both Sign-In and Sign-Up forms
- Styled to match the glass-morphism design
- Bengali locale support (button text in Bengali)
- Automatic user creation/update on successful login

### 2. **Seamless Auth Flow**
- Google credential validated on client-side
- User data (name, email, Google ID) extracted from JWT token
- Existing users are recognized by email or Google ID
- New accounts created automatically with Google-provided info
- User session stored in localStorage (same as email auth)

### 3. **Error Handling**
- User-friendly Bengali error messages
- Invalid token detection
- Failed login feedback
- Network error handling

## 🔧 Setup Instructions

### Step 1: Get Google OAuth Credentials

1. **Create Google Cloud Console Account**
   - Go to https://console.cloud.google.com/
   - Sign in with your Google account

2. **Create or Select Project**
   - Click "Select a Project"
   - Click "NEW PROJECT"
   - Name: "SunnaGhar" (or your app name)
   - Click "CREATE"

3. **Enable Google Identity Services API**
   - In the search bar, search for "Google Identity Services API"
   - Click the first result
   - Click "ENABLE"

4. **Create OAuth 2.0 Credentials**
   - Go to **Credentials** (left sidebar)
   - Click **"+ CREATE CREDENTIALS"**
   - Select **OAuth client ID**
   - Choose **Web application** as application type
   - Name it "SunnaGhar Frontend"

5. **Configure Authorized Origins**
   - Add authorized JavaScript origins:
     ```
     http://localhost:3000
     http://localhost
     https://yourdomain.com (production)
     ```
   - Click "CREATE"

6. **Copy Client ID**
   - You'll see a popup with your Client ID
   - Copy the Client ID (keep the secret safe, but not needed for frontend)

### Step 2: Configure Environment Variables

1. **Open `.env.local` file** in the project root
2. **Paste your Google Client ID:**
   ```env
   NEXT_PUBLIC_GOOGLE_CLIENT_ID=your_copied_client_id_here
   ```
3. **Save the file**

### Step 3: Install Dependencies

Run the following command to install Google OAuth package:

```bash
npm install
```

## 🧪 Testing Locally

1. **Start the development server:**
   ```bash
   npm run dev
   ```

2. **Navigate to the home page**
   - Go to http://localhost:3000

3. **Click on the user icon** (top right of header)

4. **Try Sign-In with Google:**
   - Click "Sign In"
   - Click the Google Sign-In button
   - Select a Google account
   - You should be logged in!

5. **Try Sign-Up with Google:**
   - Click "Sign Up"
   - Click the Google Sign-In button
   - New account will be created automatically

## 📁 Files Modified/Created

### New Files
- **`components/google-signin-button.tsx`** - Google Sign-In button component
- **`.env.example`** - Environment variable template
- **`.env.local`** - Your local environment config (add your Client ID here)
- **`GOOGLE_SIGNIN_SETUP.md`** - This guide

### Updated Files
- **`lib/auth.ts`** 
  - Added `User.googleId` and `User.authMethod` fields
  - Added `loginWithGoogle()` function
  - Supports both email and Google authentication

- **`components/auth-modal.tsx`**
  - Imported `GoogleSignInButton` component
  - Added Google button to Sign-In form
  - Added Google button to Sign-Up form
  - Added error state for Google login errors
  - Added "অথবা" (OR) divider between email and Google auth

- **`package.json`**
  - Added `@react-oauth/google` dependency
  - Added `jwt-decode` for token handling (optional, using native atob instead)

## 🔒 Security Notes

### Frontend (Client-Side)
- ✅ **Safe:** Google Client ID is public (prefixed with `NEXT_PUBLIC_`)
- ✅ **Safe:** JWT token is decoded on client-side only
- ✅ **Safe:** No sensitive data exposed

### Local Storage
- Users authenticated via Google are stored in localStorage
- Same as email-password auth (demo setup)
- **For production:** Implement backend session/token validation

### Production Recommendations
1. **Backend Token Verification:** Verify Google token signature on server
2. **Secure Sessions:** Use HTTP-only cookies for session management
3. **Rate Limiting:** Add rate limiting on auth endpoints
4. **HTTPS Only:** Enforce HTTPS in production
5. **CORS Configuration:** Properly configure CORS for your domain

## 🚀 Deployment

### For Vercel/Next.js Hosting

1. **Add environment variable to your hosting platform:**
   - Platform: Vercel, Netlify, AWS, etc.
   - Variable: `NEXT_PUBLIC_GOOGLE_CLIENT_ID`
   - Value: Your Google OAuth Client ID

2. **Update Google OAuth Console:**
   - Add your production domain to "Authorized JavaScript origins"
   - Example: `https://sunnaghar.vercel.app`

3. **Deploy:**
   ```bash
   git push  # Vercel auto-deploys on push
   ```

## 🐛 Troubleshooting

### Issue: "Google Client ID not found" message
- **Solution:** Check that `NEXT_PUBLIC_GOOGLE_CLIENT_ID` is set in `.env.local`
- Make sure `.env.local` is NOT in `.gitignore` (it should be, but should exist locally)

### Issue: Google button doesn't appear
- **Solution:** 
  - Check browser console for errors
  - Ensure Google Identity Services script loads (check Network tab)
  - Verify `NEXT_PUBLIC_GOOGLE_CLIENT_ID` is correct

### Issue: "Sign-In failed" popup
- **Possible causes:**
  - Domain not added to authorized origins in Google Console
  - Invalid Client ID
  - Browser cookies disabled
- **Solution:** Check Google Cloud Console settings and Browser DevTools Console

### Issue: User logs in but session not persisting
- **Solution:** Currently uses localStorage (same as email auth)
- For production, implement proper session handling on backend

## 📱 User Experience

### Desktop Flow
1. User clicks auth icon → Sign-In modal opens
2. Can enter email/password **OR** click "Sign in with Google"
3. Google popup appears for account selection
4. User is logged in instantly
5. Modal closes, user can see their name in the header

### Mobile Flow
- Same as desktop (responsive design)
- Google button adapts to screen size
- Touch-friendly UI

## 🔄 User Data Flow

```
User clicks "Sign in with Google"
    ↓
Google OAuth popup
    ↓
User selects/authenticates with Google
    ↓
Google returns JWT credential
    ↓
loginWithGoogle() decodes token
    ↓
Extract: email, name, googleId from JWT
    ↓
Check if user exists (by email or googleId)
    ↓
If exists: Update name, set authMethod="google"
If new: Create user with Google data
    ↓
Save to localStorage
    ↓
Dispatch auth event
    ↓
Modal closes, UI updates
```

## 📝 Next Steps (Optional Enhancements)

1. **Backend Integration:**
   - Create `/api/auth/verify-google` endpoint
   - Verify Google token signature server-side
   - Store sessions in database instead of localStorage

2. **Additional Providers:**
   - Add Facebook Sign-In
   - Add GitHub Sign-In
   - Add Apple Sign-In

3. **Account Linking:**
   - Allow users to link Google to existing email accounts
   - Merge user profiles

4. **Profile Completion:**
   - Ask for phone number on Google sign-up
   - Auto-fill profile from Google profile picture

## 💡 Tips

- **Test with multiple Google accounts** to ensure new and existing user flows work
- **Check localStorage** in DevTools (Application → Cookies → localhost:3000) to see saved sessions
- **Monitor Google Console API usage** to track sign-in events

---

**Happy Shipping! 🚀** Your customers can now sign in with Google in just one click!
