admin

package
v0.27.2 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	EventUserCreated          = "admin:user:created"
	EventUserUpdated          = "admin:user:updated"
	EventUserDeleted          = "admin:user:deleted"
	EventUserRoleChanged      = "admin:user:role_changed"
	EventUserBanned           = "admin:user:banned"
	EventUserUnbanned         = "admin:user:unbanned"
	EventUserImpersonated     = "admin:user:impersonated"
	EventImpersonationStopped = "admin:user:impersonation_stopped"
	EventUserPasswordChanged  = "admin:user:password_changed"
	EventSessionRevoked       = "admin:session:revoked"
	EventAllSessionsRevoked   = "admin:session:all_revoked"
)

Event bus topic string constants emitted during administrative lifecycle actions.

View Source
const (
	RoleAdmin = "admin"
	RoleUser  = "user"
)

Standard role constants.

View Source
const (
	ResourceUser    = "user"
	ResourceSession = "session"
)

Standard access control resources.

View Source
const (
	ActionCreate            = "create"
	ActionList              = "list"
	ActionGet               = "get"
	ActionUpdate            = "update"
	ActionDelete            = "delete"
	ActionSetRole           = "set-role"
	ActionBan               = "ban"
	ActionImpersonate       = "impersonate"
	ActionImpersonateAdmins = "impersonate-admins"
	ActionSetPassword       = "set-password"
	ActionSetEmail          = "set-email"
)

Standard actions for the 'user' resource.

View Source
const (
	ActionSessionList   = "list"
	ActionSessionRevoke = "revoke"
	ActionSessionDelete = "delete"
)

Standard actions for the 'session' resource.

View Source
const (
	ExtraKeyImpersonatedBy = "impersonated_by"
	ExtraKeyAdminSession   = "admin_session"
	ExtraKeyBanReason      = "ban_reason"
	ExtraKeyBanExpires     = "ban_expires"
	ExtraKeyRole           = "role"
)

Standard metadata and context keys for Extra payloads and shared plugin.Context storage.

View Source
const (
	CallerContextKey contextKey = "admin_caller"
)
View Source
const PluginID = "admin"

PluginID is the unique string identifier for the Admin plugin ("admin").

Variables

View Source
var (
	// ErrUserNotFound is returned when no user matches the queried identifier or email.
	ErrUserNotFound = errors.New("admin: user not found")

	// ErrUserAlreadyExists is returned when attempting to create a user with an email already taken.
	ErrUserAlreadyExists = errors.New("admin: user already exists")

	// ErrCannotBanSelf is returned when an administrator attempts to ban their own account.
	ErrCannotBanSelf = errors.New("admin: you cannot ban yourself")

	// ErrCannotDeleteSelf is returned when an administrator attempts to remove their own account.
	ErrCannotDeleteSelf = errors.New("admin: you cannot remove yourself")

	// ErrCannotImpersonateAdmin is returned when attempting to impersonate an administrator without explicit permission.
	ErrCannotImpersonateAdmin = errors.New("admin: you cannot impersonate admins without explicit permission")

	// ErrCannotImpersonateSelf is returned when attempting to impersonate oneself.
	ErrCannotImpersonateSelf = errors.New("admin: you cannot impersonate yourself")

	// ErrNotImpersonating is returned when attempting to stop impersonation on a session that is not impersonated.
	ErrNotImpersonating = errors.New("admin: session is not impersonated")

	// ErrAdminSessionNotFound is returned when the original administrator session cannot be found during restoration.
	ErrAdminSessionNotFound = errors.New("admin: original admin session not found")

	// ErrUnauthorized is returned when unauthenticated access is attempted.
	ErrUnauthorized = errors.New("admin: unauthorized access")

	// ErrForbidden is returned when a caller lacks the required administrative permissions.
	ErrForbidden = errors.New("admin: forbidden - insufficient permissions")

	// ErrInvalidRole is returned when assigning a role that is not recognized in the access control configuration.
	ErrInvalidRole = errors.New("admin: invalid or non-existent role")

	// ErrNoDataToUpdate is returned when an update request provides no fields to modify.
	ErrNoDataToUpdate = errors.New("admin: no data provided for update")

	// ErrPasswordTooShort is returned when a new password does not meet the minimum length constraint.
	ErrPasswordTooShort = errors.New("admin: password is too short")

	// ErrPasswordTooLong is returned when a new password exceeds the maximum allowed length.
	ErrPasswordTooLong = errors.New("admin: password is too long")

	// ErrInvalidEmail is returned when an email format validation fails.
	ErrInvalidEmail = errors.New("admin: invalid email address")

	// ErrUserBanned is returned when attempting an operation or authentication on a banned account.
	ErrUserBanned = errors.New("admin: user account is banned")

	// ErrInvalidParameter is returned when a required parameter is missing or malformed.
	ErrInvalidParameter = errors.New("admin: required parameter is missing or invalid")
)

Functions

func CheckActionGranted

func CheckActionGranted(granted Statements, resource, action string) bool

CheckActionGranted checks if a specific action on a resource is satisfied by the granted statements (with wildcard support).

func DefaultRoles

func DefaultRoles() map[string]Role

DefaultRoles defines the baseline permission matrix for built-in roles (admin, user).

func EvaluateStatements

func EvaluateStatements(granted Statements, requested Permissions, connector Connector) bool

EvaluateStatements evaluates whether granted statements satisfy the requested permissions using the given connector.

func HasAction

func HasAction(actions []string, targetAction string) bool

HasAction checks if a target action is present in an action list (or matches wildcard "*").

func HasPermission

func HasPermission(input HasPermissionInput) bool

HasPermission verifies whether a caller possesses the required permissions considering their roles, custom configs, and AdminUserIDs bypass.

Types

type AccessControl

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

AccessControl manages the registry of roles configured within the application.

func NewAccessControl

func NewAccessControl() *AccessControl

NewAccessControl initializes a new AccessControl instance populated with default roles.

func (*AccessControl) GetRole

func (ac *AccessControl) GetRole(name string) (Role, bool)

GetRole retrieves a role by name from the registry.

func (*AccessControl) RegisterRole

func (ac *AccessControl) RegisterRole(role Role) *AccessControl

RegisterRole adds or overrides a role definition in the access control registry.

func (*AccessControl) Roles

func (ac *AccessControl) Roles() map[string]Role

Roles returns a copy of all registered roles in the registry.

type AllSessionsRevokedEventPayload

type AllSessionsRevokedEventPayload struct {
	CallerID   string `json:"caller_id"`
	CallerRole string `json:"caller_role"`
	UserID     string `json:"user_id"`
	plugin.ExtraContainer
}

AllSessionsRevokedEventPayload is dispatched when all sessions for a user are invalidated.

type AuthorizeResult

type AuthorizeResult struct {
	Success bool   `json:"success"`
	Error   string `json:"error,omitempty"`
}

AuthorizeResult represents the outcome of a role permission evaluation.

type BanUserParams

type BanUserParams struct {
	Caller       CallerContext  `json:"caller"`
	UserID       string         `json:"user_id"`
	BanReason    string         `json:"ban_reason,omitempty"`
	BanExpiresIn *time.Duration `json:"ban_expires_in,omitempty"`
}

BanUserParams defines parameters for suspending a user account.

type CallerContext

type CallerContext struct {
	UserID string `json:"user_id"`
	Role   string `json:"role"`
	plugin.ExtraContainer
}

CallerContext carries identification, role, and metadata of the user initiating an administrative operation.

type CheckPermissionParams

type CheckPermissionParams struct {
	Caller      CallerContext `json:"caller"`
	Permissions Permissions   `json:"permissions"`
	Connector   Connector     `json:"connector,omitempty"`
}

CheckPermissionParams defines parameters for evaluating permission statements against a caller.

type Config

type Config struct {
	// DefaultRole is the default role assigned to users if none is specified (default: "user").
	DefaultRole string

	// AdminRoles is a list of roles considered to hold administrator privileges (default: ["admin"]).
	AdminRoles []string

	// AdminUserIDs is an explicit list of user IDs granted full administrative bypass access.
	AdminUserIDs []string

	// DefaultBanReason is the standard reason applied when suspending an account without a reason (default: "No reason provided").
	DefaultBanReason string

	// DefaultBanExpiresIn defines the default expiration duration for suspensions (default: 0, meaning permanent).
	DefaultBanExpiresIn time.Duration

	// ImpersonationSessionDuration defines the validity period for temporary impersonated sessions (default: 1 hour).
	ImpersonationSessionDuration time.Duration

	// BannedUserMessage is the user-facing message returned when a banned user attempts authentication.
	BannedUserMessage string

	// AllowImpersonatingAdmins specifies whether administrators can impersonate other administrators without explicit statement permission (default: false).
	AllowImpersonatingAdmins bool

	// MinPasswordLength is the minimum password length enforced by SetUserPassword (default: 8).
	MinPasswordLength int

	// MaxPasswordLength is the maximum allowed password length for SetUserPassword (default: 128).
	MaxPasswordLength int

	// Roles defines the complete dictionary of custom and built-in roles and statement permissions.
	Roles map[string]Role
}

Config contains runtime configuration parameters for the Admin plugin.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the recommended baseline configuration for the Admin plugin.

type Connector

type Connector string

Connector defines the logical evaluation operator for combining permission checks.

const (
	// ConnectorAND requires that all specified resource actions must be satisfied.
	ConnectorAND Connector = "AND"
	// ConnectorOR requires that at least one specified resource action must be satisfied.
	ConnectorOR Connector = "OR"
)

type CreateUserParams

type CreateUserParams struct {
	Caller   CallerContext `json:"caller"`
	Name     string        `json:"name"`
	Email    string        `json:"email"`
	Password string        `json:"password,omitempty"`
	Role     string        `json:"role,omitempty"`
	plugin.ExtraContainer
}

CreateUserParams defines payload requirements for administrative user provisioning.

type GetUserParams

type GetUserParams struct {
	Caller CallerContext `json:"caller"`
	UserID string        `json:"user_id"`
}

GetUserParams defines payload requirements for retrieving user details by ID.

type HasPermissionInput

type HasPermissionInput struct {
	UserID       string
	Role         string
	AdminUserIDs []string
	RolesConfig  map[string]Role
	DefaultRole  string
	Permissions  Permissions
	Connector    Connector
}

HasPermissionInput defines the parameters passed to HasPermission.

type ImpersonateResult

type ImpersonateResult struct {
	Session           *entity.Session `json:"session"`
	User              *entity.User    `json:"user"`
	AdminSessionToken string          `json:"admin_session_token,omitempty"`
}

ImpersonateResult contains the newly issued masquerade session and target user profile.

type ImpersonateUserParams

type ImpersonateUserParams struct {
	Caller    CallerContext  `json:"caller"`
	UserID    string         `json:"user_id"`
	IPAddress string         `json:"ip_address,omitempty"`
	UserAgent string         `json:"user_agent,omitempty"`
	Duration  *time.Duration `json:"duration,omitempty"`
}

ImpersonateUserParams defines parameters for initiating user impersonation.

type ImpersonationStoppedEventPayload

type ImpersonationStoppedEventPayload struct {
	AdminUserID  string `json:"admin_user_id"`
	TargetUserID string `json:"target_user_id"`
	SessionToken string `json:"session_token"`
	plugin.ExtraContainer
}

ImpersonationStoppedEventPayload is dispatched when an impersonation session is ended.

type ListUserSessionsParams

type ListUserSessionsParams struct {
	Caller CallerContext `json:"caller"`
	UserID string        `json:"user_id"`
}

ListUserSessionsParams defines parameters for listing active sessions of a user.

type ListUsersFilter

type ListUsersFilter struct {
	SearchValue    string `json:"search_value,omitempty"`    // Search query term
	SearchField    string `json:"search_field,omitempty"`    // Target field to search ("email", "name", etc.)
	SearchOperator string `json:"search_operator,omitempty"` // "contains", "starts_with", "ends_with", "exact"
	FilterField    string `json:"filter_field,omitempty"`    // Attribute field to filter by (e.g. "role", "banned")
	FilterOperator string `json:"filter_operator,omitempty"` // "eq", "ne", "in", etc.
	FilterValue    any    `json:"filter_value,omitempty"`    // Target value for the filter condition
	SortBy         string `json:"sort_by,omitempty"`         // Field to sort by ("created_at", "email", "name")
	SortDirection  string `json:"sort_direction,omitempty"`  // "asc" or "desc"
	Limit          int    `json:"limit,omitempty"`           // Number of records per page
	Offset         int    `json:"offset,omitempty"`          // Pagination offset
}

ListUsersFilter defines search, filter, sorting, and pagination criteria for user listings.

type ListUsersParams

type ListUsersParams struct {
	Caller CallerContext   `json:"caller"`
	Filter ListUsersFilter `json:"filter"`
}

ListUsersParams defines filtering and pagination parameters for user listings.

type ListUsersResult

type ListUsersResult struct {
	Users  []*entity.User `json:"users"`
	Total  int64          `json:"total"`
	Limit  int            `json:"limit"`
	Offset int            `json:"offset"`
}

ListUsersResult represents the paginated response containing user records and totals.

type Option

type Option func(*Config)

Option defines a functional configuration mutator for the Admin plugin.

func WithAdminRoles

func WithAdminRoles(roles ...string) Option

WithAdminRoles configures the role names recognized as administrators.

func WithAdminUserIDs

func WithAdminUserIDs(userIDs ...string) Option

WithAdminUserIDs configures specific user IDs that automatically bypass permission checks.

func WithAllowImpersonatingAdmins

func WithAllowImpersonatingAdmins(allow bool) Option

WithAllowImpersonatingAdmins configures whether admins can masquerade as other admins.

func WithBannedUserMessage

func WithBannedUserMessage(msg string) Option

WithBannedUserMessage sets the rejection message displayed to banned users.

func WithCustomRoles

func WithCustomRoles(roles map[string]Role) Option

WithCustomRoles replaces or configures the entire roles map.

func WithDefaultBanExpiresIn

func WithDefaultBanExpiresIn(d time.Duration) Option

WithDefaultBanExpiresIn sets the default expiration duration for account suspensions.

func WithDefaultBanReason

func WithDefaultBanReason(reason string) Option

WithDefaultBanReason sets the fallback reason string when suspending users.

func WithDefaultRole

func WithDefaultRole(role string) Option

WithDefaultRole sets the default role for users when unassigned.

func WithImpersonationSessionDuration

func WithImpersonationSessionDuration(d time.Duration) Option

WithImpersonationSessionDuration configures the expiration duration of temporary masquerade sessions.

func WithPasswordLength

func WithPasswordLength(minLen, maxLen int) Option

WithPasswordLength configures minimum and maximum password length limits for administrative password setting.

func WithRole

func WithRole(role Role) Option

WithRole registers or overrides an individual role in the plugin configuration.

type Permissions

type Permissions map[string][]string

Permissions represents the set of permissions required to perform an administrative operation.

type Plugin

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

Plugin provides governance, role-based access control (RBAC), user moderation, and session impersonation.

func New

func New(repo Repository, opts ...Option) *Plugin

New creates a new Admin plugin instance configured with a repository and functional options.

func (*Plugin) BanUser

func (p *Plugin) BanUser(ctx context.Context, params BanUserParams) (*entity.User, error)

BanUser suspends a user account and immediately invalidates all active sessions.

func (*Plugin) CheckPermission

func (p *Plugin) CheckPermission(ctx context.Context, params CheckPermissionParams) (bool, error)

CheckPermission evaluates whether the caller satisfies the provided permission matrix.

func (*Plugin) CheckUserBanStatus

func (p *Plugin) CheckUserBanStatus(ctx context.Context, user *entity.User) error

CheckUserBanStatus is a moderation hook for authentication and session verification workflows. If the user is currently suspended and the suspension period has expired, it automatically lifts the suspension. If the suspension remains active or is permanent, it returns ErrUserBanned.

func (*Plugin) Config

func (p *Plugin) Config() Config

Config returns the active configuration settings of the Admin plugin.

func (*Plugin) CreateUser

func (p *Plugin) CreateUser(ctx context.Context, params CreateUserParams) (*entity.User, error)

CreateUser provisions a new user record with optional password hashing and role assignment.

func (*Plugin) GetUser

func (p *Plugin) GetUser(ctx context.Context, params GetUserParams) (*entity.User, error)

GetUser retrieves a user profile by ID after verifying administrative access.

func (*Plugin) ID

func (p *Plugin) ID() string

ID returns the unique string identifier for the Admin plugin ("admin").

func (*Plugin) ImpersonateUser

func (p *Plugin) ImpersonateUser(ctx context.Context, params ImpersonateUserParams) (*ImpersonateResult, error)

ImpersonateUser generates a temporary session masquerading as the target user.

func (*Plugin) Init

func (p *Plugin) Init(ctx *plugin.Context) error

Init initializes the plugin within the global GoModularAuth runtime context.

func (*Plugin) ListUserSessions

func (p *Plugin) ListUserSessions(ctx context.Context, params ListUserSessionsParams) ([]*entity.Session, error)

ListUserSessions retrieves all active authentication sessions for a given user.

func (*Plugin) ListUsers

func (p *Plugin) ListUsers(ctx context.Context, params ListUsersParams) (*ListUsersResult, error)

ListUsers returns a filtered and paginated list of user accounts.

func (*Plugin) RemoveUser

func (p *Plugin) RemoveUser(ctx context.Context, params RemoveUserParams) error

RemoveUser permanently removes a user and terminates their active sessions.

func (*Plugin) Repository

func (p *Plugin) Repository() Repository

Repository returns the underlying storage repository instance.

func (*Plugin) RequireAdmin added in v0.20.0

func (p *Plugin) RequireAdmin() func(next http.Handler) http.Handler

RequireAdmin returns a standard net/http middleware handler requiring the caller to possess an administrator role or ID.

func (*Plugin) RequirePermission added in v0.20.0

func (p *Plugin) RequirePermission(permissions Permissions, connector ...Connector) func(next http.Handler) http.Handler

RequirePermission returns a standard net/http middleware handler verifying administrative permissions for incoming requests.

func (*Plugin) RevokeUserSession

func (p *Plugin) RevokeUserSession(ctx context.Context, params RevokeUserSessionParams) error

RevokeUserSession invalidates a specific active session.

func (*Plugin) RevokeUserSessions

func (p *Plugin) RevokeUserSessions(ctx context.Context, params RevokeUserSessionsParams) error

RevokeUserSessions invalidates all active sessions belonging to the given user.

func (*Plugin) SetRole

func (p *Plugin) SetRole(ctx context.Context, params SetRoleParams) (*entity.User, error)

SetRole updates the assigned role for a user account.

func (*Plugin) SetUserPassword

func (p *Plugin) SetUserPassword(ctx context.Context, params SetUserPasswordParams) error

SetUserPassword directly overwrites a user's credential password with length constraint checks.

func (*Plugin) StopImpersonating

func (p *Plugin) StopImpersonating(ctx context.Context, params StopImpersonatingParams) (*StopImpersonatingResult, error)

StopImpersonating invalidates the masquerade session and returns the original administrator details.

func (*Plugin) UnbanUser

func (p *Plugin) UnbanUser(ctx context.Context, params UnbanUserParams) (*entity.User, error)

UnbanUser lifts an account suspension and restores access.

func (*Plugin) UpdateUser

func (p *Plugin) UpdateUser(ctx context.Context, params UpdateUserParams) (*entity.User, error)

UpdateUser modifies specified properties on an existing user account.

type RemoveUserParams

type RemoveUserParams struct {
	Caller CallerContext `json:"caller"`
	UserID string        `json:"user_id"`
}

RemoveUserParams defines parameters for permanently removing a user account.

type Repository

type Repository interface {
	// GetUserByID retrieves a user entity matching the provided unique identifier.
	//
	// Function:
	//   Used during admin user detail lookup, role updates, and account ban/unban checks.
	//
	// Storage:
	//   Database (GORM / SQL) - Relational user entity query by primary key.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - id: Unique primary key identifier of the user.
	//
	// Returns:
	//   - *entity.User: Matching user profile.
	//   - error: ErrUserNotFound if missing.
	//
	// Example SQL:
	//   SELECT id, name, email, email_verified, two_factor_enabled, role, banned, ban_reason, ban_expires, created_at, updated_at FROM users WHERE id = $1 LIMIT 1;
	GetUserByID(ctx context.Context, id string) (*entity.User, error)

	// GetUserByEmail retrieves a user entity matching the provided normalized email address.
	//
	// Function:
	//   Used in user search or when checking duplicate email existence during admin user creation.
	//
	// Storage:
	//   Database (GORM / SQL) - Query user by normalized email.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - email: Normalized email address string.
	//
	// Returns:
	//   - *entity.User: Matching user profile.
	//   - error: ErrUserNotFound if missing.
	//
	// Example SQL:
	//   SELECT id, name, email, email_verified, two_factor_enabled, role, banned, ban_reason, ban_expires, created_at, updated_at FROM users WHERE LOWER(email) = LOWER($1) LIMIT 1;
	GetUserByEmail(ctx context.Context, email string) (*entity.User, error)

	// CreateUser persists a newly created user entity in storage.
	//
	// Function:
	//   Called by administrators creating accounts directly via the administrative portal.
	//
	// Storage:
	//   Database (GORM / SQL) - User domain entity creation.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - params: Parameters for creating a user.
	//
	// Returns:
	//   - *entity.User: Newly created user record.
	//   - error: ErrUserAlreadyExists on email conflict.
	//
	// Example SQL:
	//   INSERT INTO users (id, name, email, role, banned, ban_reason, ban_expires, email_verified, two_factor_enabled, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11);
	CreateUser(ctx context.Context, params *dto.CreateUserParams) (*entity.User, error)

	// UpdateUser updates modified fields of an existing user profile in storage.
	//
	// Function:
	//   Used when setting roles, banning/unbanning users, or updating profile attributes.
	//
	// Storage:
	//   Database (GORM / SQL) - Relational user table update.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - user: Modified User domain entity.
	//
	// Returns:
	//   - error: Nil on success.
	//
	// Example SQL:
	//   UPDATE users SET name = $1, email = $2, role = $3, banned = $4, ban_reason = $5, ban_expires = $6, email_verified = $7, updated_at = $8 WHERE id = $9;
	UpdateUser(ctx context.Context, user *entity.User) error

	// DeleteUser removes a user record and their related accounts and credentials from storage.
	//
	// Function:
	//   Called when an administrator permanently deletes a user account.
	//
	// Storage:
	//   Database (GORM / SQL) - Relational user record deletion.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - id: Target user primary key ID.
	//
	// Returns:
	//   - error: Nil on success.
	//
	// Example SQL:
	//   DELETE FROM users WHERE id = $1;
	DeleteUser(ctx context.Context, id string) error

	// ListUsers returns a paginated and filtered list of user records matching search filter criteria.
	//
	// Function:
	//   Used by admin dashboard user management tables.
	//
	// Storage:
	//   Database (GORM / SQL) - Paginated relational query with search and filters.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - filter: ListUsersFilter defining search terms, filters, sorting, and pagination parameters.
	//
	// Returns:
	//   - []*entity.User: Slice of matching user entities.
	//   - int64: Total total matching record count.
	//   - error: Nil on success.
	//
	// Example SQL:
	//   SELECT id, name, email, role, banned, ban_reason, ban_expires, email_verified, created_at, updated_at FROM users WHERE email ILIKE '%' || $1 || '%' ORDER BY created_at DESC LIMIT $2 OFFSET $3;
	ListUsers(ctx context.Context, filter ListUsersFilter) ([]*entity.User, int64, error)

	// LinkCredentialAccount links or updates provider credential password hashes for a user.
	//
	// Function:
	//   Called when an admin resets or assigns a new password to a user account.
	//
	// Storage:
	//   Database (GORM / SQL) - Credential account update or insert.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - userID: Target user ID.
	//   - passwordHash: New hashed password.
	//
	// Returns:
	//   - error: Nil on success.
	//
	// Example SQL:
	//   INSERT INTO accounts (id, user_id, provider_id, password_hash, created_at, updated_at) VALUES ($1, $2, 'credential', $3, $4, $5) ON CONFLICT (user_id, provider_id) DO UPDATE SET password_hash = $3, updated_at = $5;
	LinkCredentialAccount(ctx context.Context, userID, passwordHash string) error

	// CreateSession persists a new session entity (supporting impersonation tracking).
	//
	// Function:
	//   Called during impersonation flows when an administrator impersonates a target user.
	//
	// Storage:
	//   Database (GORM / SQL) - Active session creation.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - session: DTO for session creation.
	//
	// Returns:
	//   - *entity.Session: Active session entity.
	//   - error: Nil on success.
	//
	// Example SQL:
	//   INSERT INTO sessions (id, user_id, token, expires_at, ip_address, user_agent, impersonated_by, created_at, updated_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
	CreateSession(ctx context.Context, session *dto.CreateSessionParams) (*entity.Session, error)

	// GetSessionByToken retrieves an active session by its raw token string.
	//
	// Function:
	//   Used during impersonation verification and stop-impersonation flows.
	//
	// Storage:
	//   Both (Cache-Aside Strategy) - Cached in Redis (`session:<token>`) for fast session validation.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - token: Session token string.
	//
	// Returns:
	//   - *entity.Session: Session entity.
	//   - error: ErrAdminSessionNotFound if missing.
	//
	// Example SQL:
	//   SELECT id, user_id, token, expires_at, ip_address, user_agent, impersonated_by, created_at, updated_at FROM sessions WHERE token = $1 LIMIT 1;
	//
	// Example Cache (Redis):
	//   val, err := rdb.Get(ctx, "session:" + token).Bytes()
	GetSessionByToken(ctx context.Context, token string) (*entity.Session, error)

	// ListSessionsByUserID lists all active sessions belonging to the specified user.
	//
	// Function:
	//   Used in admin user session management panels.
	//
	// Storage:
	//   Database (GORM / SQL) - Relational user session list query.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - userID: Target user ID.
	//
	// Returns:
	//   - []*entity.Session: List of active sessions.
	//   - error: Nil on success.
	//
	// Example SQL:
	//   SELECT id, user_id, token, expires_at, ip_address, user_agent, impersonated_by, created_at, updated_at FROM sessions WHERE user_id = $1;
	ListSessionsByUserID(ctx context.Context, userID string) ([]*entity.Session, error)

	// DeleteSession deletes a specific session by token.
	//
	// Function:
	//   Called when an admin revokes a single session.
	//
	// Storage:
	//   Database (GORM / SQL) - Session record deletion.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - token: Target session token string.
	//
	// Returns:
	//   - error: Nil on success.
	//
	// Example SQL:
	//   DELETE FROM sessions WHERE token = $1;
	DeleteSession(ctx context.Context, token string) error

	// DeleteSessionsByUserID deletes all active sessions belonging to a user.
	//
	// Function:
	//   Used during account bans, security locks, and global session revocation.
	//
	// Storage:
	//   Database (GORM / SQL) - Bulk user session deletion.
	//
	// Arguments:
	//   - ctx: Request cancellation context.
	//   - userID: Target user ID.
	//
	// Returns:
	//   - error: Nil on success.
	//
	// Example SQL:
	//   DELETE FROM sessions WHERE user_id = $1;
	DeleteSessionsByUserID(ctx context.Context, userID string) error
}

Repository defines the persistent storage contract required by the Admin plugin. Implement this interface on your custom database adapter (e.g. PostgreSQL, MySQL, SQLite, MongoDB, GORM).

Implementation Example (GORM / database/sql):

type GormAdminRepository struct {
	db *gorm.DB
}

func (r *GormAdminRepository) GetUserByID(ctx context.Context, id string) (*entity.User, error) {
	var u entity.User
	if err := r.db.WithContext(ctx).Where("id = ?", id).First(&u).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, admin.ErrUserNotFound
		}
		return nil, err
	}
	return &u, nil
}

type RevokeUserSessionParams

type RevokeUserSessionParams struct {
	Caller       CallerContext `json:"caller"`
	SessionToken string        `json:"session_token"`
}

RevokeUserSessionParams defines parameters for invalidating a specific session token.

type RevokeUserSessionsParams

type RevokeUserSessionsParams struct {
	Caller CallerContext `json:"caller"`
	UserID string        `json:"user_id"`
}

RevokeUserSessionsParams defines parameters for invalidating all active sessions of a user.

type Role

type Role struct {
	Name       string     `json:"name"`
	Statements Statements `json:"statements"`
}

Role represents a named role definition paired with its granted statements.

func (*Role) Authorize

func (r *Role) Authorize(requested Permissions, connector Connector) AuthorizeResult

Authorize evaluates whether the role satisfies the requested permissions.

type SessionRevokedEventPayload

type SessionRevokedEventPayload struct {
	CallerID     string `json:"caller_id"`
	CallerRole   string `json:"caller_role"`
	SessionToken string `json:"session_token"`
	plugin.ExtraContainer
}

SessionRevokedEventPayload is dispatched when a specific session is invalidated.

type SetRoleParams

type SetRoleParams struct {
	Caller CallerContext `json:"caller"`
	UserID string        `json:"user_id"`
	Role   string        `json:"role"`
}

SetRoleParams defines parameters for assigning a new role to a user.

type SetUserPasswordParams

type SetUserPasswordParams struct {
	Caller      CallerContext `json:"caller"`
	UserID      string        `json:"user_id"`
	NewPassword string        `json:"new_password"`
}

SetUserPasswordParams defines parameters for setting a new password on a user account.

type Statements

type Statements map[string][]string

Statements defines the actions permitted per resource for a role. Example: map[string][]string{"user": {"create", "list", "ban"}, "session": {"list", "revoke"}}

func CloneStatements

func CloneStatements(s Statements) Statements

CloneStatements creates a deep copy of a Statements map.

func MergeStatements

func MergeStatements(dst, src Statements) Statements

MergeStatements combines source statements into destination statements without duplicates.

type StopImpersonatingParams

type StopImpersonatingParams struct {
	ImpersonatedSessionToken string `json:"impersonated_session_token"`
	AdminSessionToken        string `json:"admin_session_token,omitempty"`
}

StopImpersonatingParams defines tokens required to terminate an impersonation session.

type StopImpersonatingResult

type StopImpersonatingResult struct {
	AdminSession *entity.Session `json:"admin_session,omitempty"`
	AdminUser    *entity.User    `json:"admin_user"`
}

StopImpersonatingResult contains the restored administrator session and profile.

type UnbanUserParams

type UnbanUserParams struct {
	Caller CallerContext `json:"caller"`
	UserID string        `json:"user_id"`
}

UnbanUserParams defines parameters for lifting a suspension from a user account.

type UpdateUserParams

type UpdateUserParams struct {
	Caller        CallerContext `json:"caller"`
	UserID        string        `json:"user_id"`
	Name          *string       `json:"name,omitempty"`
	Email         *string       `json:"email,omitempty"`
	EmailVerified *bool         `json:"email_verified,omitempty"`
	Role          *string       `json:"role,omitempty"`
	Banned        *bool         `json:"banned,omitempty"`
	BanReason     *string       `json:"ban_reason,omitempty"`
	BanExpires    *time.Time    `json:"ban_expires,omitempty"`
	plugin.ExtraContainer
}

UpdateUserParams defines partial update fields for an existing user account.

type UserBannedEventPayload

type UserBannedEventPayload struct {
	CallerID   string       `json:"caller_id"`
	CallerRole string       `json:"caller_role"`
	UserID     string       `json:"user_id"`
	BanReason  string       `json:"ban_reason"`
	BanExpires *time.Time   `json:"ban_expires,omitempty"`
	User       *entity.User `json:"user"`
	plugin.ExtraContainer
}

UserBannedEventPayload is dispatched when a user account is suspended.

type UserCreatedEventPayload

type UserCreatedEventPayload struct {
	CallerID   string       `json:"caller_id"`
	CallerRole string       `json:"caller_role"`
	User       *entity.User `json:"user"`
	plugin.ExtraContainer
}

UserCreatedEventPayload is dispatched when a new user is provisioned by an administrator.

type UserDeletedEventPayload

type UserDeletedEventPayload struct {
	CallerID   string `json:"caller_id"`
	CallerRole string `json:"caller_role"`
	UserID     string `json:"user_id"`
	plugin.ExtraContainer
}

UserDeletedEventPayload is dispatched when a user account is deleted by an administrator.

type UserImpersonatedEventPayload

type UserImpersonatedEventPayload struct {
	CallerID     string          `json:"caller_id"`
	CallerRole   string          `json:"caller_role"`
	TargetUserID string          `json:"target_user_id"`
	Session      *entity.Session `json:"session"`
	plugin.ExtraContainer
}

UserImpersonatedEventPayload is dispatched when an administrator begins masquerading as a user.

type UserPasswordChangedEventPayload

type UserPasswordChangedEventPayload struct {
	CallerID   string `json:"caller_id"`
	CallerRole string `json:"caller_role"`
	UserID     string `json:"user_id"`
	plugin.ExtraContainer
}

UserPasswordChangedEventPayload is dispatched when an administrator changes a user's password.

type UserRoleChangedEventPayload

type UserRoleChangedEventPayload struct {
	CallerID   string       `json:"caller_id"`
	CallerRole string       `json:"caller_role"`
	UserID     string       `json:"user_id"`
	OldRole    string       `json:"old_role"`
	NewRole    string       `json:"new_role"`
	User       *entity.User `json:"user"`
	plugin.ExtraContainer
}

UserRoleChangedEventPayload is dispatched when a user's role assignment is modified.

type UserUnbannedEventPayload

type UserUnbannedEventPayload struct {
	CallerID   string       `json:"caller_id"`
	CallerRole string       `json:"caller_role"`
	UserID     string       `json:"user_id"`
	User       *entity.User `json:"user"`
	plugin.ExtraContainer
}

UserUnbannedEventPayload is dispatched when a suspension is lifted from a user.

type UserUpdatedEventPayload

type UserUpdatedEventPayload struct {
	CallerID   string       `json:"caller_id"`
	CallerRole string       `json:"caller_role"`
	User       *entity.User `json:"user"`
	plugin.ExtraContainer
}

UserUpdatedEventPayload is dispatched when an administrator updates a user record.

Jump to

Keyboard shortcuts

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