auth

package module
v2.0.0-beta.3 Latest Latest
Warning

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

Go to latest
Published: Jan 28, 2022 License: MIT Imports: 10 Imported by: 1

README

Golang HTTP authentication library, no catchy name.

This is a library I wrote when I found existing http auth libraries lacking in one area or another.
Not entirely documented yet, but I've pounded most of the kinks out and felt it was about time to share.

It's design is based on https://github.com/xyproto/permissionbolt/, initializing a 'state' that is passed
around to hold the boltDB connection and secureCookie instance.

Features:

  • Users and keys are stored inside a bboltdb
  • Cookies are authenticated and encrypted using gorilla/securecookie
    • The hash and block keys are generated upon DB initialization and stored in the auth.db
  • User registration and authentication
    • Passwords are hashed with bcrypt, using a work factor of 14
    • When logging in, a 128 character session ID is generated and stored in the DB and cookie
    • Optionally, one-time-use registration tokens can be required to sign up
  • Cross-site Request Forgery protection, using the gorilla/csrf library is integrated, storing the CSRF key in the same auth.db
  • Flash messages, stored inside a cookie and deleted once read
  • Built-in HTTP handlers are provided for some of the more agnostic POST requests, including:
    • LogoutHandler: clearing the session cookie
    • UserSignupPostHandler: provided a username and password form value, create a new user, and log that user in
    • UserSignupTokenPostHandler: provided a username, password, and register_key form value, validate the registration token, create a new user, and log that user in
    • LoginPostHandler: provided a username, and password form value, authenticate and log the user in
    • NewUserToken: generate a new registration token

Example:

There is a simple example application available in examples/simple/main.go, showing the basics of integrating this library into an application.

Documentation

Index

Constants

View Source
const (

	// Available roles for users
	RoleAdmin = "admin"
	RoleUser  = "user"
)

Variables

This section is empty.

Functions

func CheckPasswordHash

func CheckPasswordHash(hash, password []byte) error

CheckPasswordHash securely compares a bcrypt hashed password with its possible plaintext equivalent. Returns nil on success, or an error on failure.

func HashPassword

func HashPassword(password []byte) ([]byte, error)

HashPassword generates a bcrypt hash of the password using work factor 14.

func Redirect

func Redirect(state *State, w http.ResponseWriter, r *http.Request)

Redirect throws the r.URL.Path into a cookie named "redirect" and redirects to the login page

Types

type Config

type Config struct {
	CookieSecure bool
	DbPath       string
	LoginPath    string
	SignupPath   string
	// Session lifetime in hours
	SessionLifetimeHours int
}

type DB

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

DB wraps a bolt.DB struct, so I can test and interact with the db from programs using the lib, while vendoring bolt in both places

func (*DB) Auth

func (db *DB) Auth(username, password string) bool

Auth authenticates a given username and password

func (*DB) DeleteUser

func (db *DB) DeleteUser(username string) error

DeleteUser deletes a given user from the DB

func (*DB) DoesUserExist

func (db *DB) DoesUserExist(username string) bool

DoesUserExist checks if user actually exists in the DB

func (*DB) NewAdmin

func (db *DB) NewAdmin(username, password string) error

NewAdmin creates a new admin with a given plaintext username and password

func (*DB) NewUser

func (db *DB) NewUser(username, password string) error

NewUser creates a new user with a given plaintext username and password

func (*DB) UpdatePass

func (db *DB) UpdatePass(username string, hash []byte) error

UpdatePass updates a given user's password to the given hash Password hashing must be done by the caller

func (*DB) Userlist

func (db *DB) Userlist() ([]string, error)

Userlist lists all users in the DB

type State

type State struct {
	DB
	Cfg Config
	// contains filtered or unexported fields
}

State holds all required info to get authentication working in the app

func NewAuthState

func NewAuthState(cfg Config) *State

NewAuthState creates a new AuthState using the BoltDB backend, storing the boltDB connection and cookie info

func NewAuthStateWithDB

func NewAuthStateWithDB(db *DB, cfg Config) *State

NewAuthStateWithDB takes an instance of a boltDB, and returns an AuthState using the BoltDB backend

func (*State) AdminsOnly

func (state *State) AdminsOnly(next http.HandlerFunc) http.HandlerFunc

AdminsOnly is a middleware to protect a given handler; admin only access

func (*State) AdminsOnlyH

func (state *State) AdminsOnlyH(next http.Handler) http.Handler

AdminsOnlyH is a middleware to protect a given handler; admin only access

func (*State) AnyUsers

func (state *State) AnyUsers() bool

AnyUsers checks if there are any users in the DB This is useful in application initialization flows

func (*State) CloseDB

func (state *State) CloseDB()

func (*State) GetFlash

func (state *State) GetFlash(r *http.Request) string

GetFlash retrieves flash message

func (*State) GetRedirect

func (state *State) GetRedirect(r *http.Request) string

GetRedirect returns the URL from the redirect cookie

func (*State) GetUser

func (state *State) GetUser(r *http.Request) *User

GetUserState returns a *User given a session ID cookie inside the request

func (*State) IsLoggedIn

func (state *State) IsLoggedIn(r *http.Request) bool

IsLoggedIn simply tries to fetch a session ID from the request

If more user info is required, use GetUser()

func (*State) LoadAndSave

func (s *State) LoadAndSave(next http.Handler) http.Handler

Wrapping scs middleware

func (*State) Login

func (state *State) Login(username string, r *http.Request)

Login generates a random session ID, throws that into the DB,

then sets that session ID into the cookie

func (*State) LogoutHandler

func (state *State) LogoutHandler(w http.ResponseWriter, r *http.Request)

LogoutHandler clears the "user" cookie, logging the user out

func (*State) SetFlash

func (state *State) SetFlash(msg string, r *http.Request)

SetFlash sets a flash message inside a cookie, which, combined with the UserEnvMiddle

middleware, pushes the message into context and then template

func (*State) UsersOnly

func (state *State) UsersOnly(next http.HandlerFunc) http.HandlerFunc

UsersOnly is a middleware for HandlerFunc-specific stuff, to protect a given handler; users only access

func (*State) UsersOnlyH

func (state *State) UsersOnlyH(next http.Handler) http.Handler

UsersOnlyH is a middleware to protect a given handler; users only access

type User

type User struct {
	Name string
	Role string
}

User is what is stored inside the context

func (*User) GetName

func (u *User) GetName() string

GetName is a helper function that sets the user blank if User is nil This allows use in Templates and the like

func (*User) IsAdmin

func (u *User) IsAdmin() bool

IsAdmin checks if the given user is an admin

func (*User) IsValid

func (u *User) IsValid() bool

IsValid checks if the given User is valid

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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