auth

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Jun 18, 2026 License: AGPL-3.0, AGPL-3.0-or-later Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CSRFSecure = false

CSRFSecure controls the Secure flag on CSRF cookies. Set true in production with TLS. Deprecated: SetSecureCookie auto-detects TLS; this is kept for explicit config overrides.

View Source
var SessionLifetime = 24 * time.Hour

SessionLifetime is the duration for which sessions are valid. Set before creating SessionManagers.

Functions

func AuthMiddleware

func AuthMiddleware(sm *SessionManager) gin.HandlerFunc

AuthMiddleware returns a Gin middleware that validates session cookies.

func CSRFMiddleware

func CSRFMiddleware() gin.HandlerFunc

CSRFMiddleware protects state-changing requests with a double-submit cookie pattern. On first GET, a CSRF token is set as a cookie (HttpOnly=false so JS can read it). On POST/PUT/DELETE, the X-Kora-CSRF-Token header must match the cookie value. Token comparison uses constant-time comparison to prevent timing attacks.

func HashPassword

func HashPassword(password string) (string, error)

HashPassword creates a bcrypt hash of a password.

func RegisterAuthRoutes

func RegisterAuthRoutes(router *gin.Engine, sm *SessionManager, db *sql.DB)

RegisterAuthRoutes registers authentication endpoints.

func SetCSRFSecure

func SetCSRFSecure(secure bool)

SetCSRFSecure sets the Secure flag for CSRF cookies.

func SetSecureCookie

func SetSecureCookie(c *gin.Context, name, value string, maxAge int, path string, httpOnly bool)

SetSecureCookie sets a cookie with Secure auto-detected from the request's TLS state and appends SameSite=Lax. Use this instead of c.SetCookie for security-sensitive cookies.

func SiteDB

func SiteDB(c *gin.Context) *sql.DB

SiteDB returns the site's database from the request context.

func SiteRegistry

func SiteRegistry(c *gin.Context) interface{}

SiteRegistry returns the site's DocType registry from the request context.

Types

type ConsoleSession

type ConsoleSession struct {
	Email     string
	CreatedAt time.Time
	ExpiresAt time.Time
}

ConsoleSession represents an authenticated console session stored server-side.

type SessionManager

type SessionManager struct {
	DB *sql.DB
	// contains filtered or unexported fields
}

SessionManager manages user sessions with an in-memory TTL cache.

func NewSessionManager

func NewSessionManager(db *sql.DB) *SessionManager

NewSessionManager creates a new session manager. If db is nil (console-only mode with no sites), the sweep goroutine is not started.

func (*SessionManager) AuthenticateUser

func (sm *SessionManager) AuthenticateUser(email, password string) (*User, error)

AuthenticateUser verifies a username/email and password against the database.

func (*SessionManager) CreateSession

func (sm *SessionManager) CreateSession(user *User) (string, error)

CreateSession creates a new session for a user and returns the session ID.

func (*SessionManager) DeleteSession

func (sm *SessionManager) DeleteSession(sid string)

DeleteSession removes a session.

func (*SessionManager) GetSession

func (sm *SessionManager) GetSession(sid string) (*User, error)

GetSession validates a session ID and returns the associated user. Uses an in-memory TTL cache to avoid hitting the database on every request.

func (*SessionManager) InvalidateSession

func (sm *SessionManager) InvalidateSession(sid string)

InvalidateSession removes a session from the cache without deleting it from the database. Use this when user state changes (role change, password change, disable) to force re-validation.

type SiteGuard

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

SiteGuard is a unified middleware that enforces authentication, CSRF, and site context resolution for workspace and API routes. It wraps AuthMiddleware + CSRFMiddleware + site context injection.

func NewSiteGuard

func NewSiteGuard(db *sql.DB) *SiteGuard

NewSiteGuard creates a SiteGuard.

func (*SiteGuard) Middleware

func (g *SiteGuard) Middleware(skipCSRF bool) gin.HandlerFunc

Middleware returns the combined site guard middleware. It runs: Auth → CSRF → site context → handler. Uses validateSession (no c.Next() inside) so CSRF check runs BEFORE the handler, preventing double-responses.

type SystemCredentials

type SystemCredentials struct {
	SystemAdmin struct {
		Email    string `yaml:"email"`
		Password string `yaml:"password"` // plaintext — hashed on startup
	} `yaml:"system_admin"`
}

SystemCredentials holds the system admin credential loaded from YAML.

type SystemGuard

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

SystemGuard authenticates system administrator requests for /console.

func LoadSystemGuard

func LoadSystemGuard(path string) (*SystemGuard, error)

LoadSystemGuard reads system_credentials.yaml, hashes the password, and returns a guard.

func LoadSystemGuardFromEnv

func LoadSystemGuardFromEnv() *SystemGuard

LoadSystemGuardFromEnv creates a SystemGuard from environment variables. Falls back to baked-in defaults if env vars are not set. Default: admin@kora.local / kora123 (isDefault=true forces password change).

func (*SystemGuard) CreateSession

func (g *SystemGuard) CreateSession(email string) string

CreateSession creates a new console session for the given email. Returns a cryptographically random session ID.

func (*SystemGuard) DeleteSession

func (g *SystemGuard) DeleteSession(sid string)

DeleteSession removes a console session.

func (*SystemGuard) Middleware

func (g *SystemGuard) Middleware() gin.HandlerFunc

Middleware returns a Gin middleware that enforces system admin authentication. It accepts two authentication methods:

  1. Cookie: "kora_console_sid" with a server-validated session ID.
  2. Authorization header: "Basic <base64(email:password)>" for API clients.

func (*SystemGuard) UpdatePassword

func (g *SystemGuard) UpdatePassword(newPassword string) error

UpdatePassword replaces the stored password hash. Used for first-login forced change.

func (*SystemGuard) ValidateSession

func (g *SystemGuard) ValidateSession(sid string) string

ValidateSession checks whether a session ID is valid and returns the associated email. Returns empty string if the session is invalid or expired.

func (*SystemGuard) ValidateSessionBool

func (g *SystemGuard) ValidateSessionBool(sid string) bool

ValidateSessionBool returns true if the session token is valid.

func (*SystemGuard) ValidateWithChangeCheck

func (g *SystemGuard) ValidateWithChangeCheck(email, password string) (valid bool, needsChange bool)

ValidateWithChangeCheck validates credentials and returns whether a password change is required. Password change is required when using the baked-in default credentials.

func (*SystemGuard) VerifyCredentials

func (g *SystemGuard) VerifyCredentials(email, password string) error

VerifyCredentials checks if the given email and password match the system credentials.

type User

type User struct {
	Name     string   `json:"name"`
	Email    string   `json:"email"`
	FullName string   `json:"full_name"`
	Roles    []string `json:"roles"`
	Enabled  bool     `json:"enabled"`
}

User represents an authenticated user.

Jump to

Keyboard shortcuts

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