Skip to main content
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
You can have multiple auth collections in the same app to support different user types (customers, admins, vendors, etc.).

Creating an auth collection

Create an auth collection using the factory function:
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:
Primary key field (same as base collections).
&TextField{
    Name:                "id",
    System:              true,
    PrimaryKey:          true,
    Required:            true,
    Min:                 15,
    Max:                 15,
    Pattern:             "^[a-z0-9]+$",
    AutogeneratePattern: "[a-z0-9]{15}",
}

Authentication configuration

Auth collections have extensive configuration options:

Password authentication

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:
// 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"}
Identity fields must have a unique index to be used for authentication.

OAuth2 configuration

Enable social login with OAuth2 providers:
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

users.OAuth2.MappedFields.Name = "name"
users.OAuth2.MappedFields.Username = "username"
users.OAuth2.MappedFields.AvatarURL = "avatar"

Multi-factor authentication (MFA)

users.MFA.Enabled = true
users.MFA.Duration = 1800 // 30 minutes
users.MFA.Rule = "" // Required for all users
You can make MFA conditional:
// Require MFA only for admin users
users.MFA.Rule = "role = 'admin'"
MFA requires at least 2 authentication methods to be enabled (password + OAuth2, password + OTP, etc.).

One-time password (OTP)

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:
// 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:
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:
Applied after successful authentication, before returning the auth token.
// 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

Email templates

Customize email templates for various authentication flows:

Verification email

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

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

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:
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:
// 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

  • 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

Next steps

Base collections

Learn about standard collections

Fields reference

Explore all field types

Authentication

Implement auth in your app

API rules

Secure your collections