auth

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package auth resolves application users by a text subject, independently of HTTP. Jobs, MCP tools and feature packages use it to look a user up and to clean up the data attached to a user that is gone.

Subjects

A subject is the stable text reference of a user: 1 to 255 bytes of printable ASCII without spaces. It is case sensitive and compared bytewise. ValidateSubject checks the rule; ErrInvalidSubject reports a violation. NewUserDriver converts between a typed identifier and its subject: strings are used as is, integers become decimal digits, and types implementing encoding.TextMarshaler and (through a pointer) encoding.TextUnmarshaler use their text form. Parsing is canonical: a subject that does not render back to itself, such as "007" or "+1" for an integer, is an invalid subject.

Looking up users

A UserDriver finds one UserRecord by subject. Wrap it with NewUserProvider and call UserProvider.Find. A missing user is ErrUserNotFound; a user that exists but may not act is ErrUserDisabled. Only ErrUserNotFound proves a user is deleted, so cleanup code must never treat any other error as deletion.

Forgetting users

Packages that store data about users register a hook with UserProvider.OnForget. UserProvider.Forget runs the hooks in registration order in the caller's context, so hooks join the caller's database transaction. The first error stops the run and is returned. When every hook succeeded, Forget emits UserForgotten on the bus given to UserProviderBuilder.Events; without a bus nothing is emitted.

Events

UserForgotten ("auth.user.forgotten") carries only the subject. It means the forget hooks completed, not that a surrounding transaction committed.

Drivers and tests

arkoren.dev/core/auth/memoryauth is an in-memory driver and arkoren.dev/core/auth/authtest is the conformance suite every driver runs.

Example:

driver, err := auth.NewUserDriver(loadUser, func(user User) int64 { return user.ID })
if err != nil {
	return err
}
users, err := auth.NewUserProvider(driver, func(users *auth.UserProviderBuilder) {
	users.Events(app.Events())
})
if err != nil {
	return err
}
record, err := users.Find(ctx, "42")

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrUserNotFound reports that no user has the subject. Only this error
	// proves a user is deleted: code that removes data of deleted users must act
	// on it and on nothing else, so a disabled user's data is never removed.
	// A subject that cannot be parsed is [ErrInvalidSubject], never this error.
	//
	// Example:
	//
	//	if _, err := users.Find(ctx, subject); errors.Is(err, auth.ErrUserNotFound) {
	//		return users.Forget(ctx, subject)
	//	}
	ErrUserNotFound = errors.New("auth: user not found")

	// ErrUserDisabled reports that the user exists but may not act, for example
	// a suspended account. The user is not deleted: keep its data.
	//
	// Example:
	//
	//	if _, err := users.Find(ctx, subject); errors.Is(err, auth.ErrUserDisabled) {
	//		return nil // Skip the user, keep the data.
	//	}
	ErrUserDisabled = errors.New("auth: user disabled")
)
View Source
var ErrInvalidSubject = errors.New("auth: invalid subject")

ErrInvalidSubject reports a subject that is not 1 to 255 printable ASCII bytes without spaces, a subject that does not parse as the driver's identifier type or does not render back to itself, and an identifier type that is not a string, an integer or a text-marshaling type.

Example:

if _, err := users.Find(ctx, subject); errors.Is(err, auth.ErrInvalidSubject) {
	return err
}
View Source
var UserForgotten = event.NewTopic[UserForgottenEvent]("auth.user.forgotten")

UserForgotten is emitted by UserProvider.Forget with event.Bus.Emit after every hook registered with UserProvider.OnForget succeeded, and never when a hook failed. It means "forget hooks completed": the delete may still roll back with the caller's transaction. A listener whose effect needs the delete to be committed wraps that effect in Database.AfterCommit with the event context, which carries the transaction. Emit logs listener errors instead of returning them, so listeners cannot change the outcome of Forget.

Example:

unsubscribe, err := events.Listen(auth.UserForgotten, func(ctx context.Context, forgotten auth.UserForgottenEvent) error {
	return search.Remove(ctx, forgotten.Subject)
})
if err != nil {
	return err
}
defer unsubscribe()

Functions

func ValidateSubject

func ValidateSubject(subject string) error

ValidateSubject returns nil when subject is 1 to 255 bytes of printable ASCII without spaces, the OpenID Connect "sub" rule minus space because some database collations ignore trailing spaces. Store subjects in a column compared bytewise. Otherwise it returns an error wrapping ErrInvalidSubject.

Example:

if err := auth.ValidateSubject("usr_9f1c"); err != nil {
	return err
}
Example
package main

import (
	"errors"
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	fmt.Println(auth.ValidateSubject("usr_9f1c"))
	fmt.Println(errors.Is(auth.ValidateSubject("has space"), auth.ErrInvalidSubject))
}
Output:
<nil>
true

Types

type TypedUserDriver

type TypedUserDriver[K comparable, U any] struct {
	// contains filtered or unexported fields
}

TypedUserDriver is a UserDriver that adapts an application's typed loader. It converts subjects to the identifier type K, loads the user U, and builds the UserRecord from it. Create it with NewUserDriver.

Example:

driver, err := auth.NewUserDriver(loadUser, func(user User) int64 { return user.ID })
subject, err := driver.Subject(User{ID: 42}) // "42"
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	driver := exampleDriver()

	record, err := driver.Find(context.Background(), "1")

	fmt.Println(record.Value.(exampleUser).Role, err)
}
Output:
admin <nil>

func NewUserDriver

func NewUserDriver[K comparable, U any](
	load func(context.Context, K) (U, error),
	id func(U) K,
	configure ...UserDriverBuilderFunc[U],
) (*TypedUserDriver[K, U], error)

NewUserDriver returns a TypedUserDriver that loads users with load and identifies them with id. K must be a string kind, an integer kind, or a type implementing both encoding.TextMarshaler and (through its pointer) encoding.TextUnmarshaler, such as UUID, xid and ULID types; any other K fails with an error wrapping ErrInvalidSubject so the mistake surfaces at setup. It also fails for a nil load or id. Construction callbacks configure UserDriverBuilder.

load reports a deleted user with ErrUserNotFound (or an error wrapping it); returning a nil pointer with a nil error counts as not found too. Other loader errors pass through unchanged.

Example:

driver, err := auth.NewUserDriver(
	func(ctx context.Context, id int64) (User, error) { return store.User(ctx, id) },
	func(user User) int64 { return user.ID },
	func(driver *auth.UserDriverBuilder[User]) {
		driver.Disabled(func(user User) bool { return user.Suspended })
	},
)
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

func main() {
	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) { return exampleUser{ID: id}, nil },
		func(user exampleUser) int64 { return user.ID },
	)

	if err != nil {
		panic(err)
	}

	record, _ := driver.Find(context.Background(), "9")

	fmt.Println(record.Subject)
}
Output:
9

func (*TypedUserDriver[K, U]) Find

func (driver *TypedUserDriver[K, U]) Find(ctx context.Context, subject string) (UserRecord, error)

Find implements UserDriver. It parses subject canonically (an error wrapping ErrInvalidSubject otherwise, never ErrUserNotFound), calls the loader, and returns ErrUserNotFound for a nil pointer with a nil error and ErrUserDisabled when the Disabled function reports the user. The record's Value is the loaded U.

Example:

record, err := driver.Find(ctx, "42")
if err != nil {
	return err
}
user := record.Value.(User)
Example
package main

import (
	"context"
	"errors"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	_, err := exampleDriver().Find(context.Background(), "+1")

	fmt.Println(errors.Is(err, auth.ErrInvalidSubject))
}
Output:
true

func (*TypedUserDriver[K, U]) Subject

func (driver *TypedUserDriver[K, U]) Subject(user U) (string, error)

Subject returns the subject of user, derived from the identifier function. It returns an error wrapping ErrInvalidSubject when the identifier does not render to a valid subject, such as an empty string.

Example:

subject, err := driver.Subject(user)
if err != nil {
	return err
}
err = users.Forget(ctx, subject)
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	subject, err := exampleDriver().Subject(exampleUser{ID: 42})

	fmt.Println(subject, err)
}
Output:
42 <nil>

type UserDriver

type UserDriver interface {
	// Find returns the record of subject.
	//
	// Example:
	//
	//	record, err := driver.Find(ctx, "42")
	Find(ctx context.Context, subject string) (UserRecord, error)
}

UserDriver finds users by subject. Implementations must return an error wrapping ErrInvalidSubject for a subject that fails ValidateSubject, ErrUserNotFound for a missing user and ErrUserDisabled for a disabled one, with the record's Subject set to the argument. They must be safe for concurrent use. The conformance suite is arkoren.dev/core/auth/authtest.

Example:

type directory struct{}

func (directory) Find(ctx context.Context, subject string) (auth.UserRecord, error) {
	return auth.UserRecord{}, auth.ErrUserNotFound
}
Example
package main

import (
	"context"
	"errors"
	"fmt"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/auth/memoryauth"
)

func main() {
	var driver auth.UserDriver = memoryauth.New()

	_, err := driver.Find(context.Background(), "1")

	fmt.Println(errors.Is(err, auth.ErrUserNotFound))
}
Output:
true

type UserDriverBuilder

type UserDriverBuilder[U any] struct {
	// contains filtered or unexported fields
}

UserDriverBuilder configures NewUserDriver before publication. Callbacks run directly once, synchronously in order on one fresh draft; nil entries panic and expanded nil or empty slices supply no edits. Methods return the same draft. A nil function leaves the corresponding setting off.

Example:

driver, err := auth.NewUserDriver(loadUser, userID, func(driver *auth.UserDriverBuilder[User]) {
	driver.Version(func(user User) string { return user.PasswordVersion })
})
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

func main() {
	driver, _ := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) { return exampleUser{ID: id}, nil },
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Version(func(user exampleUser) string { return "v1" }).
				Claims(func(user exampleUser) map[string]any { return map[string]any{"id": user.ID} }).
				Disabled(func(user exampleUser) bool { return false })
		},
	)

	record, _ := driver.Find(context.Background(), "5")

	fmt.Println(record.Version, record.Claims["id"])
}
Output:
v1 5

func (*UserDriverBuilder[U]) Claims

func (builder *UserDriverBuilder[U]) Claims(claims func(U) map[string]any) *UserDriverBuilder[U]

Claims sets the function that derives UserRecord.Claims from a user. It replaces the previous value on the construction draft.

Example:

driver.Claims(func(user User) map[string]any { return map[string]any{"role": user.Role} })
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	record, _ := exampleDriver().Find(context.Background(), "1")

	fmt.Println(record.Claims)
}
Output:
map[role:admin]

func (*UserDriverBuilder[U]) Disabled

func (builder *UserDriverBuilder[U]) Disabled(disabled func(U) bool) *UserDriverBuilder[U]

Disabled sets the function that reports a user that exists but may not act; TypedUserDriver.Find then returns ErrUserDisabled. It replaces the previous value on the construction draft.

Example:

driver.Disabled(func(user User) bool { return user.SuspendedAt != nil })
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	_, err := exampleDriver().Find(context.Background(), "2")

	fmt.Println(err)
}
Output:
auth: user disabled

func (*UserDriverBuilder[U]) Version

func (builder *UserDriverBuilder[U]) Version(version func(U) string) *UserDriverBuilder[U]

Version sets the function that derives UserRecord.Version from a user. It replaces the previous value on the construction draft.

Example:

driver.Version(func(user User) string { return user.PasswordVersion })
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

func main() {
	driver, _ := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) { return exampleUser{ID: id}, nil },
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Version(func(user exampleUser) string { return fmt.Sprint("v", user.ID) })
		},
	)

	record, _ := driver.Find(context.Background(), "3")

	fmt.Println(record.Version)
}
Output:
v3

type UserDriverBuilderFunc

type UserDriverBuilderFunc[U any] = func(*UserDriverBuilder[U])

UserDriverBuilderFunc configures a UserDriverBuilder.

Example:

var policy auth.UserDriverBuilderFunc[User] = func(driver *auth.UserDriverBuilder[User]) {
	driver.Version(func(user User) string { return user.PasswordVersion })
}
driver, err := auth.NewUserDriver(loadUser, userID, policy)
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

func main() {
	policy := auth.UserDriverBuilderFunc[exampleUser](func(driver *auth.UserDriverBuilder[exampleUser]) {
		driver.Version(func(user exampleUser) string { return "v1" })
	})

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) { return exampleUser{ID: id}, nil },
		func(user exampleUser) int64 { return user.ID },
		policy,
	)

	fmt.Println(driver != nil, err)
}
Output:
true <nil>

type UserForgottenEvent

type UserForgottenEvent struct {
	// Subject is the subject passed to [UserProvider.Forget].
	Subject string
}

UserForgottenEvent reports that every forget hook of a user completed. It carries only the subject, never personal data.

Example:

unsubscribe, err := events.Listen(auth.UserForgotten, func(ctx context.Context, forgotten auth.UserForgottenEvent) error {
	logger.InfoContext(ctx, "user forgotten", "subject", forgotten.Subject)
	return nil
})
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth"
)

func main() {
	forgotten := auth.UserForgottenEvent{Subject: "42"}

	fmt.Println(auth.UserForgotten.Name(), forgotten.Subject)
}
Output:
auth.user.forgotten 42

type UserProvider

type UserProvider struct {
	// contains filtered or unexported fields
}

UserProvider looks users up through a UserDriver and coordinates cleanup when a user is forgotten. It is safe for concurrent use.

Example:

users, err := auth.NewUserProvider(driver)
if err != nil {
	return err
}
record, err := users.Find(ctx, "42")

func NewUserProvider

func NewUserProvider(driver UserDriver, configure ...UserProviderBuilderFunc) (*UserProvider, error)

NewUserProvider returns a provider over driver. It returns an error when driver is nil. Construction callbacks configure UserProviderBuilder.

Example:

users, err := auth.NewUserProvider(driver, func(users *auth.UserProviderBuilder) {
	users.Events(app.Events())
})
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/event"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	users, err := auth.NewUserProvider(exampleDriver(), func(users *auth.UserProviderBuilder) {
		users.Events(event.New())
	})

	if err != nil {
		panic(err)
	}

	record, err := users.Find(context.Background(), "1")

	fmt.Println(record.Subject, record.Claims["role"], err)
}
Output:
1 admin <nil>

func (*UserProvider) Find

func (provider *UserProvider) Find(ctx context.Context, subject string) (UserRecord, error)

Find returns the record of subject from the driver. Errors are the driver's: see UserDriver for ErrInvalidSubject, ErrUserNotFound and ErrUserDisabled.

Example:

record, err := users.Find(ctx, subject)
if errors.Is(err, auth.ErrUserNotFound) {
	return nil // The user was deleted.
}
Example
package main

import (
	"context"
	"errors"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	users, _ := auth.NewUserProvider(exampleDriver())

	_, err := users.Find(context.Background(), "2")
	fmt.Println(errors.Is(err, auth.ErrUserDisabled))

	_, err = users.Find(context.Background(), "3")
	fmt.Println(errors.Is(err, auth.ErrUserNotFound))
}
Output:
true
true

func (*UserProvider) Forget

func (provider *UserProvider) Forget(ctx context.Context, subject string) error

Forget removes the data of a user by running every hook registered with UserProvider.OnForget synchronously in ctx, in registration order, so the hooks join a transaction carried by ctx. The first hook error stops the run and is returned unchanged; hook panics propagate. It returns an error wrapping ErrInvalidSubject without running hooks for an invalid subject. After every hook succeeded it emits UserForgotten on the configured bus, and never after a failure. Forget does not look the user up.

Example:

err := db.WithTransaction(ctx, func(ctx context.Context) error {
	if err := removeAccount(ctx, id); err != nil {
		return err
	}
	return users.Forget(ctx, subject)
})
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/event"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	events := event.New()
	users, _ := auth.NewUserProvider(exampleDriver(), func(users *auth.UserProviderBuilder) {
		users.Events(events)
	})

	_, _ = events.Listen(auth.UserForgotten, func(_ context.Context, forgotten auth.UserForgottenEvent) error {
		fmt.Println("forgotten:", forgotten.Subject)

		return nil
	})

	fmt.Println(users.Forget(context.Background(), "1"))
}
Output:
forgotten: 1
<nil>

func (*UserProvider) OnForget

func (provider *UserProvider) OnForget(hook func(ctx context.Context, subject string) error)

OnForget registers hook to delete the data a package keeps about a user. Hooks run in registration order by UserProvider.Forget. Deletes should be idempotent, so there are no names and no duplicate check. It is safe to call concurrently with Forget; a Forget already running uses the hooks registered before it started. It panics when hook is nil.

Example:

users.OnForget(func(ctx context.Context, subject string) error {
	return subscriptions.DeleteBySubject(ctx, subject)
})
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	users, _ := auth.NewUserProvider(exampleDriver())

	users.OnForget(func(_ context.Context, subject string) error {
		fmt.Println("delete subscriptions of", subject)

		return nil
	})
	users.OnForget(func(_ context.Context, subject string) error {
		fmt.Println("delete sessions of", subject)

		return nil
	})

	_ = users.Forget(context.Background(), "1")
}
Output:
delete subscriptions of 1
delete sessions of 1

type UserProviderBuilder

type UserProviderBuilder struct {
	// contains filtered or unexported fields
}

UserProviderBuilder configures NewUserProvider before publication. Callbacks run directly once, synchronously in order on one fresh draft; nil entries panic and expanded nil or empty slices supply no edits. Methods return the same draft, and retaining it cannot change a published provider.

Example:

users, err := auth.NewUserProvider(driver, func(users *auth.UserProviderBuilder) {
	users.Events(app.Events())
})

func (*UserProviderBuilder) Events

func (builder *UserProviderBuilder) Events(events *event.Bus) *UserProviderBuilder

Events sets the bus that receives UserForgotten. Nil, the default, emits nothing. The bus is a shared service, not copied.

This setting replaces the previous value on the construction draft.

Example:

users, err := auth.NewUserProvider(driver, func(users *auth.UserProviderBuilder) {
	users.Events(event.New())
})
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/event"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	events := event.New()
	users, _ := auth.NewUserProvider(exampleDriver(), func(users *auth.UserProviderBuilder) {
		users.Events(events)
	})

	_, _ = events.Listen(auth.UserForgotten, func(context.Context, auth.UserForgottenEvent) error {
		fmt.Println("event received")

		return nil
	})

	_ = users.Forget(context.Background(), "1")
}
Output:
event received

type UserProviderBuilderFunc

type UserProviderBuilderFunc = func(*UserProviderBuilder)

UserProviderBuilderFunc configures a UserProviderBuilder.

Example:

var policy auth.UserProviderBuilderFunc = func(users *auth.UserProviderBuilder) {
	users.Events(events)
}
users, err := auth.NewUserProvider(driver, policy)
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/event"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	policy := auth.UserProviderBuilderFunc(func(users *auth.UserProviderBuilder) {
		users.Events(event.New())
	})

	users, err := auth.NewUserProvider(exampleDriver(), policy)

	fmt.Println(users != nil, err)
}
Output:
true <nil>

type UserRecord

type UserRecord struct {
	// Subject is the user's subject as passed to Find.
	Subject string

	// Version is an opaque string that changes whenever the user changes in a
	// way that should invalidate what was derived from it, such as a password
	// version. Empty means the driver has no version.
	Version string

	// Claims are application-defined attributes of the user. Treat the map as
	// read only: drivers may share it.
	Claims map[string]any

	// Value is the driver's own user value, such as the application's user
	// struct. Its type is whatever the driver documents; nil if none.
	Value any
}

UserRecord is what a UserDriver knows about one user.

Example:

record, err := users.Find(ctx, "42")
if err != nil {
	return err
}
fmt.Println(record.Subject, record.Version, record.Claims["role"])
Example
package main

import (
	"context"
	"fmt"

	"arkoren.dev/core/auth"
)

// exampleUser is the application user of the examples.
type exampleUser struct {
	ID        int64
	Role      string
	Suspended bool
}

// exampleDriver builds a typed driver over a fixed set of users.
func exampleDriver() *auth.TypedUserDriver[int64, exampleUser] {
	users := map[int64]exampleUser{1: {ID: 1, Role: "admin"}, 2: {ID: 2, Suspended: true}}

	driver, err := auth.NewUserDriver(
		func(_ context.Context, id int64) (exampleUser, error) {
			if user, ok := users[id]; ok {
				return user, nil
			}

			return exampleUser{}, auth.ErrUserNotFound
		},
		func(user exampleUser) int64 { return user.ID },
		func(driver *auth.UserDriverBuilder[exampleUser]) {
			driver.Claims(func(user exampleUser) map[string]any { return map[string]any{"role": user.Role} })
			driver.Disabled(func(user exampleUser) bool { return user.Suspended })
		},
	)

	if err != nil {
		panic(err)
	}

	return driver
}

func main() {
	record, _ := exampleDriver().Find(context.Background(), "1")

	fmt.Println(record.Subject, record.Claims["role"], record.Value.(exampleUser).ID)
}
Output:
1 admin 1

Directories

Path Synopsis
Package authtest provides a conformance suite for auth.UserDriver implementations, modeled on testing/fstest.
Package authtest provides a conformance suite for auth.UserDriver implementations, modeled on testing/fstest.
Package memoryauth provides an in-memory auth.UserDriver for tests, local development and single-process applications.
Package memoryauth provides an in-memory auth.UserDriver for tests, local development and single-process applications.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL