# Auth provider

> Session state for the whole app: who is signed in, their roles and permissions, and every sign-in action, from any backend.

Status: beta. Category: Auth.

```ts
import { AuthProvider, Can, AuthError, NEXT_PARAM } from '@glyphui/auth'
```

Exports: `AuthProvider`, `useAuth`, `useUser`, `useSession`, `useCan`, `useHasRole`, `Can`, `useAuthClient`, `createAuthClient`, `AuthError`, `isAuthError`, `can`, `hasRole`, `NEXT_PARAM`, `safeRedirectPath`, `signInPathFor`.

## Notes

- Status is loading until the adapter answers, then authenticated or unauthenticated. Guards show a spinner while loading.
- The session is re-checked when the tab regains focus and every 5 minutes (refreshInterval), and refreshed just before expiresAt.
- Signing in or out in one tab updates every other tab (syncTabs). Pass a name when two apps share an origin.
- idleTimeout signs users out after inactivity; IdleWarningDialog warns them first.
- Can and RequireRole only shape the UI. Your API must check the same permissions.
- Adapter errors are AuthError instances; fieldErrors holds messages for individual form fields.

## AuthProvider props

| Prop | Type | Default | Description |
|---|---|---|---|
| `adapter` | `AuthAdapter` |  | An adapter; the provider creates the client. Use `client` when loaders need it. |
| `client` | `AuthClient` |  | A client from `createAuthClient`, shared with route loaders. |
| `idleTimeout` | `number` |  | Sign the user out after this long without activity (ms). Off by default. |
| `idleWarning` | `number` |  | How long before the idle sign-out to warn (ms). Default 60 seconds. |
| `onSignOut` | `((reason: SignOutReason) => void)` |  | Called after any sign-out, with why it happened. |
| `refreshInterval` | `number \| false` |  | Re-check the session this often while the tab is open. Default 5 minutes; `false` to disable. |
| `refreshOnFocus` | `boolean` |  | Re-check the session when the tab regains focus. Default true. |
| `syncTabs` | `string \| boolean` |  | Keep tabs in sync: signing in or out in one tab updates the others. Pass a string to name the channel (useful when two apps share an origin). Default true. |

## Example: Session state

useAuth() gives the status, the user and every action. This demo uses the in-memory adapter.

```tsx
import { AuthProvider, useAuth } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { Avatar, Badge, Button, Card, Text } from '@glyphui/ui'

const adapter = memoryAdapter({
  latency: 400,
  users: [{ email: 'ada@example.com', password: 'correct horse', name: 'Ada Lovelace' }],
})

function SessionCard() {
  const { status, user, signIn, signOut } = useAuth()
  return (
    <Card className="w-full max-w-sm gap-4">
      <div className="flex items-center justify-between gap-3">
        <Text weight="medium">Session</Text>
        <Badge tone={status === 'authenticated' ? 'success' : 'neutral'} dot>
          {status}
        </Badge>
      </div>
      {user ? (
        <div className="flex items-center gap-3">
          <Avatar name={user.name ?? user.email} />
          <div className="grid">
            <Text weight="medium">{user.name}</Text>
            <Text size="small" tone="muted">
              {user.email}
            </Text>
          </div>
        </div>
      ) : (
        <Text size="small" tone="muted">
          Nobody is signed in.
        </Text>
      )}
      {user ? (
        <Button variant="outline" onClick={() => signOut()}>
          Sign out
        </Button>
      ) : (
        <Button
          disabled={status === 'loading'}
          onClick={() => signIn({ email: 'ada@example.com', password: 'correct horse' })}
        >
          Sign in as Ada
        </Button>
      )}
    </Card>
  )
}

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <SessionCard />
    </AuthProvider>
  )
}
```

## Example: Roles and permissions

Can and useCan read permissions such as invoices:write; invoices:* is a wildcard.

```tsx
import { AuthProvider, Can, useAuth, useCan } from '@glyphui/auth'
import { memoryAdapter } from '@glyphui/auth/memory'
import { Button, Card, SegmentedControl, Text } from '@glyphui/ui'

const adapter = memoryAdapter({
  latency: 0,
  users: [
    {
      email: 'owner@acme.dev',
      password: 'pw',
      name: 'Owner',
      permissions: ['invoices:*', 'billing:manage'],
    },
    { email: 'viewer@acme.dev', password: 'pw', name: 'Viewer', permissions: ['invoices:read'] },
  ],
})

function Invoices() {
  const { user, signIn } = useAuth()
  const canEdit = useCan('invoices:write')
  return (
    <Card className="w-full max-w-md gap-4">
      <SegmentedControl
        aria-label="Signed in as"
        value={user?.email ?? ''}
        onValueChange={(email) => signIn({ email, password: 'pw' })}
        options={[
          { value: 'owner@acme.dev', label: 'Owner' },
          { value: 'viewer@acme.dev', label: 'Viewer' },
        ]}
      />
      <Text size="small" tone="muted">
        {user ? `${user.name} can ${canEdit ? 'edit' : 'only read'} invoices.` : 'Pick a user.'}
      </Text>
      <div className="flex flex-wrap gap-2">
        <Button variant="outline" disabled={!canEdit}>
          Edit invoice
        </Button>
        <Can permission="billing:manage" fallback={<Button disabled>Billing (owners only)</Button>}>
          <Button>Manage billing</Button>
        </Can>
      </div>
    </Card>
  )
}

export default function Example() {
  return (
    <AuthProvider adapter={adapter} syncTabs={false}>
      <Invoices />
    </AuthProvider>
  )
}
```

Live page: https://glyphui.xyz/components/auth
