Help us shape the future of Go! Take the 2026 Go Developer Survey

auth

package
v0.0.12 Latest Latest
Warning

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

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

Documentation

Overview

Package auth provides authentication and authorization services.

Package auth provides authentication and authorization services.

Index

Constants

View Source
const InvitationExpiry = 7 * 24 * time.Hour // 7 days

InvitationExpiry is the default duration for invitation validity.

Variables

View Source
var (
	ErrOwnerExists         = errors.New("owner already exists, public registration is disabled")
	ErrPermissionDenied    = errors.New("permission denied")
	ErrInvalidRole         = errors.New("invalid role")
	ErrCannotRemoveOwner   = errors.New("cannot remove the only owner")
	ErrUserNotFound        = errors.New("user not found")
	ErrInvitationNotFound  = errors.New("invitation not found")
	ErrInvitationExpired   = errors.New("invitation has expired")
	ErrInvitationUsed      = errors.New("invitation has already been used")
	ErrEmailAlreadyInvited = errors.New("email has already been invited")
)

RBAC errors.

View Source
var (
	ErrInvalidToken     = errors.New("invalid token")
	ErrExpiredToken     = errors.New("token has expired")
	ErrInvalidAPIKey    = errors.New("invalid API key")
	ErrMissingClaims    = errors.New("missing required claims")
	ErrInvalidSignature = errors.New("invalid token signature")
)

Common errors returned by the auth service.

Functions

func CheckRolePermission

func CheckRolePermission(role store.Role, permission Permission) error

CheckRolePermission checks if a role has a specific permission.

func ExtractBearerToken

func ExtractBearerToken(authHeader string) string

ExtractBearerToken extracts the token from a Bearer authorization header.

func GenerateAPIKey

func GenerateAPIKey() (string, error)

GenerateAPIKey generates a new API key and returns the raw key. The raw key should be shown to the user once and never stored.

func HashAPIKey

func HashAPIKey(key string) string

HashAPIKey creates a SHA256 hash of an API key for storage.

func SecureCompare

func SecureCompare(a, b string) bool

SecureCompare performs a constant-time comparison of two strings. This helps prevent timing attacks.

Types

type APIKey

type APIKey struct {
	ID        string    `json:"id"`
	UserID    string    `json:"user_id"`
	KeyHash   string    `json:"-"` // SHA256 hash of the key
	Name      string    `json:"name"`
	CreatedAt time.Time `json:"created_at"`
	ExpiresAt time.Time `json:"expires_at,omitempty"`
}

APIKey represents a stored API key.

type APIKeyStore

type APIKeyStore interface {
	// GetByHash retrieves an API key by its hash.
	GetByHash(ctx context.Context, hash string) (*APIKey, error)
	// Create creates a new API key.
	Create(ctx context.Context, key *APIKey) error
	// Delete removes an API key.
	Delete(ctx context.Context, id string) error
	// ListByUser retrieves all API keys for a user.
	ListByUser(ctx context.Context, userID string) ([]*APIKey, error)
}

APIKeyStore defines the interface for API key storage.

type Claims

type Claims struct {
	UserID string    `json:"user_id"`
	Email  string    `json:"email"`
	Exp    time.Time `json:"exp"`
}

Claims represents the JWT claims structure.

type Config

type Config struct {
	JWTSecret   []byte
	TokenExpiry time.Duration
}

Config holds authentication configuration.

type Permission

type Permission string

Permission represents an action that can be performed.

const (
	// PermissionManageUsers allows managing users (invite, remove, change roles).
	PermissionManageUsers Permission = "manage_users"
	// PermissionManageSettings allows managing system settings.
	PermissionManageSettings Permission = "manage_settings"
	// PermissionViewUsers allows viewing the user list.
	PermissionViewUsers Permission = "view_users"
	// PermissionManageApps allows creating and deleting apps.
	PermissionManageApps Permission = "manage_apps"
	// PermissionViewApps allows viewing apps.
	PermissionViewApps Permission = "view_apps"
	// PermissionDeploy allows deploying services.
	PermissionDeploy Permission = "deploy"
)

type RBACService

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

RBACService provides role-based access control functionality.

func NewRBACService

func NewRBACService(st store.Store, logger *slog.Logger) *RBACService

NewRBACService creates a new RBAC service.

func (*RBACService) AcceptInvitation

func (s *RBACService) AcceptInvitation(ctx context.Context, token, password string) (*store.User, error)

AcceptInvitation accepts an invitation and creates a user.

func (*RBACService) CanRegister

func (s *RBACService) CanRegister(ctx context.Context) (bool, error)

CanRegister checks if public registration is allowed. Returns true if no owner exists, false otherwise.

func (*RBACService) CheckPermission

func (s *RBACService) CheckPermission(ctx context.Context, userID string, permission Permission) error

CheckPermission verifies a user has permission for an action.

func (*RBACService) CreateInvitation

func (s *RBACService) CreateInvitation(ctx context.Context, email string, invitedBy string, role store.Role) (*models.Invitation, error)

CreateInvitation creates an invitation for a new user.

func (*RBACService) ListInvitations

func (s *RBACService) ListInvitations(ctx context.Context) ([]*models.Invitation, error)

ListInvitations returns all invitations.

func (*RBACService) RemoveUser

func (s *RBACService) RemoveUser(ctx context.Context, userID string) error

RemoveUser removes a user from the system.

func (*RBACService) RevokeInvitation

func (s *RBACService) RevokeInvitation(ctx context.Context, invitationID string) error

RevokeInvitation revokes a pending invitation.

type Service

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

Service provides authentication and authorization functionality.

func NewService

func NewService(cfg *Config, apiKeyStore APIKeyStore, logger *slog.Logger) *Service

NewService creates a new authentication service.

func (*Service) GenerateToken

func (s *Service) GenerateToken(userID, email string) (string, error)

GenerateToken creates a new JWT token for the given user.

func (*Service) ValidateAPIKey

func (s *Service) ValidateAPIKey(ctx context.Context, apiKey string) (*User, error)

ValidateAPIKey validates an API key and returns the associated user.

func (*Service) ValidateToken

func (s *Service) ValidateToken(tokenString string) (*Claims, error)

ValidateToken validates a JWT token and returns the claims.

type User

type User struct {
	ID    string `json:"id"`
	Email string `json:"email"`
}

User represents an authenticated user.

Jump to

Keyboard shortcuts

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