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

# Auth collections

> Collections with built-in authentication features for managing users in PocketBase

Auth collections are specialized collections designed for user authentication. They extend base collections with built-in authentication features, password management, email verification, OAuth2 support, and more.

## When to use auth collections

Use auth collections when you need to:

* Manage user accounts with email/password authentication
* Implement OAuth2 social login (Google, Facebook, GitHub, etc.)
* Support email verification and password resets
* Enable multi-factor authentication (MFA)
* Implement one-time password (OTP) authentication
* Control user sessions and tokens

<Info>
  You can have multiple auth collections in the same app to support different user types (customers, admins, vendors, etc.).
</Info>

## Creating an auth collection

Create an auth collection using the factory function:

```go theme={null}
users := core.NewAuthCollection("users")
```

This initializes a collection with:

* Type set to `"auth"`
* All default auth fields (`email`, `password`, `verified`, etc.)
* Default authentication configuration
* Token generation settings

## Default auth fields

Auth collections automatically include these system fields:

<Tabs>
  <Tab title="id">
    Primary key field (same as base collections).

    ```go theme={null}
    &TextField{
        Name:                "id",
        System:              true,
        PrimaryKey:          true,
        Required:            true,
        Min:                 15,
        Max:                 15,
        Pattern:             "^[a-z0-9]+$",
        AutogeneratePattern: "[a-z0-9]{15}",
    }
    ```
  </Tab>

  <Tab title="email">
    User's email address (unique).

    ```go theme={null}
    &EmailField{
        Name:     "email",
        System:   true,
        Required: true,
    }
    ```

    <Note>A unique index is automatically created on the email field.</Note>
  </Tab>

  <Tab title="password">
    Hashed password (hidden from API responses).

    ```go theme={null}
    &PasswordField{
        Name:     "password",
        System:   true,
        Hidden:   true,
        Required: true,
        Min:      8,
    }
    ```
  </Tab>

  <Tab title="emailVisibility">
    Controls whether the email is visible in API responses.

    ```go theme={null}
    &BoolField{
        Name:   "emailVisibility",
        System: true,
    }
    ```
  </Tab>

  <Tab title="verified">
    Whether the user has verified their email.

    ```go theme={null}
    &BoolField{
        Name:   "verified",
        System: true,
    }
    ```
  </Tab>

  <Tab title="tokenKey">
    Unique key for invalidating user sessions.

    ```go theme={null}
    &TextField{
        Name:                "tokenKey",
        System:              true,
        Hidden:             true,
        Required:            true,
        AutogeneratePattern: "[a-zA-Z0-9]{50}",
    }
    ```

    <Note>Changing this value invalidates all existing auth tokens for the user.</Note>
  </Tab>
</Tabs>

## Authentication configuration

Auth collections have extensive configuration options:

### Password authentication

```go theme={null}
users.PasswordAuth.Enabled = true
users.PasswordAuth.IdentityFields = []string{"email"}
```

The `IdentityFields` specifies which fields can be used to identify users during login. You can add custom fields:

```go theme={null}
// Add username field
users.Fields.Add(&core.TextField{
    Name:     "username",
    Required: true,
    Pattern:  "^[a-zA-Z0-9_]+$",
})

// Allow login with email or username
users.PasswordAuth.IdentityFields = []string{"email", "username"}
```

<Note>
  Identity fields must have a unique index to be used for authentication.
</Note>

### OAuth2 configuration

Enable social login with OAuth2 providers:

```go theme={null}
users.OAuth2.Enabled = true
users.OAuth2.Providers = []core.OAuth2ProviderConfig{
    {
        Name:         "google",
        ClientId:     "your-client-id",
        ClientSecret: "your-client-secret",
    },
    {
        Name:         "github",
        ClientId:     "your-client-id",
        ClientSecret: "your-client-secret",
    },
}
```

#### Map OAuth2 fields to user fields

```go theme={null}
users.OAuth2.MappedFields.Name = "name"
users.OAuth2.MappedFields.Username = "username"
users.OAuth2.MappedFields.AvatarURL = "avatar"
```

### Multi-factor authentication (MFA)

```go theme={null}
users.MFA.Enabled = true
users.MFA.Duration = 1800 // 30 minutes
users.MFA.Rule = "" // Required for all users
```

You can make MFA conditional:

```go theme={null}
// Require MFA only for admin users
users.MFA.Rule = "role = 'admin'"
```

<Warning>
  MFA requires at least 2 authentication methods to be enabled (password + OAuth2, password + OTP, etc.).
</Warning>

### One-time password (OTP)

```go theme={null}
users.OTP.Enabled = true
users.OTP.Duration = 180 // 3 minutes
users.OTP.Length = 8
users.OTP.EmailTemplate = core.EmailTemplate{
    Subject: "Your login code",
    Body:    "Your code is: {OTP}",
}
```

### Token configuration

Configure various token lifetimes:

```go theme={null}
// Auth token (session)
users.AuthToken.Duration = 604800 // 7 days

// Password reset token
users.PasswordResetToken.Duration = 1800 // 30 minutes

// Email verification token
users.VerificationToken.Duration = 259200 // 3 days

// Email change confirmation token
users.EmailChangeToken.Duration = 1800 // 30 minutes

// File access token
users.FileToken.Duration = 180 // 3 minutes
```

## Complete example

Here's a comprehensive example of setting up a users collection:

```go theme={null}
package main

import (
    "log"
    "github.com/pocketbase/pocketbase"
    "github.com/pocketbase/pocketbase/core"
)

func main() {
    app := pocketbase.New()

    app.OnBootstrap().BindFunc(func(e *core.BootstrapEvent) error {
        // Create users collection
        users := core.NewAuthCollection("users")

        // Add custom fields
        users.Fields.Add(
            &core.TextField{
                Name:        "username",
                Required:    true,
                Min:         3,
                Max:         30,
                Pattern:     "^[a-zA-Z0-9_]+$",
                Presentable: true,
            },
            &core.TextField{
                Name: "name",
                Max:  100,
            },
            &core.TextField{
                Name: "bio",
                Max:  500,
            },
            &core.FileField{
                Name:      "avatar",
                MaxSelect: 1,
                MaxSize:   2097152, // 2MB
                MimeTypes: []string{"image/jpeg", "image/png"},
                Thumbs:    []string{"100x100", "300x300"},
            },
            &core.SelectField{
                Name:   "role",
                Values: []string{"user", "moderator", "admin"},
            },
        )

        // Add unique index on username
        users.AddIndex("idx_username", true, "`username`", "")

        // Configure password authentication
        users.PasswordAuth.Enabled = true
        users.PasswordAuth.IdentityFields = []string{"email", "username"}

        // Configure OAuth2
        users.OAuth2.Enabled = true
        users.OAuth2.MappedFields.Name = "name"
        users.OAuth2.MappedFields.Username = "username"
        users.OAuth2.MappedFields.AvatarURL = "avatar"
        users.OAuth2.Providers = []core.OAuth2ProviderConfig{
            {
                Name:         "google",
                ClientId:     "your-google-client-id",
                ClientSecret: "your-google-client-secret",
            },
        }

        // Configure MFA (optional for admins)
        users.MFA.Enabled = true
        users.MFA.Duration = 1800
        users.MFA.Rule = "role = 'admin'"

        // Configure email verification
        users.VerificationTemplate.Subject = "Verify your email"
        users.VerificationTemplate.Body = "Click here to verify: {APP_URL}/_/#/auth/confirm-verification/{TOKEN}"

        // Set auth rule (additional constraints after authentication)
        users.AuthRule = core.String("") // Allow any verified user

        // Set API rules
        users.ListRule = core.String("@request.auth.id != ''")
        users.ViewRule = core.String("@request.auth.id != ''")
        users.CreateRule = core.String("")
        users.UpdateRule = core.String("@request.auth.id = id")
        users.DeleteRule = core.String("@request.auth.id = id")

        // Set manage rule (for admin operations)
        users.ManageRule = core.String("@request.auth.role = 'admin'")

        // Save the collection
        if err := e.App.Save(users); err != nil {
            return err
        }

        return e.Next()
    })

    if err := app.Start(); err != nil {
        log.Fatal(err)
    }
}
```

## Auth rule vs API rules

Auth collections have a special `AuthRule` in addition to the standard API rules:

<Tabs>
  <Tab title="AuthRule">
    Applied **after** successful authentication, before returning the auth token.

    ```go theme={null}
    // Only allow verified users to authenticate
    users.AuthRule = core.String("verified = true")

    // Only allow active users
    users.AuthRule = core.String("status = 'active'")

    // Disable authentication entirely
    users.AuthRule = nil
    ```
  </Tab>

  <Tab title="ManageRule">
    Gives admin-like permissions to bypass normal validation (change password without old one, directly set verified status, etc.).

    ```go theme={null}
    // Only admins can manage users
    users.ManageRule = core.String("@request.auth.role = 'admin'")
    ```
  </Tab>

  <Tab title="Standard rules">
    Control regular CRUD operations (same as base collections).

    ```go theme={null}
    users.CreateRule = core.String("")
    users.UpdateRule = core.String("@request.auth.id = id")
    users.DeleteRule = core.String("@request.auth.id = id")
    ```
  </Tab>
</Tabs>

## Email templates

Customize email templates for various authentication flows:

### Verification email

```go theme={null}
users.VerificationTemplate = core.EmailTemplate{
    Subject: "Verify your email for {APP_NAME}",
    Body: `
        <p>Hello,</p>
        <p>Click the link below to verify your email:</p>
        <p><a href="{APP_URL}/_/#/auth/confirm-verification/{TOKEN}">Verify Email</a></p>
    `,
}
```

### Password reset email

```go theme={null}
users.ResetPasswordTemplate = core.EmailTemplate{
    Subject: "Reset your password",
    Body: `
        <p>Hello,</p>
        <p>Click the link below to reset your password:</p>
        <p><a href="{APP_URL}/_/#/auth/confirm-password-reset/{TOKEN}">Reset Password</a></p>
        <p>If you didn't request this, you can ignore this email.</p>
    `,
}
```

### Email change confirmation

```go theme={null}
users.ConfirmEmailChangeTemplate = core.EmailTemplate{
    Subject: "Confirm your new email",
    Body: `
        <p>Hello,</p>
        <p>Click the link below to confirm your new email address:</p>
        <p><a href="{APP_URL}/_/#/auth/confirm-email-change/{TOKEN}">Confirm Email Change</a></p>
    `,
}
```

### Available placeholders

* `{APP_NAME}` - Your application name
* `{APP_URL}` - Your application URL
* `{TOKEN}` - The verification/reset token
* `{OTP}` - The one-time password (OTP emails only)

## Auth alerts

Notify users when they log in from a new device:

```go theme={null}
users.AuthAlert.Enabled = true
users.AuthAlert.EmailTemplate = core.EmailTemplate{
    Subject: "New login detected",
    Body: `
        <p>We detected a new login to your account.</p>
        <p>Time: {ACTION_TIME}</p>
        <p>IP: {ACTION_IP}</p>
        <p>If this wasn't you, please change your password immediately.</p>
    `,
}
```

## Working with auth records

Auth records work like regular records but with additional auth-specific methods:

```go theme={null}
// Create a new user
user := core.NewRecord(users)
user.Set("email", "user@example.com")
user.Set("password", "secure_password")
user.Set("username", "johndoe")

if err := app.Save(user); err != nil {
    return err
}

// Verify email
user.Set("verified", true)
app.Save(user)

// Check password
record, err := app.FindAuthRecordByEmail("users", "user@example.com")
if err != nil {
    return err
}

valid := record.ValidatePassword("password_to_check")
```

## Best practices

<Tabs>
  <Tab title="Security">
    * Always use HTTPS in production
    * Set appropriate token durations
    * Enable email verification for sensitive apps
    * Use MFA for admin accounts
    * Implement rate limiting on auth endpoints
  </Tab>

  <Tab title="User experience">
    * Customize email templates with your branding
    * Provide clear error messages
    * Allow username as an alternative to email
    * Enable OAuth2 for easier registration
  </Tab>

  <Tab title="Data management">
    * Add custom fields for user profiles
    * Use relations to link users to their content
    * Consider separate collections for different user types
    * Implement soft deletes if needed
  </Tab>
</Tabs>

## Next steps

<CardGroup cols={2}>
  <Card title="Base collections" icon="database" href="/collections/base-collections">
    Learn about standard collections
  </Card>

  <Card title="Fields reference" icon="list" href="/collections/fields">
    Explore all field types
  </Card>

  <Card title="Authentication" icon="key" href="/auth/overview">
    Implement auth in your app
  </Card>

  <Card title="API rules" icon="shield" href="/concepts/api-rules">
    Secure your collections
  </Card>
</CardGroup>
