# Google Authentication Configuration

This document explains how Google authentication is configured in the Magasinekbh application using Better Auth.

## Overview

Google authentication is configured using Better Auth's social provider functionality, allowing users to sign in with their Google accounts.

## Configuration

### 1. Environment Variables

Add the following environment variables to your `.env.local` file:

```env
NEXT_PUBLIC_GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
```

### 2. Getting Google OAuth Credentials

To get your Google credentials:

1. Go to the [Google Cloud Console](https://console.cloud.google.com/)
2. Create a new project or select an existing one
3. Navigate to **APIs & Services** > **Credentials**
4. Click **Create Credentials** > **OAuth client ID**
5. Select **Web application** as the application type
6. Configure the authorized redirect URIs:
   - **Local development**: `http://localhost:3000/api/auth/callback/google`
   - **Production**: `https://yourdomain.com/api/auth/callback/google`

> **Note**: If you change the base path of the auth routes in your Better Auth configuration, update the redirect URL accordingly.

### 3. Server Configuration

The Google provider is configured in `src/lib/auth/auth.ts`:

```typescript
export const auth = betterAuth({
  socialProviders: {
    google: {
      clientId: config.socialAuth.google.clientId,
      clientSecret: config.socialAuth.google.clientSecret
    }
  }
});
```

### 4. Client Configuration

The auth client is configured in `src/lib/auth/auth-client.ts` and includes the Google One Tap plugin:

```typescript
export const client = createAuthClient({
  baseURL: process.env.NEXT_PUBLIC_APP_URL,
  plugins: [
    oneTapClient({
      clientId: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID!,
      promptOptions: {
        maxAttempts: 1
      }
    })
  ]
});
```

## Usage

### Sign In with Google

Google sign-in is implemented in multiple places across the application:

```typescript
import { signIn } from '@/lib/auth/auth-client';

const handleGoogleSignIn = async () => {
  await signIn.social({
    provider: 'google',
    callbackURL: '/dashboard' // or your desired redirect URL
  });
};
```

### Example Implementation

The main sign-in form (`src/app/(main)/(auth)/_components/sign-in-form.tsx`):

```tsx
<Button
  className="relative w-full bg-[#EA4335] font-medium text-white hover:bg-red-400"
  onClick={async () => {
    await signIn.social({
      provider: 'google',
      callbackURL: Routes.HOME
    });
  }}
>
  <Image src="/icons/google_icon_white.svg" alt="Google icon" />
  <span>Google</span>
</Button>
```

## Advanced Features

### Google One Tap

Google One Tap is already enabled in the application. It allows users to sign in with a single tap using their Google account without redirecting to Google's login page.

The One Tap prompt will automatically appear on your site for users who are signed in to Google.

### Account Linking

The application is configured to allow account linking with Google:

```typescript
account: {
  accountLinking: {
    trustedProviders: ['google', 'github', 'demo-app', 'facebook']
  }
}
```

This means users can link their Google account to an existing account if they signed up with email/password or another provider.

### Requesting Additional Google Scopes

If you need additional Google API access (e.g., Google Drive, Gmail), you can request additional scopes:

```typescript
const requestGoogleDriveAccess = async () => {
  await authClient.linkSocial({
    provider: 'google',
    scopes: ['https://www.googleapis.com/auth/drive.file']
  });
};
```

## Configuration Options

### Always Ask to Select Account

To force users to always select an account (even if they're already signed in), add the `prompt` parameter:

```typescript
socialProviders: {
  google: {
    clientId: config.socialAuth.google.clientId,
    clientSecret: config.socialAuth.google.clientSecret,
    prompt: 'select_account' // Forces account selection
  }
}
```

### Always Get Refresh Token

Google only issues a refresh token the first time a user authorizes your app. To always get a refresh token:

```typescript
socialProviders: {
  google: {
    clientId: config.socialAuth.google.clientId,
    clientSecret: config.socialAuth.google.clientSecret,
    accessType: 'offline',
    prompt: 'select_account consent'
  }
}
```

> **Important**: If a user has already authorized your app and you want a new refresh token, they must first revoke your app's access in their Google account settings, then re-authorize.

## Troubleshooting

### Redirect URI Mismatch

If you get a "redirect_uri_mismatch" error:
- Verify the redirect URI in Google Cloud Console matches exactly: `http://localhost:3000/api/auth/callback/google`
- Ensure there are no trailing slashes
- Check that the protocol (http/https) matches your environment

### Missing Refresh Token

If you're not receiving a refresh token:
- Set `accessType: 'offline'` in your Google provider configuration
- Have users revoke and re-authorize if they've already granted access
- Ensure `prompt: 'consent'` is set to force the consent screen

### One Tap Not Showing

If Google One Tap isn't appearing:
- Verify `NEXT_PUBLIC_GOOGLE_CLIENT_ID` is set correctly
- Check that the domain is verified in Google Cloud Console
- Ensure the user is signed in to Google in their browser
- One Tap may not show on localhost in some browsers (use a tunneling service like ngrok for testing)

## Security Considerations

1. **Never expose your client secret**: The `GOOGLE_CLIENT_SECRET` should only be used on the server side
2. **Use HTTPS in production**: Google requires HTTPS for production OAuth callbacks
3. **Validate redirect URIs**: Only add trusted redirect URIs in the Google Cloud Console
4. **Review scopes**: Only request the minimum scopes needed for your application

## Resources

- [Better Auth Google Documentation](https://www.better-auth.com/docs/authentication/google)
- [Google OAuth 2.0 Documentation](https://developers.google.com/identity/protocols/oauth2)
- [Google Cloud Console](https://console.cloud.google.com/)

## Related Files

- **Server Configuration**: `src/lib/auth/auth.ts`
- **Client Configuration**: `src/lib/auth/auth-client.ts`
- **Environment Config**: `src/config/env.ts`
- **Sign-in Form**: `src/app/(main)/(auth)/_components/sign-in-form.tsx`
- **Sign-up Form**: `src/app/(main)/(auth)/_components/sign-up-form.tsx`

