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

# Authentication Setup

> Building better-auth based authentication system in Sonamu

Learn how to set up user authentication in Sonamu. Sonamu provides an integrated authentication system based on [better-auth](https://www.better-auth.com/).

## Authentication System Overview

<CardGroup cols={2}>
  <Card title="better-auth Integration" icon="shield-halved">
    Proven authentication library

    Email/password, Social login
  </Card>

  <Card title="Auto Entity Generation" icon="wand-magic-sparkles">
    Generate entities via CLI

    User, Session, Account, Verification
  </Card>

  <Card title="Context Based" icon="diagram-project">
    User info per request

    Sonamu.getContext()
  </Card>

  <Card title="Guards System" icon="lock">
    Declarative permission control

    @api guards option
  </Card>
</CardGroup>

## Quick Start

### 1. Generate Auth Entities

Automatically generate entities required by better-auth:

```bash theme={null}
pnpm sonamu auth generate
```

This command generates 4 entities:

| Entity       | Table         | Description                                                        |
| ------------ | ------------- | ------------------------------------------------------------------ |
| User         | users         | User info (id, name, email, email\_verified, image)                |
| Session      | sessions      | Session info (id, token, expires\_at, user\_id)                    |
| Account      | accounts      | Social account linking (id, provider\_id, access\_token, user\_id) |
| Verification | verifications | Email verification etc. (id, identifier, value, expires\_at)       |

<Info>
  If entities already exist, only missing fields are added. Fields with changed types are
  automatically updated.
</Info>

### 2. Run Migrations

After generating entities, run migrations:

```bash theme={null}
pnpm sonamu migrate generate
pnpm sonamu migrate run
```

### 3. Configure Authentication

Enable authentication in `sonamu.config.ts`:

```typescript theme={null}
// sonamu.config.ts
import type { SonamuConfig } from "sonamu";

export default {
  // ... other settings
  server: {
    auth: {
      emailAndPassword: { enabled: true },
    },
  },
} satisfies SonamuConfig;
```

This enables basic email/password authentication.

## API Endpoints

API endpoints provided by better-auth are automatically registered:

| Path                      | Method | Description         |
| ------------------------- | ------ | ------------------- |
| `/api/auth/sign-up/email` | POST   | Email signup        |
| `/api/auth/sign-in/email` | POST   | Email login         |
| `/api/auth/sign-out`      | POST   | Logout              |
| `/api/auth/get-session`   | GET    | Get current session |

## Accessing User Info in Context

Access authenticated user information through Context:

```typescript theme={null}
import { Sonamu } from "sonamu";

class UserModelClass extends BaseModelClass {
  @api({ httpMethod: "GET", guards: ["user"] })
  async me(): Promise<UserSubsetA | null> {
    const { user, session } = Sonamu.getContext();

    if (!user) return null;

    // Access user.id, user.email, user.name, etc.
    return this.findById("A", user.id);
  }
}
```

### AuthContext Type

```typescript theme={null}
type AuthContext = {
  /** Currently logged in user (null if unauthenticated) */
  user: User | null;
  /** Current session info (null if unauthenticated) */
  session: Session | null;
};
```

`User` and `Session` types are provided by better-auth.

## Access Control with Guards

### Basic Guard Usage

```typescript theme={null}
class UserModelClass extends BaseModelClass {
  // Login required
  @api({ httpMethod: "GET", guards: ["user"] })
  async getProfile() {
    const { user } = Sonamu.getContext();
    return { userId: user.id };
  }

  // Admin permission required
  @api({ httpMethod: "DELETE", guards: ["admin"] })
  async deleteUser(id: string) {
    // Only admins can execute
  }
}
```

### Implementing guardHandler

Guard logic is implemented in `guardHandler` in `sonamu.config.ts`:

```typescript theme={null}
// sonamu.config.ts
import { Sonamu } from "sonamu";

export default {
  server: {
    auth: {
      emailAndPassword: { enabled: true },
    },
    apiConfig: {
      guardHandler: (guard, request, api) => {
        const { user } = Sonamu.getContext();

        switch (guard) {
          case "user":
            if (!user) {
              throw new Error("Login required");
            }
            break;

          case "admin":
            // Need to add role field to User entity
            if (!user || (user as any).role !== "admin") {
              throw new Error("Admin access only");
            }
            break;

          case "query":
            // Allow all users
            break;
        }
      },
    },
  },
} satisfies SonamuConfig;
```

## Social Login Setup

### Google Login

```typescript theme={null}
// sonamu.config.ts
export default {
  server: {
    auth: {
      emailAndPassword: { enabled: true },
      socialProviders: {
        google: {
          clientId: process.env.GOOGLE_CLIENT_ID!,
          clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
        },
      },
    },
  },
} satisfies SonamuConfig;
```

### GitHub Login

```typescript theme={null}
// sonamu.config.ts
export default {
  server: {
    auth: {
      emailAndPassword: { enabled: true },
      socialProviders: {
        github: {
          clientId: process.env.GITHUB_CLIENT_ID!,
          clientSecret: process.env.GITHUB_CLIENT_SECRET!,
        },
      },
    },
  },
} satisfies SonamuConfig;
```

## Adding User Roles

The default User entity in better-auth doesn't have a `role` field. If you need role-based authentication, add it directly to the User entity:

### 1. Add Field in Sonamu UI

Add `role` field to User entity:

* Name: `role`
* Type: `string`
* Default: `"user"`

### 2. Add Enum (Optional)

```json theme={null}
{
  "enums": {
    "UserRole": {
      "user": "Regular user",
      "admin": "Administrator",
      "manager": "Manager"
    }
  }
}
```

### 3. Check Role in guardHandler

```typescript theme={null}
guardHandler: (guard, request, api) => {
  const { user } = Sonamu.getContext();

  if (guard === "admin") {
    if (!user || (user as any).role !== "admin") {
      throw new Error("Admin permission required");
    }
  }
},
```

## Client Integration

### Using in React

```typescript theme={null}
import { createAuthClient } from "better-auth/react";

export const authClient = createAuthClient({
  baseURL: "http://localhost:4000/api/auth",
});

// Sign up
await authClient.signUp.email({
  email: "user@example.com",
  password: "password123",
  name: "John Doe",
});

// Sign in
await authClient.signIn.email({
  email: "user@example.com",
  password: "password123",
});

// Sign out
await authClient.signOut();

// Get current session
const session = await authClient.getSession();
```

## Field Mapping

better-auth uses camelCase, but Sonamu uses snake\_case. The following fields are automatically mapped:

| better-auth     | Sonamu           |
| --------------- | ---------------- |
| `emailVerified` | `email_verified` |
| `createdAt`     | `created_at`     |
| `userId`        | `user_id`        |
| `expiresAt`     | `expires_at`     |

## Checklist

Things to verify after setting up authentication:

* [ ] Run `pnpm sonamu auth generate`
* [ ] Generate and apply migrations
* [ ] Configure `server.auth` in `sonamu.config.ts`
* [ ] Implement `guardHandler`
* [ ] Verify user/session access in Context
* [ ] Add role to User entity if role-based auth is needed

## Next Steps

<CardGroup cols={2}>
  <Card title="Session Management" icon="clock-rotate-left" href="/en/api-development/authentication/session-management">
    Managing sessions and tokens
  </Card>

  <Card title="Context" icon="diagram-project" href="/en/api-development/context/sonamu-context">
    Learn more about Context
  </Card>

  <Card title="@api Decorator" icon="at" href="/en/api-development/creating-apis/api-decorator">
    API decorator options
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation" href="/en/api-reference/exceptions/sonamu-error">
    Handling authentication errors
  </Card>
</CardGroup>
