auth

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ScopeRefresh = "refresh"
	ScopeAccess  = "access"
)

Variables

View Source
var (
	ErrMissingAuthorizationHeader = fmt.Errorf("missing Authorization header")
	ErrInvalidAuthorizationHeader = fmt.Errorf("invalid Authorization header")
	ErrUnexpectedAlgorithm        = fmt.Errorf("unexpected algorithm")
	ErrNoAccessScope              = fmt.Errorf("no access scope")
)
View Source
var (
	ErrInvalidUserPass      = errors.New("invalid username or password")
	ErrTokenNotFound        = errors.New("token not found")
	ErrNonEmailVerifiedUser = errors.New("non email verified user")
)
View Source
var (
	Err401Unauthorized = request.NewHTTPError(errors.New("unauthorized"), http.StatusUnauthorized)
)
View Source
var ErrInvalidToken = fmt.Errorf("invalid token")

Functions

func AttachUser

func AttachUser() router.MiddlewareFunc

func GenerateToken

func GenerateToken(claims jwt.Claims) (string, error)

func ParseOf

func ParseOf[T jwt.Claims](token string) (T, error)

func Register

func Register[T User](ctx context.Context)

func RegisterRoutes

func RegisterRoutes(r *router.Router, controller AuthController)

func SetAppKey

func SetAppKey(key []byte)

Types

type AuthController

type AuthController interface {
	UserCreate() http.Handler
	Login() http.Handler
	VerifyEmail() http.Handler
	ResetPassword() http.Handler
	ChangePassword() http.Handler
	Refresh() http.Handler
	ForgotPassword() http.Handler
}

type AuthOption

type AuthOption func(a *basicAuthController) *basicAuthController

func AccessTokenOptions

func AccessTokenOptions[T User](cb func(u T, claims *Claims) jwt.Claims) AuthOption

func CreateUser

func CreateUser[T User, TRequest any](cb func(r *TRequest, c *BasicAuthController[T]) (*UserCreateResponse[T], error)) AuthOption

func RefreshTokenOptions

func RefreshTokenOptions[T User](cb func(u T, claims *Claims) jwt.Claims) AuthOption

func ResetPasswordName

func ResetPasswordName(name string) AuthOption

type BasicAuthController

type BasicAuthController[T User] struct {
	// contains filtered or unexported fields
}

func NewBasicAuthController

func NewBasicAuthController[T User](options ...AuthOption) *BasicAuthController[T]

func (*BasicAuthController[T]) ChangePassword

func (o *BasicAuthController[T]) ChangePassword() http.Handler

func (*BasicAuthController[T]) ForgotPassword

func (o *BasicAuthController[T]) ForgotPassword() http.Handler

func (*BasicAuthController[T]) Login

func (o *BasicAuthController[T]) Login() http.Handler

func (*BasicAuthController[T]) Refresh

func (o *BasicAuthController[T]) Refresh() http.Handler

func (*BasicAuthController[T]) ResetPassword

func (o *BasicAuthController[T]) ResetPassword() http.Handler

func (*BasicAuthController[T]) RunChangePassword

func (o *BasicAuthController[T]) RunChangePassword(r *ChangePasswordRequest[T]) (*ChangePasswordResponse[T], error)

func (*BasicAuthController[T]) RunForgotPassword

func (*BasicAuthController[T]) RunLogin

func (o *BasicAuthController[T]) RunLogin(r *LoginRequest) (*LoginResponse, error)

func (*BasicAuthController[T]) RunRefresh

func (o *BasicAuthController[T]) RunRefresh(r *RefreshRequest[T]) (*LoginResponse, error)

func (*BasicAuthController[T]) RunResetPassword

func (o *BasicAuthController[T]) RunResetPassword(r *ResetPasswordRequest) (*ResetPasswordResponse[T], error)

func (*BasicAuthController[T]) RunUserCreate

func (o *BasicAuthController[T]) RunUserCreate(u T, r *UserCreateRequest) (*UserCreateResponse[T], error)

func (*BasicAuthController[T]) RunVerifyEmail

func (o *BasicAuthController[T]) RunVerifyEmail(r *VerifyEmailRequest) (http.Handler, error)

func (*BasicAuthController[T]) UserCreate

func (o *BasicAuthController[T]) UserCreate() http.Handler

func (*BasicAuthController[T]) VerifyEmail

func (o *BasicAuthController[T]) VerifyEmail() http.Handler

type ChangePasswordRequest

type ChangePasswordRequest[T User] struct {
	OldPassword string          `json:"old_password"`
	NewPassword string          `json:"new_password"`
	User        T               `inject:""`
	Update      database.Update `inject:""`
	Ctx         context.Context `inject:""`
}

type ChangePasswordResponse

type ChangePasswordResponse[T User] struct {
	User T `json:"user"`
}

type Claims

type Claims struct {
	jwt.RegisteredClaims

	// The `scope` (Scope) claim. See https://www.rfc-editor.org/rfc/rfc8693.html#name-scope-scopes-claim
	Scope ScopeStrings `json:"scope,omitempty"`
}

func GetClaims

func GetClaims(r *http.Request) (*Claims, bool)

func GetClaimsCtx

func GetClaimsCtx(ctx context.Context) (*Claims, bool)

func NewClaims

func NewClaims() *Claims

func Parse

func Parse(token string) (*Claims, error)

func (*Claims) WithAudience

func (c *Claims) WithAudience(aud []string) *Claims

The "aud" (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the "aud" claim when this claim is present, then the JWT MUST be rejected. In the general case, the "aud" value is an array of case- sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the "aud" value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL.

func (*Claims) WithExpirationTime

func (c *Claims) WithExpirationTime(exp time.Time) *Claims

The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the "exp" claim requires that the current date/time MUST be before the expiration date/time listed in the "exp" claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.

func (*Claims) WithIssuedAtTime

func (c *Claims) WithIssuedAtTime(iat time.Time) *Claims

The "iat" (issued at) claim identifies the time at which the JWT was issued. This claim can be used to determine the age of the JWT. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.

func (*Claims) WithIssuer

func (c *Claims) WithIssuer(iss string) *Claims

The "iss" (issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. The "iss" value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL.

func (*Claims) WithJWTID

func (c *Claims) WithJWTID(jti string) *Claims

The "jti" (JWT ID) claim provides a unique identifier for the JWT. The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well. The "jti" claim can be used to prevent the JWT from being replayed. The "jti" value is a case- sensitive string. Use of this claim is OPTIONAL.

func (*Claims) WithLifetime

func (c *Claims) WithLifetime(duration time.Duration) *Claims

func (*Claims) WithNotBeforeTime

func (c *Claims) WithNotBeforeTime(nbf time.Time) *Claims

The "nbf" (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing. The processing of the "nbf" claim requires that the current date/time MUST be after or equal to the not-before date/time listed in the "nbf" claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.

func (*Claims) WithScopes

func (c *Claims) WithScopes(scope ...string) *Claims

The value of the scope claim is a JSON string containing a space-separated list of scopes associated with the token, in the format described in Section 3.3 of [RFC6749].

https://www.rfc-editor.org/rfc/rfc8693.html#name-scope-scopes-claim

func (*Claims) WithSubject

func (c *Claims) WithSubject(sub string) *Claims

The "sub" (subject) claim identifies the principal that is the subject of the JWT. The claims in a JWT are normally statements about the subject. The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique. The processing of this claim is generally application specific. The "sub" value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL.

type CreateUserFunc

type CreateUserFunc[T User] func(user T, req *UserCreateRequest) (*UserCreateResponse[T], error)

type EmailVerified

type EmailVerified interface {
	GetEmail() string
	SetLookupToken(string)
	IsVerified() bool
	SetVerified(bool)
	LookupTokenColumn() string
}

type EmailVerifiedUser

type EmailVerifiedUser struct {
	model.BaseModel

	ID           uuid.UUID `json:"id"    db:"id,primary"`
	Email        string    `json:"email" db:"email,unique"`
	PasswordHash []byte    `json:"-"     db:"password"`
	Verified     bool      `json:"-"     db:"validated"`
	LookupToken  string    `json:"-"     db:"lookup_token"`
}

func (*EmailVerifiedUser) GetEmail

func (v *EmailVerifiedUser) GetEmail() string

func (*EmailVerifiedUser) GetID

func (u *EmailVerifiedUser) GetID() string

func (*EmailVerifiedUser) GetPasswordHash

func (u *EmailVerifiedUser) GetPasswordHash() []byte

func (*EmailVerifiedUser) GetUsername

func (u *EmailVerifiedUser) GetUsername() string

func (*EmailVerifiedUser) IsVerified

func (v *EmailVerifiedUser) IsVerified() bool

func (*EmailVerifiedUser) LookupTokenColumn

func (u *EmailVerifiedUser) LookupTokenColumn() string

func (*EmailVerifiedUser) PasswordColumn

func (u *EmailVerifiedUser) PasswordColumn() string

func (*EmailVerifiedUser) SaltedPassword

func (u *EmailVerifiedUser) SaltedPassword(password string) []byte

func (*EmailVerifiedUser) SetLookupToken

func (v *EmailVerifiedUser) SetLookupToken(t string)

func (*EmailVerifiedUser) SetPasswordHash

func (u *EmailVerifiedUser) SetPasswordHash(b []byte)

func (*EmailVerifiedUser) SetVerified

func (v *EmailVerifiedUser) SetVerified(verified bool)

func (*EmailVerifiedUser) UsernameColumns

func (u *EmailVerifiedUser) UsernameColumns() []string

type EmailVerifiedUserCreateRequest

type EmailVerifiedUserCreateRequest struct {
	UserCreateRequest
	Email string `json:"username"  validate:"required|email"`
}

type ForgotPasswordRequest

type ForgotPasswordRequest struct {
	Email    string             `json:"email" validate:"required|email"`
	Update   database.Update    `inject:""`
	Ctx      context.Context    `inject:""`
	Mailer   email.Mailer       `inject:""`
	Logger   *slog.Logger       `inject:""`
	URL      router.URLResolver `inject:""`
	Template *view.ViewTemplate `inject:",optional"`
}

type ForgotPasswordResponse

type ForgotPasswordResponse struct {
}

type HasClaimMiddleware

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

func HasClaim

func HasClaim(validate func(c *Claims) bool) *HasClaimMiddleware

func (*HasClaimMiddleware) Middleware

func (m *HasClaimMiddleware) Middleware(next http.Handler) http.Handler

type LoggedInMiddleware

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

func LoggedIn

func LoggedIn() *LoggedInMiddleware

func (*LoggedInMiddleware) Middleware

func (m *LoggedInMiddleware) Middleware(next http.Handler) http.Handler

func (*LoggedInMiddleware) OperationMiddleware

func (m *LoggedInMiddleware) OperationMiddleware(s *spec.Operation) *spec.Operation

func (*LoggedInMiddleware) SecurityDefinition

func (m *LoggedInMiddleware) SecurityDefinition(name string) *LoggedInMiddleware

type LoginRequest

type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`

	Ctx  context.Context `inject:""`
	Read database.Read   `inject:""`
	Log  *slog.Logger    `inject:""`
}

type LoginResponse

type LoginResponse struct {
	AccessToken  string `json:"token"`
	TokenType    string `json:"token_type"`
	RefreshToken string `json:"refresh"`
	ExpiresIn    int    `json:"expires_in"`
}

type RefreshRequest

type RefreshRequest[T User] struct {
	RefreshToken string          `json:"refresh"`
	Read         database.Read   `inject:""`
	Ctx          context.Context `inject:""`
}

type ResetPasswordRequest

type ResetPasswordRequest struct {
	Token    string             `json:"token" validate:"required|min:1"`
	Password string             `json:"password" validate:"required"`
	Update   database.Update    `inject:""`
	Ctx      context.Context    `inject:""`
	URL      router.URLResolver `inject:""`
}

type ResetPasswordResponse

type ResetPasswordResponse[T User] struct {
	User T `json:"user"`
}

type ScopeStrings

type ScopeStrings []string

func (ScopeStrings) MarshalJSON

func (s ScopeStrings) MarshalJSON() ([]byte, error)

func (*ScopeStrings) UnmarshalJSON

func (s *ScopeStrings) UnmarshalJSON(b []byte) error

type User

type User interface {
	model.Model
	GetID() string
	GetPasswordHash() []byte
	SetPasswordHash([]byte)
	SaltedPassword(password string) []byte
	UsernameColumns() []string
}

type UserCreateRequest

type UserCreateRequest struct {
	Password string `json:"password" validate:"required"`

	Mailer   email.Mailer       `inject:""`
	Update   database.Update    `inject:""`
	Ctx      context.Context    `inject:""`
	Logger   *slog.Logger       `inject:""`
	URL      router.URLResolver `inject:""`
	Template *view.ViewTemplate `inject:",optional"`
}

type UserCreateResponse

type UserCreateResponse[T User] struct {
	User T `json:"user"`
}

type UsernameUser

type UsernameUser struct {
	model.BaseModel

	ID           uuid.UUID `json:"id"       db:"id,primary"`
	Username     string    `json:"username" db:"username,unique"`
	PasswordHash []byte    `json:"-"        db:"password"`
}

func (*UsernameUser) GetID

func (u *UsernameUser) GetID() string

func (*UsernameUser) GetPasswordHash

func (u *UsernameUser) GetPasswordHash() []byte

func (*UsernameUser) GetUsername

func (u *UsernameUser) GetUsername() string

func (*UsernameUser) PasswordColumn

func (u *UsernameUser) PasswordColumn() string

func (*UsernameUser) SaltedPassword

func (u *UsernameUser) SaltedPassword(password string) []byte

func (*UsernameUser) SetPasswordHash

func (u *UsernameUser) SetPasswordHash(b []byte)

func (*UsernameUser) UsernameColumns

func (u *UsernameUser) UsernameColumns() []string

type UsernameUserCreateRequest

type UsernameUserCreateRequest struct {
	UserCreateRequest
	Username string `json:"username" validate:"required"`
}

type VerifyEmailRequest

type VerifyEmailRequest struct {
	Token  string             `query:"token"`
	Update database.Update    `inject:""`
	Ctx    context.Context    `inject:""`
	URL    router.URLResolver `inject:""`
}

Jump to

Keyboard shortcuts

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