dashboard

package
v0.0.11 Latest Latest
Warning

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

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

README

Dashboard Plugin

A lightweight, server-rendered admin interface for AuthSome built with Alpine.js and Tailwind CSS 4 CDN.

Quick Start

import (
    "github.com/xraph/authsome"
    "github.com/xraph/authsome/plugins/dashboard"
)

auth, err := authsome.New(
    authsome.WithPlugins(
        dashboard.NewPlugin(),
    ),
)

Then access the dashboard at http://localhost:8080/dashboard/ (requires admin role).

Features

✅ Server-side rendering with Go templates
✅ ~40KB total bundle size (Alpine.js + Tailwind CSS CDN)
✅ Built-in auth, RBAC, CSRF, rate limiting, and audit logging
✅ Responsive, mobile-first design
✅ Real-time statistics and user management
Dark mode support with system preference detection and localStorage persistence

Access Control

The dashboard implements production-grade security with:

  • Fast Permission Checking: Role-based access control with 5-minute cache (< 100µs per check)
  • CSRF Protection: Session-bound tokens with HMAC signatures
  • First-User Admin: First user automatically gets admin role
Assigning Admin Role
# Using the CLI
authsome-cli user assign-role --user-id=<id> --role=admin

# Or programmatically
rbacSvc.AssignRole(ctx, userID, roleID, orgID)
Permission System
// Check permissions with expressive fluent API
checker := dashboard.NewPermissionChecker(rbacSvc, userRoleRepo)

// Simple check
canView := checker.Can(ctx, userID, "view", "users")

// Fluent API
user := checker.For(ctx, userID)
if user.Dashboard().CanAccess() {
    // Grant access
}

See DASHBOARD_STATUS.md for detailed security documentation.

Documentation

Pages

App-Based Route Structure (Breaking Change v2.0)

All dashboard routes are now app-scoped. You must select an app before accessing dashboard features.

Dashboard Index:

  • /dashboard/ - App selection (multiapp mode) or auto-redirect to default app (standalone mode)

App-Scoped Routes:

  • /dashboard/app/:appId/ - Statistics and quick actions for the app
  • /dashboard/app/:appId/users - User management within the app
  • /dashboard/app/:appId/users/:id - User details
  • /dashboard/app/:appId/organizations - User-created organizations (workspaces) within the app
  • /dashboard/app/:appId/organizations/:orgId - Organization details
  • /dashboard/app/:appId/apps-management - Platform apps management (admin only)
  • /dashboard/app/:appId/apps-management/:targetAppId - App details
  • /dashboard/app/:appId/apps-management/create - Create new app (requires multiapp plugin)
  • /dashboard/app/:appId/sessions - Active sessions in the app
  • /dashboard/app/:appId/settings - App-specific settings
  • /dashboard/app/:appId/plugins - Plugin management for the app

App Switcher: In multiapp mode, a dropdown appears in the header allowing quick switching between apps you belong to.

Breaking Changes from v1.x

⚠️ IMPORTANT: This release introduces breaking changes to the URL structure.

  1. Old routes removed:

    • /dashboard/users/dashboard/app/{appId}/users
    • /dashboard/sessions/dashboard/app/{appId}/sessions
    • All routes now require an appId in the URL path
  2. App vs. Organization distinction:

    • Apps (platform-level tenants) can be managed via the dashboard "Apps Management" section
      • List, view, edit, and delete apps are always available
      • Create new apps is only available when multiapp plugin is enabled
    • Organizations (user-created workspaces) are managed via the dashboard "Organizations" section
    • The dashboard / now displays app cards for navigation
    • Within each app, you can create and manage user organizations
  3. Context requirement:

    • All dashboard features now operate within an app context
    • Users must be members of an app to access its dashboard
    • Data is automatically scoped to the selected app
Migration Guide

If you have bookmarks or hardcoded links:

  • Update /dashboard/users to /dashboard/app/{appId}/users
  • Pattern: /dashboard/{page}/dashboard/app/{appId}/{page}

For multiapp mode:

  • Visit /dashboard/ to see all your apps
  • Click on an app card to enter its dashboard

For standalone mode:

  • /dashboard/ will auto-redirect to the default app
  • URLs will automatically include the app ID

Dark Mode

The dashboard includes a built-in dark mode switcher located in the top-right header.

Features
  • System Preference Detection: Automatically detects and respects OS-level dark mode preferences
  • localStorage Persistence: User preference is saved locally and persists across sessions
  • Smooth Transitions: All theme changes are animated with smooth CSS transitions
  • Complete Coverage: All components, forms, tables, and UI elements are fully styled for dark mode
How It Works
  1. Initial Load: Checks localStorage for saved preference, falls back to system preference
  2. Toggle Button: Click the sun/moon icon in the header to switch themes manually
  3. Automatic Updates: Listens for system preference changes when no manual preference is set
  4. CSS Classes: Uses Tailwind's dark: prefix for conditional dark mode styling
Technical Implementation
  • Alpine.js Component: themeData() component manages state and persistence
  • Tailwind CSS: darkMode: 'class' configuration for class-based toggling
  • localStorage Key: theme (values: 'light' or 'dark')
  • CSS Variables: Custom scrollbar colors for both light and dark themes

Development

# Build
go build ./plugins/dashboard/...

# Test
go test ./plugins/dashboard/... -v

# Lint
golangci-lint run ./plugins/dashboard/...

Premium React Dashboard

A premium React-based dashboard with advanced features is available separately at frontend/dashboard-premium/. See its README for details.

License

Part of AuthSome. See main LICENSE file.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrExtensionAlreadyRegistered indicates an extension with the same ID is already registered
	ErrExtensionAlreadyRegistered = &DashboardError{
		Code:    "extension_already_registered",
		Message: "dashboard extension already registered",
	}
)

Functions

func EnsureFirstUserIsAdmin

func EnsureFirstUserIsAdmin(ctx context.Context, userID, orgID xid.ID, userRoleRepo rbac.UserRoleRepository, roleRepo rbac.RoleRepository) error

EnsureFirstUserIsAdmin assigns admin role to the first user DEPRECATED: Use EnsureFirstUserIsSuperAdmin for first user setup

func EnsureFirstUserIsSuperAdmin

func EnsureFirstUserIsSuperAdmin(ctx context.Context, userID, orgID xid.ID, userRoleRepo rbac.UserRoleRepository, roleRepo rbac.RoleRepository) error

EnsureFirstUserIsSuperAdmin assigns superadmin role to the first user This makes them the platform owner with full system access

func RegisterDashboardRoles

func RegisterDashboardRoles(registry *rbac.RoleRegistry) error

RegisterDashboardRoles registers dashboard-specific roles in the RoleRegistry This extends the default platform roles with dashboard-specific permissions Supports override semantics - plugins can modify other plugins' roles

func RenderNavigationItems

func RenderNavigationItems(items []ui.NavigationItem, basePath string, currentApp *app.App, activePage string) []g.Node

RenderNavigationItems renders navigation items as gomponents nodes

func SetupDefaultPolicies

func SetupDefaultPolicies(rbacSvc *rbac.Service) error

SetupDefaultPolicies creates default RBAC policies for the dashboard Role hierarchy: superadmin > owner > admin > member This is kept for backward compatibility and immediate policy loading The role bootstrap system will persist these roles to the database

Types

type ActivityItem

type ActivityItem struct {
	Title       string
	Description string
	Time        string
	Type        string // success, warning, error, info
}

ActivityItem represents a recent activity entry

type CSRFProtector

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

CSRFProtector provides production-grade CSRF protection

func NewCSRFProtector

func NewCSRFProtector() (*CSRFProtector, error)

NewCSRFProtector creates a new CSRF protector with a random secret

func (*CSRFProtector) CleanupExpiredTokens

func (c *CSRFProtector) CleanupExpiredTokens()

CleanupExpiredTokens manually triggers cleanup of expired tokens

func (*CSRFProtector) GenerateToken

func (c *CSRFProtector) GenerateToken(sessionID string) (string, error)

GenerateToken generates a new CSRF token for a session Format: base64(randomBytes) + "." + base64(hmac(randomBytes + sessionID))

func (*CSRFProtector) InvalidateToken

func (c *CSRFProtector) InvalidateToken(token string)

InvalidateToken removes a token from the store

func (*CSRFProtector) RotateSecret

func (c *CSRFProtector) RotateSecret() error

RotateSecret generates a new CSRF secret Should be called periodically for enhanced security

func (*CSRFProtector) Stats

func (c *CSRFProtector) Stats() map[string]interface{}

Stats returns statistics about the CSRF token store

func (*CSRFProtector) ValidateToken

func (c *CSRFProtector) ValidateToken(token, sessionID string) bool

ValidateToken validates a CSRF token against a session

type Config

type Config struct {
	// EnableSignup allows new users to sign up for dashboard access
	EnableSignup bool `json:"enableSignup"`

	// RequireEmailVerification requires email verification for new signups
	RequireEmailVerification bool `json:"requireEmailVerification"`

	// SessionDuration sets the duration for dashboard sessions in hours
	SessionDuration int `json:"sessionDuration"`

	// MaxLoginAttempts sets the maximum login attempts before lockout
	MaxLoginAttempts int `json:"maxLoginAttempts"`

	// LockoutDuration sets the lockout duration in minutes
	LockoutDuration int `json:"lockoutDuration"`

	// DefaultTheme sets the default theme (light, dark, auto)
	DefaultTheme string `json:"defaultTheme"`
}

Config holds the dashboard plugin configuration

type DashboardError

type DashboardError struct {
	Code    string
	Message string
}

DashboardError represents a dashboard-specific error

func (*DashboardError) Error

func (e *DashboardError) Error() string

type DashboardErrorResponse

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

DTOs for dashboard routes

type DashboardHTMLResponse

type DashboardHTMLResponse struct {
	HTML string `json:"html" example:"<html>...</html>"`
}

type DashboardLoginResponse

type DashboardLoginResponse struct {
	RedirectURL string `json:"redirect_url" example:"/dashboard/"`
}

type DashboardPermissions

type DashboardPermissions struct {
	*PermissionBuilder
}

DashboardPermissions provides dashboard-specific permission checks

func (*DashboardPermissions) CanAccess

func (d *DashboardPermissions) CanAccess() bool

CanAccess checks if user can access the dashboard

func (*DashboardPermissions) CanManageSessions

func (d *DashboardPermissions) CanManageSessions() bool

CanManageSessions checks if user can manage sessions

func (*DashboardPermissions) CanManageUsers

func (d *DashboardPermissions) CanManageUsers() bool

CanManageUsers checks if user can manage users

func (*DashboardPermissions) CanViewAuditLogs

func (d *DashboardPermissions) CanViewAuditLogs() bool

CanViewAuditLogs checks if user can view audit logs

func (*DashboardPermissions) CanViewSessions

func (d *DashboardPermissions) CanViewSessions() bool

CanViewSessions checks if user can view sessions

func (*DashboardPermissions) CanViewUsers

func (d *DashboardPermissions) CanViewUsers() bool

CanViewUsers checks if user can view users

type DashboardPingResponse

type DashboardPingResponse struct {
	Message string `json:"message" example:"Dashboard plugin is working!"`
}

type DashboardStaticResponse

type DashboardStaticResponse struct {
	ContentType string `json:"content_type" example:"text/css"`
	Content     []byte `json:"content"`
}

type DashboardStats

type DashboardStats struct {
	TotalUsers     int
	ActiveUsers    int
	NewUsersToday  int
	TotalSessions  int
	ActiveSessions int
	FailedLogins   int
	UserGrowth     float64
	SessionGrowth  float64
	RecentActivity []ActivityItem
	SystemStatus   []StatusItem
	Plugins        []PluginItem
}

DashboardStats represents statistics for the dashboard

type DashboardStatusResponse

type DashboardStatusResponse struct {
	Status string `json:"status" example:"success"`
}

type ErrorResponse

type ErrorResponse = responses.ErrorResponse

Response types - use shared responses from core

type ExtensionRegistry

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

ExtensionRegistry manages dashboard extensions from plugins

func NewExtensionRegistry

func NewExtensionRegistry() *ExtensionRegistry

NewExtensionRegistry creates a new extension registry

func (*ExtensionRegistry) Get

Get retrieves an extension by ID

func (*ExtensionRegistry) GetAllRoutes

func (r *ExtensionRegistry) GetAllRoutes() []ui.Route

GetAllRoutes returns all routes from all extensions

func (*ExtensionRegistry) GetDashboardWidgets

func (r *ExtensionRegistry) GetDashboardWidgets() []ui.DashboardWidget

GetDashboardWidgets returns all dashboard widgets sorted by order

func (*ExtensionRegistry) GetHandler

func (r *ExtensionRegistry) GetHandler() *Handler

GetHandler returns the handler instance for extensions to use Extensions can use this to access renderWithLayout and other helpers

func (*ExtensionRegistry) GetNavigationItems

func (r *ExtensionRegistry) GetNavigationItems(position ui.NavigationPosition, enabledPlugins map[string]bool) []ui.NavigationItem

GetNavigationItems returns all navigation items for a specific position

func (*ExtensionRegistry) GetSettingsPages

func (r *ExtensionRegistry) GetSettingsPages(enabledPlugins map[string]bool) []ui.SettingsPage

GetSettingsPages returns all settings pages from extensions

func (*ExtensionRegistry) GetSettingsSections

func (r *ExtensionRegistry) GetSettingsSections() []ui.SettingsSection

GetSettingsSections returns all settings sections sorted by order Deprecated: Use GetSettingsPages for the new sidebar layout

func (*ExtensionRegistry) List

List returns all registered extensions

func (*ExtensionRegistry) Register

func (r *ExtensionRegistry) Register(ext ui.DashboardExtension) error

Register registers a dashboard extension

func (*ExtensionRegistry) SetHandler

func (r *ExtensionRegistry) SetHandler(h *Handler)

SetHandler sets the handler instance (called by dashboard plugin during init)

type Handler

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

Handler handles dashboard HTTP requests

func NewHandler

func NewHandler(
	assets embed.FS,
	appService app.Service,
	userSvc user.ServiceInterface,
	sessionSvc session.ServiceInterface,
	auditSvc *audit.Service,
	rbacSvc *rbac.Service,
	apikeyService *apikey.Service,
	orgService *organization.Service,
	envService environment.EnvironmentService,
	db *bun.DB,
	isMultiApp bool,
	basePath string,
	enabledPlugins map[string]bool,
	hookRegistry *hooks.HookRegistry,
	configManager forge.ConfigManager,
) *Handler

NewHandler creates a new dashboard handler

func (*Handler) GetBasePath

func (h *Handler) GetBasePath() string

GetBasePath returns the dashboard base path

func (*Handler) GetCSRFToken

func (h *Handler) GetCSRFToken(c forge.Context) string

GetCSRFToken returns the CSRF token for the request

func (*Handler) GetCurrentApp

func (h *Handler) GetCurrentApp(c forge.Context) (*app.App, error)

GetCurrentApp extracts and returns the current app from URL parameter This handles parsing the appId param and fetching the app

func (*Handler) GetCurrentEnvironment

func (h *Handler) GetCurrentEnvironment(c forge.Context, appID xid.ID) (*environment.Environment, error)

GetCurrentEnvironment returns the current environment from cookie or default

func (*Handler) GetEnabledPlugins

func (h *Handler) GetEnabledPlugins() map[string]bool

GetEnabledPlugins returns map of enabled plugins

func (*Handler) GetUserApps

func (h *Handler) GetUserApps(c forge.Context, userID xid.ID) ([]*app.App, error)

GetUserApps returns all apps the user has access to

func (*Handler) GetUserEnvironments

func (h *Handler) GetUserEnvironments(c forge.Context, appID xid.ID) ([]*environment.Environment, error)

GetUserEnvironments returns all environments for the given app

func (*Handler) GetUserFromContext

func (h *Handler) GetUserFromContext(c forge.Context) *user.User

GetUserFromContext returns the authenticated user from request context Extensions should use this instead of c.Get("user")

func (*Handler) HandleAppMgmtCreate

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

HandleAppMgmtCreate processes app creation

func (*Handler) HandleAppMgmtDelete

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

HandleAppMgmtDelete processes app deletion

func (*Handler) HandleAppMgmtEdit

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

HandleAppMgmtEdit processes app update

func (*Handler) HandleEnvironmentCreate

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

HandleEnvironmentCreate processes environment creation

func (*Handler) HandleEnvironmentDelete

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

HandleEnvironmentDelete processes environment deletion

func (*Handler) HandleEnvironmentEdit

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

HandleEnvironmentEdit processes environment update

func (*Handler) HandleEnvironmentSwitch

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

HandleEnvironmentSwitch switches the current environment

func (*Handler) HandleLogin

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

HandleLogin processes the login form

func (*Handler) HandleLogout

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

HandleLogout processes the logout request

func (*Handler) HandleOrganizationCreate

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

HandleOrganizationCreate processes organization creation

func (*Handler) HandleOrganizationDelete

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

HandleOrganizationDelete processes organization deletion

func (*Handler) HandleOrganizationEdit

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

HandleOrganizationEdit processes organization update

func (*Handler) HandleRevokeSession

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

HandleRevokeSession revokes a single session

func (*Handler) HandleRevokeUserSessions

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

HandleRevokeUserSessions revokes all sessions for a specific user

func (*Handler) HandleSignup

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

HandleSignup processes the signup form

func (*Handler) HandleUserDelete

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

HandleUserDelete deletes a user

func (*Handler) HandleUserEdit

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

HandleUserEdit processes the user edit form

func (*Handler) RenderSettingsPage

func (h *Handler) RenderSettingsPage(c forge.Context, pageID string, content g.Node) error

RenderSettingsPage renders content within the settings layout with sidebar navigation Extensions should use this to render their settings pages instead of RenderWithLayout The pageID should match the ID in the SettingsPage definition

func (*Handler) RenderWithBaseLayout added in v0.0.3

func (h *Handler) RenderWithBaseLayout(c forge.Context, pageData components.PageData, content g.Node) error

renderWithLayout renders content within the base layout RenderWithLayout renders content with the dashboard layout (public for extensions) This method automatically populates app, environment, and extension data

func (*Handler) RenderWithHeaderLayout added in v0.0.3

func (h *Handler) RenderWithHeaderLayout(c forge.Context, pageData components.PageData, content g.Node) error

renderWithLayout renders content within the base layout RenderWithLayout renders content with the dashboard layout (public for extensions) This method automatically populates app, environment, and extension data

func (*Handler) RenderWithLayout

func (h *Handler) RenderWithLayout(c forge.Context, pageData components.PageData, content g.Node) error

renderWithLayout renders content within the base layout RenderWithLayout renders content with the dashboard layout (public for extensions) This method automatically populates app, environment, and extension data

func (*Handler) RenderWithSidebarLayout added in v0.0.3

func (h *Handler) RenderWithSidebarLayout(c forge.Context, pageData components.PageData, content g.Node) error

renderWithLayout renders content within the base layout RenderWithLayout renders content with the dashboard layout (public for extensions) This method automatically populates app, environment, and extension data

func (*Handler) Serve404

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

Serve404 serves the 404 page

func (*Handler) ServeAppMgmtCreate

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

ServeAppMgmtCreate renders the app creation form

func (*Handler) ServeAppMgmtDetail

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

ServeAppMgmtDetail renders the app management detail page

func (*Handler) ServeAppMgmtEdit

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

ServeAppMgmtEdit renders the app edit form

func (*Handler) ServeAppsList

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

ServeAppsList serves the dashboard index page - shows app cards or redirects to default app

func (*Handler) ServeConfigViewer added in v0.0.9

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

ServeConfigViewer serves the configuration viewer page This page displays all configuration values from Forge ConfigManager as YAML

func (*Handler) ServeDashboard

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

ServeDashboard serves the main dashboard page

func (*Handler) ServeEnvironmentCreate

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

ServeEnvironmentCreate renders the create environment page

func (*Handler) ServeEnvironmentDetail

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

ServeEnvironmentDetail renders the environment detail page

func (*Handler) ServeEnvironmentEdit

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

ServeEnvironmentEdit renders the edit environment page

func (*Handler) ServeEnvironments

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

ServeEnvironments renders the environments list page

func (*Handler) ServeLogin

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

ServeLogin serves the login page

func (*Handler) ServeOrganizationCreate

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

ServeOrganizationCreate renders the organization creation form

func (*Handler) ServeOrganizationDetail

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

ServeOrganizationDetail renders the organization detail page

func (*Handler) ServeOrganizationEdit

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

ServeOrganizationEdit renders the organization edit form

func (*Handler) ServeOrganizations

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

ServeOrganizations renders the organizations list page

func (*Handler) ServePlugins

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

ServePlugins serves the plugins management page

func (*Handler) ServeSessions

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

ServeSessions serves the sessions list page

func (*Handler) ServeSettings

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

ServeSettings serves the settings page

func (*Handler) ServeSettingsGeneral

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

ServeSettingsGeneral handles the general settings page

func (*Handler) ServeSignup

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

ServeSignup serves the signup page

func (*Handler) ServeStatic

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

ServeStatic serves static assets (CSS, JS, images)

func (*Handler) ServeUserDetail

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

ServeUserDetail serves a single user detail page

func (*Handler) ServeUserEdit

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

ServeUserEdit serves the user edit page

func (*Handler) ServeUsers

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

ServeUsers serves the users list page

type MessageResponse

type MessageResponse = responses.MessageResponse

type PageData

type PageData struct {
	Title          string
	User           *user.User
	CSRFToken      string
	ActivePage     string
	BasePath       string
	Data           interface{}
	Error          string
	Success        string
	Year           int
	EnabledPlugins map[string]bool
}

PageData represents common data for all pages

type Permission

type Permission struct {
	Action   string // e.g., "view", "edit", "delete"
	Resource string // e.g., "dashboard", "users", "sessions"
}

Permission represents a fine-grained permission check

type PermissionBuilder

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

PermissionBuilder provides a fluent API for building permission checks

func (*PermissionBuilder) Can

func (b *PermissionBuilder) Can(action, resource string) bool

Can checks a single permission

func (*PermissionBuilder) CanCreate

func (b *PermissionBuilder) CanCreate(resource string) bool

CanCreate is a shorthand for Can("create", resource)

func (*PermissionBuilder) CanDelete

func (b *PermissionBuilder) CanDelete(resource string) bool

CanDelete is a shorthand for Can("delete", resource)

func (*PermissionBuilder) CanEdit

func (b *PermissionBuilder) CanEdit(resource string) bool

CanEdit is a shorthand for Can("edit", resource)

func (*PermissionBuilder) CanView

func (b *PermissionBuilder) CanView(resource string) bool

CanView is a shorthand for Can("view", resource)

func (*PermissionBuilder) Dashboard

func (b *PermissionBuilder) Dashboard() *DashboardPermissions

Dashboard returns a dashboard-specific permission checker

func (*PermissionBuilder) HasRole

func (b *PermissionBuilder) HasRole(roleName string) bool

HasRole checks if the user has a specific role

func (*PermissionBuilder) IsAdmin

func (b *PermissionBuilder) IsAdmin() bool

IsAdmin checks if the user has the admin role

func (*PermissionBuilder) IsOwner

func (b *PermissionBuilder) IsOwner() bool

IsOwner checks if the user has the owner role

func (*PermissionBuilder) IsSuperAdmin

func (b *PermissionBuilder) IsSuperAdmin() bool

IsSuperAdmin checks if the user has the superadmin role

type PermissionChecker

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

PermissionChecker provides a fast, expressive API for checking permissions

func NewPermissionChecker

func NewPermissionChecker(rbacSvc *rbac.Service, userRoleRepo rbac.UserRoleRepository) *PermissionChecker

NewPermissionChecker creates a new permission checker

func (*PermissionChecker) Can

func (p *PermissionChecker) Can(ctx context.Context, userID xid.ID, action, resource string) bool

Can checks if a user has permission to perform an action on a resource This is the main expressive API for permission checking

func (*PermissionChecker) CanAll

func (p *PermissionChecker) CanAll(ctx context.Context, userID xid.ID, permissions ...Permission) bool

CanAll checks if a user has all of the specified permissions

func (*PermissionChecker) CanAny

func (p *PermissionChecker) CanAny(ctx context.Context, userID xid.ID, permissions ...Permission) bool

CanAny checks if a user has any of the specified permissions

func (*PermissionChecker) For

For creates a new permission builder for a user

func (*PermissionChecker) HasAnyRole

func (p *PermissionChecker) HasAnyRole(ctx context.Context, userID xid.ID, roleNames ...string) bool

HasAnyRole checks if a user has any of the specified roles

func (*PermissionChecker) HasRole

func (p *PermissionChecker) HasRole(ctx context.Context, userID xid.ID, roleName string) bool

HasRole checks if a user has a specific role

func (*PermissionChecker) InvalidateUserCache

func (p *PermissionChecker) InvalidateUserCache(userID xid.ID)

InvalidateUserCache clears the cached roles for a user Call this when user roles are modified

type Plugin

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

Plugin implements the dashboard plugin for AuthSome

func NewPlugin

func NewPlugin(opts ...PluginOption) *Plugin

NewPlugin creates a new dashboard plugin instance with optional configuration

func (*Plugin) AppContext

func (p *Plugin) AppContext() func(func(forge.Context) error) func(forge.Context) error

AppContext middleware injects app context into dashboard requests for authless routes

func (*Plugin) AuditLog

func (p *Plugin) AuditLog() func(func(forge.Context) error) func(forge.Context) error

AuditLog middleware logs all dashboard access

func (*Plugin) CSRF

func (p *Plugin) CSRF() func(func(forge.Context) error) func(forge.Context) error

CSRF middleware provides CSRF protection

func (*Plugin) Dependencies

func (p *Plugin) Dependencies() []string

Dependencies declares the plugin dependencies Dashboard requires multiapp plugin for environment management

func (*Plugin) EnvironmentContext

func (p *Plugin) EnvironmentContext() func(func(forge.Context) error) func(forge.Context) error

EnvironmentContext middleware injects environment context into all dashboard requests

This middleware ensures that every app-scoped dashboard request has an environment ID set in the context. This is critical for: - Environment-scoped data operations - Multi-environment isolation - Audit trails with environment information - Dashboard extensions that need environment context

The middleware follows this flow: 1. Extract app ID from URL path parameter (:appId) 2. Check for environment ID in cookie (authsome_environment) 3. If no cookie, fetch the default environment for the app 4. Set environment context using contexts.SetEnvironmentID() 5. Update cookie for future requests (30-day expiry)

Routes without :appId parameter are skipped (e.g., /dashboard/login) Gracefully handles missing environment service for backward compatibility

func (*Plugin) ID

func (p *Plugin) ID() string

ID returns the unique identifier for this plugin

func (*Plugin) Init

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

Init initializes the plugin with dependencies

func (*Plugin) Migrate

func (p *Plugin) Migrate() error

Migrate runs database migrations for the dashboard plugin

func (*Plugin) PlatformOrgContext

func (p *Plugin) PlatformOrgContext() func(func(forge.Context) error) func(forge.Context) error

PlatformOrgContext middleware injects platform organization context into all dashboard requests Dashboard always operates in the context of the platform organization without requiring API keys

func (*Plugin) RateLimit

func (p *Plugin) RateLimit() func(func(forge.Context) error) func(forge.Context) error

RateLimit middleware implements rate limiting

func (*Plugin) RegisterHooks

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

RegisterHooks registers hooks for the dashboard plugin

func (*Plugin) RegisterRoles

func (p *Plugin) RegisterRoles(registry interface{}) error

RegisterRoles implements the PluginWithRoles optional interface This is called automatically during server initialization to register dashboard roles

func (*Plugin) RegisterRoutes

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

RegisterRoutes registers the dashboard routes

func (*Plugin) RegisterServiceDecorators

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

RegisterServiceDecorators registers service decorators

func (*Plugin) RequireAdmin

func (p *Plugin) RequireAdmin() func(func(forge.Context) error) func(forge.Context) error

RequireAdmin middleware ensures the user has admin role

func (*Plugin) RequireAuth

func (p *Plugin) RequireAuth() func(func(forge.Context) error) func(forge.Context) error

RequireAuth middleware ensures the user is authenticated

type PluginItem

type PluginItem struct {
	ID          string
	Name        string
	Description string
	Category    string
	Status      string // enabled, disabled
	Icon        string // lucide icon name
}

PluginItem represents a plugin entry

type PluginOption

type PluginOption func(*Plugin)

PluginOption is a functional option for configuring the dashboard plugin

func WithDefaultConfig

func WithDefaultConfig(cfg Config) PluginOption

WithDefaultConfig sets the default configuration for the plugin

func WithDefaultTheme

func WithDefaultTheme(theme string) PluginOption

WithDefaultTheme sets the default theme

func WithEnableSignup

func WithEnableSignup(enabled bool) PluginOption

WithEnableSignup sets whether signup is enabled

func WithLockoutDuration

func WithLockoutDuration(minutes int) PluginOption

WithLockoutDuration sets the lockout duration in minutes

func WithMaxLoginAttempts

func WithMaxLoginAttempts(max int) PluginOption

WithMaxLoginAttempts sets the maximum login attempts

func WithRequireEmailVerification

func WithRequireEmailVerification(required bool) PluginOption

WithRequireEmailVerification sets whether email verification is required

func WithSessionDuration

func WithSessionDuration(hours int) PluginOption

WithSessionDuration sets the session duration in hours

type StatusItem

type StatusItem struct {
	Name   string
	Status string // operational, degraded, down
	Color  string // green, yellow, red
}

StatusItem represents a system status entry

type StatusResponse

type StatusResponse = responses.StatusResponse

type SuccessResponse

type SuccessResponse = responses.SuccessResponse

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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