admin

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package admin provides admin functionality for Kuta authentication.

The admin plugin adds role-based access control, user management, ban functionality, and session management capabilities for administrators.

Features:

  • Role management (set user roles)
  • User management (create, list, get, update, delete users)
  • Ban system (ban/unban users with optional expiration)
  • Session management (list, revoke user sessions)
  • Password management (set user passwords)
  • Permission-based access control

Usage:

k, err := kuta.New(kuta.Config{
    Secret:   "secretshouldbeatleast32charslong",
    Database: pgxadapter.New(pool),
    HTTP:     fiberadapter.New(app),
    Plugins: []kuta.Plugin{
        admin.New(admin.DefaultConfig()),
    },
})

See the Config type for configuration options.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Permission errors
	ErrNotAuthorized              = errors.New("not authorized")
	ErrNotAllowedToSetRole        = errors.New("you are not allowed to change user roles")
	ErrNotAllowedToCreateUser     = errors.New("you are not allowed to create users")
	ErrNotAllowedToListUsers      = errors.New("you are not allowed to list users")
	ErrNotAllowedToGetUser        = errors.New("you are not allowed to get user")
	ErrNotAllowedToUpdateUser     = errors.New("you are not allowed to update users")
	ErrNotAllowedToDeleteUser     = errors.New("you are not allowed to delete users")
	ErrNotAllowedToBanUser        = errors.New("you are not allowed to ban users")
	ErrNotAllowedToSetPassword    = errors.New("you are not allowed to set user passwords")
	ErrNotAllowedToListSessions   = errors.New("you are not allowed to list user sessions")
	ErrNotAllowedToRevokeSessions = errors.New("you are not allowed to revoke user sessions")
	ErrNotAllowedToImpersonate    = errors.New("you are not allowed to impersonate users")

	// Ban errors
	ErrUserBanned       = errors.New("user is banned")
	ErrCannotBanSelf    = errors.New("you cannot ban yourself")
	ErrCannotDeleteSelf = errors.New("you cannot delete yourself")

	// Role errors
	ErrInvalidRole      = errors.New("invalid role")
	ErrRoleDoesNotExist = errors.New("role does not exist")

	// Impersonation errors
	ErrNotImpersonating     = errors.New("you are not impersonating anyone")
	ErrImpersonationFailed  = errors.New("impersonation failed")
	ErrAdminSessionNotFound = errors.New("admin session not found")

	// General errors
	ErrNoDataToUpdate = errors.New("no data to update")
)

Admin plugin errors

Functions

func DefaultRoles

func DefaultRoles() map[string]*Role

DefaultRoles returns the default role configuration

Types

type AdminPlugin

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

AdminPlugin wraps the admin service and implements core.Plugin

func New

func New(config Config) *AdminPlugin

New creates a new admin plugin with the given configuration

func (*AdminPlugin) Endpoints

func (p *AdminPlugin) Endpoints() []core.PluginEndpoint

Endpoints returns all admin HTTP endpoints. Each handler is self-contained — no adapter-specific code needed.

func (*AdminPlugin) ID

func (p *AdminPlugin) ID() string

ID returns the plugin identifier

func (*AdminPlugin) Init

func (p *AdminPlugin) Init(deps core.PluginDependencies) error

Init initializes the admin plugin with core dependencies

func (*AdminPlugin) Service

func (p *AdminPlugin) Service() *Service

Service returns the initialized admin service This should only be called after Init()

type AdminSessionStorage

type AdminSessionStorage interface {
	// Create session with impersonation info
	CreateImpersonationSession(session *SessionWithImpersonation) (string, error)

	// Get session with impersonation info
	GetSessionWithImpersonation(tokenHash string) (*SessionWithImpersonation, error)
}

AdminSessionStorage extends session storage with admin-specific operations

type AdminStorageProvider

type AdminStorageProvider interface {
	core.StorageProvider
	AdminUserStorage
	AdminSessionStorage
}

AdminStorageProvider combines all admin storage requirements

type AdminUserStorage

type AdminUserStorage interface {
	// Extend user with role/ban fields
	GetUserWithRole(id string) (*UserWithRole, error)
	GetUserWithRoleByEmail(email string) (*UserWithRole, error)

	// Role management
	SetUserRole(userID string, role string) error

	// Ban management
	BanUser(userID string, reason string, expiresAt *time.Time) error
	UnbanUser(userID string) error
	IsBanned(userID string) (bool, *time.Time, error) // Returns banned status and expiry

	// User listing
	ListUsers(opts ListUsersInput) (*ListUsersResult, error)
	CountUsers(opts ListUsersInput) (int, error)

	// Admin user creation (with role)
	CreateUserWithRole(user *UserWithRole, password string) error

	// Update user with arbitrary fields
	UpdateUserFields(userID string, fields map[string]any) error
}

AdminUserStorage extends user storage with admin-specific operations

type BanUserInput

type BanUserInput struct {
	UserID     string         `json:"userId"`
	Reason     string         `json:"reason,omitempty"`
	ExpiresIn  *time.Duration `json:"expiresIn,omitempty"` // Duration until ban expires
	BanExpires *time.Time     `json:"banExpires,omitempty"`
}

BanUserInput is the input for banning a user

type Config

type Config struct {
	// DefaultRole is assigned to new users (default: "user")
	DefaultRole string

	// AdminRoles are roles that have admin privileges (default: ["admin"])
	AdminRoles []string

	// AdminUserIDs is a list of user IDs that always have admin access
	// This bypasses role checks
	AdminUserIDs []string

	// DefaultBanReason is used when no reason is provided
	DefaultBanReason string

	// DefaultBanDuration is used when no duration is provided (0 = permanent)
	DefaultBanDuration time.Duration

	// ImpersonationDuration is how long an impersonation session lasts (default: 1 hour)
	ImpersonationDuration time.Duration

	// BannedUserMessage is shown when a banned user tries to sign in
	BannedUserMessage string

	// Roles defines custom roles and their permissions
	Roles map[string]*Role
}

Config options for the admin plugin

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default admin configuration

type CreateUserInput

type CreateUserInput struct {
	Email    string         `json:"email"`
	Password string         `json:"password"`
	Name     string         `json:"name"`
	Role     string         `json:"role,omitempty"`
	Data     map[string]any `json:"data,omitempty"` // Extra fields
}

CreateUserInput is the input for admin user creation

type ImpersonateResult

type ImpersonateResult struct {
	Session *SessionWithImpersonation `json:"session"`
	User    *UserWithRole             `json:"user"`
	Token   string                    `json:"token"`
}

ImpersonateResult is the result of impersonating a user

type ListUsersInput

type ListUsersInput struct {
	Limit          int    `json:"limit,omitempty"`
	Offset         int    `json:"offset,omitempty"`
	SortBy         string `json:"sortBy,omitempty"`
	SortDirection  string `json:"sortDirection,omitempty"` // "asc" or "desc"
	SearchValue    string `json:"searchValue,omitempty"`
	SearchField    string `json:"searchField,omitempty"` // "email" or "name"
	FilterField    string `json:"filterField,omitempty"`
	FilterValue    string `json:"filterValue,omitempty"`
	FilterOperator string `json:"filterOperator,omitempty"` // "eq", "ne", "contains"
}

ListUsersInput is the input for listing users

type ListUsersResult

type ListUsersResult struct {
	Users  []*UserWithRole `json:"users"`
	Total  int             `json:"total"`
	Limit  int             `json:"limit,omitempty"`
	Offset int             `json:"offset,omitempty"`
}

ListUsersResult is the result of listing users

type PermissionChecker

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

PermissionChecker handles permission verification for admin operations

func NewPermissionChecker

func NewPermissionChecker(config *Config) *PermissionChecker

NewPermissionChecker creates a new permission checker

func (*PermissionChecker) CanPerform

func (p *PermissionChecker) CanPerform(userID, role, resource, action string) bool

CanPerform is a convenience method that checks a single permission

func (*PermissionChecker) HasPermission

func (p *PermissionChecker) HasPermission(userID, role string, permissions Permissions) bool

HasPermission checks if a user has the required permissions

func (*PermissionChecker) IsAdminRole

func (p *PermissionChecker) IsAdminRole(role string) bool

IsAdminRole checks if the given role is an admin role

type Permissions

type Permissions map[string][]string

Permissions defines what actions can be performed on resources

type Role

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

Role represents a set of permissions

func NewRole

func NewRole(name string, permissions map[string][]string) *Role

NewRole creates a new role with the given name and permissions

func (*Role) Authorize

func (r *Role) Authorize(permissions map[string][]string) bool

Authorize checks if the role has all required permissions

func (*Role) HasPermission

func (r *Role) HasPermission(resource, action string) bool

HasPermission checks if the role has a specific permission

type Service

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

Service provides admin functionality

func NewService

func NewService(
	config Config,
	storage AdminStorageProvider,
	passwords crypto.PasswordHandler,
	sessions core.AuthProvider,
) *Service

NewService creates a new admin service

func (*Service) BanUser

func (s *Service) BanUser(actorID, actorRole string, input BanUserInput) (*UserWithRole, error)

BanUser bans a user (requires "user:ban" permission)

func (*Service) CheckBanStatus

func (s *Service) CheckBanStatus(userID string) error

CheckBanStatus checks if a user is banned (and clears expired bans) This is called during sign-in to prevent banned users from authenticating

func (*Service) Config

func (s *Service) Config() Config

Config returns the service configuration (for handlers)

func (*Service) CreateUser

func (s *Service) CreateUser(actorID, actorRole string, input CreateUserInput) (*UserWithRole, error)

CreateUser creates a new user (requires "user:create" permission)

func (*Service) DeleteUser

func (s *Service) DeleteUser(actorID, actorRole, targetUserID string) error

DeleteUser deletes a user (requires "user:delete" permission)

func (*Service) GetUser

func (s *Service) GetUser(actorID, actorRole, targetUserID string) (*UserWithRole, error)

GetUser gets a user by ID (requires "user:get" permission)

func (*Service) ListUserSessions

func (s *Service) ListUserSessions(actorID, actorRole, targetUserID string) ([]*core.Session, error)

ListUserSessions lists a user's sessions (requires "session:list" permission)

func (*Service) ListUsers

func (s *Service) ListUsers(actorID, actorRole string, input ListUsersInput) (*ListUsersResult, error)

ListUsers lists users with pagination (requires "user:list" permission)

func (*Service) Permissions

func (s *Service) Permissions() *PermissionChecker

Permissions returns the permission checker (for handlers)

func (*Service) RevokeSession

func (s *Service) RevokeSession(actorID, actorRole, sessionID string) error

RevokeSession revokes a specific session (requires "session:revoke" permission)

func (*Service) RevokeUserSessions

func (s *Service) RevokeUserSessions(actorID, actorRole, targetUserID string) (int, error)

RevokeUserSessions revokes all sessions for a user (requires "session:revoke" permission)

func (*Service) SetRole

func (s *Service) SetRole(actorID, actorRole string, input SetRoleInput) (*UserWithRole, error)

SetRole sets a user's role (requires "user:set-role" permission)

func (*Service) SetUserPassword

func (s *Service) SetUserPassword(actorID, actorRole, targetUserID, newPassword string) error

SetUserPassword sets a user's password (requires "user:set-password" permission)

func (*Service) UnbanUser

func (s *Service) UnbanUser(actorID, actorRole, targetUserID string) (*UserWithRole, error)

UnbanUser unbans a user (requires "user:ban" permission)

func (*Service) UpdateUser

func (s *Service) UpdateUser(actorID, actorRole string, input UpdateUserInput) (*UserWithRole, error)

UpdateUser updates a user's fields (requires "user:update" permission)

type SessionWithImpersonation

type SessionWithImpersonation struct {
	core.Session
	ImpersonatedBy *string `json:"impersonatedBy,omitempty"`
}

SessionWithImpersonation extends Session with impersonation info

type SetRoleInput

type SetRoleInput struct {
	UserID string   `json:"userId"`
	Role   string   `json:"role"`
	Roles  []string `json:"roles,omitempty"` // For multiple roles
}

SetRoleInput is the input for setting a user's role

type UpdateUserInput

type UpdateUserInput struct {
	UserID string         `json:"userId"`
	Data   map[string]any `json:"data"`
}

UpdateUserInput is the input for admin user updates

type UserWithRole

type UserWithRole struct {
	core.User
	Role       string     `json:"role"`
	Banned     bool       `json:"banned"`
	BanReason  *string    `json:"banReason,omitempty"`
	BanExpires *time.Time `json:"banExpires,omitempty"`
}

UserWithRole extends the base User with admin-specific fields

Jump to

Keyboard shortcuts

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