services

package
v0.7.43 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 10 Imported by: 2 modules, 2 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package services provides reusable service implementations for user management and authentication. These services are designed to be backend-agnostic and can be used with different storage providers (filesystem, GORM, Google Datastore).

Architecture

The package follows a layered architecture:

  • UsersService interface: defines the contract for user operations
  • BaseUsersService: provides shared logic (caching, common operations)
  • UserStorageProvider: abstracts raw storage operations
  • Backend implementations (fs, gorm, gae): concrete storage providers

Usage

Applications should use one of the concrete backend implementations:

// FileSystem backend (for development/testing)
userService := fs.NewUsersService("/path/to/storage")

// GORM backend (for PostgreSQL/MySQL)
userService := gorm.NewUsersService(db)

// GAE Datastore backend (for Google Cloud)
userService := gae.NewUsersService(client, "namespace")

Caching

All implementations include optional in-memory caching via BaseUsersService. Enable it by calling InitializeCache() after creation.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUserIDRequired = &UserError{Message: "user ID is required"}
	ErrUserNotFound   = &UserError{Message: "user not found"}
)

Error types

Functions

This section is empty.

Types

type AuthService deprecated

type AuthService struct {
	UserStore     accounts.UserStore
	IdentityStore accounts.IdentityStore
	ChannelStore  accounts.ChannelStore
	TokenStore    localauth.VerificationTokenStore
	UsernameStore accounts.UsernameStore // Optional - for username uniqueness
	// contains filtered or unexported fields
}

AuthService orchestrates authentication by coordinating oneauth stores.

Deprecated: AuthService is a thin wrapper around oneauth. For new code, use oneauth directly with federatedauth.NewEnsureAuthUserFunc and the helper functions. This wrapper is maintained for backwards compatibility.

Migration Guide

Instead of:

authService := services.NewAuthService("/path")
user, _ := authService.EnsureAuthUser("oauth", "google", token, userInfo)

Use oneauth directly:

config := federatedauth.EnsureAuthUserConfig{
    UserStore:     gorm.NewUserStore(db),
    IdentityStore: gorm.NewIdentityStore(db),
    ChannelStore:  gorm.NewChannelStore(db),
    UsernameStore: gorm.NewUsernameStore(db), // Optional
}
ensureUser := federatedauth.NewEnsureAuthUserFunc(config)
user, _ := ensureUser("oauth", "google", token, userInfo)

Integration with UsersService

AuthService manages the auth-level user (accounts.User), while UsersService manages the application-level user profile (goapplib.v1.User). After successful authentication, use UsersService.EnsureUser to sync the profile:

user, err := authService.EnsureAuthUser("oauth", "google", token, userInfo)
profile, err := userService.EnsureUser(ctx, user.Id(), name, email, imageUrl)

func NewAuthService deprecated

func NewAuthService(storagePath string) *AuthService

NewAuthService creates a new AuthService with file-based stores.

Deprecated: Use oneauth stores directly. See AuthService documentation.

func NewAuthServiceWithAllStores

func NewAuthServiceWithAllStores(userStore accounts.UserStore, identityStore accounts.IdentityStore, channelStore accounts.ChannelStore, tokenStore localauth.VerificationTokenStore, usernameStore accounts.UsernameStore) *AuthService

NewAuthServiceWithAllStores creates a new AuthService with all stores including UsernameStore.

func NewAuthServiceWithStores deprecated

func NewAuthServiceWithStores(userStore accounts.UserStore, identityStore accounts.IdentityStore, channelStore accounts.ChannelStore, tokenStore localauth.VerificationTokenStore) *AuthService

NewAuthServiceWithStores creates a new AuthService with custom stores.

Deprecated: Use oneauth stores directly. See AuthService documentation.

func (*AuthService) CreateLocalUser

func (s *AuthService) CreateLocalUser(creds *localauth.Credentials) (accounts.User, error)

CreateLocalUser creates a new user with local authentication. Pass-through to localauth.NewCreateUserFunc.

func (*AuthService) CreateUser

Implement accounts.UserStore interface.

func (*AuthService) EnsureAuthUser

func (s *AuthService) EnsureAuthUser(authtype, provider string, token *oauth2.Token, userInfo map[string]any) (accounts.User, error)

EnsureAuthUser handles user creation/lookup for both OAuth and local authentication. Pass-through to federatedauth.NewEnsureAuthUserFunc with channel linking support.

func (*AuthService) GetChannel

Implement accounts.ChannelStore interface.

func (*AuthService) GetIdentity

Implement accounts.IdentityStore interface.

func (*AuthService) GetUserById

func (*AuthService) SaveChannel

func (*AuthService) SaveIdentity

func (*AuthService) SaveUser

func (*AuthService) UpdatePassword

func (s *AuthService) UpdatePassword(email, newPassword string) error

UpdatePassword updates the password for a user identified by email. Pass-through to localauth.NewUpdatePasswordFunc.

func (*AuthService) ValidateLocalCredentials

func (s *AuthService) ValidateLocalCredentials(username, password, usernameType string) (accounts.User, error)

ValidateLocalCredentials validates username/password and returns the user. Pass-through to localauth.NewCredentialsValidator.

func (*AuthService) ValidateLocalCredentialsWithUsername

func (s *AuthService) ValidateLocalCredentialsWithUsername(username, password, usernameType string) (accounts.User, error)

ValidateLocalCredentialsWithUsername validates credentials allowing username-based login. Pass-through to localauth.NewCredentialsValidatorWithUsername.

func (*AuthService) VerifyEmailByToken

func (s *AuthService) VerifyEmailByToken(token string) error

VerifyEmailByToken verifies an email using a verification token. Pass-through to localauth.NewVerifyEmailFunc.

type BaseUsersService

type BaseUsersService struct {
	Self            UsersService        // The actual implementation
	StorageProvider UserStorageProvider // Set by concrete implementations

	// Optional in-memory cache
	CacheEnabled bool
	UserCache    map[string]*v1.User
	CacheMu      sync.RWMutex
}

BaseUsersService provides shared logic for user services

func (*BaseUsersService) DeleteUser

DeleteUser removes a user

func (*BaseUsersService) EnsureUser

func (s *BaseUsersService) EnsureUser(ctx context.Context, userId string, name string, email string, imageUrl string) (*v1.User, error)

EnsureUser creates or updates a user profile

func (*BaseUsersService) GetUser

GetUser returns a specific user by ID

func (*BaseUsersService) GetUsers

GetUsers returns multiple users by ID

func (*BaseUsersService) InitializeCache

func (s *BaseUsersService) InitializeCache()

InitializeCache sets up the in-memory cache

func (*BaseUsersService) ListUsers

ListUsers returns all users with pagination

type UserBridge

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

UserBridge wraps a goapplib.v1.User to implement the oneauth accounts.User interface. This allows seamless integration between goapplib's User proto and oneauth's authentication system.

Usage

After authenticating with AuthService, create a UserBridge to pass to systems that expect a accounts.User:

user := &v1.User{Id: "123", Name: "John"}
bridge := services.NewUserBridge(user)
// bridge now implements accounts.User interface
fmt.Println(bridge.Id())       // "123"
fmt.Println(bridge.Profile())  // map[name:John ...]

accounts.User Interface

The accounts.User interface requires:

  • Id() string: returns the user's unique identifier
  • Profile() map[string]any: returns user profile data as a map

UserBridge satisfies this interface by extracting data from the wrapped goapplib.v1.User proto message.

func NewUserBridge

func NewUserBridge(user *v1.User) *UserBridge

NewUserBridge creates a UserBridge wrapping the given User proto.

func (*UserBridge) Id

func (u *UserBridge) Id() string

Id implements accounts.User interface. Returns the user's unique identifier.

func (*UserBridge) Profile

func (u *UserBridge) Profile() map[string]any

Profile implements accounts.User interface. Returns user profile data as a map, including name, email, image_url, description, and tags. The extras field is also included if present.

func (*UserBridge) User

func (u *UserBridge) User() *v1.User

User returns the underlying User proto. Useful when you need to access the full proto message.

type UserError

type UserError struct {
	Message string
}

func (*UserError) Error

func (e *UserError) Error() string

type UserStorageProvider

type UserStorageProvider interface {
	// Read operations
	LoadUser(ctx context.Context, id string) (*v1.User, error)
	ListAllUsers(ctx context.Context) ([]*v1.User, error)

	// Write operations
	SaveUser(ctx context.Context, id string, user *v1.User) error
	DeleteFromStorage(ctx context.Context, id string) error

	// Check if user exists
	UserExists(ctx context.Context, id string) bool
}

UserStorageProvider is implemented by concrete backends (fs, gorm, gae) to provide raw storage operations for users

type UsersService

type UsersService interface {
	// Create a new user profile
	CreateUser(context.Context, *v1.CreateUserRequest) (*v1.CreateUserResponse, error)
	// Batch get multiple users by ID
	GetUsers(context.Context, *v1.GetUsersRequest) (*v1.GetUsersResponse, error)
	// List users with pagination
	ListUsers(context.Context, *v1.ListUsersRequest) (*v1.ListUsersResponse, error)
	// Get a specific user by ID
	GetUser(context.Context, *v1.GetUserRequest) (*v1.GetUserResponse, error)
	// Delete a user
	DeleteUser(context.Context, *v1.DeleteUserRequest) (*v1.DeleteUserResponse, error)
	// Update a user profile
	UpdateUser(context.Context, *v1.UpdateUserRequest) (*v1.UpdateUserResponse, error)
	// EnsureUser creates or updates a user profile (used after auth)
	EnsureUser(ctx context.Context, userId string, name string, email string, imageUrl string) (*v1.User, error)
}

UsersService defines the interface for user management operations. Implementations should handle CRUD operations for user profiles, with support for caching and app-specific extensions via the Extras field.

Directories

Path Synopsis
backends
fs
Package fs provides a filesystem-based implementation of the UsersService.
Package fs provides a filesystem-based implementation of the UsersService.
gae
Package gae provides a Google Cloud Datastore session store for scs (alexedwards/scs/v2).
Package gae provides a Google Cloud Datastore session store for scs (alexedwards/scs/v2).
gorm
Package gorm provides a GORM-based implementation of the UsersService.
Package gorm provides a GORM-based implementation of the UsersService.

Jump to

Keyboard shortcuts

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