auth

package
v0.11.1 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2024 License: MIT Imports: 24 Imported by: 2

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidAuthorizationHeader = fmt.Errorf("missing or invalid Authorization header")
	ErrUnexpectedAlgorithm        = fmt.Errorf("unexpected algorithm")
)
View Source
var (
	TypeAccess  = ClaimType("access")
	TypeRefresh = ClaimType("refresh")
)
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(modifyClaims ...TokenOptions) (string, error)

func GenerateTokenFrom added in v0.8.0

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

func HasClaim

func HasClaim(validate func(c *Claims) bool) router.MiddlewareFunc

func LoggedIn

func LoggedIn() router.MiddlewareFunc

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[T User, R any](r *router.Router, newUser func(request R) T, resetPasswordName string)

func SetAppKey

func SetAppKey(key []byte)

Types

type AuthRoutes added in v0.8.0

func Routes added in v0.8.0

func Routes[T User, R any](newUser func(request R) T, resetPasswordName string) *AuthRoutes[T]

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

type ClaimType string

type Claims

type Claims struct {
	jwt.RegisteredClaims
	Type ClaimType `json:"type,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 Parse added in v0.6.0

func Parse(token string) (*Claims, 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 NewEmailVerifiedUser added in v0.8.0

func NewEmailVerifiedUser(request *EmailVerifiedUserCreateRequest) *EmailVerifiedUser

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 {
	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 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:""`
}

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

type RouteOptions[T User, R any] struct {
	NewUser           func(request R) T
	ResetPasswordName string
}

type TokenOptions

type TokenOptions func(claims jwt.MapClaims) jwt.MapClaims

func WithAudience

func WithAudience(aud []string) TokenOptions

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 WithClaim

func WithClaim(key string, value any) TokenOptions

func WithExpirationTime

func WithExpirationTime(exp time.Time) TokenOptions

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 WithIssuedAtTime

func WithIssuedAtTime(iat time.Time) TokenOptions

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 WithIssuer

func WithIssuer(iss string) TokenOptions

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 WithJWTID

func WithJWTID(jti string) TokenOptions

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 WithLifetime

func WithLifetime(duration time.Duration) TokenOptions

func WithNotBeforeTime

func WithNotBeforeTime(nbf time.Time) TokenOptions

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 WithSubject

func WithSubject[T string | int](sub T) TokenOptions

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 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"`

	Mailer   email.Mailer       `inject:""`
	Update   database.Update    `inject:""`
	Ctx      context.Context    `inject:""`
	Logger   *slog.Logger       `inject:""`
	Request  *http.Request      `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"`
}

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

func NewUsernameUser(request *UsernameUserCreateRequest) *UsernameUser

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 {
	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