Documentation
¶
Index ¶
- Constants
- Variables
- func CheckActionGranted(granted Statements, resource, action string) bool
- func DefaultRoles() map[string]Role
- func EvaluateStatements(granted Statements, requested Permissions, connector Connector) bool
- func HasAction(actions []string, targetAction string) bool
- func HasPermission(input HasPermissionInput) bool
- type AccessControl
- type AllSessionsRevokedEventPayload
- type AuthorizeResult
- type BanUserParams
- type CallerContext
- type CheckPermissionParams
- type Config
- type Connector
- type CreateUserParams
- type GetUserParams
- type HasPermissionInput
- type ImpersonateResult
- type ImpersonateUserParams
- type ImpersonationStoppedEventPayload
- type ListUserSessionsParams
- type ListUsersFilter
- type ListUsersParams
- type ListUsersResult
- type Option
- func WithAdminRoles(roles ...string) Option
- func WithAdminUserIDs(userIDs ...string) Option
- func WithAllowImpersonatingAdmins(allow bool) Option
- func WithBannedUserMessage(msg string) Option
- func WithCustomRoles(roles map[string]Role) Option
- func WithDefaultBanExpiresIn(d time.Duration) Option
- func WithDefaultBanReason(reason string) Option
- func WithDefaultRole(role string) Option
- func WithImpersonationSessionDuration(d time.Duration) Option
- func WithPasswordLength(minLen, maxLen int) Option
- func WithRole(role Role) Option
- type Permissions
- type Plugin
- func (p *Plugin) BanUser(ctx context.Context, params BanUserParams) (*entity.User, error)
- func (p *Plugin) CheckPermission(ctx context.Context, params CheckPermissionParams) (bool, error)
- func (p *Plugin) CheckUserBanStatus(ctx context.Context, user *entity.User) error
- func (p *Plugin) Config() Config
- func (p *Plugin) CreateUser(ctx context.Context, params CreateUserParams) (*entity.User, error)
- func (p *Plugin) GetUser(ctx context.Context, params GetUserParams) (*entity.User, error)
- func (p *Plugin) ID() string
- func (p *Plugin) ImpersonateUser(ctx context.Context, params ImpersonateUserParams) (*ImpersonateResult, error)
- func (p *Plugin) Init(ctx *plugin.Context) error
- func (p *Plugin) ListUserSessions(ctx context.Context, params ListUserSessionsParams) ([]*entity.Session, error)
- func (p *Plugin) ListUsers(ctx context.Context, params ListUsersParams) (*ListUsersResult, error)
- func (p *Plugin) RemoveUser(ctx context.Context, params RemoveUserParams) error
- func (p *Plugin) Repository() Repository
- func (p *Plugin) RequireAdmin() func(next http.Handler) http.Handler
- func (p *Plugin) RequirePermission(permissions Permissions, connector ...Connector) func(next http.Handler) http.Handler
- func (p *Plugin) RevokeUserSession(ctx context.Context, params RevokeUserSessionParams) error
- func (p *Plugin) RevokeUserSessions(ctx context.Context, params RevokeUserSessionsParams) error
- func (p *Plugin) SetRole(ctx context.Context, params SetRoleParams) (*entity.User, error)
- func (p *Plugin) SetUserPassword(ctx context.Context, params SetUserPasswordParams) error
- func (p *Plugin) StopImpersonating(ctx context.Context, params StopImpersonatingParams) (*StopImpersonatingResult, error)
- func (p *Plugin) UnbanUser(ctx context.Context, params UnbanUserParams) (*entity.User, error)
- func (p *Plugin) UpdateUser(ctx context.Context, params UpdateUserParams) (*entity.User, error)
- type RemoveUserParams
- type Repository
- type RevokeUserSessionParams
- type RevokeUserSessionsParams
- type Role
- type SessionRevokedEventPayload
- type SetRoleParams
- type SetUserPasswordParams
- type Statements
- type StopImpersonatingParams
- type StopImpersonatingResult
- type UnbanUserParams
- type UpdateUserParams
- type UserBannedEventPayload
- type UserCreatedEventPayload
- type UserDeletedEventPayload
- type UserImpersonatedEventPayload
- type UserPasswordChangedEventPayload
- type UserRoleChangedEventPayload
- type UserUnbannedEventPayload
- type UserUpdatedEventPayload
Constants ¶
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.
const ( RoleAdmin = "admin" RoleUser = "user" )
Standard role constants.
const ( ResourceUser = "user" ResourceSession = "session" )
Standard access control resources.
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.
const ( ActionSessionList = "list" ActionSessionRevoke = "revoke" ActionSessionDelete = "delete" )
Standard actions for the 'session' resource.
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.
const (
CallerContextKey contextKey = "admin_caller"
)
const PluginID = "admin"
PluginID is the unique string identifier for the Admin plugin ("admin").
Variables ¶
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 = 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 ¶
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 ¶
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 ¶
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.
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 ¶
WithAdminRoles configures the role names recognized as administrators.
func WithAdminUserIDs ¶
WithAdminUserIDs configures specific user IDs that automatically bypass permission checks.
func WithAllowImpersonatingAdmins ¶
WithAllowImpersonatingAdmins configures whether admins can masquerade as other admins.
func WithBannedUserMessage ¶
WithBannedUserMessage sets the rejection message displayed to banned users.
func WithCustomRoles ¶
WithCustomRoles replaces or configures the entire roles map.
func WithDefaultBanExpiresIn ¶
WithDefaultBanExpiresIn sets the default expiration duration for account suspensions.
func WithDefaultBanReason ¶
WithDefaultBanReason sets the fallback reason string when suspending users.
func WithDefaultRole ¶
WithDefaultRole sets the default role for users when unassigned.
func WithImpersonationSessionDuration ¶
WithImpersonationSessionDuration configures the expiration duration of temporary masquerade sessions.
func WithPasswordLength ¶
WithPasswordLength configures minimum and maximum password length limits for administrative password setting.
type Permissions ¶
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 ¶
BanUser suspends a user account and immediately invalidates all active sessions.
func (*Plugin) CheckPermission ¶
CheckPermission evaluates whether the caller satisfies the provided permission matrix.
func (*Plugin) CheckUserBanStatus ¶
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) CreateUser ¶
CreateUser provisions a new user record with optional password hashing and role assignment.
func (*Plugin) GetUser ¶
GetUser retrieves a user profile by ID after verifying administrative access.
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) 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
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) 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) UpdateUser ¶
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 ¶
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.