---
title: "Authentication"
description: "Configure sign-in methods, OAuth providers, and multi-factor authentication."
order: 4
---

## Overview

Authentication runs inside the API server (`/api/auth`, Better Auth). It supports:

- **Email/password** sign-up and sign-in
- **OAuth** providers (Google, Microsoft)
- **Magic links**: passwordless email authentication
- **Multi-factor authentication** (TOTP)

All auth state is managed through the `useAuth()` hook on the client and the session middleware on the server, which reads the HttpOnly session cookie.

## useAuth() Hook

The `useAuth()` hook (from `AuthProvider`) exposes everything you need for auth in React components:

| Property | Type | Description |
|----------|------|-------------|
| `user` | `User \| null` | Signed-in user (`id`, `email`, `name`, `image`, `role`) |
| `session` | `Session \| null` | Current session (no tokens: it lives in an HttpOnly cookie) |
| `isLoading` | `boolean` | `true` while session is being validated |
| `isSuperAdmin` | `boolean` | User's `role` is `super_admin` |
| `mfaRequired` | `boolean` | MFA is enforced app-wide (set by admin) |
| `hasMfaEnabled` | `boolean` | Current user has enrolled a TOTP factor |
| `signIn` | `object` | Sign-in methods (see below) |
| `signUp` | `function` | Create a new account |
| `signOut` | `function` | Sign out and clear session |
| `mfa` | `object` | MFA operations (enroll, challenge, verify) |
| `impersonateUser` | `function` | Impersonate a user (super admin only) |
| `stopImpersonating` | `function` | Return to admin session |

```typescript
import { useAuth } from '@/components/auth/AuthProvider';

function MyComponent() {
  const { user, isLoading, isSuperAdmin } = useAuth();

  if (isLoading) return <p>Loading...</p>;
  if (!user) return <p>Not signed in</p>;

  return <p>Hello, {user.email}</p>;
}
```

## Sign-In Methods

### Email & Password

The default sign-in method. Calls the server-side login endpoint which handles account lockout checks before authenticating.

```typescript
const { signIn } = useAuth();

try {
  const { requiresMfa } = await signIn.email('user@example.com', 'password');
  if (requiresMfa) {
    // Redirect to MFA verification page
  }
} catch (error) {
  // Handle error (invalid credentials, account locked, etc.)
}
```

The `signIn.email()` method returns `{ requiresMfa: boolean }`. When `true`, the user has MFA enrolled and must verify a TOTP code before accessing the app.

### Magic Links

Users receive a sign-in link via email; no password required. It needs SMTP and `MAGIC_LINK_ENABLED` (on by default). Without SMTP the sign-in page hides the option, and the send endpoint answers 400 `MAGIC_LINK_UNAVAILABLE`, so nobody waits for an email that never comes.

```typescript
const { signIn } = useAuth();

await signIn.magicLink('user@example.com');
// User receives an email with a sign-in link
```

### OAuth Providers

Google and Microsoft sign-in are built in. Each has a dedicated method:

```typescript
const { signIn } = useAuth();

await signIn.google();
await signIn.microsoft();
```

To enable one (the app's auth reads its credentials from environment variables):

1. Set the provider's credentials. `vibecarbon configure` → **OAuth** writes `GOOGLE_ENABLED` / `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET` (and the Microsoft equivalents, plus `MICROSOFT_TENANT_ID`) to `.env` / `.env.local`, and `vibecarbon deploy` ships them to the server.
2. In the provider's developer console, set the **authorized redirect URI** to `<SITE_URL>/api/auth/callback/google` (or `/microsoft`).
3. The provider button automatically appears on the sign-in page.

## Sign-Up

Create a new account with email, password, and an optional display name:

```typescript
const { signUp } = useAuth();

await signUp('user@example.com', 'password', 'Jane Smith');
// User is signed in and redirected to onboarding
```

The `name` parameter is stored in `user.name`.

## Route Protection

Two route guard components are defined in `App.tsx`:

**`ProtectedRoute`** requires any authenticated user. Redirects to `/sign-in` if not logged in. Also redirects to `/mfa-verify` if MFA is required but not yet verified.

**`SuperAdminProtectedRoute`** requires the `super_admin` role. Redirects to the dashboard if the user is not a super admin.

```tsx
// In App.tsx routes
<Route
  path="/dashboard"
  element={
    <ProtectedRoute>
      <Dashboard />
    </ProtectedRoute>
  }
/>

<Route
  path="/admin/*"
  element={
    <SuperAdminProtectedRoute>
      <AdminPanel />
    </SuperAdminProtectedRoute>
  }
/>
```

Public pages (like the landing page, blog, docs) don't need a wrapper.

## Multi-Factor Authentication

### Enrollment

Users enroll in MFA from **Settings → Security**. The flow:

1. Call `mfa.enroll()` to generate a TOTP secret and QR code
2. User scans the QR code with an authenticator app
3. User enters a TOTP code to verify enrollment

```typescript
const { mfa } = useAuth();

// Step 1: Enroll
const data = await mfa.enroll('My Authenticator');
// data.totp.qr_code: data URI for the QR code
// data.totp.uri: otpauth:// URI for manual entry

// Step 2: Verify enrollment with a code from the authenticator app
await mfa.challengeAndVerify(data.id, '123456');
```

### Sign-In with MFA

When a user with MFA signs in via email/password:

1. `signIn.email()` returns `{ requiresMfa: true }`
2. The app redirects to `/mfa-verify`
3. User enters their TOTP code
4. The code is verified against the pending challenge

```typescript
const { signIn, pendingMfaChallenge, mfa } = useAuth();

// During sign-in
const { requiresMfa } = await signIn.email(email, password);
if (requiresMfa) {
  // Navigate to MFA verification page
}

// On the MFA verification page
if (pendingMfaChallenge) {
  await mfa.verify(
    pendingMfaChallenge.factorId,
    pendingMfaChallenge.challengeId,
    totpCode
  );
}
```

### Admin Enforcement

Super admins can require MFA for all users from the admin dashboard. This sets the `mfa_enabled` key in the `app_settings` table. When enforced, `ProtectedRoute` redirects users without MFA to the enrollment page.

Your users can still turn their own two-factor off from **Settings → Security** while it is required. They confirm a code from their authenticator first (step-up), and then the requirement sends them back to enrollment.

## Account Lockout

Brute force protection is built in. After **5 failed login attempts** from the same email and IP address within a **15-minute window**, the account is locked.

- Locked accounts receive an HTTP `429 Too Many Requests` response with `remaining_minutes`
- Failed attempts are tracked in the `failed_login_attempts` table
- Successful login clears all failed attempts for that email/IP pair
- Super admins can unlock accounts via the `admin_unlock_account(email)` database function

## Server-Side Auth

API requests carry the session cookie the browser holds (HttpOnly, so page JavaScript never sees it). The server middleware checks it and makes the user available in route handlers:

```typescript
const user = c.get('user');
if (!user) return c.json({ error: 'Unauthorized' }, 401);
```

The middleware chain runs on every request:

1. **Read the session cookie** the auth API set at sign-in
2. **Look up the session and its user** in the database, so a revoked session, a banned user or a changed role takes effect on the next request
3. **Set context**: `c.set('user', user)` and `c.set('session', session)`, which routes read with `c.get('user')`

Mutating requests that carry the cookie also pass a CSRF origin check, so a script that calls your API must send a matching `Origin` header.

Routes then query the database as that user with `withUserDb(user.id, ...)`, so row-level security applies. For operations that need to bypass RLS (admin tasks, webhooks), the server uses `adminDb`, after checking the caller may do it:

```typescript
import { adminDb } from '../../db/client';
import { organizations } from '../../db/schema';

const all = await adminDb.select().from(organizations);
```

See [Database](/docs/database) for both.
