session

package
v0.0.14 Latest Latest
Warning

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

Go to latest
Published: Jan 4, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CodeSessionNotFound         = "SESSION_NOT_FOUND"
	CodeSessionExpired          = "SESSION_EXPIRED"
	CodeSessionCreationFailed   = "SESSION_CREATION_FAILED"
	CodeSessionRevocationFailed = "SESSION_REVOCATION_FAILED"
	CodeInvalidToken            = "INVALID_TOKEN"
	CodeMaxSessionsReached      = "MAX_SESSIONS_REACHED"
	CodeMissingAppContext       = "MISSING_APP_CONTEXT"
)

Variables

View Source
var (
	ErrSessionNotFound         = &errs.AuthsomeError{Code: CodeSessionNotFound}
	ErrSessionExpired          = &errs.AuthsomeError{Code: CodeSessionExpired}
	ErrSessionCreationFailed   = &errs.AuthsomeError{Code: CodeSessionCreationFailed}
	ErrSessionRevocationFailed = &errs.AuthsomeError{Code: CodeSessionRevocationFailed}
	ErrInvalidToken            = &errs.AuthsomeError{Code: CodeInvalidToken}
	ErrMaxSessionsReached      = &errs.AuthsomeError{Code: CodeMaxSessionsReached}
	ErrMissingAppContext       = &errs.AuthsomeError{Code: CodeMissingAppContext}
)

Functions

func ClearCookie added in v0.0.3

func ClearCookie(c forge.Context, config *CookieConfig) error

ClearCookie clears a session cookie by setting it to expire immediately

func InvalidToken

func InvalidToken() *errs.AuthsomeError

func MaxSessionsReached

func MaxSessionsReached(limit int) *errs.AuthsomeError

func MissingAppContext

func MissingAppContext() *errs.AuthsomeError

func ParseSameSite added in v0.0.2

func ParseSameSite(s string) http.SameSite

ParseSameSite converts a string to http.SameSite constant Returns Lax as default for invalid values

func SessionCreationFailed

func SessionCreationFailed(err error) *errs.AuthsomeError

func SessionExpired

func SessionExpired() *errs.AuthsomeError

func SessionNotFound

func SessionNotFound() *errs.AuthsomeError

func SessionRevocationFailed

func SessionRevocationFailed(err error) *errs.AuthsomeError

func SetCookie added in v0.0.2

func SetCookie(
	c forge.Context,
	token string,
	expiresAt time.Time,
	config *CookieConfig,
) error

SetCookie sets a session cookie based on the provided configuration It handles auto-detection of the Secure flag, SameSite parsing, and MaxAge calculation

Types

type Config

type Config struct {
	// Basic TTL settings
	DefaultTTL      time.Duration
	RememberTTL     time.Duration
	AllowMultiple   bool
	RequireUserAuth bool

	// Sliding session renewal (Option 1)
	EnableSlidingWindow bool          // Enable automatic session renewal
	SlidingRenewalAfter time.Duration // Only renew if session age > this (default: 5 min)

	// Refresh token support (Option 3)
	EnableRefreshTokens bool          // Enable refresh token pattern
	RefreshTokenTTL     time.Duration // Refresh token lifetime (default: 30 days)
	AccessTokenTTL      time.Duration // Short-lived access token (default: 15 min)
}

Config represents session service configuration

type CookieConfig added in v0.0.2

type CookieConfig struct {
	Enabled  bool   `json:"enabled"`            // Enable/disable cookie setting
	Name     string `json:"name"`               // Cookie name (default: "authsome_session")
	Domain   string `json:"domain,omitempty"`   // Cookie domain
	Path     string `json:"path"`               // Cookie path (default: "/")
	Secure   *bool  `json:"secure,omitempty"`   // Secure flag (nil = auto-detect based on TLS)
	HttpOnly bool   `json:"httpOnly"`           // HttpOnly flag (default: true)
	SameSite string `json:"sameSite,omitempty"` // SameSite: "Strict", "Lax", "None" (default: "Lax")
	MaxAge   *int   `json:"maxAge,omitempty"`   // MaxAge in seconds (nil = use session duration)
}

CookieConfig represents the configuration for session cookies

func DefaultCookieConfig added in v0.0.2

func DefaultCookieConfig() CookieConfig

DefaultCookieConfig returns a cookie configuration with sensible defaults

func UnmarshalCookieConfigFromJSON added in v0.0.2

func UnmarshalCookieConfigFromJSON(data []byte) (*CookieConfig, error)

UnmarshalCookieConfigFromJSON unmarshals cookie config from JSON bytes This is a helper for extracting cookie config from app metadata

func (*CookieConfig) Merge added in v0.0.2

func (c *CookieConfig) Merge(override *CookieConfig) *CookieConfig

Merge applies per-app overrides to the base config and returns a new merged config The override config takes precedence over the base config for non-zero values Special handling for boolean fields: - Enabled: Only override if override.Enabled is true (can't distinguish false from unset) - HttpOnly: Only override if override.HttpOnly is false (since default is true)

type CreateSessionRequest

type CreateSessionRequest struct {
	AppID          xid.ID  `json:"appID"`
	EnvironmentID  *xid.ID `json:"environmentID,omitempty"`
	OrganizationID *xid.ID `json:"organizationID,omitempty"`
	UserID         xid.ID  `json:"userId"`
	IPAddress      string  `json:"ipAddress"`
	UserAgent      string  `json:"userAgent"`
	Remember       bool    `json:"remember"`
}

CreateSessionRequest represents the data to create a session

type HookExecutor added in v0.0.3

type HookExecutor interface {
	ExecuteBeforeSessionCreate(ctx context.Context, req *CreateSessionRequest) error
	ExecuteAfterSessionCreate(ctx context.Context, session *Session) error
	ExecuteBeforeSessionRevoke(ctx context.Context, token string) error
	ExecuteAfterSessionRevoke(ctx context.Context, sessionID xid.ID) error
}

HookExecutor defines the interface for executing session-related hooks This interface allows the session service to execute hooks without importing the hooks package, avoiding circular dependencies (hooks package imports session for types)

type ListSessionsFilter

type ListSessionsFilter struct {
	pagination.PaginationParams
	AppID          xid.ID  `json:"appId" query:"app_id"`
	EnvironmentID  *xid.ID `json:"environmentId,omitempty" query:"environment_id"`
	OrganizationID *xid.ID `json:"organizationId,omitempty" query:"organization_id"`
	UserID         *xid.ID `json:"userId,omitempty" query:"user_id"`
	Active         *bool   `json:"active,omitempty" query:"active"` // Filter by expired/active
}

ListSessionsFilter represents filter parameters for listing sessions

type ListSessionsResponse

type ListSessionsResponse = pagination.PageResponse[*Session]

ListSessionsResponse is a type alias for paginated response

type RefreshResponse added in v0.0.3

type RefreshResponse struct {
	Session          *Session  `json:"session"`          // Updated session with new access token
	AccessToken      string    `json:"accessToken"`      // New short-lived access token
	RefreshToken     string    `json:"refreshToken"`     // Refresh token (may be rotated)
	ExpiresAt        time.Time `json:"expiresAt"`        // Access token expiry
	RefreshExpiresAt time.Time `json:"refreshExpiresAt"` // Refresh token expiry
}

RefreshResponse represents the response from refreshing a session

type Repository

type Repository interface {
	// Create/Read operations
	CreateSession(ctx context.Context, s *schema.Session) error
	FindSessionByID(ctx context.Context, id xid.ID) (*schema.Session, error)
	FindSessionByToken(ctx context.Context, token string) (*schema.Session, error)
	FindSessionByRefreshToken(ctx context.Context, refreshToken string) (*schema.Session, error)

	// List with pagination
	ListSessions(ctx context.Context, filter *ListSessionsFilter) (*pagination.PageResponse[*schema.Session], error)

	// Update/Delete operations
	RevokeSession(ctx context.Context, token string) error
	RevokeSessionByID(ctx context.Context, id xid.ID) error
	UpdateSessionExpiry(ctx context.Context, id xid.ID, expiresAt time.Time) error
	RefreshSessionTokens(ctx context.Context, id xid.ID, newAccessToken string, accessTokenExpiresAt time.Time, newRefreshToken string, refreshTokenExpiresAt time.Time) error

	// Count operations
	CountSessions(ctx context.Context, appID xid.ID, userID *xid.ID) (int, error)

	// Maintenance
	CleanupExpiredSessions(ctx context.Context) (int, error)
}

Repository defines session persistence operations Following ISP - works with schema types

type Service

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

Service provides session-related operations

func NewService

func NewService(repo Repository, cfg Config, webhookSvc *webhook.Service, hookExecutor HookExecutor) *Service

NewService creates a new session service

func (*Service) Create

func (s *Service) Create(ctx context.Context, req *CreateSessionRequest) (*Session, error)

Create creates a new session for a user

func (*Service) FindByID

func (s *Service) FindByID(ctx context.Context, id xid.ID) (*Session, error)

FindByID retrieves a session by ID

func (*Service) FindByToken

func (s *Service) FindByToken(ctx context.Context, token string) (*Session, error)

FindByToken retrieves a session by token

func (*Service) ListSessions

func (s *Service) ListSessions(ctx context.Context, filter *ListSessionsFilter) (*ListSessionsResponse, error)

ListSessions retrieves sessions with filtering and pagination

func (*Service) RefreshSession added in v0.0.3

func (s *Service) RefreshSession(ctx context.Context, refreshToken string) (*RefreshResponse, error)

RefreshSession refreshes an access token using a refresh token (Option 3) This implements the refresh token pattern for long-lived sessions

func (*Service) Revoke

func (s *Service) Revoke(ctx context.Context, token string) error

Revoke revokes a session by token

func (*Service) RevokeByID

func (s *Service) RevokeByID(ctx context.Context, id xid.ID) error

RevokeByID revokes a session by ID

func (*Service) TouchSession added in v0.0.3

func (s *Service) TouchSession(ctx context.Context, sess *Session) (*Session, bool, error)

TouchSession extends the session expiry time if sliding window is enabled Returns the updated session and whether it was actually updated

type ServiceInterface

type ServiceInterface interface {
	Create(ctx context.Context, req *CreateSessionRequest) (*Session, error)
	FindByToken(ctx context.Context, token string) (*Session, error)
	FindByID(ctx context.Context, id xid.ID) (*Session, error)
	ListSessions(ctx context.Context, filter *ListSessionsFilter) (*ListSessionsResponse, error)
	Revoke(ctx context.Context, token string) error
	RevokeByID(ctx context.Context, id xid.ID) error

	// Sliding session renewal (Option 1)
	TouchSession(ctx context.Context, sess *Session) (*Session, bool, error)

	// Refresh token pattern (Option 3)
	RefreshSession(ctx context.Context, refreshToken string) (*RefreshResponse, error)
}

ServiceInterface defines the contract for session service operations This allows plugins to decorate the service with additional behavior

type Session

type Session = base.Session

Session represents a user session (DTO)

func FromSchemaSession

func FromSchemaSession(s *schema.Session) *Session

FromSchemaSession converts schema.Session to Session DTO

func FromSchemaSessions

func FromSchemaSessions(sessions []*schema.Session) []*Session

FromSchemaSessions converts multiple schema.Session to Session DTOs

Jump to

Keyboard shortcuts

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