session

package
v2.11.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 13 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 session owns the Issue and Validate primitives for opaque session tokens. Only the sha256 hash is persisted; the raw token is returned exactly once.

Index

Constants

View Source
const (
	// OverflowEvictOldest revokes the user's oldest sessions to make room.
	OverflowEvictOldest = "evict_oldest"
	// OverflowReject refuses the new session.
	OverflowReject = "reject"
)

Overflow values for Cap.Mode.

Variables

This section is empty.

Functions

func DeviceLabel

func DeviceLabel(ua string) string

DeviceLabel derives a short "Browser on OS" label from a User-Agent string. It returns "Unknown device" when nothing recognizable is present.

func IPPrefix

func IPPrefix(ip string) string

IPPrefix masks an address to /24 (IPv4) or /48 (IPv6) so a session list can show where a session is from without exposing the full address. Returns "" when ip does not parse.

func WithoutLimits added in v2.10.0

func WithoutLimits(ctx context.Context) context.Context

WithoutLimits returns a context under which session issuance skips the concurrent session cap. It is for probe sessions that are revoked at once.

Types

type AccountGate added in v2.10.0

type AccountGate interface {
	CheckSignin(ctx context.Context, userID models.ULID) error
}

AccountGate vetoes issuing a session for a user, for example because the account is disabled or must change its password. It runs after the credential was verified, so its error may be specific.

type AuthAppender added in v2.11.0

type AuthAppender interface {
	AppendSessionAuthMethods(ctx context.Context, id models.ULID, methods []string, at time.Time) ([]string, time.Time, error)
}

AuthAppender is the storage capability Append needs; it is satisfied by theauth.SessionAuthStorage.

type Cap added in v2.10.0

type Cap struct {
	Max     int
	Mode    string
	Lister  SessionLister
	Revoker Revoker
}

Cap limits how many full sessions one user may hold at once. The zero value disables the cap. Enforcement is best effort under concurrency: two simultaneous sign-ins may both pass the check.

type CredentialChecker

type CredentialChecker interface {
	CheckCredential(ctx context.Context, credentialID string) error
}

CredentialChecker reports whether the upstream credential a session is tied to is still valid. It returns models.ErrCredentialRevoked when it is not; any other error is treated as transient and fails the validation closed.

type IssueOptions

type IssueOptions struct {
	UserAgent    string
	IP           string
	CredentialID string
	// TTL overrides the service default when positive.
	TTL time.Duration
}

IssueOptions customizes Service.IssueWith.

type Policy

type Policy struct {
	IdleTimeout   time.Duration
	TouchInterval time.Duration
	Toucher       Toucher
	Revoker       Revoker
	Credentials   CredentialChecker
}

Policy configures idle timeout, last-seen throttling and credential re-checks. The zero value keeps the original absolute-TTL-only behavior.

type Revoker

type Revoker interface {
	RevokeSession(ctx context.Context, id models.ULID) error
}

Revoker revokes one session by id.

type Service

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

Service holds the dependencies needed to issue and validate sessions. Constructed once in theauth.New and reused for the lifetime of the process.

func New

func New(storage Storage, ttl time.Duration) *Service

New constructs a session Service.

func (*Service) Append added in v2.11.0

func (s *Service) Append(ctx context.Context, id models.ULID, at time.Time, methods ...string) ([]string, time.Time, error)

Append atomically adds methods to the session's record and advances its AuthTime to at (now when zero). It returns the resulting record. When the storage lacks the capability it is a no-op returning nil, so third party storages keep working without a record.

func (*Service) CapRoom added in v2.10.0

func (s *Service) CapRoom(ctx context.Context, userID, exclude models.ULID) error

CapRoom returns CodeSessionLimit when the cap is in reject mode and userID is already at it, without revoking anything. Callers use it before spending a one-time credential (a recovery code) so a refusal does not burn it.

func (*Service) Check

func (s *Service) Check(ctx context.Context, token string) (*models.Session, *models.User, error)

Check is Validate without the last-seen update, for liveness probes such as long-lived stream re-checks that must not count as user activity.

func (*Service) CheckAccount added in v2.10.0

func (s *Service) CheckAccount(ctx context.Context, userID models.ULID) error

CheckAccount runs the account gate for userID. It returns nil when no gate is set.

func (*Service) EnforceCap added in v2.10.0

func (s *Service) EnforceCap(ctx context.Context, userID, exclude models.ULID) error

EnforceCap makes room for one more full session of userID, ignoring the session exclude (use the zero ULID for none). With OverflowEvictOldest it revokes the oldest sessions; with OverflowReject it returns CodeSessionLimit.

func (*Service) Issue

func (s *Service) Issue(ctx context.Context, user models.User, userAgent, ip string) (token string, sess models.Session, err error)

Issue mints a fresh opaque token, stores its sha256 hash with a new Session row, and returns the raw token. The raw token is what the caller puts in a cookie / sends to the user; the hash is what's persisted.

func (*Service) IssueWith

func (s *Service) IssueWith(ctx context.Context, user models.User, opts IssueOptions) (token string, sess models.Session, err error)

IssueWith is Issue with per-session options.

func (*Service) SetAccountGate added in v2.10.0

func (s *Service) SetAccountGate(g AccountGate)

SetAccountGate installs the gate consulted before every full session is issued. Call before the Service is shared.

func (*Service) SetCap added in v2.10.0

func (s *Service) SetCap(c Cap)

SetCap installs the concurrent session cap. Call before the Service is shared.

func (*Service) SetPolicy

func (s *Service) SetPolicy(p Policy)

SetPolicy installs the policy. Call before the Service is shared.

func (*Service) Validate

func (s *Service) Validate(ctx context.Context, token string) (*models.Session, *models.User, error)

Validate looks up a session by the hash of the supplied token, verifies it is not expired or revoked, and returns the session and its user. Returns models.ErrInvalidToken for missing/unknown tokens and models.ErrSessionExpired for expired or revoked sessions.

type SessionLister added in v2.10.0

type SessionLister interface {
	ListUserSessions(ctx context.Context, userID models.ULID) ([]models.Session, error)
}

SessionLister lists a user's live sessions, newest first.

type SessionUserStorage added in v2.8.0

type SessionUserStorage interface {
	SessionAndUserByTokenHash(ctx context.Context, hash []byte) (*models.Session, *models.User, error)
}

SessionUserStorage is an optional Storage extension that returns a session and its user together. Adapters that can do it in one round trip (a join) implement it; validate then skips the separate user lookup.

type Storage

type Storage interface {
	CreateSession(ctx context.Context, s models.Session) (models.Session, error)
	SessionByTokenHash(ctx context.Context, hash []byte) (*models.Session, error)
	UserByID(ctx context.Context, id models.ULID) (*models.User, error)
}

Storage is the minimal persistence subset this package needs. Declared here (not imported from root) so that internal/session does not import github.com/glincker/theauth-go/v2, which would form an import cycle with the root constructor.

Any type satisfying these three methods (notably the root theauth.Storage interface) is a valid argument to New. Duck-typed against the larger root contract by design.

type Toucher

type Toucher interface {
	TouchSession(ctx context.Context, id models.ULID, at time.Time) error
}

Toucher persists a session's last-seen time.

Jump to

Keyboard shortcuts

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