auth

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultIterations     = 600000
	DefaultMinPasswordLen = 8
	MaxPasswordLength     = 1024
)
View Source
const (
	ActionCreate = "create"
	ActionRead   = "read"
	ActionUpdate = "update"
	ActionDelete = "delete"
)

Variables

View Source
var (
	ErrPasswordMismatch = errors.New("coyote/auth: the new passwords do not match")
	ErrWrongPassword    = errors.New("coyote/auth: the current password is not right")
	ErrChangeDisabled   = errors.New("coyote/auth: password changes are turned off")
)
View Source
var (
	ErrUserNotFound   = errors.New("coyote/auth: user not found")
	ErrUserExists     = errors.New("coyote/auth: username already taken")
	ErrEmailExists    = errors.New("coyote/auth: email already registered")
	ErrInvalidUser    = errors.New("coyote/auth: invalid username")
	ErrInvalidEmail   = errors.New("coyote/auth: invalid email address")
	ErrLastSuperadmin = errors.New("coyote/auth: cannot remove the last superadmin")
)
View Source
var (
	ErrInvalidHash      = errors.New("coyote/auth: malformed password hash")
	ErrPasswordTooShort = errors.New("coyote/auth: password is too short")
	ErrPasswordTooLong  = errors.New("coyote/auth: password is too long")
	ErrPasswordRejected = errors.New("coyote/auth: password rejected")
)
View Source
var (
	ErrPasswordNumericOnly = errors.New("coyote/auth: password is entirely numeric")
	ErrPasswordSimilar     = errors.New("coyote/auth: password is too similar to the account details")
	ErrPasswordCommon      = errors.New("coyote/auth: password is one of the most commonly used")
)
View Source
var (
	ErrInvalidCredentials = errors.New("coyote/auth: invalid username or password")
	ErrInactiveAccount    = errors.New("coyote/auth: account is disabled")
)
View Source
var (
	ErrTokenInvalid = errors.New("coyote/auth: reset token is unknown, used or expired")
	ErrNoTokenStore = errors.New("coyote/auth: no reset token store configured")
)
View Source
var ErrTooManyAttempts = errors.New("coyote/auth: too many failed sign-in attempts")

Functions

func Actions

func Actions() []string

func ApplyPasswordRules

func ApplyPasswordRules(rules []PasswordRule, password string, user *User) error

func Codename

func Codename(resource, action string) string

func CommonPasswords

func CommonPasswords() []string

func HashPassword

func HashPassword(password string) (string, error)

func LooksHashed

func LooksHashed(encoded string) bool

func Matches

func Matches(u *User, term string) bool

func Prepare

func Prepare(u *User)

func SplitCodename

func SplitCodename(codename string) (resource, action string, ok bool)

func TokenDigest

func TokenDigest(plain string) string

func ValidatePassword

func ValidatePassword(password string) error

func ValidatePasswordLength

func ValidatePasswordLength(password string, minLength int) error

func VerifyPassword

func VerifyPassword(password, encoded string) bool

Types

type Hasher

type Hasher struct {
	Iterations int
}

func DefaultHasher

func DefaultHasher() Hasher

func (Hasher) Hash

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

func (Hasher) NeedsRehash

func (h Hasher) NeedsRehash(encoded string) bool

type LoginLimiter

type LoginLimiter interface {
	Allow(key string) bool
	Fail(key string)
	Reset(key string)
}

func NewLoginLimiter

func NewLoginLimiter(policy ThrottlePolicy) LoginLimiter

type MemoryStore

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

func NewMemoryStore

func NewMemoryStore() *MemoryStore

func (*MemoryStore) All

func (m *MemoryStore) All(_ context.Context) ([]*User, error)

func (*MemoryStore) ByEmail

func (m *MemoryStore) ByEmail(_ context.Context, email string) (*User, error)

func (*MemoryStore) ByID

func (m *MemoryStore) ByID(_ context.Context, id string) (*User, error)

func (*MemoryStore) ByUsername

func (m *MemoryStore) ByUsername(_ context.Context, username string) (*User, error)

func (*MemoryStore) Count

func (m *MemoryStore) Count(_ context.Context) (int, error)

func (*MemoryStore) CountActiveSuperadmins

func (m *MemoryStore) CountActiveSuperadmins(_ context.Context) (int, error)

func (*MemoryStore) Create

func (m *MemoryStore) Create(_ context.Context, u *User) error

func (*MemoryStore) Delete

func (m *MemoryStore) Delete(_ context.Context, id string) error

func (*MemoryStore) Recent

func (m *MemoryStore) Recent(ctx context.Context, n int) ([]*User, error)

func (*MemoryStore) Search

func (m *MemoryStore) Search(ctx context.Context, term string, limit, offset int) ([]*User, int, error)

func (*MemoryStore) Stats

func (m *MemoryStore) Stats(ctx context.Context) (Stats, error)

func (*MemoryStore) Update

func (m *MemoryStore) Update(_ context.Context, u *User) error

type NewUser

type NewUser struct {
	Username     string
	Email        string
	FirstName    string
	LastName     string
	Password     string
	IsStaff      bool
	IsSuperadmin bool
}

type Options

type Options struct {
	Hasher            Hasher
	MinPasswordLength int
	PasswordRules     []PasswordRule
	Throttle          ThrottlePolicy
	Limiter           LoginLimiter
	TrustedProxyCount int
	PermissionStore   PermissionStore
	AllowChange       bool
	Tokens            TokenStore
	TokenLifetime     time.Duration
}

type PasswordChange

type PasswordChange struct {
	Current string
	New     string
	Confirm string
}

type PasswordRule

type PasswordRule func(password string, user *User) error

func DefaultPasswordRules

func DefaultPasswordRules(minLength int) []PasswordRule

func MinimumLength

func MinimumLength(minLength int) PasswordRule

func NotCommon

func NotCommon(list []string) PasswordRule

func NotEntirelyNumeric

func NotEntirelyNumeric() PasswordRule

func NotSimilarToAccount

func NotSimilarToAccount() PasswordRule

type Permission

type Permission struct {
	ID        string `gorm:"primaryKey;size:64"`
	Resource  string `gorm:"uniqueIndex:idx_permission_codename;size:100;not null"`
	Action    string `gorm:"uniqueIndex:idx_permission_codename;size:20;not null"`
	Label     string `gorm:"size:150"`
	CreatedAt time.Time
}

func PermissionsFor

func PermissionsFor(resource string) []Permission

func (Permission) Codename

func (p Permission) Codename() string

func (Permission) TableName

func (Permission) TableName() string

type PermissionStore

type PermissionStore interface {
	SyncPermissions(ctx context.Context, resources []string) (SyncReport, error)
	AllPermissions(ctx context.Context) ([]Permission, error)
	CodenamesForUser(ctx context.Context, userID string) ([]string, error)

	AllRoles(ctx context.Context) ([]Role, error)
	RoleByID(ctx context.Context, id string) (*Role, error)
	CreateRole(ctx context.Context, role *Role) error
	UpdateRole(ctx context.Context, role *Role) error
	DeleteRole(ctx context.Context, id string) error

	RolePermissions(ctx context.Context, roleID string) ([]string, error)
	SetRolePermissions(ctx context.Context, roleID string, permissionIDs []string) error
	RolesForUser(ctx context.Context, userID string) ([]string, error)
	SetUserRoles(ctx context.Context, userID string, roleIDs []string) error
}

type ResetToken

type ResetToken struct {
	Digest    string `gorm:"primaryKey;size:64"`
	UserID    string `gorm:"index;size:64;not null"`
	CreatedAt time.Time
	ExpiresAt time.Time `gorm:"index"`
	UsedAt    *time.Time
}

func (ResetToken) TableName

func (ResetToken) TableName() string

type Role

type Role struct {
	ID          string `gorm:"primaryKey;size:64"`
	Name        string `gorm:"uniqueIndex;size:100;not null"`
	Description string `gorm:"size:255"`
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

func (Role) TableName

func (Role) TableName() string

type RolePermission

type RolePermission struct {
	RoleID       string `gorm:"primaryKey;size:64"`
	PermissionID string `gorm:"primaryKey;size:64"`
}

func (RolePermission) TableName

func (RolePermission) TableName() string

type Service

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

func NewService

func NewService(users Store, sessions *session.Manager, opts Options) *Service

func (*Service) AllowsPasswordChange

func (s *Service) AllowsPasswordChange() bool

func (*Service) Authenticate

func (s *Service) Authenticate(ctx context.Context, username, password string) (*User, error)

func (*Service) AuthenticateRequest

func (s *Service) AuthenticateRequest(r *http.Request, username, password string) (*User, error)

func (*Service) Can

func (s *Service) Can(r *http.Request, codename string) bool

func (*Service) CanAny

func (s *Service) CanAny(r *http.Request, codenames ...string) bool

func (*Service) ChangePassword

func (s *Service) ChangePassword(r *http.Request, in PasswordChange) error

func (*Service) CheckResetToken

func (s *Service) CheckResetToken(ctx context.Context, plain string) (*User, error)

func (*Service) CreateResetToken

func (s *Service) CreateResetToken(ctx context.Context, userID string) (string, error)

func (*Service) CreateSuperadmin

func (s *Service) CreateSuperadmin(ctx context.Context, username, email, password string) (*User, error)

func (*Service) CreateUser

func (s *Service) CreateUser(ctx context.Context, in NewUser) (*User, error)

func (*Service) CurrentUser

func (s *Service) CurrentUser(r *http.Request) *User

func (*Service) GrantedTo

func (s *Service) GrantedTo(ctx context.Context, userID string) ([]string, error)

func (*Service) HashPassword

func (s *Service) HashPassword(password string) (string, error)

func (*Service) Login

func (s *Service) Login(r *http.Request, u *User) error

func (*Service) Logout

func (s *Service) Logout(r *http.Request) error

func (*Service) Middleware

func (s *Service) Middleware(next http.Handler) http.Handler

func (*Service) MinPasswordLength

func (s *Service) MinPasswordLength() int

func (*Service) PasswordRules

func (s *Service) PasswordRules() []PasswordRule

func (*Service) Permissions

func (s *Service) Permissions() PermissionStore

func (*Service) RequireLogin

func (s *Service) RequireLogin(loginURL string) func(http.Handler) http.Handler

func (*Service) RequirePermission

func (s *Service) RequirePermission(codename string) func(http.Handler) http.Handler

func (*Service) RequireStaff

func (s *Service) RequireStaff(loginURL string) func(http.Handler) http.Handler

func (*Service) RequireSuperadmin

func (s *Service) RequireSuperadmin(loginURL string) func(http.Handler) http.Handler

func (*Service) ResetPassword

func (s *Service) ResetPassword(ctx context.Context, userID string, in PasswordChange) error

func (*Service) RevokeOtherSessions

func (s *Service) RevokeOtherSessions(r *http.Request) int

func (*Service) SetPassword

func (s *Service) SetPassword(ctx context.Context, id, password string) error

func (*Service) Tokens

func (s *Service) Tokens() TokenStore

func (*Service) UseResetToken

func (s *Service) UseResetToken(ctx context.Context, plain string, in PasswordChange) (*User, error)

func (*Service) Users

func (s *Service) Users() Store

func (*Service) ValidatePassword

func (s *Service) ValidatePassword(password string) error

func (*Service) ValidatePasswordFor

func (s *Service) ValidatePasswordFor(password string, user *User) error

type Stats

type Stats struct {
	Total       int
	Superadmins int
	Staff       int
}

type Store

type Store interface {
	ByID(ctx context.Context, id string) (*User, error)
	ByUsername(ctx context.Context, username string) (*User, error)
	ByEmail(ctx context.Context, email string) (*User, error)
	Create(ctx context.Context, u *User) error
	Update(ctx context.Context, u *User) error
	Delete(ctx context.Context, id string) error
	All(ctx context.Context) ([]*User, error)
	Search(ctx context.Context, term string, limit, offset int) ([]*User, int, error)
	Recent(ctx context.Context, n int) ([]*User, error)
	Count(ctx context.Context) (int, error)
	Stats(ctx context.Context) (Stats, error)
}

func Guarded

func Guarded(store Store) Store

type SuperadminCounter

type SuperadminCounter interface {
	CountActiveSuperadmins(ctx context.Context) (int, error)
}

type SyncReport

type SyncReport struct {
	Created []string
	Stale   []string
}

func (SyncReport) Empty

func (r SyncReport) Empty() bool

type ThrottlePolicy

type ThrottlePolicy struct {
	Enabled     bool
	MaxAttempts int
	Window      time.Duration
	Lockout     time.Duration
}

type TokenStore

type TokenStore interface {
	Save(ctx context.Context, token ResetToken) error
	ByDigest(ctx context.Context, digest string) (ResetToken, error)
	MarkUsed(ctx context.Context, digest string, at time.Time) error
	DeleteForUser(ctx context.Context, userID string) error
	Sweep(ctx context.Context, before time.Time) (int, error)
}

type User

type User struct {
	ID           string `gorm:"primaryKey;size:64"`
	FirstName    string
	LastName     string
	Email        string `gorm:"index;size:320"`
	Username     string `gorm:"uniqueIndex;size:64;not null"`
	Password     string `gorm:"not null"`
	IsActive     bool   `gorm:"index;default:true"`
	IsStaff      bool   `gorm:"index"`
	IsSuperadmin bool   `gorm:"index"`
	LastLoginAt  time.Time
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

func UserFrom

func UserFrom(ctx context.Context) *User

func Window

func Window(users []*User, limit, offset int) []*User

func (*User) CanReachAdmin

func (u *User) CanReachAdmin() bool

func (*User) Clone

func (u *User) Clone() *User

func (*User) DisplayName

func (u *User) DisplayName() string

func (*User) FullName

func (u *User) FullName() string

func (*User) HasLoggedIn

func (u *User) HasLoggedIn() bool

func (*User) HasUsablePassword

func (u *User) HasUsablePassword() bool

func (*User) Initials

func (u *User) Initials() string

func (*User) Validate

func (u *User) Validate() error

type UserRole

type UserRole struct {
	UserID string `gorm:"primaryKey;size:64"`
	RoleID string `gorm:"primaryKey;size:64"`
}

func (UserRole) TableName

func (UserRole) TableName() string

Jump to

Keyboard shortcuts

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