> ## Documentation Index
> Fetch the complete documentation index at: https://docs.modelence.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Google Sign-In

Modelence supports OAuth authentication with Google, allowing users to sign in with their Google accounts.

## Prerequisites

Before implementing Google Sign-In, you need to:

1. Create a project in the [Google Cloud Console](https://console.cloud.google.com/)
2. Configure the OAuth consent screen
3. Create OAuth 2.0 credentials (Client ID and Client Secret)
4. Configure authorized redirect URIs

## Google Cloud Console Setup

1. **Create a Project**
   * Go to [Google Cloud Console](https://console.cloud.google.com/)
   * Click "Select a project" → "New Project"
   * Name your project and click "Create"

2. **Configure OAuth Consent Screen**
   * Go to "APIs & Services" → "OAuth consent screen"
   * Choose user type (External for most applications)
   * Fill in the required fields:
     * App name
     * User support email
     * Developer contact information
   * Click "Save and Continue"
   * Add scopes if needed (profile and email are included by default)
   * Click "Save and Continue"

3. **Create OAuth Credentials**
   * Go to "APIs & Services" → "Credentials"
   * Click "Create Credentials" → "OAuth client ID"
   * Select "Web application" as the application type
   * Add a name for your OAuth client

4. **Configure Redirect URIs**
   * Under "Authorized JavaScript origins", add:
     * `http://localhost:3000` (for local development)
     * `https://yourdomain.com` (for production)
   * Under "Authorized redirect URIs", add:
     * `http://localhost:3000/api/_internal/auth/google/callback` (for local development)
     * `https://yourdomain.com/api/_internal/auth/google/callback` (for production)
   * Click "Create"

5. **Save Credentials**
   * Copy your **Client ID** and **Client Secret**
   * Store them securely (use environment variables or Modelence Cloud config)

## Server-Side Configuration

Google Sign-In is built into Modelence and requires no additional packages.

### Option 1: Modelence Cloud (Recommended)

The preferred way to configure Google authentication is through [Modelence Cloud](https://cloud.modelence.com/):

1. Go to [https://cloud.modelence.com/](https://cloud.modelence.com/)
2. Navigate to your project
3. Go to **Users → Auth Providers → Google**
4. Enable Google authentication
5. Enter your **Client ID** and **Client Secret** from Google Cloud Console
6. Save the configuration

This approach allows you to manage your configuration centrally through an intuitive UI and keeps sensitive credentials secure.

### Option 2: Environment Variables

Alternatively, you can use environment variables. Create a `.env` file in your project root:

```bash theme={null}
MODELENCE_AUTH_GOOGLE_ENABLED=true
MODELENCE_AUTH_GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
MODELENCE_AUTH_GOOGLE_CLIENT_SECRET=your-client-secret
```

Make sure to add `.env` to your `.gitignore` file to keep credentials secure.

The Google authentication is automatically enabled when these configurations are set. No additional server code is needed.

## Client-Side Implementation

To initiate Google Sign-In, redirect the user to the Google authentication endpoint:

```typescript theme={null}
function handleGoogleSignIn() {
  // Redirect to Google OAuth flow
  window.location.href = '/api/_internal/auth/google';
}
```

## UI Integration

Add a Google Sign-In button to your UI:

```typescript theme={null}
function LoginForm() {
  return (
    <div>
      <h2>Sign In</h2>
      <button onClick={() => window.location.href = '/api/_internal/auth/google'}>
        Sign in with Google
      </button>
    </div>
  );
}
```

## How Google Sign-In Works

1. **Initiation** - User clicks "Sign in with Google" button
2. **Redirect** - User is redirected to Google's OAuth consent screen
3. **Authorization** - User grants permission to your app
4. **Callback** - Google redirects back to your app with an authorization code
5. **Token Exchange** - Your server exchanges the code for user information
6. **User Creation/Login** - If user doesn't exist, a new account is created; otherwise, user is logged in
7. **Session Creation** - A session is established and the user is authenticated

## User Data Handling

When a user signs in with Google, Modelence automatically:

* Creates a user account if one doesn't exist
* Links the Google account to the user profile
* Retrieves profile information (first name, last name, email, avatar URL)
* Marks the email as verified (since Google has verified it)
* **Backfills missing profile fields** — If an existing user is missing `firstName`, `lastName`, or `avatarUrl`, these fields are automatically populated from their Google profile on login

The user object will contain:

```typescript theme={null}
{
  email: string;           // Google account email
  handle: string;          // Generated from email or name
  emailVerified: true;     // Always true for Google sign-in
  googleId: string;        // Google user ID
  firstName?: string;      // First name from Google
  lastName?: string;       // Last name from Google
  avatarUrl?: string;      // Avatar URL from Google
}
```

## Combining with Email/Password Authentication

Users can have both Google and email/password authentication on the same account:

```typescript theme={null}
import { loginWithPassword, logout } from 'modelence/client';
import { useState } from 'react';

function LoginOptions() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  return (
    <div>
      <h2>Sign In</h2>

      {/* Google Sign-In */}
      <button onClick={() => window.location.href = '/api/_internal/auth/google'}>
        Sign in with Google
      </button>

      <div>or</div>

      {/* Email/Password Sign-In */}
      <form onSubmit={async (e) => {
        e.preventDefault();
        await loginWithPassword({ email, password });
      }}>
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="Email"
        />
        <input
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder="Password"
        />
        <button type="submit">Sign In</button>
      </form>
    </div>
  );
}
```

## Troubleshooting

**Redirect URI Mismatch Error**

* Ensure the redirect URI in Google Cloud Console exactly matches your application URL
* Check for trailing slashes and http vs https
* Common format: `https://yourdomain.com/api/_internal/auth/google/callback`

**Invalid Client Error**

* Verify your Client ID and Client Secret are correct
* Check that environment variables are properly loaded
* Ensure credentials are from the correct Google Cloud project

**Access Blocked: Authorization Error**

* Make sure Google+ API is enabled in your project
* Verify your OAuth consent screen is configured
* Check that your domain is authorized
