controller

package
v0.29.1 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2024 License: MIT Imports: 37 Imported by: 0

Documentation

Index

Constants

View Source
const (
	In30Days   = 720 * time.Hour
	InAMonth   = 30 * 24 * time.Hour
	In5Minutes = 5 * time.Minute //nolint:revive
)

Variables

View Source
var (
	ErrUserEmailNotFound               = &APIError{api.InvalidEmailPassword}
	ErrEmailAlreadyInUse               = &APIError{api.EmailAlreadyInUse}
	ErrForbiddenAnonymous              = &APIError{api.ForbiddenAnonymous}
	ErrInternalServerError             = &APIError{api.InternalServerError}
	ErrInvalidEmailPassword            = &APIError{api.InvalidEmailPassword}
	ErrPasswordTooShort                = &APIError{api.PasswordTooShort}
	ErrPasswordInHibpDatabase          = &APIError{api.PasswordInHibpDatabase}
	ErrRoleNotAllowed                  = &APIError{api.RoleNotAllowed}
	ErrDefaultRoleMustBeInAllowedRoles = &APIError{api.DefaultRoleMustBeInAllowedRoles}
	ErrRedirecToNotAllowed             = &APIError{api.RedirectToNotAllowed}
	ErrDisabledUser                    = &APIError{api.DisabledUser}
	ErrUnverifiedUser                  = &APIError{api.UnverifiedUser}
	ErrUserNotAnonymous                = &APIError{api.UserNotAnonymous}
	ErrInvalidPat                      = &APIError{api.InvalidPat}
	ErrInvalidRequest                  = &APIError{api.InvalidRequest}
	ErrSignupDisabled                  = &APIError{api.SignupDisabled}
	ErrDisabledEndpoint                = &APIError{api.DisabledEndpoint}
	ErrEmailAlreadyVerified            = &APIError{api.EmailAlreadyVerified}
	ErrInvalidRefreshToken             = &APIError{api.InvalidRefreshToken}
)
View Source
var ErrElevatedClaimRequired = errors.New("elevated-claim-required")

Functions

func GenLink(serverURL url.URL, typ LinkType, ticket, redirectTo string) (string, error)

func GravatarURLFunc

func GravatarURLFunc(enabled bool, def string, rating string) func(string) string

func ValidateEmail added in v0.28.0

func ValidateEmail(
	blockedEmailDomains []string,
	blockedEmails []string,
	allowedEmailDomains []string,
	allowedEmails []string,
) func(email string) bool

func ValidateRedirectTo

func ValidateRedirectTo(
	allowedRedirectURLs []*url.URL,
) (
	func(redirectTo string) bool,
	error,
)

Types

type APIError added in v0.28.0

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

func (*APIError) Error added in v0.28.0

func (e *APIError) Error() string

type Config

type Config struct {
	HasuraGraphqlURL           string        `json:"HASURA_GRAPHQL_GRAPHQL_URL"`
	HasuraAdminSecret          string        `json:"HASURA_GRAPHQL_ADMIN_SECRET"`
	AllowedEmailDomains        stringlice    `json:"AUTH_ACCESS_CONTROL_ALLOWED_EMAIL_DOMAINS"`
	AllowedEmails              stringlice    `json:"AUTH_ACCESS_CONTROL_ALLOWED_EMAILS"`
	AllowedRedirectURLs        []*url.URL    `json:"AUTH_ACCESS_CONTROL_ALLOWED_REDIRECT_URLS"`
	BlockedEmailDomains        stringlice    `json:"AUTH_ACCESS_CONTROL_BLOCKED_EMAIL_DOMAINS"`
	BlockedEmails              stringlice    `json:"AUTH_ACCESS_CONTROL_BLOCKED_EMAILS"`
	ClientURL                  *url.URL      `json:"AUTH_CLIENT_URL"`
	CustomClaims               string        `json:"AUTH_JWT_CUSTOM_CLAIMS"`
	ConcealErrors              bool          `json:"AUTH_CONCEAL_ERRORS"`
	DisableSignup              bool          `json:"AUTH_DISABLE_SIGNUP"`
	DisableNewUsers            bool          `json:"AUTH_DISABLE_NEW_USERS"`
	DefaultAllowedRoles        []string      `json:"AUTH_DEFAULT_ALLOWED_ROLES"`
	DefaultRole                string        `json:"AUTH_DEFAULT_ROLE"`
	DefaultLocale              string        `json:"AUTH_DEFAULT_LOCALE"`
	AllowedLocales             stringlice    `json:"AUTH_LOCALE_ALLOWED_LOCALES"`
	GravatarEnabled            bool          `json:"AUTH_GRAVATAR_ENABLED"`
	GravatarDefault            string        `json:"AUTH_GRAVATAR_DEFAULT"`
	GravatarRating             string        `json:"AUTH_GRAVATAR_RATING"`
	PasswordMinLength          int           `json:"AUTH_PASSWORD_MIN_LENGTH"`
	PasswordHIBPEnabled        bool          `json:"AUTH_PASSWORD_HIBP_ENABLED"`
	RefreshTokenExpiresIn      int           `json:"AUTH_REFRESH_TOKEN_EXPIRES_IN"`
	AccessTokenExpiresIn       int           `json:"AUTH_ACCESS_TOKEN_EXPIRES_IN"`
	JWTSecret                  string        `json:"HASURA_GRAPHQL_JWT_SECRET"`
	RequireEmailVerification   bool          `json:"AUTH_EMAIL_SIGNIN_EMAIL_VERIFIED_REQUIRED"`
	ServerURL                  *url.URL      `json:"AUTH_SERVER_URL"`
	EmailPasswordlessEnabled   bool          `json:"AUTH_EMAIL_PASSWORDLESS_ENABLED"`
	WebauthnEnabled            bool          `json:"AUTH_WEBAUTHN_ENABLED"`
	WebauthnRPID               string        `json:"AUTH_WEBAUTHN_RPID"`
	WebauthnRPName             string        `json:"AUTH_WEBAUTHN_RPNAME"`
	WebauthnRPOrigins          []string      `json:"AUTH_WEBAUTHN_RP_ORIGINS"`
	WebauhtnAttestationTimeout time.Duration `json:"AUTH_WEBAUTHN_ATTESTATION_TIMEOUT"`
}

func (*Config) UnmarshalJSON

func (c *Config) UnmarshalJSON(b []byte) error

type Controller

type Controller struct {
	Webauthn *Webauthn
	// contains filtered or unexported fields
}

func New

func New(
	db DBClient,
	config Config,
	jwtGetter *JWTGetter,
	emailer Emailer,
	hibp HIBPClient,
	version string,
) (*Controller, error)

func (*Controller) GetHealthz added in v0.28.0

func (*Controller) GetVersion added in v0.28.0

func (*Controller) HeadHealthz added in v0.28.0

func (*Controller) PostChangeEnv

func (ctrl *Controller) PostChangeEnv(fn gin.HandlerFunc) gin.HandlerFunc

func (*Controller) PostPat added in v0.28.0

func (*Controller) PostSigninEmailPassword added in v0.28.0

func (*Controller) PostSigninPasswordlessEmail added in v0.28.0

func (*Controller) PostSigninPat added in v0.28.0

func (*Controller) PostSignupWebauthn added in v0.28.0

func (*Controller) PostSignupWebauthnVerify added in v0.28.0

func (*Controller) PostToken added in v0.29.0

func (*Controller) PostUserDeanonymize added in v0.28.0

func (*Controller) PostUserEmailChange added in v0.28.0

func (*Controller) PostUserEmailSendVerificationEmail added in v0.28.0

func (*Controller) PostUserPasswordReset added in v0.28.0

type CustomClaimer

type CustomClaimer interface {
	GetClaims(ctx context.Context, userID string) (map[string]any, error)
}

type CustomClaims

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

func NewCustomClaims

func NewCustomClaims(
	claimsString string,
	httpclient *http.Client,
	graphqlURL string,
	requestInterceptor ...RequestInterceptor,
) (*CustomClaims, error)

func (*CustomClaims) ExtractClaims

func (c *CustomClaims) ExtractClaims(data any) (map[string]any, error)

func (*CustomClaims) GetClaims

func (c *CustomClaims) GetClaims(ctx context.Context, userID string) (map[string]any, error)

func (*CustomClaims) GraphQLQuery

func (c *CustomClaims) GraphQLQuery() string

type DBClient

type DBClient interface {
	DBClientGetUser
	DBClientInsertUser
	DBClientUpdateUser

	CountSecurityKeysUser(ctx context.Context, userID uuid.UUID) (int64, error)
	DeleteRefreshTokens(ctx context.Context, userID uuid.UUID) error
	DeleteUserRoles(ctx context.Context, userID uuid.UUID) error
	GetUserRoles(ctx context.Context, userID uuid.UUID) ([]sql.AuthUserRole, error)
	InsertRefreshtoken(ctx context.Context, arg sql.InsertRefreshtokenParams) (uuid.UUID, error)
	RefreshTokenAndGetUserRoles(
		ctx context.Context,
		arg sql.RefreshTokenAndGetUserRolesParams,
	) ([]sql.RefreshTokenAndGetUserRolesRow, error)
}

type DBClientGetUser added in v0.28.0

type DBClientGetUser interface {
	GetUser(ctx context.Context, id uuid.UUID) (sql.AuthUser, error)
	GetUserByEmail(ctx context.Context, email pgtype.Text) (sql.AuthUser, error)
	GetUserByRefreshTokenHash(
		ctx context.Context, arg sql.GetUserByRefreshTokenHashParams,
	) (sql.AuthUser, error)
}

type DBClientInsertUser added in v0.28.0

type DBClientInsertUser interface {
	InsertUser(ctx context.Context, arg sql.InsertUserParams) (sql.InsertUserRow, error)
	InsertUserWithRefreshToken(
		ctx context.Context, arg sql.InsertUserWithRefreshTokenParams,
	) (sql.InsertUserWithRefreshTokenRow, error)
	InsertUserWithSecurityKeyAndRefreshToken(
		ctx context.Context,
		arg sql.InsertUserWithSecurityKeyAndRefreshTokenParams,
	) (sql.InsertUserWithSecurityKeyAndRefreshTokenRow, error)
}

type DBClientUpdateUser added in v0.28.0

type DBClientUpdateUser interface {
	UpdateUserChangeEmail(
		ctx context.Context,
		arg sql.UpdateUserChangeEmailParams,
	) (sql.AuthUser, error)
	UpdateUserDeanonymize(ctx context.Context, arg sql.UpdateUserDeanonymizeParams) error
	UpdateUserLastSeen(ctx context.Context, id uuid.UUID) (pgtype.Timestamptz, error)
	UpdateUserTicket(ctx context.Context, arg sql.UpdateUserTicketParams) (uuid.UUID, error)
	InsertUserWithSecurityKey(
		ctx context.Context, arg sql.InsertUserWithSecurityKeyParams,
	) (uuid.UUID, error)
}

type Emailer

type Emailer interface {
	SendEmail(
		ctx context.Context,
		to string,
		locale string,
		templateName notifications.TemplateName,
		data notifications.TemplateData,
	) error
}

type ErrorResponse

type ErrorResponse api.ErrorResponse

func (ErrorResponse) VisitPostPatResponse added in v0.28.0

func (response ErrorResponse) VisitPostPatResponse(w http.ResponseWriter) error

func (ErrorResponse) VisitPostSigninEmailPasswordResponse added in v0.28.0

func (response ErrorResponse) VisitPostSigninEmailPasswordResponse(w http.ResponseWriter) error

func (ErrorResponse) VisitPostSigninPasswordlessEmailResponse added in v0.28.0

func (response ErrorResponse) VisitPostSigninPasswordlessEmailResponse(
	w http.ResponseWriter,
) error

func (ErrorResponse) VisitPostSigninPatResponse added in v0.28.0

func (response ErrorResponse) VisitPostSigninPatResponse(w http.ResponseWriter) error

func (ErrorResponse) VisitPostSignupEmailPasswordResponse

func (response ErrorResponse) VisitPostSignupEmailPasswordResponse(w http.ResponseWriter) error

func (ErrorResponse) VisitPostSignupWebauthnResponse added in v0.28.0

func (response ErrorResponse) VisitPostSignupWebauthnResponse(w http.ResponseWriter) error

func (ErrorResponse) VisitPostSignupWebauthnVerifyResponse added in v0.28.0

func (response ErrorResponse) VisitPostSignupWebauthnVerifyResponse(w http.ResponseWriter) error

func (ErrorResponse) VisitPostTokenResponse added in v0.29.0

func (response ErrorResponse) VisitPostTokenResponse(w http.ResponseWriter) error

func (ErrorResponse) VisitPostUserDeanonymizeResponse added in v0.28.0

func (response ErrorResponse) VisitPostUserDeanonymizeResponse(w http.ResponseWriter) error

func (ErrorResponse) VisitPostUserEmailChangeResponse added in v0.28.0

func (response ErrorResponse) VisitPostUserEmailChangeResponse(w http.ResponseWriter) error

func (ErrorResponse) VisitPostUserEmailSendVerificationEmailResponse added in v0.28.0

func (response ErrorResponse) VisitPostUserEmailSendVerificationEmailResponse(
	w http.ResponseWriter,
) error

func (ErrorResponse) VisitPostUserPasswordResetResponse added in v0.28.0

func (response ErrorResponse) VisitPostUserPasswordResetResponse(w http.ResponseWriter) error

type HIBPClient

type HIBPClient interface {
	IsPasswordPwned(ctx context.Context, password string) (bool, error)
}

type JWTGetter

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

func NewJWTGetter

func NewJWTGetter(
	jwtSecretb []byte,
	accessTokenExpiresIn time.Duration,
	customClaimer CustomClaimer,
	elevatedClaimMode string,
	db DBClient,
) (*JWTGetter, error)

func (*JWTGetter) FromContext added in v0.28.0

func (j *JWTGetter) FromContext(ctx context.Context) (*jwt.Token, bool)

func (*JWTGetter) GetCustomClaim added in v0.28.0

func (j *JWTGetter) GetCustomClaim(token *jwt.Token, customClaim string) string

func (*JWTGetter) GetToken

func (j *JWTGetter) GetToken(
	ctx context.Context,
	userID uuid.UUID,
	isAnonymous bool,
	allowedRoles []string,
	defaultRole string,
	logger *slog.Logger,
) (string, int64, error)

func (*JWTGetter) GetUserID added in v0.28.0

func (j *JWTGetter) GetUserID(token *jwt.Token) (uuid.UUID, error)

func (*JWTGetter) IsAnonymous added in v0.28.0

func (j *JWTGetter) IsAnonymous(token *jwt.Token) bool

func (*JWTGetter) MiddlewareFunc added in v0.28.0

func (j *JWTGetter) MiddlewareFunc(
	ctx context.Context, input *openapi3filter.AuthenticationInput,
) error

func (*JWTGetter) ToContext added in v0.28.0

func (j *JWTGetter) ToContext(ctx context.Context, jwtToken *jwt.Token) context.Context

func (*JWTGetter) Validate

func (j *JWTGetter) Validate(accessToken string) (*jwt.Token, error)

type JWTSecret

type JWTSecret struct {
	Key             string `json:"key"`
	Type            string `json:"type"`
	Issuer          string `json:"issuer"`
	ClaimsNamespace string `json:"claims_namespace"`
}

type LinkType

type LinkType string
const (
	LinkTypeEmailVerify        LinkType = "emailVerify"
	LinkTypeEmailConfirmChange LinkType = "emailConfirmChange"
	LinkTypePasswordlessEmail  LinkType = "signinPasswordless"
	LinkTypePasswordReset      LinkType = "passwordReset"
)

type RequestInterceptor

type RequestInterceptor func(*http.Request)

func CustomClaimerAddAdminSecret

func CustomClaimerAddAdminSecret(adminSecret string) RequestInterceptor

type SignUpFn added in v0.28.0

type SignUpFn func(input *sql.InsertUserParams) error

func SignupUserWithID added in v0.28.0

func SignupUserWithID(id uuid.UUID) SignUpFn

func SignupUserWithPassword added in v0.28.0

func SignupUserWithPassword(password string) SignUpFn

func SignupUserWithTicket added in v0.28.0

func SignupUserWithTicket(ticket string, expiresAt time.Time) SignUpFn

type TicketType added in v0.28.0

type TicketType string
const (
	TicketTypeEmailConfirmChange TicketType = "emailConfirmChange"
	TicketTypePasswordLessEmail  TicketType = "passwordlessEmail"
	TicketTypeVerifyEmail        TicketType = "verifyEmail"
	TicketTypePasswordReset      TicketType = "passwordReset"
)

type Webauthn added in v0.28.0

type Webauthn struct {
	Storage map[string]WebauthnChallenge
	// contains filtered or unexported fields
}

func NewWebAuthn added in v0.28.0

func NewWebAuthn(config Config) (*Webauthn, error)

func (*Webauthn) BeginRegistration added in v0.28.0

func (w *Webauthn) BeginRegistration(
	user WebauthnUser,
	options *api.SignUpOptions,
	logger *slog.Logger,
) (*protocol.CredentialCreation, *APIError)

func (*Webauthn) FinishRegistration added in v0.28.0

func (w *Webauthn) FinishRegistration(
	response *protocol.ParsedCredentialCreationData,
	logger *slog.Logger,
) (*webauthn.Credential, WebauthnUser, *APIError)

type WebauthnChallenge added in v0.28.0

type WebauthnChallenge struct {
	Session webauthn.SessionData
	User    WebauthnUser
	Options *api.SignUpOptions
}

type WebauthnUser added in v0.28.0

type WebauthnUser struct {
	ID    uuid.UUID
	Name  string
	Email string
}

func (WebauthnUser) WebAuthnCredentials added in v0.28.0

func (u WebauthnUser) WebAuthnCredentials() []webauthn.Credential

func (WebauthnUser) WebAuthnDisplayName added in v0.28.0

func (u WebauthnUser) WebAuthnDisplayName() string

func (WebauthnUser) WebAuthnID added in v0.28.0

func (u WebauthnUser) WebAuthnID() []byte

func (WebauthnUser) WebAuthnIcon added in v0.28.0

func (u WebauthnUser) WebAuthnIcon() string

func (WebauthnUser) WebAuthnName added in v0.28.0

func (u WebauthnUser) WebAuthnName() string

type Workflows added in v0.28.0

type Workflows struct {
	ValidateEmail func(email string) bool
	// contains filtered or unexported fields
}

func NewWorkflows added in v0.28.0

func NewWorkflows(
	cfg *Config,
	jwtGetter JWTGetter,
	db DBClient,
	hibp HIBPClient,
	email Emailer,
	gravatarURL func(string) string,
) (*Workflows, error)

func (*Workflows) ChangeEmail added in v0.28.0

func (wf *Workflows) ChangeEmail(
	ctx context.Context,
	userID uuid.UUID,
	newEmail string,
	logger *slog.Logger,
) (sql.AuthUser, *APIError)

func (*Workflows) DeanonymizeUser added in v0.28.0

func (wf *Workflows) DeanonymizeUser(
	ctx context.Context,
	userID uuid.UUID,
	email string,
	password string,
	ticket string,
	ticketExpiresAt time.Time,
	options *api.SignUpOptions,
	deleteRefreshTokens bool,
	logger *slog.Logger,
) *APIError

func (*Workflows) GetUser added in v0.28.0

func (wf *Workflows) GetUser(
	ctx context.Context,
	id uuid.UUID,
	logger *slog.Logger,
) (sql.AuthUser, *APIError)

func (*Workflows) GetUserByEmail added in v0.28.0

func (wf *Workflows) GetUserByEmail(
	ctx context.Context,
	email string,
	logger *slog.Logger,
) (sql.AuthUser, *APIError)

func (*Workflows) GetUserByRefreshTokenHash added in v0.28.0

func (wf *Workflows) GetUserByRefreshTokenHash(
	ctx context.Context,
	refreshToken string,
	refreshTokenType sql.RefreshTokenType,
	logger *slog.Logger,
) (sql.AuthUser, *APIError)

func (*Workflows) GetUserFromJWTInContext added in v0.28.0

func (wf *Workflows) GetUserFromJWTInContext(
	ctx context.Context,
	logger *slog.Logger,
) (sql.AuthUser, *APIError)

func (*Workflows) InsertRefreshtoken added in v0.28.0

func (wf *Workflows) InsertRefreshtoken(
	ctx context.Context,
	userID uuid.UUID,
	refreshToken string,
	refreshTokenExpiresAt time.Time,
	refreshTokenType sql.RefreshTokenType,
	metadata map[string]any,
	logger *slog.Logger,
) (uuid.UUID, *APIError)

func (*Workflows) NewSession added in v0.28.0

func (wf *Workflows) NewSession(
	ctx context.Context,
	user sql.AuthUser,
	logger *slog.Logger,
) (*api.Session, error)

func (*Workflows) SendEmail added in v0.28.0

func (wf *Workflows) SendEmail(
	ctx context.Context,
	to string,
	locale string,
	linkType LinkType,
	ticket string,
	redirectTo string,
	templateName notifications.TemplateName,
	displayName string,
	email string,
	newEmail string,
	logger *slog.Logger,
) *APIError

func (*Workflows) SetTicket added in v0.28.0

func (wf *Workflows) SetTicket(
	ctx context.Context,
	userID uuid.UUID,
	ticket string,
	expiresAt time.Time,
	logger *slog.Logger,
) *APIError

func (*Workflows) SignUpUser added in v0.28.0

func (wf *Workflows) SignUpUser(
	ctx context.Context,
	email string,
	options *api.SignUpOptions,
	logger *slog.Logger,
	withInputFn ...SignUpFn,
) (sql.AuthUser, *APIError)

func (*Workflows) SignupUserWithRefreshToken added in v0.28.0

func (wf *Workflows) SignupUserWithRefreshToken(
	ctx context.Context,
	email string,
	password string,
	refreshToken uuid.UUID,
	expiresAt time.Time,
	options *api.SignUpOptions,
	logger *slog.Logger,
) (*api.User, sql.InsertUserWithRefreshTokenRow, *APIError)

func (*Workflows) SignupUserWithSecurityKey added in v0.28.0

func (wf *Workflows) SignupUserWithSecurityKey(
	ctx context.Context,
	userID uuid.UUID,
	email string,
	ticket string,
	ticketExpiresAt time.Time,
	options *api.SignUpOptions,
	credentialID []byte,
	credentialPublicKey []byte,
	nickname string,
	logger *slog.Logger,
) (*api.User, *APIError)

func (*Workflows) SignupUserWithSecurityKeyAndRefreshToken added in v0.28.0

func (wf *Workflows) SignupUserWithSecurityKeyAndRefreshToken(
	ctx context.Context,
	userID uuid.UUID,
	email string,
	refreshToken uuid.UUID,
	expiresAt time.Time,
	options *api.SignUpOptions,
	credentialID []byte,
	credentialPublicKey []byte,
	nickname string,
	logger *slog.Logger,
) (*api.User, uuid.UUID, *APIError)

func (*Workflows) UpdateSession added in v0.29.0

func (wf *Workflows) UpdateSession(
	ctx context.Context,
	user sql.AuthUser,
	refreshToken string,
	logger *slog.Logger,
) (*api.Session, *APIError)

func (*Workflows) UserByEmailExists added in v0.28.0

func (wf *Workflows) UserByEmailExists(
	ctx context.Context,
	email string,
	logger *slog.Logger,
) (bool, *APIError)

func (*Workflows) ValidateOptionsRedirectTo added in v0.28.0

func (wf *Workflows) ValidateOptionsRedirectTo(
	options *api.OptionsRedirectTo,
	logger *slog.Logger,
) (*api.OptionsRedirectTo, *APIError)

func (*Workflows) ValidatePassword added in v0.28.0

func (wf *Workflows) ValidatePassword(
	ctx context.Context, password string, logger *slog.Logger,
) *APIError

func (*Workflows) ValidateSignUpOptions added in v0.28.0

func (wf *Workflows) ValidateSignUpOptions(
	options *api.SignUpOptions, defaultName string, logger *slog.Logger,
) (*api.SignUpOptions, *APIError)

func (*Workflows) ValidateSignupEmail added in v0.28.0

func (wf *Workflows) ValidateSignupEmail(
	ctx context.Context, email types.Email, logger *slog.Logger,
) *APIError

func (*Workflows) ValidateUser added in v0.28.0

func (wf *Workflows) ValidateUser(
	user sql.AuthUser,
	logger *slog.Logger,
) *APIError

Directories

Path Synopsis
Package mock is a generated GoMock package.
Package mock is a generated GoMock package.

Jump to

Keyboard shortcuts

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