accounts

package
v0.1.0-alpha.39 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: GPL-3.0 Imports: 20 Imported by: 0 modules, 0 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 accounts owns authenticated user identities and opaque browser sessions. It borrows MagicHandy's process-owned SQLite handle; it never owns a second database or closes the shared handle.

Index

Constants

View Source
const (
	// ControlRelationshipSelf is the authenticated account itself.
	ControlRelationshipSelf = "self"
	// ControlRelationshipLinked is an explicitly active directional link.
	ControlRelationshipLinked = "linked"
)
View Source
const (
	// MinPasswordCharacters is the minimum accepted Unicode password length.
	MinPasswordCharacters = 8
	// MaxPasswordBytes bounds password-hashing work and request memory.
	MaxPasswordBytes = 1024
)
View Source
const (
	// MaxProfileImageBytes bounds an accepted browser-normalized JPEG.
	MaxProfileImageBytes = 2 << 20
	// MaxProfileImageEdge is the largest decoded dimension accepted by the API.
	MaxProfileImageEdge = 1024
)
View Source
const (
	// RoleAdmin can manage accounts and use the shared application.
	RoleAdmin = "admin"
	// RoleOperator can use the shared application but cannot manage accounts.
	RoleOperator = "operator"

	// DefaultSessionLifetime is the absolute server-side session limit.
	DefaultSessionLifetime = 12 * time.Hour
	// DefaultSessionIdleLimit expires a session not seen by the server.
	DefaultSessionIdleLimit = 30 * time.Minute
	// MaxSessionsPerAccount bounds persistent sessions for one account.
	MaxSessionsPerAccount = 20
)

Variables

View Source
var (
	// ErrProfileImageInvalid reports a payload that is not a bounded JPEG.
	ErrProfileImageInvalid = errors.New("profile image is not a supported JPEG")
	// ErrProfileImageNotFound reports an account with no stored image.
	ErrProfileImageNotFound = errors.New("profile image has not been set")
)
View Source
var (
	// ErrAlreadyInitialized prevents a second first-account bootstrap.
	ErrAlreadyInitialized = errors.New("user accounts are already initialized")
	// ErrInvalidCredentials deliberately covers every failed login reason.
	ErrInvalidCredentials = errors.New("invalid username or password")
	// ErrInvalidRole marks an unsupported account role.
	ErrInvalidRole = errors.New("invalid account role")
	// ErrInvalidSession deliberately covers missing, expired, and revoked tokens.
	ErrInvalidSession = errors.New("invalid or expired session")
	// ErrInvalidUsername marks a username syntax or length failure.
	ErrInvalidUsername = errors.New("invalid username")
	// ErrLastAdmin prevents loss of the final enabled administrator.
	ErrLastAdmin = errors.New("the last enabled administrator cannot be disabled")
	// ErrNotFound reports a requested account ID that does not exist.
	ErrNotFound = errors.New("user account not found")
	// ErrUsernameTaken reports a case-insensitive username collision.
	ErrUsernameTaken = errors.New("username is already in use")
)
View Source
var ErrControlIdentityNotAllowed = errors.New("control identity is not available to this account")

ErrControlIdentityNotAllowed rejects a target that is neither self nor an enabled account connected by an active backend-owned link.

View Source
var ErrInvalidPassword = errors.New("invalid password")

ErrInvalidPassword marks a password-policy failure without exposing a hash.

Functions

func HashPassword

func HashPassword(password string) (string, error)

HashPassword returns a self-describing Argon2id PHC string. The parameters are stored with each hash so they can be raised later without invalidating existing accounts.

func ValidatePassword

func ValidatePassword(password string) error

ValidatePassword applies only safety bounds. MagicHandy deliberately avoids composition rules that encourage predictable substitutions; callers should use a long, unique passphrase.

func VerifyPassword

func VerifyPassword(password, encoded string) (bool, error)

VerifyPassword compares password to a bounded Argon2id PHC string. Database values are treated as untrusted: excessive cost values are rejected before they can consume attacker-controlled memory or CPU.

Types

type Account

type Account struct {
	ID               string `json:"id"`
	Username         string `json:"username"`
	Role             string `json:"role"`
	Disabled         bool   `json:"disabled"`
	HasProfileImage  bool   `json:"has_profile_image"`
	ProfileUpdatedAt string `json:"profile_updated_at,omitempty"`
	LastLoginAt      string `json:"last_login_at,omitempty"`
	CreatedAt        string `json:"created_at"`
	UpdatedAt        string `json:"updated_at"`
}

Account is the non-secret public view of a user identity.

type ControlIdentity

type ControlIdentity struct {
	Account      Account `json:"account"`
	Relationship string  `json:"relationship"`
	Label        string  `json:"label"`
	Selected     bool    `json:"selected"`
}

ControlIdentity is an account this login session may represent in the shell's control-context selector. It never changes authentication role or grants controller ownership.

type Session

type Session struct {
	Account          Account   `json:"account"`
	ControlAccountID string    `json:"control_account_id"`
	ExpiresAt        time.Time `json:"expires_at"`
}

Session is an authenticated account plus the server-enforced absolute expiration. The raw bearer token is returned only by NewSession.

type Store

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

Store provides account operations over the process-owned datastore.

func New

func New(db *appstore.DB) (*Store, error)

New creates the account domain over an existing process-owned datastore.

func (*Store) Authenticate

func (s *Store) Authenticate(ctx context.Context, username, password string) (Account, error)

Authenticate performs the same Argon2id work for missing, disabled, and existing accounts and returns one generic credential error.

func (*Store) BootstrapAdmin

func (s *Store) BootstrapAdmin(ctx context.Context, username, password string) (Account, error)

BootstrapAdmin creates the first account. The emptiness check and insert use the shared serialized writer so simultaneous bootstrap requests cannot both succeed.

func (*Store) CanViewProfile

func (s *Store) CanViewProfile(ctx context.Context, viewer Account, targetAccountID string) (bool, error)

CanViewProfile reports whether viewer may fetch target's profile image.

func (*Store) ControlIdentities

func (s *Store) ControlIdentities(ctx context.Context, ownerID, selectedID string) ([]ControlIdentity, error)

ControlIdentities returns the backend-authorized choices for one signed-in account. The authenticated account is always first and labeled Self.

func (*Store) Create

func (s *Store) Create(ctx context.Context, username, password, role string) (Account, error)

Create adds an account after the HTTP edge has authorized an administrator.

func (*Store) DeleteProfileImage

func (s *Store) DeleteProfileImage(ctx context.Context, id string) (Account, error)

DeleteProfileImage returns the account to its generated monogram.

func (*Store) EnabledCount

func (s *Store) EnabledCount(ctx context.Context) (int, error)

EnabledCount returns the number of accounts allowed to authenticate.

func (*Store) Initialized

func (s *Store) Initialized(ctx context.Context) (bool, error)

Initialized reports whether any account exists, including disabled rows.

func (*Store) List

func (s *Store) List(ctx context.Context) ([]Account, error)

List returns public account metadata. Password hashes never leave this package, even to another backend package.

func (*Store) NewSession

func (s *Store) NewSession(ctx context.Context, accountID string) (string, Session, error)

NewSession creates a high-entropy bearer token while storing only its SHA-256 digest. A database disclosure therefore does not reveal live tokens.

func (*Store) OpenProfileImage

func (s *Store) OpenProfileImage(ctx context.Context, id string) (*os.File, error)

OpenProfileImage opens a stable image file while holding the read lock only for lookup/open. The returned descriptor remains valid after the lock exits.

func (*Store) ProfileImageDir

func (s *Store) ProfileImageDir() string

ProfileImageDir is app-owned and removed with the rest of MagicHandy data.

func (*Store) ResolveSession

func (s *Store) ResolveSession(ctx context.Context, token string) (Session, error)

ResolveSession authenticates a token and advances its idle timestamp at most once per minute, avoiding a SQLite write for every UI polling request.

func (*Store) RevokeSession

func (s *Store) RevokeSession(ctx context.Context, token string) error

RevokeSession invalidates one opaque bearer token. It is idempotent.

func (*Store) SaveProfileImage

func (s *Store) SaveProfileImage(ctx context.Context, id string, data []byte) (Account, error)

SaveProfileImage validates and atomically replaces one account image.

func (*Store) SetControlIdentity

func (s *Store) SetControlIdentity(ctx context.Context, token, targetAccountID string) error

SetControlIdentity changes only this opaque login session's attribution context. It cannot change authentication role or controller ownership.

func (*Store) SetDisabled

func (s *Store) SetDisabled(ctx context.Context, accountID string, disabled bool) error

SetDisabled changes login eligibility and revokes sessions when disabling. At least one enabled administrator is always retained.

func (*Store) SetPassword

func (s *Store) SetPassword(ctx context.Context, accountID, password string) error

SetPassword replaces a hash and transactionally invalidates every existing session for the account.

Jump to

Keyboard shortcuts

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