auth

package
v0.18.2 Latest Latest
Warning

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

Go to latest
Published: Dec 8, 2024 License: MIT Imports: 29 Imported by: 5

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 added in v0.8.0

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

func Register added in v0.8.0

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

func RegisterRoutes added in v0.8.0

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

func SetAppKey

func SetAppKey(key []byte)

Types

type AuthController added in v0.12.0

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 added in v0.12.0

type AuthOption func(a *basicAuthController) *basicAuthController

func AccessTokenOptions added in v0.12.0

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

func CreateUser added in v0.14.0

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

func RefreshTokenOptions added in v0.12.0

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

func ResetPasswordName added in v0.12.0

func ResetPasswordName(name string) AuthOption

type BasicAuthController added in v0.12.0

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

func NewBasicAuthController added in v0.12.0

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

func (*BasicAuthController[T]) ChangePassword added in v0.12.0

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

func (*BasicAuthController[T]) ForgotPassword added in v0.12.0

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

func (*BasicAuthController[T]) Login added in v0.12.0

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

func (*BasicAuthController[T]) Refresh added in v0.12.0

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

func (*BasicAuthController[T]) ResetPassword added in v0.12.0

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

func (*BasicAuthController[T]) RunChangePassword added in v0.12.0

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

func (*BasicAuthController[T]) RunForgotPassword added in v0.12.0

func (*BasicAuthController[T]) RunLogin added in v0.12.0

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

func (*BasicAuthController[T]) RunRefresh added in v0.12.0

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

func (*BasicAuthController[T]) RunResetPassword added in v0.12.0

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

func (*BasicAuthController[T]) RunUserCreate added in v0.12.0

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

func (*BasicAuthController[T]) RunVerifyEmail added in v0.12.0

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

func (*BasicAuthController[T]) UserCreate added in v0.12.0

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

func (*BasicAuthController[T]) VerifyEmail added in v0.12.0

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

type ChangePasswordRequest added in v0.8.0

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 added in v0.8.0

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 added in v0.8.0

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

func GetClaimsCtx added in v0.8.0

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

func NewClaims added in v0.12.0

func NewClaims() *Claims

func Parse added in v0.6.0

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

func (*Claims) WithAudience added in v0.12.0

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 added in v0.12.0

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 added in v0.12.0

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 added in v0.12.0

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 added in v0.12.0

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 added in v0.12.0

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

func (*Claims) WithNotBeforeTime added in v0.12.0

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 added in v0.12.0

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 added in v0.12.0

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 added in v0.14.0

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

type EmailVerified added in v0.8.0

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

type EmailVerifiedUser added in v0.8.0

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 added in v0.8.0

func (v *EmailVerifiedUser) GetEmail() string

func (*EmailVerifiedUser) GetID added in v0.8.0

func (u *EmailVerifiedUser) GetID() string

func (*EmailVerifiedUser) GetPasswordHash added in v0.8.0

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

func (*EmailVerifiedUser) GetUsername added in v0.8.0

func (u *EmailVerifiedUser) GetUsername() string

func (*EmailVerifiedUser) IsVerified added in v0.8.0

func (v *EmailVerifiedUser) IsVerified() bool

func (*EmailVerifiedUser) LookupTokenColumn added in v0.8.0

func (u *EmailVerifiedUser) LookupTokenColumn() string

func (*EmailVerifiedUser) PasswordColumn added in v0.8.0

func (u *EmailVerifiedUser) PasswordColumn() string

func (*EmailVerifiedUser) SaltedPassword added in v0.8.0

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

func (*EmailVerifiedUser) SetLookupToken added in v0.8.0

func (v *EmailVerifiedUser) SetLookupToken(t string)

func (*EmailVerifiedUser) SetPasswordHash added in v0.8.0

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

func (*EmailVerifiedUser) SetVerified added in v0.8.0

func (v *EmailVerifiedUser) SetVerified(verified bool)

func (*EmailVerifiedUser) UsernameColumns added in v0.8.1

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

type EmailVerifiedUserCreateRequest added in v0.8.1

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

type ForgotPasswordRequest added in v0.8.6

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 added in v0.8.6

type ForgotPasswordResponse struct {
}

type HasClaimMiddleware added in v0.13.1

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

func HasClaim

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

func (*HasClaimMiddleware) Middleware added in v0.13.1

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

type LoggedInMiddleware added in v0.13.1

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

func LoggedIn

func LoggedIn() *LoggedInMiddleware

func (*LoggedInMiddleware) Middleware added in v0.13.1

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

func (*LoggedInMiddleware) OperationMiddleware added in v0.13.1

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

func (*LoggedInMiddleware) SecurityDefinition added in v0.13.1

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

type LoginRequest added in v0.8.0

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 added in v0.8.0

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

type RefreshRequest added in v0.8.0

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

type ResetPasswordRequest added in v0.8.0

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 added in v0.8.0

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

type ScopeStrings added in v0.12.0

type ScopeStrings []string

func (ScopeStrings) MarshalJSON added in v0.12.0

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

func (*ScopeStrings) UnmarshalJSON added in v0.12.0

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

type User added in v0.8.0

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

type UserCreateRequest added in v0.8.0

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 added in v0.8.0

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

func NewUsernameUser added in v0.8.0

type UsernameUser added in v0.8.0

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 added in v0.8.0

func (u *UsernameUser) GetID() string

func (*UsernameUser) GetPasswordHash added in v0.8.0

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

func (*UsernameUser) GetUsername added in v0.8.0

func (u *UsernameUser) GetUsername() string

func (*UsernameUser) PasswordColumn added in v0.8.0

func (u *UsernameUser) PasswordColumn() string

func (*UsernameUser) SaltedPassword added in v0.8.0

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

func (*UsernameUser) SetPasswordHash added in v0.8.0

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

func (*UsernameUser) UsernameColumns added in v0.8.1

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

type UsernameUserCreateRequest added in v0.8.1

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

type VerifyEmailRequest added in v0.8.0

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