auth

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

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

Go to latest
Published: Aug 22, 2018 License: MIT Imports: 8 Imported by: 0

README

auth

Godoc Reference Go Report Card

A simple (but opinionated) Golang authentication library with a very simple interface (below). You can use this library to pull in core authentication functionality (minting tokens, validating tokens, & registering) to your application quickly and easily.

type Auth interface {
	Register(user User, password string) error
	GetToken(email string, password string, reqPermissions Permissions) (token string, err error)
	Validate(token string) (*Claims, error)
}

A gRPC microservice wrapping this interface is in progress and can be found at suyashkumar/auth-grpc.

You only need to provide a database connectionString and signingKey, and everything else is taken care of for you including:

  • table and database setup (including uniqueness constraints and useful indicies)
  • hashing passwords using bcrypt on register
  • comparing hashed passwords on login
  • validation of new user fields like "Email" (TBD)
  • encoding and extraction of key fields stored in the JSON Web Token (JWT)
  • ensuring that a token's requested permissions does not exceed the user's maximum permission level

A minimal example is below:

a, _ := auth.NewAuthenticator(db_string, signing_key)

u := auth.User{
	UUID:               uuid.NewV4(),
	Email:              "test@test.com",
	MaxPermissionLevel: auth.PERMISSIONS_USER,
}

// Register a new user
a.Register(u, "password")

// Login as user
token, err := a.GetToken(u.Email, "password", auth.PERMISSIONS_USER)
if err != nil {
	log.Fatal(err)
}
fmt.Printf("JWT Token: %s\n\n", token)

// Validate the user's token
claims, _ := a.Validate(token)
fmt.Printf("%+v", claims)

Documentation

Index

Constants

View Source
const (
	PERMISSIONS_API   = 0
	PERMISSIONS_USER  = 1
	PERMISSIONS_ADMIN = 2
)

These permission levels are ORDERED lowest to highest

View Source
const DefaultMaxIdleConns = 5

DefaultMaxIdleConns represents the default maximum idle connections to the db

View Source
const DefaultTTL = time.Duration(2.88e13)

DefaultTTL represents the default time to live for a newly issued token in nanoseconds, in this case 8 hours

Variables

View Source
var ErrorExceededMaxPermissionLevel = errors.New(
	"you're requesting a token permission level that exceeds this user's maximum permission level",
)

ErrorExceededMaxPermissionLevel indicates that a requested op exceeded the maximum permission level

View Source
var ErrorNoConnectionString = errors.New("A connection string must be specified on the first call to Get")

ErrorNoConnectionString indicates no connection string was provided

View Source
var ErrorValidatingToken = errors.New("problem validating token")

ErrorValidatingToken indicates issues validating the provided token

Functions

This section is empty.

Types

type Authenticator

type Authenticator interface {
	Register(user *User, password string) error
	GetToken(email string, password string, opts *GetTokenOpts) (token string, err error)
	Validate(token string) (*Claims, error)
}

Authenticator exposes the minimal set of operations needed for authentication

func NewAuthenticator

func NewAuthenticator(dbConnection string, signingKey []byte) (Authenticator, error)

NewAuthenticator returns a newly initialized Authenticator

func NewAuthenticatorFromGORM

func NewAuthenticatorFromGORM(db *gorm.DB, signingKey []byte) (Authenticator, error)

NewAuthenticatorFromGORM returns a newly init'd Authenticator from a *gorm.DB

type Claims

type Claims struct {
	UserUUID    string    `json:"user_uuid"`
	Permissions int64     `json:"permissions"`
	Email       string    `json:"email"`
	Data        TokenData `json:"data"`
	jwt.StandardClaims
}

Claims represents data that are encoded into an authentication token

type DatabaseHandler

type DatabaseHandler interface {
	// GetUser gets a user from the database that matches constraints on the input user
	GetUser(u User) (User, error)
	// UpsertUser updates a user (if input user UUID matches one in the db) or inserts a user
	UpsertUser(u User) error
	// GetDB returns the *gorm.DB instance used by this handler
	GetDB() *gorm.DB
}

DatabaseHandler abstracts away common persistence operations needed for this package

func NewDatabaseHandler

func NewDatabaseHandler(dbConnection string) (DatabaseHandler, error)

NewDatabaseHandler initializes and returns a new DatabaseHandler

func NewDatabaseHandlerFromGORM

func NewDatabaseHandlerFromGORM(db *gorm.DB) (DatabaseHandler, error)

NewDatabaseHandlerFromGORM initializes and returns a DatabaseHandler from a supplied *gorm.DB connection

type GetTokenOpts

type GetTokenOpts struct {
	RequestedPermissions Permissions
	TimeToLive           time.Duration
	Data                 TokenData
}

type Permissions

type Permissions int64

Permissions represents different permission levels that can be encoded in a token or attached to a user

func (*Permissions) Scan

func (p *Permissions) Scan(value interface{}) error

Scan assigns a value from a database driver

func (Permissions) Value

func (p Permissions) Value() (driver.Value, error)

Value returns a driver value to be used in a db

type TokenData

type TokenData map[string]string

type User

type User struct {
	UUID               uuid.UUID `sql:"type:uuid;"`
	Email              string    `gorm:"unique_index"`
	HashedPassword     string
	FirstName          string
	LastName           string
	MaxPermissionLevel Permissions
	CreatedAt          time.Time
	UpdatedAt          time.Time
	DeletedAt          time.Time `sql:"default:NULL"`
}

User represents a generic User that Suyash expects in his projects. TODO: generalize

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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