easyauth

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

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

Go to latest
Published: Oct 13, 2017 License: MIT Imports: 12 Imported by: 3

README

easyauth

This package aims to make authentication in go apps as simple as possible. It currently supports the following authentication methods:

  • LDAP
  • Api Tokens
  • Oauth (soon)
  • Custom user database (soon)

It provides an end-to-end solution for integrating any or all of these providers into your app, including:

  • Access control middleware (compatible with almost any web framework)
  • Secure session cookie management
  • Fine grained, endpoint level access control
  • All needed http handlers, callbacks, login pages, etc. generated for you
  • Full customizability

Usage

Role based access-control

easyauth uses a role-based permission system to control access to resources. Your application can define whatever roles and access levels that are appropriate. A typical setup may look like this:

const(
    //capabilities are bit flags. Content usually requires specific capabilities/
    CanRead easyauth.Role = 1 << iota
    CanWrite
    CanModerate
    CanViewSystemStats
    CanChangeSettings

    //roles combine flags. Users have an associated role value
    RoleReader = CanRead
    RoleWriter = RoleReader | CanWrite
    RoleMod = RoleWriter | CanModerate
    RoleAdmin = RoleMod | CanViewSystemStats | CanChangeSettings 
)
Getting Started

import "github.com/captncraig/easyauth"

  1. Create a new AuthManager.
auth := easyAuth.New(...)

This call accepts any number of option modifiers. See options for full options documentation.

  1. Add Providers:

Here I will add an ldap provider:

l := &ldap.LdapProvider{
  LdapAddr:          "ad.myorg.com:3269",
  DefaultPermission: RoleReader,
  Domain:            "MYORG",
}
auth.AddProvider("ldap", l)

Anyone who enters valid credentials will be granted the "Reader" role as defined by my app's role structure.

You can add as many different providers as you wish. See providers for detailed info on how to use and configure indivisual providers.

  1. Register auth handler:
http.Handle("/auth/", http.StripPrefix("/auth", auth.LoginHandler()))

This handler will handle all requests to /auth/* and handle them as appropriate. This include login pages, callbacks, form posts, logout requests, deny pages and so forth.

  1. Apply middeware to your app's http handlers:
http.Handle("/api/stats", auth.Wrap(myStatHandler,CanViewSystemStats))

Each handler can specify their own requirements for user capabilities to access that content.

options
  • CookieSecret("superSecretString"): set the secret used to hash and encrypt all cookies made by the system. Can be any string, but I recommend using 64 bytes of random data, base64 encoded. You can generate a suitable secret with this command: go test github.com/captncraig/easyauth -run TestGenerateKey -v
  • CookieDuration(int seconds): Set the default duration for all session cookies. Defaults to 30 days.
  • LoginTemplate(tmpl string): Override the built-in template for the login page. The context is a bit tricky to support multiple types of providers, but the example should serve as a decent model. If your app has a known set of providers/options, then a custom login page may be much easier.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetRedirector

func GetRedirector(r *http.Request) func()

func RandomString

func RandomString(length int) string

RandomString returns a random string of bytes length long, base64 encoded.

Types

type AuthManager

type AuthManager interface {
	AddProvider(string, AuthProvider)
	LoginHandler() http.Handler
	Wrapper(required Role) func(http.Handler) http.Handler
	Wrap(next http.Handler, required Role) http.Handler
	WrapFunc(next http.HandlerFunc, required Role) http.Handler
}

func New

func New(opts ...Option) (AuthManager, error)

type AuthProvider

type AuthProvider interface {
	//Retreive a user from the current http request if present.
	GetUser(r *http.Request) (*User, error)
}

AuthProvider is any source of user authentication. These core methods must be implemented by all providers.

type CookieManager

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

func GetCookieManager

func GetCookieManager(r *http.Request) *CookieManager

func (*CookieManager) ClearCookie

func (cm *CookieManager) ClearCookie(w http.ResponseWriter, name string)

func (*CookieManager) ReadCookie

func (cm *CookieManager) ReadCookie(r *http.Request, name string, maxAge int, dst interface{}) error

func (*CookieManager) ReadCookiePlain

func (cm *CookieManager) ReadCookiePlain(r *http.Request, name string) (string, error)

func (*CookieManager) SetCookie

func (cm *CookieManager) SetCookie(w http.ResponseWriter, name string, maxAge int, dat interface{}) error

func (*CookieManager) SetCookiePlain

func (cm *CookieManager) SetCookiePlain(w http.ResponseWriter, name string, maxAge int, value string)

type FormProvider

type FormProvider interface {
	AuthProvider
	GetRequiredFields() []string
	HandlePost(http.ResponseWriter, *http.Request)
}

FormProvider is a provider that accepts login info from an html form.

type HTTPProvider

type HTTPProvider interface {
	AuthProvider
	http.Handler
}

HTTPProvider is a provider that provides an http handler form managing its own login endpoints, for example oauth. Will receive all calls to /{providerName}/*

type Logoutable

type Logoutable interface {
	//Logout allows the provider to delete any relevant cookies or session data in order to log the user out.
	//The provider should not otherwise write to the response, or redirect
	Logout(w http.ResponseWriter, r *http.Request)
}

type Option

type Option func(*authManager) error

func CookieDuration

func CookieDuration(seconds int) Option

func CookieSecret

func CookieSecret(s string) Option

func LoginTemplate

func LoginTemplate(t string) Option

type Role

type Role uint32

Role is a number representing a permission level. Specific roles will be defined by the host application. It is intended to be a bitmask. Each user will have a certain permission level associated, as can any endpoint or content. If the user permissions and the content requirement have any common bits (user & content != 0), then access will be granted.

type User

type User struct {
	Username string
	Access   Role
	Method   string
	Data     interface{}
}

func GetUser

func GetUser(r *http.Request) *User

Directories

Path Synopsis
providers

Jump to

Keyboard shortcuts

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