> ## 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.

# Auth Overview

Modelence provides a comprehensive built-in authentication system with support for email/password authentication, email verification, password reset, and session management. This guide explains how authentication works in Modelence and how to implement it in your application.

## Overview

Modelence authentication includes:

* **Email/Password Authentication** - User signup and login with email and password
* **Session Management** - Secure session handling with automatic token rotation
* **[User Management](/authentication/user-management)** - User profile and role management
* **[Email Verification](/authentication/email-verification)** - Optional email verification for new signups
* **[Password Reset](/authentication/password-reset)** - Secure password reset flow with email tokens
* **[Hooks](/authentication/hooks)** - Add custom handlers and error rendering components for your authentication flow
* **[Rate Limiting](/authentication/rate-limiting)** - Built-in protection against brute force attacks
* **[Google Sign-In](/authentication/google-sign-in)** - OAuth authentication with Google accounts
* **[GitHub Sign-In](/authentication/github-sign-in)** - OAuth authentication with GitHub accounts

## Where to configure what

Modelence splits authentication configuration across two top-level keys in `startApp`:

* **`auth: { ... }`** — authentication *lifecycle*: validation hooks (`validateSignup`, `validateProfileUpdate`), event callbacks (`onAfterLogin`, `onAfterSignup`, `onAfterEmailVerification`, …), `generateHandle`, OAuth linking behavior, and `rateLimits`. See [AuthConfig](/api-reference/modelence/server/type-aliases/AuthConfig) and [Hooks](/authentication/hooks).
* **`email: { ... }`** — email *delivery*: the email provider, sender address, and per-flow templates/subjects/redirect URLs for `verification` and `passwordReset`. See [Email Configuration](/email).

The two are complementary: `email:` controls whether and how the verification/reset email is delivered; `auth:` controls what happens when the user clicks the link (and the rest of the auth lifecycle).

## How Authentication Works

### Session Management

When a user visits your application, Modelence automatically creates a session:

1. **Session Creation** - A secure session token is generated using cryptographically random bytes
2. **Token Storage** - The session token is stored in the database and sent to the client
3. **Automatic Expiration** - Sessions expire after 7 days of inactivity
4. **Heartbeat Updates** - Active sessions are automatically renewed through periodic heartbeat requests

Sessions are stored in the `_modelenceSessions` collection and tracked with the following properties:

```typescript theme={null}
{
  authToken: string;      // Secure random token
  createdAt: Date;        // Session creation timestamp
  expiresAt: Date;        // Automatic expiration date
  userId: ObjectId | null; // Associated user (null for guest sessions)
}
```

### User Authentication Flow

#### Signup Process

When a user signs up with email and password:

1. **Validation** - Email format and password strength are validated
2. **Duplicate Check** - System checks if email already exists
3. **Validate Signup** (Optional) - If provided, validates signup using `validateSignup` hook
4. **Password Hashing** - Password is securely hashed using bcrypt (never stored in plain text)
5. **User Creation** - User record is created in the `_modelenceUsers` collection
6. **Session Linking** - The session is linked to the new user
7. **Email Verification** (Optional) - If enabled, a verification email is sent

#### Login Process

When a user logs in:

1. **Credential Verification** - Email and password are validated against stored credentials
2. **Session Update** - Current session is linked to the authenticated user
3. **User Data** - User information is returned to the client
4. **State Update** - Client-side session state is updated

### OAuth Account Linking

When a user signs in with an OAuth provider (Google or GitHub) using an email that already matches an existing email/password account, behavior is controlled by the [`oauthAccountLinking`](/api-reference/modelence/server/type-aliases/AuthConfig#oauthaccountlinking) auth config option:

* **`'manual'`** (default) - The OAuth sign-in is rejected with an error: *"User with this email already exists. Please log in instead."* The user must log in with their existing password first and link the provider deliberately.
* **`'auto'`** - The OAuth provider is automatically linked to the existing account, but only when **both** the OAuth-provided email is verified by the provider **and** the matching email on the existing account is also marked verified locally. This dual-verification requirement prevents pre-registration account takeover (e.g., someone registering a password account against an email they don't own, then waiting for the real owner to sign in via OAuth). When auto-linking succeeds, missing `firstName`, `lastName`, and `avatarUrl` fields are backfilled from the provider profile.

If either email is unverified — even in `'auto'` mode — the sign-in is rejected with the same error.

Once an OAuth provider is linked, subsequent sign-ins with the same provider look up the user directly by the provider's user ID, regardless of email.

## Basic Implementation

### Client-Side Usage

#### Signup

```typescript theme={null}
import { signupWithPassword } from 'modelence/client';

async function handleSignup(email: string, password: string) {
  try {
    await signupWithPassword({ email, password });
    // User is now signed up
    // If email verification is disabled, user is automatically logged in
  } catch (error) {
    console.error('Signup failed:', error.message);
  }
}

// You can also pass optional profile fields during signup
await signupWithPassword({
  email: 'test@example.com',
  password: 'securepassword',
  firstName: 'John',
  lastName: 'Doe',
  avatarUrl: 'https://example.com/avatar.jpg',
  handle: 'johndoe',
});
```

#### Login

```typescript theme={null}
import { loginWithPassword } from 'modelence/client';

async function handleLogin(email: string, password: string) {
  try {
    const user = await loginWithPassword({ email, password });
    console.log('Logged in as:', user.handle);
  } catch (error) {
    console.error('Login failed:', error.message);
  }
}
```

#### Logout

```typescript theme={null}
import { logout } from 'modelence/client';

async function handleLogout() {
  await logout();
  // User is now logged out
}
```

#### Update Profile

```typescript theme={null}
import { updateProfile } from 'modelence/client';

async function handleUpdateProfile() {
  try {
    const user = await updateProfile({
      firstName: 'John',
      lastName: 'Doe',
      avatarUrl: 'https://example.com/avatar.jpg',
      handle: 'johndoe',
    });
    console.log('Profile updated:', user.handle);
  } catch (error) {
    console.error('Update failed:', error.message);
  }
}
```

All fields are optional — pass only the ones you want to update. Modelence automatically updates the user in `useSession()`.

#### Accessing Current User

```typescript theme={null}
import { useSession } from 'modelence/client';

function MyComponent() {
  const { user } = useSession();

  if (!user) {
    return <div>Please log in</div>;
  }

  return <div>Welcome, {user.handle}!</div>;
}
```

## API Reference

### Client Functions

* [signupWithPassword](/api-reference/modelence/client/functions/signupWithPassword) - Sign up with email and password
* [loginWithPassword](/api-reference/modelence/client/functions/loginWithPassword) - Log in with email and password
* [logout](/api-reference/modelence/client/functions/logout) - Log out current user
* [useSession](/api-reference/modelence/client/functions/useSession) - Access current user session
* [verifyEmail](/api-reference/modelence/client/functions/verifyEmail) - Verify email with token
* [sendResetPasswordToken](/api-reference/modelence/client/functions/sendResetPasswordToken) - Request password reset
* [resetPassword](/api-reference/modelence/client/functions/resetPassword) - Set a new password (token is exchanged server-side via cookie)

### Server Types

* [AuthConfig](/api-reference/modelence/server/type-aliases/AuthConfig) - Authentication configuration
* [UserInfo](/api-reference/modelence/server/type-aliases/UserInfo) - User information type
* [dbUsers](/api-reference/modelence/server/variables/dbUsers) - User database collection

### Error Types

* [AuthError](/api-reference/modelence/index/classes/AuthError) - Authentication errors
* [ValidationError](/api-reference/modelence/index/classes/ValidationError) - Validation errors
* [RateLimitError](/api-reference/modelence/index/classes/RateLimitError) - Rate limit errors
