Documentation
¶
Overview ¶
Package auth provides password policy, signed token verification, session helpers, verified request identity, role checks, and attribute policies. Applications retain ownership of accounts, recovery, identity providers, secret storage, and authorization rules.
Index ¶
- Variables
- func Authenticate(secret string) gpp.HandlerFunc
- func AuthenticateWithManager(manager *TokenManager) gpp.HandlerFunc
- func GenerateJWT(claims UserClaims, secret string, ttl ...time.Duration) string
- func GeneratePASETO(UserClaims, string) string
- func GenerateTOTPCode(secret string, at time.Time) string
- func GenerateToken(userID int64, secret string, ttl ...time.Duration) string
- func HashLegacyPassword(password, secret string) string
- func HashPassword(password, secret string) string
- func HashPasswordWithConfig(password string, pepper []byte, config PasswordConfig) (string, error)
- func NeedsRehash(encodedHash string, desired PasswordConfig) bool
- func OptionalAuthenticateWithManager(manager *TokenManager) gpp.HandlerFunc
- func RequireJWT(secret string) gpp.HandlerFunc
- func RequireMFA(secret string) gpp.HandlerFunc
- func RequirePASETO(string) gpp.HandlerFunc
- func RequirePolicy(policy func(u *UserClaims) bool) gpp.HandlerFunc
- func RequireRoles(requiredRoles ...string) gpp.HandlerFunc
- func UniversalAuth(secret string, sessions *RedisSessionManager) gpp.HandlerFunc
- func UniversalAuthWithManager(manager *TokenManager, sessions *RedisSessionManager) gpp.HandlerFunc
- func VerifyLegacyPassword(password, secret, expectedHash string) bool
- func VerifyPassword(password, secret, encodedHash string) bool
- func VerifyPasswordWithMigration(password, secret, encodedHash string) (valid, needsUpgrade bool)
- func VerifyTOTPCode(secret, code string, at time.Time) bool
- type Config
- type LegacyPasswordConfig
- type LegacyPasswordVerifier
- type LegacyTokenConfig
- type LoginRequest
- type PasswordCompatibility
- type PasswordConfig
- type PasswordPolicy
- type PasswordPolicyConfig
- type PasswordVerification
- type RedisSessionManager
- type RegisterRequest
- type Response
- type SessionConfig
- type TokenClaims
- type TokenCompatibility
- type TokenConfig
- type TokenManager
- func (manager *TokenManager) Issue(userID int64, email string, ttl time.Duration) (string, error)
- func (manager *TokenManager) IssueUser(user UserClaims, ttl time.Duration) (string, error)
- func (manager *TokenManager) Verify(token string) (*TokenClaims, error)
- func (manager *TokenManager) VerifyToken(ctx context.Context, token string) (UserClaims, error)
- type TokenVerifier
- type User
- type UserClaims
Constants ¶
This section is empty.
Variables ¶
var ErrPasswordFormatNotRecognized = errors.New("auth: password hash format not recognized")
ErrPasswordFormatNotRecognized permits the policy to try the next explicitly configured verification-only compatibility adapter.
var ErrTokenFormatNotRecognized = errors.New("auth: token format not recognized")
ErrTokenFormatNotRecognized is the only error that permits verification to continue to the next explicitly configured compatibility verifier.
Functions ¶
func Authenticate ¶
func Authenticate(secret string) gpp.HandlerFunc
Authenticate verifies bearer JWTs using the compatibility single-key manager.
func AuthenticateWithManager ¶
func AuthenticateWithManager(manager *TokenManager) gpp.HandlerFunc
AuthenticateWithManager installs identity only after complete token verification.
func GenerateJWT ¶
func GenerateJWT(claims UserClaims, secret string, ttl ...time.Duration) string
GenerateJWT creates a standards-compliant signed JWT with an explicit TTL.
func GeneratePASETO ¶
func GeneratePASETO(UserClaims, string) string
GeneratePASETO is disabled because GoPlusPlus does not ship a complete PASETO implementation. Deprecated: use TokenManager.IssueUser.
func GenerateTOTPCode ¶
GenerateTOTPCode generates a six-digit Time-Based One-Time Password.
func GenerateToken ¶
GenerateToken creates a verified-compatible token. Exactly one explicit TTL is required.
func HashLegacyPassword ¶
HashLegacyPassword reproduces the pre-v1.11 HMAC format for controlled migrations only. Deprecated: legacy formats are verification-only; retain only in migration tests.
func HashPassword ¶
HashPassword hashes a password with Argon2id and a random salt. The secret is used as an application pepper. It returns an empty string on invalid input or entropy failure.
func HashPasswordWithConfig ¶
func HashPasswordWithConfig(password string, pepper []byte, config PasswordConfig) (string, error)
HashPasswordWithConfig returns a versioned PHC-style Argon2id hash.
func NeedsRehash ¶
func NeedsRehash(encodedHash string, desired PasswordConfig) bool
NeedsRehash reports whether a valid PHC hash uses parameters below the desired configuration.
func OptionalAuthenticateWithManager ¶ added in v1.11.9
func OptionalAuthenticateWithManager(manager *TokenManager) gpp.HandlerFunc
OptionalAuthenticateWithManager installs identity if a valid bearer token is present, but permits unauthenticated requests to proceed.
func RequireJWT ¶
func RequireJWT(secret string) gpp.HandlerFunc
RequireJWT verifies JWT bearer tokens using the compatibility single-key manager.
func RequireMFA ¶
func RequireMFA(secret string) gpp.HandlerFunc
RequireMFA verifies an RFC 6238-style six-digit TOTP within one clock step.
func RequirePASETO ¶
func RequirePASETO(string) gpp.HandlerFunc
RequirePASETO fails closed instead of accepting the former placeholder token format. Deprecated: use AuthenticateWithManager.
func RequirePolicy ¶
func RequirePolicy(policy func(u *UserClaims) bool) gpp.HandlerFunc
RequirePolicy enforces Attribute-Based Access Control (ABAC).
func RequireRoles ¶
func RequireRoles(requiredRoles ...string) gpp.HandlerFunc
RequireRoles enforces Role-Based Access Control (RBAC).
func UniversalAuth ¶
func UniversalAuth(secret string, sessions *RedisSessionManager) gpp.HandlerFunc
UniversalAuth accepts a valid process-local session or compatibility JWT. New applications should prefer UniversalAuthWithManager.
func UniversalAuthWithManager ¶
func UniversalAuthWithManager(manager *TokenManager, sessions *RedisSessionManager) gpp.HandlerFunc
UniversalAuthWithManager accepts a verified session or JWT using explicit token policy.
func VerifyLegacyPassword ¶
VerifyLegacyPassword verifies the pre-v1.11 HMAC format in constant time. Deprecated: use PasswordPolicy with LegacyV1 and an explicit acceptance deadline.
func VerifyPassword ¶
VerifyPassword verifies only Argon2id hashes. Use VerifyLegacyPassword explicitly for migration.
func VerifyPasswordWithMigration ¶
VerifyPasswordWithMigration verifies Argon2id or an explicitly recognized legacy HMAC hash. needsUpgrade is true only for a valid legacy hash or weaker Argon2id parameters. Deprecated: use PasswordPolicy.Verify for explicit compatibility deadlines and timing protection.
Types ¶
type LegacyPasswordConfig ¶
LegacyPasswordConfig explicitly enables GoPlusPlus's pre-v1.11 HMAC hashes.
type LegacyPasswordVerifier ¶
type LegacyPasswordVerifier interface {
VerifyPassword(password, encodedHash string) (bool, error)
}
LegacyPasswordVerifier verifies one application-private historical hash format. It must never generate hashes and must use constant-time secret comparison.
type LegacyTokenConfig ¶
type LegacyTokenConfig struct {
SigningKey []byte
AcceptUntil time.Time
MaxTTL time.Duration
MaxTokenBytes int
}
LegacyTokenConfig enables verification of GoPlusPlus's signed pre-v1.11 two-part HMAC token. It never enables token generation.
type LoginRequest ¶ added in v1.11.9
type LoginRequest struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required"`
}
LoginRequest represents the payload for user login authentication.
type PasswordCompatibility ¶
type PasswordCompatibility struct {
Verifier LegacyPasswordVerifier
AcceptUntil time.Time
}
PasswordCompatibility bounds one temporary application-private verifier.
type PasswordConfig ¶
type PasswordConfig struct {
Memory uint32
Iterations uint32
Parallelism uint8
SaltLength uint32
KeyLength uint32
}
PasswordConfig defines bounded Argon2id cost and output parameters.
func DefaultPasswordConfig ¶
func DefaultPasswordConfig() PasswordConfig
DefaultPasswordConfig returns RFC 9106's memory-constrained recommendation.
type PasswordPolicy ¶
type PasswordPolicy struct {
// contains filtered or unexported fields
}
PasswordPolicy owns Argon2id hashing, verification, missing-account timing protection, and explicit verification-only migration adapters.
func NewPasswordPolicy ¶
func NewPasswordPolicy(config PasswordPolicyConfig) (*PasswordPolicy, error)
NewPasswordPolicy validates and copies all configuration before constructing a dummy Argon2id hash used for missing-account and non-current-hash paths.
func (*PasswordPolicy) Hash ¶
func (policy *PasswordPolicy) Hash(password string) (string, error)
Hash creates a new randomized Argon2id PHC hash using the configured policy.
func (*PasswordPolicy) Verify ¶
func (policy *PasswordPolicy) Verify(password, encodedHash string) PasswordVerification
Verify performs exactly one bounded Argon2id verification operation. Empty, missing, malformed, and legacy hashes use the policy's dummy hash first.
func (*PasswordPolicy) VerifyMissing ¶
func (policy *PasswordPolicy) VerifyMissing(password string) PasswordVerification
VerifyMissing executes the same bounded dummy Argon2id path used when Verify receives an empty account hash.
type PasswordPolicyConfig ¶
type PasswordPolicyConfig struct {
Pepper []byte
Argon2id PasswordConfig
LegacyV1 *LegacyPasswordConfig
Compatibility []PasswordCompatibility
Now func() time.Time
}
PasswordPolicyConfig defines immutable password hashing and migration policy.
type PasswordVerification ¶
type PasswordVerification uint8
PasswordVerification is the complete credential-verification result.
const ( // PasswordInvalid indicates that credential verification failed. PasswordInvalid PasswordVerification = iota // PasswordValid indicates a valid credential using the current policy. PasswordValid // PasswordValidNeedsRehash indicates valid credentials stored with an outdated policy. PasswordValidNeedsRehash )
type RedisSessionManager ¶
type RedisSessionManager struct {
// contains filtered or unexported fields
}
RedisSessionManager retains its public name for compatibility. Sessions are process-local unless applications replace this primitive with their shared store.
func NewRedisSessionManager ¶
func NewRedisSessionManager(string) *RedisSessionManager
NewRedisSessionManager returns the secure compatibility session manager. The URL is retained for source compatibility and is not logged or treated as a credential.
func NewSessionManager ¶
func NewSessionManager(config SessionConfig) (*RedisSessionManager, error)
NewSessionManager constructs a bounded process-local session manager.
func (*RedisSessionManager) CreateSession ¶
func (manager *RedisSessionManager) CreateSession(c *gpp.Context, claims UserClaims) string
CreateSession rotates any presented session, creates a cryptographically random ID, and sets a bounded HttpOnly cookie.
func (*RedisSessionManager) RevokeSession ¶
func (manager *RedisSessionManager) RevokeSession(identifier string)
RevokeSession removes a server-side session identifier.
func (*RedisSessionManager) SessionMiddleware ¶
func (manager *RedisSessionManager) SessionMiddleware() gpp.HandlerFunc
SessionMiddleware authenticates a request using the configured session cookie.
type RegisterRequest ¶ added in v1.11.9
type RegisterRequest struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=6"`
Name string `json:"name"`
}
RegisterRequest represents the payload for user registration.
type Response ¶ added in v1.11.9
Response represents the payload returned upon successful auth operations.
type SessionConfig ¶
type SessionConfig struct {
TTL time.Duration
CookieName string
// AllowInsecureHTTP disables Secure cookies for explicit local-development use only.
AllowInsecureHTTP bool
SameSite http.SameSite
Now func() time.Time
MaxSessions int
}
SessionConfig defines cookie and server-side session lifetime policy.
type TokenClaims ¶
type TokenClaims struct {
Subject string `json:"sub"`
UserID int64 `json:"-"`
UserIDString string `json:"-"`
Email string `json:"email,omitempty"`
Roles []string `json:"roles,omitempty"`
Attributes map[string]string `json:"attributes,omitempty"`
TenantID string `json:"tenant_id,omitempty"`
Issuer string `json:"iss"`
Audience string `json:"aud"`
ExpiresAt int64 `json:"exp"`
NotBefore int64 `json:"nbf"`
IssuedAt int64 `json:"iat"`
JWTID string `json:"jti"`
}
TokenClaims contains verified JWT claims.
func VerifyToken ¶
func VerifyToken(token, secret string) (*TokenClaims, error)
VerifyToken verifies a token produced by GenerateToken.
func (TokenClaims) MarshalJSON ¶
func (claims TokenClaims) MarshalJSON() ([]byte, error)
MarshalJSON encodes numeric and opaque user identities without ambiguity.
func (*TokenClaims) UnmarshalJSON ¶
func (claims *TokenClaims) UnmarshalJSON(data []byte) error
UnmarshalJSON strictly decodes token claims and preserves identity shape.
type TokenCompatibility ¶
type TokenCompatibility struct {
Verifier TokenVerifier
AcceptUntil time.Time
MaxTokenBytes int
}
TokenCompatibility configures one temporary application-private verifier. AcceptUntil and MaxTokenBytes are mandatory so compatibility is bounded.
type TokenConfig ¶
type TokenConfig struct {
Issuer string
Audience string
ActiveKeyID string
Keys map[string][]byte
MaxTTL time.Duration
ClockSkew time.Duration
Now func() time.Time
LegacyV1 *LegacyTokenConfig
Compatibility []TokenCompatibility
}
TokenConfig defines immutable JWT verification and key-rotation policy.
type TokenManager ¶
type TokenManager struct {
// contains filtered or unexported fields
}
TokenManager issues and verifies HS256 JWTs using explicit key IDs.
func Enable ¶ added in v1.11.9
func Enable(engine *gpp.Engine, configs ...Config) (*TokenManager, error)
Enable mounts built-in zero-code authentication endpoints (/api/auth/register, /api/auth/login, /api/auth/me).
func NewTokenManager ¶
func NewTokenManager(config TokenConfig) (*TokenManager, error)
NewTokenManager validates and copies immutable signing and compatibility policy.
func (*TokenManager) Issue ¶
Issue creates a signed JWT for a positive numeric user ID and explicit bounded TTL.
func (*TokenManager) IssueUser ¶
func (manager *TokenManager) IssueUser(user UserClaims, ttl time.Duration) (string, error)
IssueUser creates a signed JWT containing trusted authorization claims.
func (*TokenManager) Verify ¶
func (manager *TokenManager) Verify(token string) (*TokenClaims, error)
Verify authenticates a JWT signature and all required registered claims.
func (*TokenManager) VerifyToken ¶
func (manager *TokenManager) VerifyToken(ctx context.Context, token string) (UserClaims, error)
VerifyToken implements TokenVerifier for current GoPlusPlus JWTs.
type TokenVerifier ¶
type TokenVerifier interface {
VerifyToken(context.Context, string) (UserClaims, error)
}
TokenVerifier verifies one bounded token format and returns trusted claims. Implementations must return ErrTokenFormatNotRecognized only when the token is unambiguously not their format; recognized invalid tokens must return a different error so the chain fails closed.
type User ¶ added in v1.11.9
type User struct {
ID int64 `json:"id" db:"id,pk,auto_id"`
Email string `json:"email" db:"email,unique" validate:"required,email"`
PasswordHash string `json:"-" db:"password_hash"`
Name string `json:"name" db:"name"`
Role string `json:"role" db:"role"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
}
User represents the standard identity model for built-in authentication.
type UserClaims ¶
type UserClaims struct {
ID string `json:"id"`
Subject string `json:"sub,omitempty"`
Email string `json:"email"`
Roles []string `json:"roles"`
Attributes map[string]string `json:"attributes"`
TenantID string `json:"tenant_id"`
}
UserClaims holds verified user identity, roles, attributes, and tenant context.
func GetUser ¶
func GetUser(c *gpp.Context) (*UserClaims, bool)
GetUser extracts verified UserClaims from the context.
func (*UserClaims) HasRole ¶
func (u *UserClaims) HasRole(role string) bool
HasRole checks if user claims contain a target role.