Documentation
¶
Index ¶
- Variables
- func CheckPassword(plain, hash string) error
- func GenerateResetToken() (string, error)
- func HashPassword(cfg Config, plain string) (string, error)
- func HashResetToken(rawToken string) string
- func ValidatePasswordStrength(cfg Config, plain string) error
- type Claims
- type Config
- type Group
- type Mailer
- type MigrationRecord
- type Migrator
- type OTP
- type Organization
- type PasswordReset
- type Permission
- type Store
- type TokenPair
- type User
Constants ¶
This section is empty.
Variables ¶
var ( ErrOTPExpired = errors.New("auth: otp has expired") ErrOTPInvalid = errors.New("auth: invalid otp code") ErrUserNotFound = errors.New("auth: user not found") ErrPermissionNotFound = errors.New("auth: permission not found") ErrPermissionExists = errors.New("auth: permission already exists") ErrGroupNotFound = errors.New("auth: group not found") ErrGroupExists = errors.New("auth: group already exists") ErrPasswordInvalid = errors.New("auth: invalid password") ErrPasswordTooWeak = errors.New("auth: password does not meet strength requirements") ErrPasswordNotSet = errors.New("auth: user has no password set") ErrEmailAlreadyRegistered = errors.New("auth: email is already registered") ErrResetTokenInvalid = errors.New("auth: invalid or expired password reset token") ErrResetTokenUsed = errors.New("auth: password reset token has already been used") ErrOrganizationNotFound = errors.New("auth: organization not found") ErrOrganizationExists = errors.New("auth: organization already exists") ErrInvalidOrganization = errors.New("auth: invalid organization") ErrGroupMembershipFailed = errors.New("auth: failed to update group membership") )
Functions ¶
func CheckPassword ¶
CheckPassword compares plain text against bcrypt hash. Returns ErrPasswordInvalid on mismatch.
func GenerateResetToken ¶
GenerateResetToken returns a 32-byte CSPRNG token as base64url string (43 chars).
func HashPassword ¶
HashPassword validates password strength then bcrypt-hashes the plain text password.
func HashResetToken ¶
HashResetToken returns the SHA-256 hex of the raw token (stored in DB, never the raw token).
func ValidatePasswordStrength ¶
ValidatePasswordStrength enforces password strength requirements: - min/max length (max is 72 due to bcrypt limit) - uppercase, lowercase, digit, special character
Types ¶
type Claims ¶
type Claims struct {
UserID string `json:"user_id"`
Email string `json:"email"`
Type string `json:"type"` // "access" or "refresh"
Permissions []string `json:"permissions,omitempty"`
Groups []string `json:"groups,omitempty"` // group names
Meta map[string]any `json:"meta,omitempty"` // custom app-level claims (e.g. college_id)
}
Claims represents the JWT token claims.
type Config ¶
type Config struct {
JWTSecret string
OTPLength int
OTPExpiry time.Duration
AccessExpiry time.Duration
RefreshExpiry time.Duration
SuperAdminEmail string
AutoMigrate bool // if true, Bootstrap() runs migrations automatically
BcryptCost int
PasswordResetExpiry time.Duration
MinPasswordLength int
MaxPasswordLength int
}
Config holds the configuration for the auth package.
func DefaultConfig ¶
DefaultConfig returns a Config with sensible defaults.
type Group ¶
type Group struct {
ID string `json:"id"`
Name string `json:"name"` // e.g. "Editor"
Permissions []Permission `json:"permissions,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
Group represents a permission group for bulk assignment.
type Mailer ¶
type Mailer interface {
SendOTP(ctx context.Context, email string, code string, expiresIn time.Duration) error
SendPasswordReset(ctx context.Context, email string, resetURL string, expiresIn time.Duration) error
SendWelcome(ctx context.Context, user *User) error
}
Mailer defines the contract for sending auth emails. Implementors use their own templates and sender identity — auth only calls these methods.
type MigrationRecord ¶
MigrationRecord represents an applied database migration.
type Migrator ¶
type Migrator interface {
// Migrate applies all pending migrations in order.
Migrate(ctx context.Context) error
// Rollback rolls back the last applied migration.
Rollback(ctx context.Context) error
// MigrationStatus returns all migrations with their applied status.
MigrationStatus(ctx context.Context) ([]MigrationRecord, error)
}
Migrator defines the contract for managing database migrations.
type OTP ¶
type OTP struct {
ID string `json:"id"`
Email string `json:"email"`
Code string `json:"code"`
ExpiresAt time.Time `json:"expires_at"`
Verified bool `json:"verified"`
CreatedAt time.Time `json:"created_at"`
}
OTP represents a one-time password sent to a user's email.
type Organization ¶ added in v2.1.0
type Organization struct {
ID string `json:"id"`
Name string `json:"name"` // e.g. "trainer", "student"
Permissions []Permission `json:"permissions,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
Organization represents an organizational role with base permissions.
type PasswordReset ¶
type PasswordReset struct {
ID string `json:"id"`
UserID string `json:"user_id"`
ExpiresAt time.Time `json:"expires_at"`
Used bool `json:"used"`
CreatedAt time.Time `json:"created_at"`
}
PasswordReset represents a password reset request.
type Permission ¶
type Permission struct {
ID string `json:"id"`
Key string `json:"key"` // e.g. "forms:create"
Description string `json:"description"` // e.g. "Can create forms"
CreatedAt time.Time `json:"created_at"`
}
Permission represents a single permission that can be assigned to users or groups.
type Store ¶
type Store interface {
// Schema
CreateSchema(ctx context.Context) error
DropSchema(ctx context.Context) error
// OTP
CreateOTP(ctx context.Context, email string) (*OTP, error)
VerifyOTP(ctx context.Context, email string, code string) (*User, error)
// Users
CreateUser(ctx context.Context, email string) (*User, error)
GetUserByID(ctx context.Context, id string) (*User, error)
GetUserByEmail(ctx context.Context, email string) (*User, error)
ListUsers(ctx context.Context) ([]User, error)
// Permissions
CreatePermission(ctx context.Context, key string, description string) (*Permission, error)
GetPermission(ctx context.Context, key string) (*Permission, error)
ListPermissions(ctx context.Context) ([]Permission, error)
DeletePermission(ctx context.Context, id string) error
// User Permissions (direct)
AssignPermission(ctx context.Context, userID string, permissionKey string) error
RevokePermission(ctx context.Context, userID string, permissionKey string) error
GetUserPermissions(ctx context.Context, userID string) ([]Permission, error)
HasPermission(ctx context.Context, userID string, permissionKey string) (bool, error)
// Groups
CreateGroup(ctx context.Context, name string) (*Group, error)
GetGroup(ctx context.Context, id string) (*Group, error)
ListGroups(ctx context.Context) ([]Group, error)
DeleteGroup(ctx context.Context, id string) error
AddPermissionToGroup(ctx context.Context, groupID string, permissionKey string) error
RemovePermissionFromGroup(ctx context.Context, groupID string, permissionID string) error
// User Groups
AssignUserToGroup(ctx context.Context, userID string, groupID string) error
RemoveUserFromGroup(ctx context.Context, userID string, groupID string) error
GetUserGroups(ctx context.Context, userID string) ([]Group, error)
// Resolved Permissions (direct + from groups + from organizations)
GetResolvedPermissions(ctx context.Context, userID string) ([]Permission, error)
HasResolvedPermission(ctx context.Context, userID string, permissionKey string) (bool, error)
// Organizations
CreateOrganizationWithPermissions(ctx context.Context, name string, permissionKeys []string) (*Organization, error)
AssignPermissionsToOrganization(ctx context.Context, orgID string, permissionKeys []string) error
RemovePermissionsFromOrganization(ctx context.Context, orgID string, permissionKeys []string) error
GetOrganizationPermissions(ctx context.Context, orgID string) ([]Permission, error)
ListOrganizations(ctx context.Context) ([]Organization, error)
GetOrganization(ctx context.Context, id string) (*Organization, error)
GetOrganizationByName(ctx context.Context, name string) (*Organization, error)
// User-Organization
CreateUserWithOrganization(ctx context.Context, email string, organization string) (*User, error)
GetUserOrganization(ctx context.Context, userID string) (string, error)
// Enhanced Permission Resolution
GetAllUserPermissions(ctx context.Context, userID string) ([]Permission, error)
HasAnyPermission(ctx context.Context, userID string, permissionKeys []string) (bool, error)
// Bulk Group Operations
AddUsersToGroup(ctx context.Context, groupID string, userIDs []string) error
RemoveUsersFromGroup(ctx context.Context, groupID string, userIDs []string) error
GetGroupMembers(ctx context.Context, groupID string) ([]User, error)
// Bootstrap
Bootstrap(ctx context.Context, superAdminEmail string, superAdminPassword string, organizations ...map[string][]string) error
// Password Auth
RegisterWithPassword(ctx context.Context, email string, plainPassword string) (*User, error)
LoginWithPassword(ctx context.Context, email string, plainPassword string) (*User, error)
SetPassword(ctx context.Context, userID string, plainPassword string) error
ChangePassword(ctx context.Context, userID string, currentPassword string, newPassword string) error
HasPassword(ctx context.Context, userID string) (bool, error)
CreatePasswordReset(ctx context.Context, email string) (rawToken string, expiresAt time.Time, err error)
ResetPassword(ctx context.Context, rawToken string, newPassword string) error
}
Store defines the contract for persisting and retrieving auth data.
type TokenPair ¶
type TokenPair struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
TokenPair holds the JWT access and refresh tokens.
func GenerateTokenPair ¶
func GenerateTokenPair(cfg Config, user *User, permissions []string, groups []string, meta map[string]any) (*TokenPair, error)
GenerateTokenPair creates a signed access token and refresh token for the given user. meta is optional — pass nil or a map of custom claims to embed in the access token (e.g. {"college_id": "xyz"}).
func RefreshTokenPair ¶ added in v2.0.4
func RefreshTokenPair(ctx context.Context, cfg Config, store Store, refreshToken string) (*TokenPair, error)
RefreshTokenPair validates a refresh token and issues a new token pair. Fetches the latest user data and permissions from the store. Returns ErrUserNotFound if the user no longer exists.