auth

package
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2024 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package auth handles auth

Index

Constants

View Source
const (
	Authorization             = "Authorization"
	DefaultKeysURL            = "http://localhost:17608/.well-known/jwks.json"
	DefaultAudience           = "http://localhost:17608"
	DefaultIssuer             = "http://localhost:17608"
	DefaultMinRefreshInterval = 5 * time.Minute
	DefaultCookieDomain       = "localhost:17608"
	AccessTokenCookie         = "access_token"
	RefreshTokenCookie        = "refresh_token"
)

Variables

View Source
var (
	ErrUnauthenticated  = errors.New("request is unauthenticated")
	ErrNoClaims         = errors.New("no claims found on the request context")
	ErrNoUserInfo       = errors.New("no user info found on the request context")
	ErrInvalidAuthToken = errors.New("invalid authorization token")
	ErrAuthRequired     = errors.New("this endpoint requires authentication")
	ErrNoPermission     = errors.New("user does not have permission to perform this operation")
	ErrNoAuthUser       = errors.New("could not identify authenticated user in request")
	ErrNoAuthUserData   = errors.New("could not retrieve user data")
	ErrIncompleteUser   = errors.New("user is missing required fields")
	ErrUnverifiedUser   = errors.New("user is not verified")
	ErrCSRFVerification = errors.New("csrf verification failed for request")
	ErrParseBearer      = errors.New("could not parse bearer token from authorization header")
	ErrNoAuthorization  = errors.New("no authorization header in request")
	ErrNoRequest        = errors.New("no request found on the context")
	ErrRateLimit        = errors.New("rate limit reached: too many requests")
	ErrNoRefreshToken   = errors.New("no refresh token available on request")
	ErrRefreshDisabled  = errors.New("re-authentication with refresh tokens disabled")
	ErrShitWentBad      = errors.New("shit went bad")
)
View Source
var (
	ErrInvalidCredentials = errors.New("datum credentials are missing or invalid")
	ErrExpiredCredentials = errors.New("datum credentials have expired")
	ErrPasswordMismatch   = errors.New("passwords do not match")
	ErrPasswordTooWeak    = errors.New("password is too weak: use a combination of upper and lower case letters, numbers, and special characters")
	ErrNonUniquePassword  = errors.New("password was already used, please try again")
	ErrMissingID          = errors.New("missing required id")
	ErrMissingField       = errors.New("missing required field")
	ErrInvalidField       = errors.New("invalid or unparsable field")
	ErrRestrictedField    = errors.New("field restricted for request")
	ErrConflictingFields  = errors.New("only one field can be set")
	ErrModelIDMismatch    = errors.New("resource id does not match id of endpoint")
	ErrUserExists         = errors.New("user or organization already exists")
	ErrInvalidUserClaims  = errors.New("user claims invalid or unavailable")
	ErrUnparsable         = errors.New("could not parse request")
	ErrUnknownUserRole    = errors.New("unknown user role")
)
View Source
var ContextAccessToken = &ContextKey{"access_token"}

ContextAccessToken is the context key for the access token

View Source
var ContextRequestID = &ContextKey{"request_id"}

ContextRequestID is the context key for the request ID

View Source
var ContextUserClaims = &ContextKey{"user_claims"}

ContextUserClaims is the context key for the user claims

Functions

func AuthContextFromRequest

func AuthContextFromRequest(c echo.Context) (*context.Context, error)

AuthContextFromRequest creates a context from the echo request context, copying fields that may be required for forwarded requests. This method should be called by handlers which need to forward requests to other services and need to preserve data from the original request such as the user's credentials.

func Authenticate

func Authenticate() echo.MiddlewareFunc

func ClearAuthCookies

func ClearAuthCookies(c echo.Context, domain string)

ClearAuthCookies is a helper function to clear authentication cookies on a echo request to effectively logger out a user.

func ConflictingFields

func ConflictingFields(fields ...string) error

func CookieExpired

func CookieExpired(cookie *http.Cookie) bool

CookieExpired checks to see if a cookie is expired

func ErrorResponse

func ErrorResponse(err interface{}) *echo.HTTPError

ErrorResponse constructs a new response for an error or simply returns unsuccessful

func GetAccessToken

func GetAccessToken(c echo.Context) (string, error)

GetAccessToken retrieves the bearer token from the authorization header and parses it to return only the JWT access token component of the header. Alternatively, if the authorization header is not present, then the token is fetched from cookies. If the header is missing or the token is not available, an error is returned.

NOTE: the authorization header takes precedence over access tokens in cookies.

func GetActorUserID

func GetActorUserID(c echo.Context) (string, error)

GetActorUserID returns the user from the echo.Context

func GetClaims

func GetClaims(c echo.Context) (*tokens.Claims, error)

GetClaims fetches and parses datum claims from the echo context. Returns an error if no claims exist on the context

func GetRefreshToken

func GetRefreshToken(c echo.Context) (string, error)

GetRefreshToken retrieves the refresh token from the cookies in the request. If the cookie is not present or expired then an error is returned.

func GetUserIDFromContext

func GetUserIDFromContext(ctx context.Context) (string, error)

GetUserIDFromContext returns the actor subject from the echo context

func InvalidField

func InvalidField(field string) error

func MissingField

func MissingField(field string) error

func NewTestContextWithValidUser

func NewTestContextWithValidUser(subject string) (echo.Context, error)

NewTestContextWithValidUser creates an echo context with a fake subject for testing purposes ONLY

func NotAllowed

func NotAllowed(c echo.Context) error

NotAllowed returns a JSON 405 response for the API.

func NotFound

func NotFound(c echo.Context) error

NotFound returns a JSON 404 response for the API. NOTE: we know it's weird to put server-side handlers like NotFound and NotAllowed here in the client/api side package but it unifies where we keep our error handling mechanisms.

func Reauthenticate

func Reauthenticate(conf AuthOptions, validator tokens.Validator) func(c echo.Context) (string, error)

Reauthenticate is a middleware helper that can use refresh tokens in the echo context to obtain a new access token. If it is unable to obtain a new valid access token, then an error is returned and processing should stop.

func RestrictedField

func RestrictedField(field string) error

func SetAuthCookies

func SetAuthCookies(c echo.Context, accessToken, refreshToken, domain string) error

SetAuthCookies is a helper function to set authentication cookies on a echo request. The access token cookie (access_token) is an http only cookie that expires when the access token expires. The refresh token cookie is not an http only cookie (it can be accessed by client-side scripts) and it expires when the refresh token expires. Both cookies require https and will not be set (silently) over http connections.

func Unauthorized

func Unauthorized(c echo.Context) error

Unauthorized returns a JSON 401 response indicating that the request failed authorization

func Unverified

func Unverified(c echo.Context) error

Unverified returns a JSON 403 response indicating that the user has not verified their email address.

Types

type AuthOption

type AuthOption func(opts *AuthOptions)

AuthOption allows users to optionally supply configuration to the Authorization middleware.

func WithAudience

func WithAudience(audience string) AuthOption

WithAudience allows the user to specify an alternative audience.

func WithAuthOptions

func WithAuthOptions(opts AuthOptions) AuthOption

WithAuthOptions allows the user to update the default auth options with an auth options struct to set many options values at once. Zero values are ignored, so if using this option, the defaults will still be preserved if not set on the input.

func WithContext

func WithContext(ctx context.Context) AuthOption

WithContext allows the user to specify an external, cancelable context to control the background refresh behavior of the JWKS cache.

func WithIssuer

func WithIssuer(issuer string) AuthOption

WithIssuer allows the user to specify an alternative issuer.

func WithJWKSEndpoint

func WithJWKSEndpoint(url string) AuthOption

WithJWKSEndpoint allows the user to specify an alternative endpoint to fetch the JWKS public keys from. This is useful for testing or for different environments.

func WithMinRefreshInterval

func WithMinRefreshInterval(interval time.Duration) AuthOption

WithMinRefreshInterval allows the user to specify an alternative minimum duration between cache refreshes to control refresh behavior for the JWKS public keys.

func WithReauthenticator

func WithReauthenticator(reauth Reauthenticator) AuthOption

WithReauthenticator allows the user to specify a reauthenticator to the auth middleware.

func WithValidator

func WithValidator(validator tokens.Validator) AuthOption

WithValidator allows the user to specify an alternative validator to the auth middleware. This is particularly useful for testing authentication.

type AuthOptions

type AuthOptions struct {
	// KeysURL endpoint to the JWKS public keys on the datum server
	KeysURL string
	// Audience to verify on tokens
	Audience string
	// Issuer to verify on tokens
	Issuer string
	// MinRefreshInterval to cache the JWKS public keys
	MinRefreshInterval time.Duration
	// CookieDomain to use for auth cookies
	CookieDomain string
	// Context to control the lifecycle of the background fetch routine
	Context context.Context
	// contains filtered or unexported fields
}

AuthOptions is constructed from variadic AuthOption arguments with reasonable defaults.

func NewAuthOptions

func NewAuthOptions(opts ...AuthOption) (conf AuthOptions)

NewAuthOptions creates an AuthOptions object with reasonable defaults and any user supplied input from the AuthOption variadic arguments.

func (*AuthOptions) Validator

func (conf *AuthOptions) Validator() (tokens.Validator, error)

Validator returns the user supplied validator or constructs a new JWKS Cache Validator from the supplied options. If the options are invalid or the validator cannot be created an error is returned

type ContextKey

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

ContextKey is the key name for the additional context

type FieldError

type FieldError struct {
	Field string `json:"field"`
	Err   error  `json:"error"`
}

FieldError provides a general mechanism for specifying errors with specific API object fields such as missing required field or invalid field and giving some feedback about which fields are the problem. TODO: allow multiple field errors to be specified in one response.

func (*FieldError) Error

func (e *FieldError) Error() string

func (*FieldError) Is

func (e *FieldError) Is(target error) bool

func (*FieldError) Unwrap

func (e *FieldError) Unwrap() error

type LoginReply

type LoginReply struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token,omitempty"`
	LastLogin    string `json:"last_login,omitempty"`
}

type Reauthenticator

type Reauthenticator interface {
	Refresh(context.Context, *RefreshRequest) (*LoginReply, error)
}

Reauthenticator generates new access and refresh pair given a valid refresh token.

type RefreshRequest

type RefreshRequest struct {
	RefreshToken string `json:"refresh_token"`
	OrgID        string `json:"org_id,omitempty"`
}

Jump to

Keyboard shortcuts

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