auth

package module
v1.5.6 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2017 License: MIT Imports: 18 Imported by: 29

README

Package Auth

Package auth provides helpers for encryption, hashing and encoding.

Setup

Setup the package on startup

  auth.HMACKey = auth.HexToBytes("myhmac_key_from_config")
  auth.SecretKey = auth.HexToBytes("my_secret_key_from_config")
  auth.SessionName = "my_cookie_name"
  auth.SecureCookies = true
Hashed Passwords

Use auth.HashPassword to encrypt and auth.CheckPassword to check hashed passwords (with bcrypt)

  user.HashedPassword, err = auth.HashPassword(params.Get("password")
  if err != nil {
    return err
  }
  err = auth.CheckPassword(params.Get("password"), user.HashedPassword)
Encrypted Sessions

Use auth.Session to set and get values from cookies, encrypted with AES GCM.

  // Build the session from the secure cookie, or create a new one
  session, err := auth.Session(writer, request)
  if err != nil {
    return err
  }
  
  // Store something in the session
  session.Set("my_key","my_value")
  session.Save(writer)
Random Tokens

Generate and compare random tokens in constant time using the crypto/rand and crypto/subtle packages.

// Generate a new token
token := auth.RandomToken(32)

// Check tokens
if auth.CheckRandomToken(tok1,tok2) {
  // Tokens match
}

Authorisation

You can use auth/can (separately) to authorise access to resources.

To authorise actions:

// Add an authorisation for admins to manage the pages resource
can.Authorise(role.Admin, can.ManageResource, "pages")

To check authorisation in handlers:

// Check whether resource (conforming to can.Resource)
// can be managed by user (conforming to can.User) 
can.Manage(resource,user)
// Interfaces for Users and Resources

// User defines the interface for users which must have numeric roles
type User interface {
	RoleID() int64 // for role check
	UserID() int64 // for ownership check
}

// Resource defines the interface for resources
type Resource interface {
	OwnedBy(int64) bool // for ownership check, passed a UserID
	ResourceID() string // for check against abilities registered on this resource
}

Documentation

Overview

Package auth provides helpers for encryption, hashing and encoding.

Index

Constants

View Source
const HashCost = 10

HashCost sets the cost of bcrypt hashes - if this changes hashed passwords would need to be recalculated.

View Source
const TokenLength = 32

TokenLength sets the length of random tokens used for authenticity tokens.

Variables

View Source
var HMACKey []byte

HMACKey is a 32 byte key for generating HMAC distinct from SecretKey.

View Source
var MaxAge = 86400 * 60

MaxAge is the age in seconds of a cookie before it expires, default 60 days.

View Source
var MaxCookieSize = 4096

MaxCookieSize is the maximum length of a cookie in bytes, defaults to 4096.

View Source
var SecretKey []byte

SecretKey is a 32 byte key for encrypting content with AES-GCM.

View Source
var SecureCookies = false

SecureCookies is true if we use secure https cookies.

View Source
var SessionName = "fragmenta_session"

SessionName is the name of the ssions.

View Source
var SessionTokenKey = "authenticity_token"

SessionTokenKey is the session token key.

View Source
var SessionUserKey = "user_id"

SessionUserKey is the session user key.

Functions

func AuthenticityToken

func AuthenticityToken(writer http.ResponseWriter, request *http.Request) (string, error)

AuthenticityToken returns a new token for a request, and if necessary sets the cookie with our secret.

func AuthenticityTokenWithSecret

func AuthenticityTokenWithSecret(secret []byte) []byte

AuthenticityTokenWithSecret generates a new authenticity token from the secret by xoring a new random token with it and prepending the random bytes See https://github.com/rails/rails/pull/16570 or gorilla/csrf for justification.

func Base64ToBytes

func Base64ToBytes(h string) []byte

Base64ToBytes converts from a b64 string to bytes

func BytesToBase64

func BytesToBase64(b []byte) string

BytesToBase64 converts bytes to a base64 string representation

func BytesToHex

func BytesToHex(b []byte) string

BytesToHex converts bytes to a hex string representation of bytes

func CSRFToken

func CSRFToken(token string) (string, error)

CSRFToken DEPRECATED this function will be removed in 2.0

func CheckAuthenticityToken

func CheckAuthenticityToken(token string, request *http.Request) error

CheckAuthenticityToken checks the token against that stored in a session cookie, and returns an error if the check fails.

func CheckAuthenticityTokenWithSecret

func CheckAuthenticityTokenWithSecret(token, secret []byte) error

CheckAuthenticityTokenWithSecret checks an auth token against a secret.

func CheckCSRFToken

func CheckCSRFToken(token, b64 string) error

CheckCSRFToken DEPRECATED this function will be removed in 2.0

func CheckPassword

func CheckPassword(pass, hash string) error

CheckPassword compares a password hashed with bcrypt.

func CheckRandomToken

func CheckRandomToken(a, b []byte) bool

CheckRandomToken performs a comparison of two tokens resistant to timing attacks.

func ClearSession

func ClearSession(w http.ResponseWriter)

ClearSession clears the current session cookie

func CreateMAC

func CreateMAC(h hash.Hash, value []byte) []byte

CreateMAC creates a MAC.

func Decrypt

func Decrypt(ciphertext []byte, key []byte) (plaintext []byte, err error)

Decrypt decrypts data using 256-bit AES-GCM. This both hides the content of the data and provides a check that it hasn't been altered. Expects input form nonce|ciphertext|tag where '|' indicates concatenation.

func Encrypt

func Encrypt(plaintext []byte, key []byte) (ciphertext []byte, err error)

Encrypt encrypts data using 256-bit AES-GCM. This both hides the content of the data and provides a check that it hasn't been altered. Output takes the form nonce|ciphertext|tag where '|' indicates concatenation.

func EncryptPassword

func EncryptPassword(pass string) (string, error)

EncryptPassword renamed and DEPRECATED this function will be removed in 2.0

func HashPassword

func HashPassword(pass string) (string, error)

HashPassword hashes a password with a random salt using bcrypt.

func HexToBytes

func HexToBytes(h string) []byte

HexToBytes converts a hex string representation of bytes to a byte representation

func RandomToken

func RandomToken(args ...int) []byte

RandomToken generates a random token 32 bytes long, or at a specified length if arguments are provided.

func VerifyMAC

func VerifyMAC(h hash.Hash, value []byte, mac []byte) error

VerifyMAC verifies the MAC is valid with ConstantTimeCompare.

Types

type CookieSessionStore

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

CookieSessionStore is a concrete version of SessionStore, which stores the information encrypted in cookies.

func (*CookieSessionStore) Clear

func (s *CookieSessionStore) Clear(writer http.ResponseWriter)

Clear the session values from the cookie.

func (*CookieSessionStore) Decode

func (s *CookieSessionStore) Decode(name string, hashKey []byte, secretKey []byte, value string, dst interface{}) error

Decode the value in the session cookie.

func (*CookieSessionStore) Encode

func (s *CookieSessionStore) Encode(name string, value interface{}, hashKey []byte, secretKey []byte) (string, error)

Encode a given value in the session cookie.

func (*CookieSessionStore) Get

func (s *CookieSessionStore) Get(key string) string

Get a value from the session.

func (*CookieSessionStore) Load

func (s *CookieSessionStore) Load(request *http.Request) error

Load the session from cookie.

func (*CookieSessionStore) Save

func (s *CookieSessionStore) Save(writer http.ResponseWriter) error

Save the session to a cookie.

func (*CookieSessionStore) Set

func (s *CookieSessionStore) Set(key string, value string)

Set a value in the session, this does not save to the cookie.

type SessionStore

type SessionStore interface {
	Get(string) string
	Set(string, string)
	Load(request *http.Request) error
	Save(http.ResponseWriter) error
	Clear(http.ResponseWriter)
}

SessionStore is the interface for a session store.

func Session

func Session(writer http.ResponseWriter, request *http.Request) (SessionStore, error)

Session loads the current sesions or returns a new blank session.

func SessionGet

func SessionGet(request *http.Request) (SessionStore, error)

SessionGet loads the current session (if any)

Directories

Path Synopsis
Package can implements basic role-based permissions for golang - controlling who can.Do certain actions for a given database table.
Package can implements basic role-based permissions for golang - controlling who can.Do certain actions for a given database table.

Jump to

Keyboard shortcuts

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