auth

package
v0.2.2-beta Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Overview

Package auth provides authentication and authorization utilities for the krkn-operator ecosystem.

This package contains reusable authentication components that can be shared across all operators in the krkn-operator-ecosystem, including:

  • JWT token generation and validation
  • Password hashing and verification using bcrypt
  • User authentication helpers

JWT Authentication

The package provides a TokenGenerator for creating and validating JWT tokens:

secretKey := []byte("your-secret-key-at-least-32-bytes-long")
tokenGen := auth.NewTokenGenerator(secretKey, 24*time.Hour, "krkn-operator")

// Generate a token
token, err := tokenGen.GenerateToken("[email protected]", "admin", "John", "Doe", "Example Corp")
if err != nil {
    // handle error
}

// Validate a token
claims, err := tokenGen.ValidateToken(token)
if err != nil {
    // handle error
}

// Check if user is admin
isAdmin, err := tokenGen.IsAdmin(token)

Password Management

The package provides secure password hashing using bcrypt:

// Hash a password
hash, err := auth.HashPassword("user-password-123")
if err != nil {
    // handle error
}

// Verify a password
if auth.VerifyPassword("user-password-123", hash) {
    // password is correct
}

// Validate password meets requirements
if err := auth.ValidatePassword(password); err != nil {
    // password doesn't meet requirements
}

All utilities in this package are thread-safe and can be used concurrently across multiple goroutines.

Package auth provides authentication utilities for the krkn-operator ecosystem. This includes JWT token generation, validation, and password hashing utilities that can be shared across all operators in the ecosystem.

Index

Constants

View Source
const (
	// UserClaimsKey is the context key for storing JWT claims
	UserClaimsKey ContextKey = "user-claims"
	// AuthorizationHeader is the HTTP header name for authorization
	AuthorizationHeader = "Authorization"
	// BearerPrefix is the expected prefix for bearer tokens
	BearerPrefix = "Bearer "
)
View Source
const (
	// DefaultCost is the default bcrypt cost (10 is a good balance between security and performance)
	DefaultCost = bcrypt.DefaultCost
	// MinPasswordLength is the minimum password length required
	MinPasswordLength = 8
)

Variables

This section is empty.

Functions

func HashPassword

func HashPassword(password string) (string, error)

HashPassword hashes a password using bcrypt.

Parameters:

  • password: The plaintext password to hash

Returns the bcrypt hash or an error.

func IsAdmin

func IsAdmin(ctx context.Context) bool

IsAdmin checks if the user in the context is an admin

Parameters:

  • ctx: The request context

Returns true if the user is an admin, false otherwise

func ValidatePassword

func ValidatePassword(password string) error

ValidatePassword checks if a password meets the minimum requirements.

Parameters:

  • password: The password to validate

Returns an error if the password doesn't meet requirements, nil otherwise.

func VerifyPassword

func VerifyPassword(password, hash string) bool

VerifyPassword compares a plaintext password with a bcrypt hash.

Parameters:

  • password: The plaintext password to verify
  • hash: The bcrypt hash to compare against

Returns true if the password matches the hash, false otherwise.

Types

type Claims

type Claims struct {
	UserID       string `json:"userId"`       // User's email address
	Role         string `json:"role"`         // User role: "user" or "admin"
	Name         string `json:"name"`         // User's first name
	Surname      string `json:"surname"`      // User's last name
	Organization string `json:"organization"` // User's organization
	jwt.RegisteredClaims
}

Claims represents the JWT claims for krkn-operator authentication. It extends the standard JWT claims with user-specific information.

func GetClaimsFromContext

func GetClaimsFromContext(ctx context.Context) *Claims

GetClaimsFromContext extracts JWT claims from the request context

Parameters:

  • ctx: The request context

Returns the claims if found, nil otherwise

type ContextKey

type ContextKey string

ContextKey is a custom type for context keys to avoid collisions

type Middleware

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

Middleware provides HTTP middleware for JWT authentication and authorization

func NewLazyMiddleware

func NewLazyMiddleware(tokenGenLoader func() *TokenGenerator) *Middleware

NewLazyMiddleware creates a new authentication middleware with lazy token generator loading

Parameters:

  • tokenGenLoader: A function that returns the TokenGenerator (called on first use)

Returns a new Middleware instance that loads the TokenGenerator when first needed

func NewMiddleware

func NewMiddleware(tokenGen *TokenGenerator) *Middleware

NewMiddleware creates a new authentication middleware

Parameters:

  • tokenGen: The TokenGenerator used to validate JWT tokens

Returns a new Middleware instance

func (*Middleware) RequireAnyRole

func (m *Middleware) RequireAnyRole(roles []Role, next http.Handler) http.Handler

RequireAnyRole is a middleware that requires any of the specified roles Must be used after RequireAuth middleware

func (*Middleware) RequireAuth

func (m *Middleware) RequireAuth(next http.Handler) http.Handler

RequireAuth is a middleware that requires a valid JWT token It validates the token and adds the claims to the request context

func (*Middleware) RequireRole

func (m *Middleware) RequireRole(role Role, next http.Handler) http.Handler

RequireRole is a middleware that requires a specific role Must be used after RequireAuth middleware

type Role

type Role string

Role represents a user role

const (
	// RoleAdmin represents an admin user
	RoleAdmin Role = "admin"
	// RoleUser represents a regular user
	RoleUser Role = "user"
)

type TokenGenerator

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

TokenGenerator handles JWT token generation and validation.

func NewTokenGenerator

func NewTokenGenerator(secretKey []byte, tokenDuration time.Duration, issuer string) *TokenGenerator

NewTokenGenerator creates a new JWT token generator.

Parameters:

  • secretKey: The secret key used to sign JWT tokens (should be at least 32 bytes)
  • tokenDuration: How long tokens remain valid (e.g., 24 hours)
  • issuer: The issuer claim for tokens (typically "krkn-operator")

Returns a TokenGenerator instance.

func (*TokenGenerator) GenerateToken

func (tg *TokenGenerator) GenerateToken(userID, role, name, surname, organization string) (string, error)

GenerateToken creates a new JWT token for a user.

Parameters:

  • userID: The user's email address
  • role: The user's role ("user" or "admin")
  • name: The user's first name
  • surname: The user's last name
  • organization: The user's organization (optional)

Returns the signed JWT token string or an error.

func (*TokenGenerator) IsAdmin

func (tg *TokenGenerator) IsAdmin(tokenString string) (bool, error)

IsAdmin checks if the token belongs to an admin user.

Parameters:

  • tokenString: The JWT token to check

Returns true if the user has admin role, false otherwise.

func (*TokenGenerator) RefreshToken

func (tg *TokenGenerator) RefreshToken(tokenString string) (string, error)

RefreshToken generates a new token with the same claims but updated expiration.

Parameters:

  • tokenString: The current JWT token to refresh

Returns a new JWT token with extended expiration or an error.

func (*TokenGenerator) ValidateToken

func (tg *TokenGenerator) ValidateToken(tokenString string) (*Claims, error)

ValidateToken validates a JWT token and returns the claims.

Parameters:

  • tokenString: The JWT token string to validate

Returns the claims if valid, or an error if the token is invalid or expired.

Jump to

Keyboard shortcuts

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