multisession

package
v0.0.11 Latest Latest
Warning

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

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatExpiresIn added in v0.0.3

func FormatExpiresIn(t time.Time) string

FormatExpiresIn formats time until expiration

func FormatRelativeTime added in v0.0.3

func FormatRelativeTime(t time.Time) string

FormatRelativeTime formats a time as relative time (e.g., "2 hours ago")

func IsSessionActive added in v0.0.3

func IsSessionActive(expiresAt time.Time) bool

IsSessionActive checks if a session is currently active

func IsSessionExpiringSoon added in v0.0.3

func IsSessionExpiringSoon(expiresAt time.Time, within time.Duration) bool

IsSessionExpiringSoon checks if session expires within given duration

Types

type Config

type Config struct {
	// MaxSessionsPerUser is the maximum concurrent sessions per user
	MaxSessionsPerUser int `json:"maxSessionsPerUser"`
	// EnableDeviceTracking enables device fingerprinting
	EnableDeviceTracking bool `json:"enableDeviceTracking"`
	// SessionExpiry is the session expiry time in hours
	SessionExpiryHours int `json:"sessionExpiryHours"`
	// AllowCrossPlatform allows sessions across different platforms
	AllowCrossPlatform bool `json:"allowCrossPlatform"`
}

Config holds the multisession plugin configuration

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default multisession plugin configuration

type DashboardExtension

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

DashboardExtension implements the ui.DashboardExtension interface This allows the multisession plugin to add its own screens to the dashboard

func NewDashboardExtension

func NewDashboardExtension(plugin *Plugin) *DashboardExtension

NewDashboardExtension creates a new dashboard extension for multisession

func (*DashboardExtension) DashboardWidgets

func (e *DashboardExtension) DashboardWidgets() []ui.DashboardWidget

DashboardWidgets returns widgets to show on the main dashboard

func (*DashboardExtension) ExtensionID

func (e *DashboardExtension) ExtensionID() string

ExtensionID returns the unique identifier for this extension

func (*DashboardExtension) NavigationItems

func (e *DashboardExtension) NavigationItems() []ui.NavigationItem

NavigationItems returns navigation items to register

func (*DashboardExtension) RenderDashboardWidget

func (e *DashboardExtension) RenderDashboardWidget(basePath string, currentApp *app.App) g.Node

RenderDashboardWidget renders the dashboard widget showing session stats

func (*DashboardExtension) RevokeAllUserSessions

func (e *DashboardExtension) RevokeAllUserSessions(c forge.Context) error

RevokeAllUserSessions handles revoking all sessions for a user

func (*DashboardExtension) RevokeSession

func (e *DashboardExtension) RevokeSession(c forge.Context) error

RevokeSession handles session revocation

func (*DashboardExtension) Routes

func (e *DashboardExtension) Routes() []ui.Route

Routes returns routes to register under /dashboard/app/:appId/

func (*DashboardExtension) SaveSettings

func (e *DashboardExtension) SaveSettings(c forge.Context) error

SaveSettings handles saving multisession settings

func (*DashboardExtension) ServeMultiSessionPage

func (e *DashboardExtension) ServeMultiSessionPage(c forge.Context) error

ServeMultiSessionPage renders the multi-session management page with dashboard layout

func (*DashboardExtension) ServeSessionDetailPage added in v0.0.3

func (e *DashboardExtension) ServeSessionDetailPage(c forge.Context) error

ServeSessionDetailPage renders detailed information about a single session

func (*DashboardExtension) ServeSettings

func (e *DashboardExtension) ServeSettings(c forge.Context) error

ServeSettings renders the multisession settings page

func (*DashboardExtension) ServeUserSessionsPage added in v0.0.3

func (e *DashboardExtension) ServeUserSessionsPage(c forge.Context) error

ServeUserSessionsPage renders all sessions for a specific user

func (*DashboardExtension) SetRegistry

func (e *DashboardExtension) SetRegistry(registry *dashboard.ExtensionRegistry)

SetRegistry sets the extension registry reference (called by dashboard after registration)

func (*DashboardExtension) SettingsPages

func (e *DashboardExtension) SettingsPages() []ui.SettingsPage

SettingsPages returns full settings pages for the new sidebar layout

func (*DashboardExtension) SettingsSections

func (e *DashboardExtension) SettingsSections() []ui.SettingsSection

SettingsSections returns settings sections to add to the settings page Deprecated: Use SettingsPages() instead

type DeviceInfo added in v0.0.3

type DeviceInfo struct {
	DeviceType string // Desktop, Mobile, Tablet, Bot, Unknown
	OS         string // Windows, macOS, Linux, iOS, Android, ChromeOS, etc.
	OSVersion  string // OS version if available
	Browser    string // Chrome, Firefox, Safari, Edge, etc.
	BrowserVer string // Browser version if available
	IsMobile   bool
	IsTablet   bool
	IsDesktop  bool
	IsBot      bool
}

DeviceInfo contains parsed device information from user agent

func ParseUserAgent added in v0.0.3

func ParseUserAgent(ua string) *DeviceInfo

ParseUserAgent parses a user agent string and extracts device information

func (*DeviceInfo) FormatDeviceInfo added in v0.0.3

func (d *DeviceInfo) FormatDeviceInfo() string

FormatDeviceInfo returns a human-readable device string

func (*DeviceInfo) ShortDeviceInfo added in v0.0.3

func (d *DeviceInfo) ShortDeviceInfo() string

ShortDeviceInfo returns a compact device string

type ErrorResponse

type ErrorResponse = responses.ErrorResponse

Response types - use shared responses from core

type Handler

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

func NewHandler

func NewHandler(s *Service) *Handler

func (*Handler) Delete

func (h *Handler) Delete(c forge.Context) error

Delete revokes a session by id for the current user

func (*Handler) GetByID added in v0.0.6

func (h *Handler) GetByID(c forge.Context) error

GetByID returns details about a specific session by ID

func (*Handler) GetCurrent added in v0.0.6

func (h *Handler) GetCurrent(c forge.Context) error

GetCurrent returns details about the currently active session

func (*Handler) GetStats added in v0.0.6

func (h *Handler) GetStats(c forge.Context) error

GetStats returns aggregated session statistics for the current user

func (*Handler) List

func (h *Handler) List(c forge.Context) error

List returns sessions for the current user with optional filtering

func (*Handler) Refresh added in v0.0.6

func (h *Handler) Refresh(c forge.Context) error

Refresh extends the current session's expiry time

func (*Handler) RevokeAll added in v0.0.6

func (h *Handler) RevokeAll(c forge.Context) error

RevokeAll revokes all sessions for the current user

func (*Handler) RevokeOthers added in v0.0.6

func (h *Handler) RevokeOthers(c forge.Context) error

RevokeOthers revokes all sessions except the current one

func (*Handler) SetActive

func (h *Handler) SetActive(c forge.Context) error

SetActive switches the current session cookie to the provided session id

type ListSessionsRequest added in v0.0.7

type ListSessionsRequest struct {
	// Filtering
	Active      *bool   `json:"active" query:"active"`
	UserAgent   *string `json:"userAgent" query:"user_agent"`
	IPAddress   *string `json:"ipAddress" query:"ip_address"`
	CreatedFrom *string `json:"createdFrom" query:"created_from"`
	CreatedTo   *string `json:"createdTo" query:"created_to"`

	// Sorting
	SortBy    *string `json:"sortBy" query:"sort_by"`
	SortOrder *string `json:"sortOrder" query:"sort_order"`

	// Pagination
	Limit  int `json:"limit" query:"limit"`
	Offset int `json:"offset" query:"offset"`
}

ListSessionsRequest represents filtering and pagination options for listing sessions

type MessageResponse

type MessageResponse = responses.MessageResponse

type MultiSessionErrorResponse

type MultiSessionErrorResponse struct {
	Error string `json:"error" example:"Error message"`
}

Response types for multi-session routes

type Plugin

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

Plugin wires the multi-session service and registers routes

func NewPlugin

func NewPlugin(opts ...PluginOption) *Plugin

NewPlugin creates a new multisession plugin instance with optional configuration

func (*Plugin) DashboardExtension

func (p *Plugin) DashboardExtension() ui.DashboardExtension

DashboardExtension implements the PluginWithDashboardExtension interface This allows the multisession plugin to extend the dashboard with custom screens

func (*Plugin) GetAuthService

func (p *Plugin) GetAuthService() *auth.Service

GetAuthService returns the auth service for testing

func (*Plugin) ID

func (p *Plugin) ID() string

func (*Plugin) Init

func (p *Plugin) Init(authInst core.Authsome) error

Init accepts auth instance with GetDB method

func (*Plugin) Migrate

func (p *Plugin) Migrate() error

func (*Plugin) RegisterHooks

func (p *Plugin) RegisterHooks(_ *hooks.HookRegistry) error

func (*Plugin) RegisterRoutes

func (p *Plugin) RegisterRoutes(router forge.Router) error

RegisterRoutes mounts endpoints under /api/auth/multi-session

func (*Plugin) RegisterServiceDecorators

func (p *Plugin) RegisterServiceDecorators(_ *registry.ServiceRegistry) error

type PluginOption

type PluginOption func(*Plugin)

PluginOption is a functional option for configuring the multisession plugin

func WithAllowCrossPlatform

func WithAllowCrossPlatform(allow bool) PluginOption

WithAllowCrossPlatform sets whether cross-platform sessions are allowed

func WithDefaultConfig

func WithDefaultConfig(cfg Config) PluginOption

WithDefaultConfig sets the default configuration for the plugin

func WithEnableDeviceTracking

func WithEnableDeviceTracking(enable bool) PluginOption

WithEnableDeviceTracking sets whether device tracking is enabled

func WithMaxSessionsPerUser

func WithMaxSessionsPerUser(max int) PluginOption

WithMaxSessionsPerUser sets the maximum concurrent sessions per user

func WithSessionExpiryHours

func WithSessionExpiryHours(hours int) PluginOption

WithSessionExpiryHours sets the session expiry time

type RevokeAllRequest added in v0.0.7

type RevokeAllRequest struct {
	IncludeCurrentSession bool `json:"includeCurrentSession"`
}

RevokeAllRequest represents the request to revoke all sessions

type RevokeResponse added in v0.0.7

type RevokeResponse struct {
	RevokedCount int    `json:"revokedCount"`
	Status       string `json:"status"`
}

RevokeResponse represents the response from revoking sessions

type Service

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

Service provides multi-session operations

func NewService

func NewService(sr session.Repository, sessionSvc session.ServiceInterface, dr dev.Repository, a *auth.Service, _ interface{}) *Service

func (*Service) CurrentUserFromToken

func (s *Service) CurrentUserFromToken(ctx context.Context, token string) (xid.ID, error)

CurrentUserFromToken validates token and returns userID

func (*Service) Delete

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

Delete revokes a session by id ensuring ownership

func (*Service) Find

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

Find returns a specific session by ID ensuring ownership

func (*Service) GetCurrent added in v0.0.6

func (s *Service) GetCurrent(ctx context.Context, userID, sessionID xid.ID) (*session.Session, error)

GetCurrent returns the current session by ID with ownership verification. This is a convenience method that wraps Find to retrieve the active session. Returns an error if the session doesn't exist or doesn't belong to the user.

func (*Service) GetCurrentSessionID added in v0.0.6

func (s *Service) GetCurrentSessionID(ctx context.Context, token string) (xid.ID, error)

GetCurrentSessionID extracts the session ID from a session token. It validates the token and returns the associated session ID. Returns an error if the token is invalid or expired.

func (*Service) GetStats added in v0.0.6

func (s *Service) GetStats(ctx context.Context, userID xid.ID) (*SessionStats, error)

GetStats returns aggregated session statistics for a user. Calculates total and active session counts, unique device and location counts, and identifies the oldest and newest sessions. Useful for security dashboards and user account management interfaces. Returns SessionStats containing all aggregated data or an error if retrieval fails.

func (*Service) List

List returns all sessions for a user with optional filtering

func (*Service) RefreshCurrent added in v0.0.6

func (s *Service) RefreshCurrent(ctx context.Context, userID, sessionID xid.ID) (*session.Session, error)

RefreshCurrent extends the current session's expiry time using the sliding session pattern. This updates the session's expiration timestamp to prevent automatic logout during active use. Returns the updated session with the new expiry time or an error if the refresh fails.

func (*Service) RevokeAll added in v0.0.6

func (s *Service) RevokeAll(ctx context.Context, userID xid.ID, includeCurrentSession bool, currentSessionID xid.ID) (int, error)

RevokeAll revokes all sessions for a user with optional current session inclusion. If includeCurrentSession is false, the current session specified by currentSessionID is preserved. Returns the count of successfully revoked sessions and any error encountered. Use case: Sign out from all devices, or sign out everywhere except current device.

func (*Service) RevokeAllExceptCurrent added in v0.0.6

func (s *Service) RevokeAllExceptCurrent(ctx context.Context, userID, currentSessionID xid.ID) (int, error)

RevokeAllExceptCurrent revokes all sessions except the current one. This is commonly used after password changes or when suspicious activity is detected to ensure security while keeping the user logged in on their current device. Returns the count of successfully revoked sessions and any error encountered.

type SessionStats added in v0.0.6

type SessionStats struct {
	TotalSessions  int              // Total number of sessions (active + expired)
	ActiveSessions int              // Number of currently active (non-expired) sessions
	DeviceCount    int              // Number of unique devices
	LocationCount  int              // Number of unique IP addresses (proxy for locations)
	OldestSession  *session.Session // Oldest session by creation time
	NewestSession  *session.Session // Newest session by creation time
}

SessionStats holds aggregated session statistics for a user. Provides an overview of the user's session landscape including counts, unique devices, unique locations (based on IP addresses), and session age range.

type SessionStatsResponse added in v0.0.6

type SessionStatsResponse struct {
	TotalSessions  int     `json:"totalSessions"`
	ActiveSessions int     `json:"activeSessions"`
	DeviceCount    int     `json:"deviceCount"`
	LocationCount  int     `json:"locationCount"`
	OldestSession  *string `json:"oldestSession,omitempty"` // ISO8601 timestamp
	NewestSession  *string `json:"newestSession,omitempty"` // ISO8601 timestamp
}

SessionStatsResponse represents aggregated session statistics

type SessionTokenResponse

type SessionTokenResponse struct {
	Session *session.Session `json:"session"`
	Token   string           `json:"token"`
}

type SessionsResponse

type SessionsResponse = session.ListSessionsResponse

type SetActiveRequest added in v0.0.7

type SetActiveRequest struct {
	ID string `json:"id"`
}

SetActiveRequest represents the request to set an active session

type StatusResponse

type StatusResponse = responses.StatusResponse

Jump to

Keyboard shortcuts

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