Documentation ¶
Overview ¶
Package auth provides JSON Web Token (JWT) authentication and authorization middleware. It implements a passwordless authentication flow by sending login tokens vie email which are then exchanged for JWT access and refresh tokens.
Index ¶
- Variables
- func AuthenticateRefreshJWT(next http.Handler) http.Handler
- func Authenticator(next http.Handler) http.Handler
- func ErrInvalidRequest(err error) render.Renderer
- func ErrRender(err error) render.Renderer
- func ErrUnauthorized(err error) render.Renderer
- func RefreshTokenFromCtx(ctx context.Context) string
- func RequiresRole(role string) func(next http.Handler) http.Handler
- type Account
- type AccountFilter
- type AppClaims
- type ErrResponse
- type LoginToken
- type LoginTokenAuth
- type Mailer
- type MockStorer
- func (s *MockStorer) DeleteRefreshToken(t *Token) error
- func (s *MockStorer) GetByEmail(email string) (*Account, error)
- func (s *MockStorer) GetByID(id int) (*Account, error)
- func (s *MockStorer) GetByRefreshToken(token string) (*Account, *Token, error)
- func (s *MockStorer) PurgeExpiredToken() error
- func (s *MockStorer) SaveRefreshToken(t *Token) error
- func (s *MockStorer) UpdateAccount(a *Account) error
- type Resource
- type Storer
- type Token
- type TokenAuth
Constants ¶
This section is empty.
Variables ¶
var ( ErrBadRequest = &ErrResponse{HTTPStatusCode: http.StatusBadRequest, StatusText: http.StatusText(http.StatusBadRequest)} ErrForbidden = &ErrResponse{HTTPStatusCode: http.StatusForbidden, StatusText: http.StatusText(http.StatusForbidden)} ErrNotFound = &ErrResponse{HTTPStatusCode: http.StatusNotFound, StatusText: http.StatusText(http.StatusNotFound)} ErrInternalServerError = &ErrResponse{HTTPStatusCode: http.StatusInternalServerError, StatusText: http.StatusText(http.StatusInternalServerError)} )
The list of default error types without specific error message.
var ( ErrInvalidLogin = errors.New("invalid email address") ErrUnknownLogin = errors.New("email not registered") ErrLoginDisabled = errors.New("login for account disabled") ErrLoginToken = errors.New("invalid or expired login token") )
The list of error types presented to the end user as error message.
Functions ¶
func AuthenticateRefreshJWT ¶
AuthenticateRefreshJWT checks validity of refresh tokens and is only used for access token refresh and logout requests. It responds with 401 Unauthorized for invalid or expired refresh tokens.
func Authenticator ¶
Authenticator is a default authentication middleware to enforce access from the Verifier middleware request context values. The Authenticator sends a 401 Unauthorized response for any unverified tokens and passes the good ones through.
func ErrInvalidRequest ¶
ErrInvalidRequest returns status 422 Unprocessable Entity with validation errors
func ErrUnauthorized ¶
ErrUnauthorized renders status 401 Unauthorized with custom error message.
func RefreshTokenFromCtx ¶
RefreshTokenFromCtx retrieves the parsed refresh token from context.
Types ¶
type Account ¶
type Account struct { ID int `json:"id"` CreatedAt time.Time `json:"created_at,omitempty"` UpdatedAt time.Time `json:"updated_at,omitempty"` LastLogin time.Time `json:"last_login,omitempty"` Email string `json:"email"` Name string `json:"name"` Active bool `sql:",notnull" json:"active"` Roles []string `pg:",array" json:"roles,omitempty"` Token []Token `json:"token,omitempty"` }
Account represents an authenticated application user
func (*Account) BeforeDelete ¶
BeforeDelete hook executed before database delete operation.
func (*Account) BeforeInsert ¶
BeforeInsert hook executed before database insert operation.
func (*Account) BeforeUpdate ¶
BeforeUpdate hook executed before database update operation.
type AccountFilter ¶
AccountFilter provides pagination and filtering options on accounts.
func NewAccountFilter ¶
func NewAccountFilter(v url.Values) AccountFilter
NewAccountFilter returns an AccountFilter with options parsed from request url values.
type AppClaims ¶
AppClaims represent the claims extracted from JWT token.
func ClaimsFromCtx ¶
ClaimsFromCtx retrieves the parsed AppClaims from request context.
type ErrResponse ¶
type ErrResponse struct { Err error `json:"-"` // low-level runtime error HTTPStatusCode int `json:"-"` // http response status code StatusText string `json:"status"` // user-level status message AppCode int64 `json:"code,omitempty"` // application-specific error code ErrorText string `json:"error,omitempty"` // application-level error message, for debugging }
ErrResponse renderer type for handling all sorts of errors.
func (*ErrResponse) Render ¶
func (e *ErrResponse) Render(w http.ResponseWriter, r *http.Request) error
Render sets the application-specific error code in AppCode.
type LoginToken ¶
LoginToken is an in-memory saved token referencing an account ID and an expiry date.
type LoginTokenAuth ¶
type LoginTokenAuth struct {
// contains filtered or unexported fields
}
LoginTokenAuth implements passwordless login authentication flow using temporary in-memory stored tokens.
func NewLoginTokenAuth ¶
func NewLoginTokenAuth() (*LoginTokenAuth, error)
NewLoginTokenAuth configures and returns a LoginToken authentication instance.
func (*LoginTokenAuth) CreateToken ¶
func (a *LoginTokenAuth) CreateToken(id int) LoginToken
CreateToken creates an in-memory login token referencing account ID. It returns a token containing a random tokenstring and expiry date.
func (*LoginTokenAuth) GetAccountID ¶
func (a *LoginTokenAuth) GetAccountID(token string) (int, error)
GetAccountID looks up the token by tokenstring and returns the account ID or error if token not found or expired.
type Mailer ¶
type Mailer interface {
LoginToken(name, email string, c email.ContentLoginToken) error
}
Mailer defines methods to send account emails.
type MockStorer ¶
type MockStorer struct { GetByIDFn func(id int) (*Account, error) GetByIDInvoked bool GetByEmailFn func(email string) (*Account, error) GetByEmailInvoked bool GetByRefreshTokenFn func(token string) (*Account, *Token, error) GetByRefreshTokenInvoked bool UpdateAccountFn func(a *Account) error UpdateAccountInvoked bool SaveRefreshTokenFn func(t *Token) error SaveRefreshTokenInvoked bool DeleteRefreshTokenFn func(t *Token) error DeleteRefreshTokenInvoked bool PurgeExpiredTokenFn func() error PurgeExpiredTokenInvoked bool }
MockStorer mocks Storer interface.
func (*MockStorer) DeleteRefreshToken ¶
func (s *MockStorer) DeleteRefreshToken(t *Token) error
DeleteRefreshToken mock deletes a refresh token.
func (*MockStorer) GetByEmail ¶
func (s *MockStorer) GetByEmail(email string) (*Account, error)
GetByEmail mock returns an account by email.
func (*MockStorer) GetByID ¶
func (s *MockStorer) GetByID(id int) (*Account, error)
GetByID mock returns an account by ID.
func (*MockStorer) GetByRefreshToken ¶
func (s *MockStorer) GetByRefreshToken(token string) (*Account, *Token, error)
GetByRefreshToken mock returns an account and refresh token by token identifier.
func (*MockStorer) PurgeExpiredToken ¶
func (s *MockStorer) PurgeExpiredToken() error
PurgeExpiredToken mock deletes expired refresh token.
func (*MockStorer) SaveRefreshToken ¶
func (s *MockStorer) SaveRefreshToken(t *Token) error
SaveRefreshToken mock creates or updates a refresh token.
func (*MockStorer) UpdateAccount ¶
func (s *MockStorer) UpdateAccount(a *Account) error
UpdateAccount mock upates account data related to authentication.
type Resource ¶
type Resource struct { Login *LoginTokenAuth Token *TokenAuth // contains filtered or unexported fields }
Resource implements passwordless token authentication against a database.
func NewResource ¶
NewResource returns a configured authentication resource.
type Storer ¶
type Storer interface { GetByID(id int) (*Account, error) GetByEmail(email string) (*Account, error) GetByRefreshToken(token string) (*Account, *Token, error) UpdateAccount(a *Account) error SaveRefreshToken(t *Token) error DeleteRefreshToken(t *Token) error PurgeExpiredToken() error }
Storer defines database operations on account and token data.
type Token ¶
type Token struct { ID int `json:"id,omitempty"` CreatedAt time.Time `json:"created_at,omitempty"` UpdatedAt time.Time `json:"updated_at,omitempty"` AccountID int `json:"-"` Token string `json:"-"` Expiry time.Time `json:"-"` Mobile bool `sql:",notnull" json:"mobile"` Identifier string `json:"identifier,omitempty"` }
Token holds refresh jwt information.
func (*Token) BeforeInsert ¶
BeforeInsert hook executed before database insert operation.
func (*Token) BeforeUpdate ¶
BeforeUpdate hook executed before database update operation.
type TokenAuth ¶
TokenAuth implements JWT authentication flow.
func NewTokenAuth ¶
NewTokenAuth configures and returns a JWT authentication instance.
func (*TokenAuth) CreateRefreshJWT ¶
CreateRefreshJWT returns a refresh token for provided token Claims.
func (*TokenAuth) GenTokenPair ¶
GenTokenPair returns both an access token and a refresh token.