hashauth

package module
v0.0.0-...-ec6ff65 Latest Latest
Warning

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

Go to latest
Published: May 4, 2016 License: BSD-3-Clause Imports: 17 Imported by: 0

README

GoDoc TravisCI

Hashauth provides functions for working with authentication tokens. A token generated by hashauth contains arbitrary key/value pairs and an HMAC authentication code, serialized together in a url- and cookie-friendly form.

Documentation

Overview

Package hashauth provides a means of creating a cookie- and url-friendly token containing arbitrary encoded information, with an embedded authentication code that ensures that it was created by you (not forged) and is in its original form (not tampered with).

Primary use-cases are login sessions, password reset tokens, and the like. Any situation where you need to provide to the user a token they can present back to you which contains a small amount of data and authentication guarantees.

The package provides methods for Encoding, Validating, and Decoding tokens, and also a higher-level API for interacting with HTTP request and response cookies for sessions.

Login session example:

var Signer = hashauth.New([]byte("secret key"), nil)

type LoginSession struct {
	UserID     int
	Expiration time.Time
}

// implementing this method causes hashauth to set the Expires cookie attr
func (sess *LoginSession) Expires() time.Time {
	return sess.Expiration
}

func AuthRequired(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		sess := new(LoginSession)
		err := Signer.Authenticate(r, sess)
		if err != nil {
			http.Error(w, "Login Required", http.StatusForbidden)
		} else {
			h.ServeHTTP(w, r)
		}
	})
}

func LogUserIn(w http.ResponseWriter, uid int) error {
	return Signer.SetCookie(w, &LoginSession{
		UserID:     uid,
		Expiration: time.Now().UTC().Add(7*24*time.Hour),
	})
}

func LogUserOut(w http.ResponseWriter) {
	Signer.ClearCookie(w)
}

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalid is returned when an authentication check fails.
	ErrInvalid = errors.New("hashauth: token validation failed")

	// ErrExpired is returned when an Expirer session indicates that
	// an authentication token's expiration time has passed.
	ErrExpired = errors.New("hashauth: expiration time has passed")
)

Functions

This section is empty.

Types

type Expirer

type Expirer interface {
	Expires() time.Time
}

Expirer can be implemented by session data types, in which case their expiration time will be set as the cookie expiration time in HashAuth.SetCookie.

type HashAuth

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

HashAuth is an Encoder and Decoder of tokens.

func New

func New(key []byte, opts *Options) *HashAuth

New creates a new HashAuth En/Decoder. key should be a carefully guarded secret, with it anyone could forge a token. opts can be nil, in which case a sha256 hasher, a default cookie name, and no cookie attributes will be used.

func (*HashAuth) Authenticate

func (ha *HashAuth) Authenticate(r *http.Request, container interface{}) error

Authenticate finds and decodes the auth token from a request, populating the container with the session data. It will return nil on success, or:

  • http.ErrNoCookie if there is no auth header at all
  • a decoding error if it is malformed
  • ErrInvalid if there is a properly formatted token that is invalid
  • ErrExpired if the session has expired

func (*HashAuth) CheckPin

func (ha *HashAuth) CheckPin(pin string, token []byte) bool

CheckPin validates a PIN code for a given token.

func (*HashAuth) ClearCookie

func (ha *HashAuth) ClearCookie(w http.ResponseWriter)

ClearCookie adds a Set-Cookie header to a response that will remove the auth cookie.

func (*HashAuth) Decode

func (ha *HashAuth) Decode(token []byte, container interface{}) error

Decode checks a token's validity and extracts the data encoded in it. May return ErrInvalid if the validity check fails. If the container is an Expirer and the token contains an expired session, it will return ErrExpired but still populate the container with token data.

func (*HashAuth) Encode

func (ha *HashAuth) Encode(session interface{}) ([]byte, error)

Encode produces a signed token with session data.

func (*HashAuth) Pin

func (ha *HashAuth) Pin(token []byte) (string, error)

Pin generates a PIN code (string of a decimal number) from a token.

func (*HashAuth) SetCookie

func (ha *HashAuth) SetCookie(w http.ResponseWriter, session interface{}) error

SetCookie adds an encoded token as a cookie on an HTTP response. If the provided session data object implements the Expirer or MaxAger interfaces, then the corresponding cookie attribute will also be set. Other cookie attributes will be set according to the *Options with which the HashAuth was created.

func (*HashAuth) Validate

func (ha *HashAuth) Validate(token []byte) bool

Validate tests a token's signature and returns whether it it valid.

type MaxAger

type MaxAger interface {
	MaxAge() time.Duration
}

MaxAger can be implemented by session data types, in which case the HashAuth.SetCookie method will set a max-age attribute (unless it also implements Expirer, which takes precedence).

type Options

type Options struct {

	// The hash implementation to use. Defaults to sha256.New.
	Hash func() hash.Hash

	// A separate signing key to use for PIN codes (Pin() and CheckPin()
	// methods). Defaults to the main signing key.
	PINSignKey []byte

	// The length of PIN codes generated by this HashAuth. Defaults to 5,
	// has a maximum value of 18.
	PINLength int

	// The name of the cookie to use for Authenticate(), SetCookie(), and
	// ClearCookie(). Defaults to "_ha".
	CookieName string

	// The 'path' attribute to use for the cookie. Defaults to none/empty.
	CookiePath string

	// The 'domain' attribute for the cookie. Defaults to none/empty.
	CookieDomain string

	// Whether to include the 'secure' cookie attribute. Defaults to false.
	CookieSecure bool

	// Whether to include the 'httponly' cookie attribute. Defaults to false.
	CookieHTTPOnly bool
}

Options is a simple container for various HashAuth options.

Jump to

Keyboard shortcuts

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