auth

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Aug 8, 2026 License: EUPL-1.2 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultSessionCookieName = "taskemon_session"
	DefaultCSRFCookieName    = "taskemon_csrf"
	CSRFHeaderName           = "X-CSRF-Token"
)

Variables

View Source
var (
	ErrAlreadySetup            = errors.New("taskemon is already configured")
	ErrUserAlreadyExists       = errors.New("user already exists")
	ErrAPIKeyNotFound          = errors.New("api key not found")
	ErrEmptyAPIKeyName         = errors.New("api key name cannot be empty")
	ErrAPIKeyNameTooLong       = errors.New("api key name is too long")
	ErrInvalidAPIKeyExpiration = errors.New("api key expiration must be in the future")
	ErrEmptyDisplayName        = errors.New("display name cannot be empty")
	ErrDisplayNameTooLong      = errors.New("display name is too long")
	ErrEmptyUsername           = errors.New("username cannot be empty")
	ErrUsernameTooShort        = errors.New("username is too short")
	ErrUsernameTooLong         = errors.New("username is too long")
	ErrInvalidTimezone         = errors.New("invalid timezone")
	ErrNoUserChanges           = errors.New("no user changes provided")
	ErrUnauthorized            = errors.New("unauthorized")
	ErrInvalidCredentials      = errors.New("invalid username or password")
	ErrInvalidCurrentPassword  = errors.New("current password is invalid")
	ErrPasswordTooShort        = errors.New("password must contain at least 15 characters")
	ErrPasswordTooLong         = errors.New("password must contain at most 128 characters")
	ErrPasswordInvalidUTF8     = errors.New("password must be valid UTF-8")
	ErrPasswordUnchanged       = errors.New("new password must be different")
	ErrPasswordChanged         = errors.New("password changed during operation")
	ErrInvalidPasswordHash     = errors.New("invalid password hash")
	ErrTooManyLoginAttempts    = errors.New("too many login attempts")
	ErrAuthenticationBusy      = errors.New("authentication is temporarily busy")
	ErrWebSessionRequired      = errors.New("web session required")
	ErrInvalidCSRFToken        = errors.New("invalid csrf token")
	ErrWebSessionNotFound      = errors.New("web session not found")
	ErrUserNotFound            = errors.New("user not found")
	ErrUserNotDisabled         = errors.New("user not disabled")
	ErrUserAlreadyDisabled     = errors.New("user already disabled")
	ErrLastEnabledAdmin        = errors.New("cannot disable/delete last enabled admin")
	ErrLastEnabledAdminDemote  = errors.New("cannot demote last enabled admin")
	ErrDisabledUserAdminChange = errors.New("cannot change admin status of a disabled user")
)

Functions

func GenerateAPIKey

func GenerateAPIKey() (plain, hash, prefix string, err error)

func GenerateSetupToken

func GenerateSetupToken() (string, error)

func WithAuthentication

func WithAuthentication(ctx context.Context, authentication Authentication) context.Context

Types

type APIKey

type APIKey struct {
	CreatedAt  time.Time
	ExpiresAt  *time.Time
	LastUsedAt *time.Time
	RevokedAt  *time.Time
	Name       string
	KeyPrefix  string
	ID         int64
	UserID     int64
}

type APIKeyCreate

type APIKeyCreate struct {
	ExpiresAt *time.Time
	Name      string
}

type AuthMethod

type AuthMethod string
const (
	AuthMethodAPIKey  AuthMethod = "api_key"
	AuthMethodSession AuthMethod = "session"
)

type Authentication

type Authentication struct {
	Method AuthMethod

	User         User
	CredentialID int64
	// contains filtered or unexported fields
}

func AuthenticationFromContext

func AuthenticationFromContext(ctx context.Context) (Authentication, bool)

type CreateUser

type CreateUser struct {
	Username    string
	DisplayName string
	Password    string
	Timezone    string
}

type CreatedAPIKey

type CreatedAPIKey struct {
	Token  string
	APIKey APIKey
}

type Login

type Login struct {
	Username  string
	Password  string
	IPAddress string
	UserAgent string
}

type LoginLimiter

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

func NewLoginLimiter

func NewLoginLimiter() *LoginLimiter

func (*LoginLimiter) Allow

func (l *LoginLimiter) Allow(ipAddress, username string) bool

func (*LoginLimiter) ResetUsername

func (l *LoginLimiter) ResetUsername(username string)

type LoginResult

type LoginResult struct {
	ExpiresAt    time.Time
	SessionToken string
	CSRFToken    string
	User         User
}

type Middleware

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

func NewMiddleware

func NewMiddleware(service Service, sessionCookieName string) Middleware

func (Middleware) Admin

func (m Middleware) Admin(next http.Handler) http.Handler

func (Middleware) Authenticate

func (m Middleware) Authenticate(next http.Handler) http.Handler

func (Middleware) Protect

func (m Middleware) Protect(next http.Handler) http.Handler

func (Middleware) RequireAdmin

func (m Middleware) RequireAdmin(next http.Handler) http.Handler

func (Middleware) RequireCSRF

func (m Middleware) RequireCSRF(next http.Handler) http.Handler

func (Middleware) RequireWebSession

func (m Middleware) RequireWebSession(next http.Handler) http.Handler

func (Middleware) WebSession

func (m Middleware) WebSession(next http.Handler) http.Handler

type PasswordChange

type PasswordChange struct {
	CurrentPassword string
	NewPassword     string
}

type PasswordCredentials

type PasswordCredentials struct {
	PasswordHash string
	User         User
}

type PasswordHasher

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

func NewPasswordHasher

func NewPasswordHasher() PasswordHasher

func (PasswordHasher) Hash

func (h PasswordHasher) Hash(password string) (string, error)

func (PasswordHasher) NeedsRehash

func (h PasswordHasher) NeedsRehash(encodedHash string) (bool, error)

func (PasswordHasher) Verify

func (h PasswordHasher) Verify(password, encodedHash string) (bool, error)

type Repository

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

func NewRepository

func NewRepository(sqlDB *sql.DB) Repository

func (Repository) CountUsers

func (r Repository) CountUsers(ctx context.Context) (int64, error)

func (Repository) CreateAPIKey

func (r Repository) CreateAPIKey(ctx context.Context, userID int64, create APIKeyCreate, apiKeyHash, prefix string) (APIKey, error)

func (Repository) CreateFirstUser

func (r Repository) CreateFirstUser(ctx context.Context, username, displayName, passwordHash, timezone string) (User, error)

func (Repository) CreateUser

func (r Repository) CreateUser(ctx context.Context, username, displayName, passwordHash, timezone string) (User, error)

func (Repository) CreateWebSession

func (r Repository) CreateWebSession(ctx context.Context, userID int64, tokenHash, csrfTokenHash, userAgent, passwordHash string, expiresAt, idleExpiresAt time.Time) (WebSession, error)

func (Repository) DeleteExpiredWebSessions

func (r Repository) DeleteExpiredWebSessions(ctx context.Context) error

func (Repository) DeleteUser

func (r Repository) DeleteUser(ctx context.Context, userID int64) error

func (Repository) DemoteUser

func (r Repository) DemoteUser(ctx context.Context, userID int64) error

func (Repository) DisableUser

func (r Repository) DisableUser(ctx context.Context, userID int64) error

func (Repository) EnableUser

func (r Repository) EnableUser(ctx context.Context, userID int64) (User, error)

func (Repository) GetPasswordCredentialsByUsername

func (r Repository) GetPasswordCredentialsByUsername(ctx context.Context, username string) (PasswordCredentials, error)

func (Repository) GetUserByAPIKeyHash

func (r Repository) GetUserByAPIKeyHash(ctx context.Context, tokenHash string) (User, int64, error)

func (Repository) GetUserByID

func (r Repository) GetUserByID(ctx context.Context, userID int64) (User, error)

func (Repository) GetUserByUsername

func (r Repository) GetUserByUsername(ctx context.Context, username string) (User, error)

func (Repository) GetWebSessionAuthData

func (r Repository) GetWebSessionAuthData(ctx context.Context, tokenHash string) (SessionAuthData, error)

func (Repository) InitializeUserStatistic

func (r Repository) InitializeUserStatistic(ctx context.Context, userID int64) error

func (Repository) IsLastEnabledAdmin

func (r Repository) IsLastEnabledAdmin(ctx context.Context, userID int64) (bool, error)

func (Repository) ListAPIKeysByUser

func (r Repository) ListAPIKeysByUser(ctx context.Context, userID int64) ([]APIKey, error)

func (Repository) ListDisabledUsers

func (r Repository) ListDisabledUsers(ctx context.Context) ([]User, error)

func (Repository) ListUsers

func (r Repository) ListUsers(ctx context.Context) ([]User, error)

func (Repository) ListWebSessions

func (r Repository) ListWebSessions(ctx context.Context, userID int64) ([]WebSession, error)

func (Repository) PromoteUser

func (r Repository) PromoteUser(ctx context.Context, userID int64) error

func (Repository) RevokeAPIKey

func (r Repository) RevokeAPIKey(ctx context.Context, keyID, userID int64) error

func (Repository) RevokeAllAPIKeys

func (r Repository) RevokeAllAPIKeys(ctx context.Context, userID int64) error

func (Repository) RevokeAllWebSessions

func (r Repository) RevokeAllWebSessions(ctx context.Context, userID int64) error

func (Repository) RevokeWebSession

func (r Repository) RevokeWebSession(ctx context.Context, sessionID, userID int64) error

func (Repository) RevokeWebSessionByTokenHash

func (r Repository) RevokeWebSessionByTokenHash(ctx context.Context, tokenHash string) error

func (Repository) TouchAPIKey

func (r Repository) TouchAPIKey(ctx context.Context, keyID int64) error

func (Repository) TouchWebSession

func (r Repository) TouchWebSession(ctx context.Context, sessionID int64, idleExpiresAt time.Time) error

func (Repository) UpdateAPIKey

func (r Repository) UpdateAPIKey(ctx context.Context, userID, keyID int64, apiKeyName string) (APIKey, error)

func (Repository) UpdatePasswordHash

func (r Repository) UpdatePasswordHash(ctx context.Context, userID int64, currentPasswordHash, newPasswordHash string) error

func (Repository) UpdateUser

func (r Repository) UpdateUser(ctx context.Context, userID int64, displayName, timezone *string) (User, error)

func (Repository) WithTx

func (r Repository) WithTx(ctx context.Context, fn func(Repository) error) error

type Service

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

func NewService

func NewService(repo Repository, passwords PasswordHasher, config ServiceConfig) (Service, error)

func (Service) AuthenticateAPIKey

func (s Service) AuthenticateAPIKey(ctx context.Context, token string) (Authentication, error)

func (Service) AuthenticateWebSession

func (s Service) AuthenticateWebSession(ctx context.Context, token string) (Authentication, error)

func (Service) ChangePassword

func (s Service) ChangePassword(ctx context.Context, user User, change PasswordChange) error

func (Service) CleanupExpiredWebSessions

func (s Service) CleanupExpiredWebSessions(ctx context.Context) error

func (Service) CreateAPIKey

func (s Service) CreateAPIKey(ctx context.Context, userID int64, create APIKeyCreate) (CreatedAPIKey, error)

func (Service) CreateUser

func (s Service) CreateUser(ctx context.Context, create CreateUser) (User, error)

func (Service) DeleteUser

func (s Service) DeleteUser(ctx context.Context, userID int64) error

func (Service) DemoteUser

func (s Service) DemoteUser(ctx context.Context, userID int64) error

func (Service) DisableUser

func (s Service) DisableUser(ctx context.Context, userID int64) error

func (Service) EnableUser

func (s Service) EnableUser(ctx context.Context, userID int64) (User, error)

func (Service) GetUser

func (s Service) GetUser(ctx context.Context, userID int64) (User, error)

func (Service) GetUserByUsername

func (s Service) GetUserByUsername(ctx context.Context, username string) (User, error)

func (Service) ListAPIKeys

func (s Service) ListAPIKeys(ctx context.Context, userID int64) ([]APIKey, error)

func (Service) ListDisabledUsers

func (s Service) ListDisabledUsers(ctx context.Context) ([]User, error)

func (Service) ListUsers

func (s Service) ListUsers(ctx context.Context) ([]User, error)

func (Service) ListWebSessions

func (s Service) ListWebSessions(ctx context.Context, userID, currentSessionID int64) ([]WebSession, error)

func (Service) Login

func (s Service) Login(ctx context.Context, login Login) (LoginResult, error)

func (Service) Logout

func (s Service) Logout(ctx context.Context, token string) error

func (Service) PromoteUser

func (s Service) PromoteUser(ctx context.Context, userID int64) error

func (Service) RevokeAPIKey

func (s Service) RevokeAPIKey(ctx context.Context, keyID, userID int64) error

func (Service) RevokeAllWebSessions

func (s Service) RevokeAllWebSessions(ctx context.Context, userID int64) error

func (Service) RevokeWebSession

func (s Service) RevokeWebSession(ctx context.Context, sessionID, userID int64) error

func (Service) SetupFirstUser

func (s Service) SetupFirstUser(ctx context.Context, setup Setup) (SetupResult, error)

func (Service) SetupRequired

func (s Service) SetupRequired(ctx context.Context) (bool, error)

func (Service) UpdateAPIKey

func (s Service) UpdateAPIKey(ctx context.Context, userID, keyID int64, apiKeyName string) (APIKey, error)

func (Service) UpdateUser

func (s Service) UpdateUser(ctx context.Context, userID int64, update UserUpdate) (User, error)

type ServiceConfig

type ServiceConfig struct {
	SessionLifetime               time.Duration
	SessionIdleTimeout            time.Duration
	MaximumConcurrentPasswordWork int
}

func DefaultServiceConfig

func DefaultServiceConfig() ServiceConfig

type SessionAuthData

type SessionAuthData struct {
	LastUsedAt    time.Time
	ExpiresAt     time.Time
	CSRFTokenHash string
	User          User
	SessionID     int64
}

type Setup

type Setup struct {
	Username    string
	DisplayName string
	Password    string
	APIKeyName  string
	Timezone    string
}

type SetupResult

type SetupResult struct {
	APIKey CreatedAPIKey
	User   User
}

type User

type User struct {
	CreatedAt   time.Time
	DisabledAt  *time.Time
	Username    string
	DisplayName string
	Timezone    string
	ID          int64
	IsAdmin     bool
}

func UserFromContext

func UserFromContext(ctx context.Context) (User, bool)

type UserUpdate

type UserUpdate struct {
	DisplayName *string
	Timezone    *string
}

type WebSession

type WebSession struct {
	CreatedAt     time.Time
	ExpiresAt     time.Time
	IdleExpiresAt time.Time
	LastUsedAt    time.Time
	RevokedAt     *time.Time
	UserAgent     string
	ID            int64
	UserID        int64
	IsCurrent     bool
}

Jump to

Keyboard shortcuts

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