service

package
v0.11.1 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 31 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 service provides business logic services for the application.

Package service provides business logic services for GoatFlow.

Index

Constants

View Source
const (
	WebAuthnUserTypeAgent    = "agent"
	WebAuthnUserTypeCustomer = "customer"
)
View Source
const TimezonePreferenceKey = "UserTimeZone"

TimezonePreferenceKey is the user_preferences key holding the user's IANA time zone (the OTRS name, so imported preference rows keep working).

Variables

View Source
var ErrInvalidTimezone = errors.New("time zone must be an IANA name such as Europe/London")

ErrInvalidTimezone is returned by SetTimezone for a name that is not an IANA zone the host can load.

View Source
var ErrRefreshRejected = errors.New("refresh token rejected")

ErrRefreshRejected is returned by Refresh for any refresh token that cannot be exchanged: malformed, wrongly signed, expired, an access token, bound to a killed session, or belonging to an account that no longer exists or is no longer valid.

Functions

func AgentWebAuthnUserKey

func AgentWebAuthnUserKey(userID int) string

func CountWebAuthnCredentials added in v0.10.0

func CountWebAuthnCredentials(db *sql.DB, userType, userKey string) (int, error)

CountWebAuthnCredentials counts an account's registered passkeys. It needs no relying-party configuration, so login gates can check it directly.

func DeleteAllWebAuthnCredentials added in v0.10.0

func DeleteAllWebAuthnCredentials(db *sql.DB, userType, userKey string) error

DeleteAllWebAuthnCredentials removes every passkey of an account. Like CountWebAuthnCredentials it needs no relying-party configuration, so it works on hosts a WebAuthn config cannot be built for.

func SetConfigAdapter

func SetConfigAdapter(ca *yamlmgmt.ConfigAdapter)

func ValidateAuthProviders added in v0.10.0

func ValidateAuthProviders() error

ValidateAuthProviders checks provider settings at startup. Invalid LDAP settings (LDAP_ENABLED=true) are returned as an error naming each bad variable; an LDAP_ENABLED flag that disagrees with Auth::Providers is logged.

func ValidateTimezone added in v0.11.0

func ValidateTimezone(name string) error

ValidateTimezone reports whether name is an IANA zone the host can load. "Local" is refused: it names the server process's zone, not the user's.

Types

type AuthService

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

AuthService handles authentication and authorization.

func NewAuthService

func NewAuthService(db *sql.DB, jwtManager *auth.JWTManager, oidcClient *http.Client, stateStore auth.StateStore, sessions SessionStore) *AuthService

NewAuthService creates a new authentication service with a JWT manager. sessions may be nil (no session tracking): then no token pair can be issued or refreshed.

func (*AuthService) GetUser

func (s *AuthService) GetUser(ctx context.Context, identifier string) (*platformmodels.User, error)

GetUser retrieves user information by identifier.

func (*AuthService) IssueTokens added in v0.10.0

func (s *AuthService) IssueTokens(user *platformmodels.User, remoteAddr, userAgent string, accessDuration time.Duration) (sessionID, accessToken, refreshToken string, err error)

IssueTokens creates a sessions row for the authenticated user (remoteAddr and userAgent are shown in the admin session list) and returns its id with an access token of accessDuration (0 = default) and a refresh token, both bound to that session.

func (*AuthService) Login

func (s *AuthService) Login(ctx context.Context, username, password string) (*platformmodels.User, string, error)

Login authenticates a user and names the provider that accepted the login (see auth.Authenticator.Authenticate for the errors). It issues no tokens: callers decide whether a second factor is still due, then call IssueTokens.

func (*AuthService) Refresh added in v0.10.0

func (s *AuthService) Refresh(ctx context.Context, refreshToken string) (*platformmodels.User, string, string, error)

Refresh exchanges a refresh token for a new access token and a new refresh token, both bound to the session of the presented token. The session must still exist (a killed session ends the refresh chain) and the account is reloaded from the database (users for agents, customer_user for customers), so the new access token carries the current id, role and admin-group membership, and accounts that were renamed, deleted or set invalid (valid_id != 1) are rejected with ErrRefreshRejected. Refresh tokens are not tracked server-side, so the presented one stays valid until it expires or its session is killed.

func (*AuthService) ValidateToken

func (s *AuthService) ValidateToken(tokenString string) (*platformmodels.User, error)

ValidateToken validates a JWT token and returns the user.

type CustomerPreferencesBackend

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

CustomerPreferencesBackend stores preferences in customer_preferences table (string user_id/login).

func NewCustomerPreferencesBackend

func NewCustomerPreferencesBackend(db *sql.DB, userLogin string) *CustomerPreferencesBackend

NewCustomerPreferencesBackend creates a backend for customer users.

func (*CustomerPreferencesBackend) Delete

func (b *CustomerPreferencesBackend) Delete(key string) error

func (*CustomerPreferencesBackend) Get

func (*CustomerPreferencesBackend) Set

func (b *CustomerPreferencesBackend) Set(key, value string) error

func (*CustomerPreferencesBackend) SetAndDelete

func (b *CustomerPreferencesBackend) SetAndDelete(sets map[string]string, deletes []string) error

SetAndDelete performs multiple set and delete operations atomically.

type DashboardWidgetConfig

type DashboardWidgetConfig struct {
	WidgetID string `json:"widget_id"` // Format: "plugin_name:widget_id"
	Enabled  bool   `json:"enabled"`
	Position int    `json:"position"`    // Order on dashboard (lower = first)
	X        int    `json:"x"`           // Grid column position
	Y        int    `json:"y"`           // Grid row position
	W        int    `json:"w,omitempty"` // Grid width (columns)
	H        int    `json:"h,omitempty"` // Grid height (rows)
}

DashboardWidgetConfig represents the configuration for a dashboard widget.

type PasskeyLoginResult

type PasskeyLoginResult struct {
	UserType string
	UserKey  string
}

type PreferencesBackend

type PreferencesBackend interface {
	Get(key string) (string, error)
	Set(key, value string) error
	Delete(key string) error
	// SetAndDelete performs multiple set and delete operations atomically in a single transaction.
	// This ensures all-or-nothing semantics for multi-step preference changes.
	SetAndDelete(sets map[string]string, deletes []string) error
}

PreferencesBackend abstracts preference storage for TOTP. Allows the same TOTP logic to work with different storage backends.

type SessionStore added in v0.10.0

type SessionStore interface {
	CreateSession(userID int, userLogin, userType, remoteAddr, userAgent string) (string, error)
	GetSession(sessionID string) (*platformmodels.Session, error)
}

SessionStore is the session persistence AuthService needs: every token pair names a sessions row, and refresh refuses tokens whose row was killed.

type TOTPService

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

TOTPService handles two-factor authentication using TOTP.

func NewCustomerTOTPService

func NewCustomerTOTPService(db *sql.DB, issuer string, userLogin string) *TOTPService

NewCustomerTOTPService creates a TOTP service for customer users (string login).

func NewTOTPService

func NewTOTPService(db *sql.DB, issuer string) *TOTPService

NewTOTPService creates a TOTP service for agent/admin users (numeric ID).

func (*TOTPService) ClearRecoveryCodes added in v0.10.0

func (s *TOTPService) ClearRecoveryCodes(userID int) error

ClearRecoveryCodes deletes the account's recovery codes. Used when the last second factor is removed, so leftover codes cannot keep 2FA half-on.

func (*TOTPService) ConfirmSetup

func (s *TOTPService) ConfirmSetup(userID int, code string) error

ConfirmSetup verifies the TOTP code and enables 2FA for the user.

func (*TOTPService) ConfirmSetupForCustomer

func (s *TOTPService) ConfirmSetupForCustomer(userLogin string, code string) error

ConfirmSetupForCustomer verifies and enables 2FA for a customer.

func (*TOTPService) Disable

func (s *TOTPService) Disable(userID int, code string) error

Disable turns off 2FA for a user.

func (*TOTPService) DisableForCustomer

func (s *TOTPService) DisableForCustomer(userLogin string, code string) error

DisableForCustomer turns off 2FA for a customer.

func (*TOTPService) EnsureRecoveryCodes added in v0.10.0

func (s *TOTPService) EnsureRecoveryCodes(userID int) ([]string, error)

EnsureRecoveryCodes gives the account its first set of recovery codes and returns them so they can be shown once. It returns nil when the account already holds codes. Called when a passkey is added, so a passkey is never the only way through the second step.

func (*TOTPService) ForCustomer

func (s *TOTPService) ForCustomer(userLogin string) *TOTPService

ForCustomer returns a TOTPService bound to a specific customer login.

func (*TOTPService) ForUser

func (s *TOTPService) ForUser(userID int) *TOTPService

ForUser returns a TOTPService bound to a specific agent user ID.

func (*TOTPService) ForceDisable

func (s *TOTPService) ForceDisable(userID int) error

ForceDisable turns off 2FA for a user without requiring a code (admin override).

func (*TOTPService) ForceDisableForCustomer

func (s *TOTPService) ForceDisableForCustomer(userLogin string) error

ForceDisableForCustomer turns off 2FA for a customer without requiring a code (admin override).

func (*TOTPService) GenerateSetup

func (s *TOTPService) GenerateSetup(userID int, userEmail string) (*TOTPSetupData, error)

GenerateSetup creates a new TOTP secret and recovery codes for a user. The secret is NOT saved until ConfirmSetup is called with a valid code.

func (*TOTPService) GenerateSetupForCustomer

func (s *TOTPService) GenerateSetupForCustomer(userLogin string) (*TOTPSetupData, error)

GenerateSetupForCustomer creates a new TOTP secret for a customer.

func (*TOTPService) GetRemainingRecoveryCodes

func (s *TOTPService) GetRemainingRecoveryCodes(userID int) int

GetRemainingRecoveryCodes returns count of unused recovery codes.

func (*TOTPService) GetRemainingRecoveryCodesForCustomer

func (s *TOTPService) GetRemainingRecoveryCodesForCustomer(userLogin string) int

GetRemainingRecoveryCodesForCustomer returns count for a customer.

func (*TOTPService) IsEnabled

func (s *TOTPService) IsEnabled(userID int) bool

IsEnabled checks if 2FA is enabled for a user.

func (*TOTPService) IsEnabledForCustomer

func (s *TOTPService) IsEnabledForCustomer(userLogin string) bool

IsEnabledForCustomer checks if 2FA is enabled for a customer.

func (*TOTPService) LoginStatus added in v0.10.0

func (s *TOTPService) LoginStatus(userID int) (enabled bool, recoveryCodes int, err error)

LoginStatus reports whether TOTP is enabled for an agent and how many recovery codes remain. Unlike IsEnabled it returns lookup errors, so a login gate can fail closed instead of skipping the second factor.

func (*TOTPService) LoginStatusForCustomer added in v0.10.0

func (s *TOTPService) LoginStatusForCustomer(userLogin string) (enabled bool, recoveryCodes int, err error)

LoginStatusForCustomer is LoginStatus for a customer account.

func (*TOTPService) RegenerateRecoveryCodes added in v0.10.0

func (s *TOTPService) RegenerateRecoveryCodes(userID int) ([]string, error)

RegenerateRecoveryCodes replaces the account's recovery codes with a new set and returns it. The old codes stop working.

func (*TOTPService) ValidateCode

func (s *TOTPService) ValidateCode(userID int, code string) (bool, error)

ValidateCode checks if a TOTP code is valid for the user.

func (*TOTPService) ValidateCodeForCustomer

func (s *TOTPService) ValidateCodeForCustomer(userLogin string, code string) (bool, error)

ValidateCodeForCustomer checks if a TOTP code is valid for a customer.

type TOTPSetupData

type TOTPSetupData struct {
	Secret        string   `json:"secret"`
	URL           string   `json:"url"`
	RecoveryCodes []string `json:"recovery_codes"`
}

TOTPSetupData contains data needed for 2FA setup.

type UserPreferencesBackend

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

UserPreferencesBackend stores preferences in user_preferences table (numeric user_id).

func NewUserPreferencesBackend

func NewUserPreferencesBackend(db *sql.DB, userID int) *UserPreferencesBackend

NewUserPreferencesBackend creates a backend for agent/admin users.

func (*UserPreferencesBackend) Delete

func (b *UserPreferencesBackend) Delete(key string) error

func (*UserPreferencesBackend) Get

func (b *UserPreferencesBackend) Get(key string) (string, error)

func (*UserPreferencesBackend) Set

func (b *UserPreferencesBackend) Set(key, value string) error

func (*UserPreferencesBackend) SetAndDelete

func (b *UserPreferencesBackend) SetAndDelete(sets map[string]string, deletes []string) error

SetAndDelete performs multiple set and delete operations atomically.

type UserPreferencesService

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

UserPreferencesService handles user preference operations.

func NewUserPreferencesService

func NewUserPreferencesService(db *sql.DB) *UserPreferencesService

NewUserPreferencesService creates a new user preferences service.

func (*UserPreferencesService) DeletePreference

func (s *UserPreferencesService) DeletePreference(userID int, key string) error

DeletePreference removes a user preference.

func (*UserPreferencesService) GetDashboardWidgets

func (s *UserPreferencesService) GetDashboardWidgets(userID int) ([]DashboardWidgetConfig, error)

GetDashboardWidgets returns the user's dashboard widget configuration. Returns nil if no configuration is set (show all widgets with defaults).

func (*UserPreferencesService) GetLanguage

func (s *UserPreferencesService) GetLanguage(userID int) string

GetLanguage returns the user's preferred language. Returns empty string if no preference is set (use system detection).

func (*UserPreferencesService) GetPreference

func (s *UserPreferencesService) GetPreference(userID int, key string) (string, error)

GetPreference retrieves a user preference by key.

func (*UserPreferencesService) GetRemindersEnabled

func (s *UserPreferencesService) GetRemindersEnabled(userID int) (bool, error)

GetRemindersEnabled returns whether pending reminders are enabled for the user. No stored preference means enabled; a failed lookup is returned as an error.

func (*UserPreferencesService) GetSessionTimeout

func (s *UserPreferencesService) GetSessionTimeout(userID int) int

Returns 0 if no preference is set (use system default).

func (*UserPreferencesService) GetTheme

func (s *UserPreferencesService) GetTheme(userID int) string

GetTheme returns the user's preferred theme. Returns empty string if no preference is set.

func (*UserPreferencesService) GetThemeMode

func (s *UserPreferencesService) GetThemeMode(userID int) string

GetThemeMode returns the user's preferred theme mode (light/dark). Returns empty string if no preference is set.

func (*UserPreferencesService) GetTimezone added in v0.11.0

func (s *UserPreferencesService) GetTimezone(userID int) string

GetTimezone returns the user's IANA time zone preference, or "" when the user follows the instance default (app.timezone). A stored value the host can no longer load is treated as unset rather than passed on.

func (*UserPreferencesService) IsWidgetEnabled

func (s *UserPreferencesService) IsWidgetEnabled(userID int, pluginName, widgetID string) bool

IsWidgetEnabled checks if a specific widget is enabled for the user. If no config exists, returns true (all widgets enabled by default).

func (*UserPreferencesService) SetDashboardWidgets

func (s *UserPreferencesService) SetDashboardWidgets(userID int, config []DashboardWidgetConfig) error

SetDashboardWidgets saves the user's dashboard widget configuration.

func (*UserPreferencesService) SetLanguage

func (s *UserPreferencesService) SetLanguage(userID int, lang string) error

SetLanguage sets the user's preferred language.

func (*UserPreferencesService) SetPreference

func (s *UserPreferencesService) SetPreference(userID int, key string, value string) error

SetPreference sets a user preference. Uses delete-then-insert within a transaction to avoid duplicates and ensure atomicity. (MySQL reports 0 rows affected when UPDATE sets the same value, which would cause incorrect INSERT with the old update-then-insert pattern.)

func (*UserPreferencesService) SetRemindersEnabled

func (s *UserPreferencesService) SetRemindersEnabled(userID int, enabled bool) error

SetRemindersEnabled sets whether pending reminders are enabled for the user.

func (*UserPreferencesService) SetSessionTimeout

func (s *UserPreferencesService) SetSessionTimeout(userID int, timeout int) error

SetSessionTimeout sets the user's preferred session timeout.

func (*UserPreferencesService) SetTheme

func (s *UserPreferencesService) SetTheme(userID int, theme string) error

SetTheme sets the user's preferred theme.

func (*UserPreferencesService) SetThemeMode

func (s *UserPreferencesService) SetThemeMode(userID int, mode string) error

SetThemeMode sets the user's preferred theme mode (light/dark).

func (*UserPreferencesService) SetTimezone added in v0.11.0

func (s *UserPreferencesService) SetTimezone(userID int, name string) error

SetTimezone stores the user's IANA time zone; "" clears the preference so the user follows the instance default again.

type WebAuthnCredentialOrigin added in v0.10.0

type WebAuthnCredentialOrigin struct {
	Host       string // host the credential was registered on; "" if unknown
	UsableHere bool
}

WebAuthnCredentialOrigin says where a credential was registered and whether it can sign in here. A passkey is bound to the RP ID (host name) it was created for, so one made on another address can never be used on this one.

type WebAuthnCredentialRecord

type WebAuthnCredentialRecord struct {
	ID           int64      `json:"id"`
	UserType     string     `json:"user_type"`
	UserKey      string     `json:"user_key"`
	CredentialID string     `json:"credential_id"`
	Name         string     `json:"name"`
	SignCount    uint32     `json:"sign_count"`
	LastUsedAt   *time.Time `json:"last_used_at,omitempty"`
	CreatedAt    time.Time  `json:"created_at"`
	UpdatedAt    time.Time  `json:"updated_at"`
	// contains filtered or unexported fields
}

type WebAuthnService

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

func NewWebAuthnService

func NewWebAuthnService(db *sql.DB, r *http.Request) (*WebAuthnService, error)

func (*WebAuthnService) BeginLogin

func (s *WebAuthnService) BeginLogin(userType, userKey, displayName string) (interface{}, error)

func (*WebAuthnService) BeginPasskeyLogin

func (s *WebAuthnService) BeginPasskeyLogin(userType string) (interface{}, string, error)

func (*WebAuthnService) BeginRegistration

func (s *WebAuthnService) BeginRegistration(userType, userKey, displayName string) (interface{}, error)

func (*WebAuthnService) CountCredentials

func (s *WebAuthnService) CountCredentials(userType, userKey string) (int, error)

func (*WebAuthnService) CredentialOrigin added in v0.10.0

CredentialOrigin reads the registration origin and RP ID hash stored with the credential and compares the hash with this request's RP ID. Credentials without stored registration data are assumed usable.

func (*WebAuthnService) DeleteCredential

func (s *WebAuthnService) DeleteCredential(userType, userKey string, id int64) error

func (*WebAuthnService) FinishLogin

func (s *WebAuthnService) FinishLogin(userType, userKey, displayName string, r *http.Request) error

func (*WebAuthnService) FinishPasskeyLogin

func (s *WebAuthnService) FinishPasskeyLogin(userType, token string, r *http.Request) (*PasskeyLoginResult, error)

func (*WebAuthnService) FinishRegistration

func (s *WebAuthnService) FinishRegistration(userType, userKey, displayName, keyName string, r *http.Request) (*WebAuthnCredentialRecord, error)

func (*WebAuthnService) IsEnabled

func (s *WebAuthnService) IsEnabled(userType, userKey string) bool

func (*WebAuthnService) ListCredentials

func (s *WebAuthnService) ListCredentials(userType, userKey string) ([]WebAuthnCredentialRecord, error)

func (*WebAuthnService) RenameCredential

func (s *WebAuthnService) RenameCredential(userType, userKey string, id int64, name string) error

Jump to

Keyboard shortcuts

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