Documentation ¶
Overview ¶
Package tinyauth provides super simple token-based authentication tools that are compatible with the standard library HTTP handler APIs. It uses authenticated encryption by default, to ensure the authenticity, privacy, and integrity of the token content. tinyauth was designed to keep the API minimal while still being easy to integrate with existing services and user models.
Index ¶
Constants ¶
const ( Second = int64(1) Minute = Second * 60 Hour = Minute * 60 )
Time constants for convenience.
Variables ¶
var LoginErrorHandler = func(w http.ResponseWriter, r *http.Request, err *Error) { log.Println(err.Error()) switch err.ErrType { case ErrBadInput: http.Error(w, err.Msg, http.StatusBadRequest) case ErrInternal: http.Error(w, err.Msg, http.StatusInternalServerError) case ErrAuthFailed: http.Error(w, err.Msg, http.StatusUnauthorized) } }
LoginErrorHandler is called if the user cannot be authenticated. It is exposed so that users can replace it with custom logic if desired.
var LoginSuccessHandler = func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("login successful")) }
LoginSuccessHandler returns status 200 with text "login successful". It is exposed so that users can replace it with custom logic if desired.
var LogoutErrorHandler = func(w http.ResponseWriter, r *http.Request, err *Error) { http.Error(w, err.Msg, http.StatusInternalServerError) }
LogoutErrorHandler is called if the logout fails for any reason. It is exposed so that users can replace it with custom logic if desired.
var LogoutSuccessHandler = func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("session terminated")) }
LogoutSuccessHandler returns status 200 with text "session terminated". It is exposed so that users can replace it with custom logic if desired.
var MiddlewareErrorHandler = func(w http.ResponseWriter, r *http.Request, err *Error) { log.Printf("auth failed: %v", err) http.Error(w, "authentication failed", http.StatusUnauthorized) }
MiddlewareErrorHandler processes errors thrown by the middleware. It is exposed so that users of the library can replace it to provide their own custom error handling.
Functions ¶
func CheckPassword ¶
CheckPassword re-exports the hash/password authentication utility used.
func HashPassword ¶
HashPassword re-exports the password hash utility used (currently acrypt).
Types ¶
type Authable ¶
type Authable interface {
GetID() (id string)
}
Authable represents a user.
func ExtractUser ¶
ExtractUser returns the Authable from the token that is carried in the context of the request.
Ex. user, ok := tinyauth.ExtractUser(r).(*User) if !ok { log.Warn("failed to find *User in request context") }
type ErrType ¶
type ErrType int
ErrType categorizes the Err stored in tinyauth.Error.
const ( // ErrBadInput indicates that input was invalid. ErrBadInput ErrType = iota // ErrAuthFailed indicates that the authentication failed. ErrAuthFailed // ErrInternal indicates that an error was neither recognized as bad input // nor as explicit auth failure (for example, a data store was unreachable). ErrInternal )
type Error ¶
Error is an augmenting wrapper error type.
func NewErrorAuthFailed ¶
NewErrorBadInput constructs an Error with ErrType ErrAuthFailed.
func NewErrorBadInput ¶
NewErrorBadInput constructs an Error with ErrType ErrBadInput.
func NewErrorInternal ¶
NewErrorBadInput constructs an Error with ErrType ErrInternal.
type Guard ¶
type Guard struct {
// contains filtered or unexported fields
}
Guard holds the state used for authentication. Auth middleware are therefore defined as methods on the Guard.
func CustomGuard ¶
func CustomGuard(cfg TokenConfig, keyset *tinycrypto.Keyset, db Repo, userPrototypePtr Authable) *Guard
CustomGuard creates an authenticator with a custom configuration.
func NewGuard ¶
func NewGuard(keyset *tinycrypto.Keyset, db Repo, userPrototypePtr Authable) *Guard
NewGuard creates an authenticator using the default configuration.
func (*Guard) LoginHandler ¶
LoginHandler authenticates a user. If successful, it puts the auth token into the Authorization header and then calls the LoginSuccessHandler. If the user cannot be authenticated, it calls the LoginErrorHandler. The inbound POST request must contain: `{"user_id": "alice", password:"secret"}`.
func (*Guard) LogoutHandler ¶
LogoutHandler returns an http.Handler that is used to add the session to a blacklist of cancelled sessions, to prevent further auto-refresh. If success- ful, it calls the LogoutSuccessHandler, otherwise it calls the LogoutErrorHandler.
func (*Guard) Middleware ¶
Middleware provides token-based auth protection for routes. If it incurs an error, it calls the MiddlewareErrorHandler to process it. This middleware is compatible with the standard library API.
func (*Guard) RequestWithUpdatedAuthable ¶
func (g *Guard) RequestWithUpdatedAuthable(w http.ResponseWriter, r *http.Request, a Authable) (*http.Request, error)
RequestWithUpdatedAuthable takes an updated Authable, regenerates the auth token, injects it into the response header, and returns a new request with the updated Authable value in context. Clients can use this to persist property changes for the current user into the auth token.
type Repo ¶
type Repo interface { // GetAuthable returns the user with the given ID, IF valid. If the password // hash is required, it is returned separately and will immediately be // discarded after the user is authenticated. GetAuthable(id string, includePasswordHash bool) (user Authable, hash []byte, err error) // BlacklistSession registers a session as dead, so that it cannot be used // to auto-refresh an auth token. The repo is also provided with a timestamp // indicating when it will become safe to prune the session. BlacklistSession(sessionID string, until time.Time) error // CheckSessionBlacklist returns nil if the sessionID is NOT present in the // dead session blacklist. CheckSessionBlacklist(sessionID string) error }
Repo defines the data persistence API for auth-related entities.
type TokenConfig ¶
type TokenConfig struct { // Longest period between db checks. MaxTrustSecs int64 // Longest inactive period between logins. MaxStaleSecs int64 // Longest period between logins. MaxTokenSecs int64 }
TokenConfig defines the behavior of the auth token.