auth

package
v0.0.0-...-3cdf4da Latest Latest
Warning

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

Go to latest
Published: Jul 22, 2017 License: MIT Imports: 8 Imported by: 0

README

GoDoc

Auth package

Super-simple, yet secure, token-based auth package for Go's http.Request. Compatible with Yarf framework, includes Middleware ready to insert into your Yarf router.

Tokens

Tokens are generated from calculating the SHA512 hash from 256 bytes randomly generated and returned as a string encoded in UTF-8. The result is a 128 characters long string all lower case representing the hash like:

b6e184525010a39057878fb7d7eca73c39dde0ac8b2bcff26acd71034e5922d6b5a9e30923d5d35482df396e11e57df9adc085cdd47cd2b1095b1d2880f38d01

Storage

The package uses an internal storage engine that consists in a in-memory (volatile) map. Check the Storage interface to implement your own storage.

Examples

Create token:
import (
    "github.com/yarf-framework/extras/auth"
    //...
)

func Login(username, password) string {
    // ...
    
    // Some user service login
    if user.Login(username, password) {
        // Create new token valid for 10 minutes and return it.
        return auth.NewToken(user.Id, 600) // 10 minutes token
    }
}
Get, Validate and Refresh token

(This is what Auth middleware does)

import (
    "github.com/yarf-framework/yarf"
    "github.com/yarf-framework/extras/auth"
    //...
)

func (sr *SomeResource) Get(c *yarf.Context) error {
    // Obtains Auth token from "Auth" header value.
    token := auth.GetToken(c.Request)
    
    // Validate token, return error if invalid
    data, err := auth.ValidateToken(token)
    if err != nil {
        return err
    }

    // Refresh token expiration when valid, if we want to.
    auth.RefreshToken(token)
    
    //...
}
Custom storage
import (
    "github.com/yarf-framework/extras/auth"
)

func SomeInitMethod() {
    // ...
    
    myStore := new(MyCustomStorageEngine)
    auth.RegisterStorage(myStore)
    
    // ...
}
Set Yarf middleware
import (
    "github.com/yarf-framework/yarf"
    "github.com/yarf-framework/extras/auth"
    //...
)

func main() {
    y := yarf.New()
    
    y.Insert(new(auth.Auth))
    
    //...
    
    y.Start(":80")
}
Delete token
import (
    "github.com/yarf-framework/yarf"
    "github.com/yarf-framework/extras/auth"
    //...
)

func (sr *SomeResource) Delete(c *yarf.Context) error {
    // Obtains Auth token from "Auth" header value.
    token := auth.GetToken(c.Request)
    
    // Delete token
    auth.DeleteToken(token)
    
    //...
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DeleteToken

func DeleteToken(token string)

DeleteToken removes the token data from the storage.

func GetToken

func GetToken(r *http.Request) string

GetToken tries to retrieve the token from the request object. It looks for the value of a request cookie named "Auth" first, and then for the value of a request header named "Auth" to retrieve the first value found: If the token is not found, returns an empty string.

func NewToken

func NewToken(data string, d int) string

NewToken creates and stores a new token on the local storage. It handles the token's uniqueness. It associates a token to the provided data so it can be identified and returned by the ValidateToken method. It should be used from a Login method after a successful authentication.

func RefreshToken

func RefreshToken(token string)

RefreshToken resets the timer of the token to extend its valid status. It sets the same duration time as when it was created, but starting now.

func RegisterStorage

func RegisterStorage(s Storage)

RegisterStorage replaces the default storage engine by a custom one. Replacing the storage means all data stored previously will be lost, so it should be done during initialization. Takes a Storage interface parameter and isn't safe for concurrent access.

func ValidateToken

func ValidateToken(token string) (string, error)

ValidateToken checks if a token is valid and returns the data contained on it. Otherwise it will return an error status together with an empty string.

Types

type Auth

type Auth struct {
	yarf.Middleware
}

Auth middleware performs auth on pre-dispatch after a token expected on the request. It also provides methods to generate and validate the tokens, that can be used by clients to perform authentication and authorization.

func (*Auth) PreDispatch

func (a *Auth) PreDispatch(c *yarf.Context) error

PreDispatch checks if a token has been sent on the request, either by cookie or Auth header. If the token is invalid or non-present, it will return an error to stop execution of the following resources. If a token is valid, it returns its data on the "Auth" index of the yarf.Context.Data object.

type InvalidKeyError

type InvalidKeyError struct{}

InvalidKeyError indicates that a key isn't present or that has expired so the data isn't available.

func (InvalidKeyError) Error

func (err InvalidKeyError) Error() string

type Storage

type Storage interface {
	// Get returns the data for a given key or an error if the key isn't valid.
	Get(key string) (string, error)

	// Set stores the data for a key for a given duration in seconds.
	// Returns error if it fails.
	Set(key, data string, duration int) error

	// Refresh extends the expiration of a key by the same time it had when it was created.
	Refresh(key string) error

	// Del removes the data and invalidates a key.
	// Returns error if it fails.
	Del(key string) error
}

Storage interface is used to register any custom storage system for auth module.

type UnauthorizedError

type UnauthorizedError struct{}

UnauthorizedError is the custom error type returned by the Auth middleware to be compatible with Yarf's YError

func (*UnauthorizedError) Body

func (e *UnauthorizedError) Body() string

Body returns the error's content body, if needed, to be returned in the HTTP response.

func (*UnauthorizedError) Code

func (e *UnauthorizedError) Code() int

Code returns the error's HTTP code to be used in the response.

func (*UnauthorizedError) Error

func (e *UnauthorizedError) Error() string

Implements the error interface returning the ErrorMsg value of each error.

func (*UnauthorizedError) ID

func (e *UnauthorizedError) ID() int

ID returns the error's ID for further reference.

func (*UnauthorizedError) Msg

func (e *UnauthorizedError) Msg() string

Msg returns the error's message, used to implement the Error interface.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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