auth

package
v0.0.0-...-b61be5c Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2016 License: Apache-2.0 Imports: 13 Imported by: 0

README

auth

import "github.com/ardanlabs/kit/auth"

Package auth package provides API's for managing users who will be accessing our web API's and applications. This includes all the CRUD related support for users and authentication. For now the user system is simple since users are pre-registered using our cli tool kit. In the future this can be expanded to provide more UI based support.

Users

A user is an entity that can be authenticated on the system and granted rights to the API's and applications that we build. From an authentication standpoint several fields from a User document are important:

PublicID : This is the users public identifier and can be shared with the world. It provides a unique id for each user. It is used to lookup users from the database. This is a randomlu generated UUID.

PrivateID : This is the users private identifier and must not be shared with the world. It is used in conjunction with the user supplied password to create an encrypted password. To authenticate with a password you need the users password and this private id. This is a randomlu generated UUID.

Password : This is a hased value based on a user provided string and the user's private identifier. These values are combined and encrypted to create a hash value that is stored in the user document as the password.

A user can be looked up by their public identifier or by email address. The email address can be used as a username and an index in the collection for users but make this field unique.

Sessions

A session is a document in the database tied to a user via their PublicID. Sessions provide a level of security for web tokens by giving them an expiration date and a lookup point for the user accessing the API. The SessionID is what is used to look up the user performing the web call. Though the user's PublicID is not private, it is not used directly.

Web Tokens

Access to the different web service API's using kit require sending a web token on every request. HTTP Basic Authorization is being used:

Authorization: Basic WebToken

A web token is a value that is not stored in the database but can be consistently generated by having a user document and a session identifier. It is made up of two parts, a SessionID and a Token which are concatinated together and then base64 encoded for use over HTTP:

base64Encode(SessionID:Token)

The SessionID is a randomly generated UUID and is recorded in the sessions collection. It is tied to a user via their PublicID and has an expiration date:

SessionID   string
PublicID    string
DateExpires time.Time
DateCreated time.Time

The Token is generated by using the following fields from the user document:

Password     string
PublicID     string
PrivateID    string
Email        string

The PublicID, PrivateID, Email fields are used to create a Salt that is combined with the Password to create a signed SHA256 hash value. This is a value that can be consistenly re-created when all the same values are present. If any of the fields used in this token change, the token will be invalidated.

Web Token Authentication

To make things as secure as possible, database lookups are performed as part of web token authentication. The user must keep their token secure.

Here are the steps to web token authentication:

* Decode the web token and break it into its parts of SessionID and Token.
* Retrieve the session document for the SessionID and validate it has not expired.
* Retrieve the user document from the PublicID in the session document.
* Validate the Token is valid by generating a new token from the retrieved user document.

If any of these steps fail, authorization fails.

User Login

This has not been coded yet.

Constants

const (
    StatusUnknown = iota
    StatusActive
    StatusDisabled
)

Set of user status codes.

const Collection = "auth_users"

collection contains the name of the auth_users collection.

func CreateUser

func CreateUser(context interface{}, db *db.DB, u *User) error

CreateUser adds a new user to the database.

func CreateWebToken

func CreateWebToken(context interface{}, db *db.DB, u *User, expires time.Duration) (string, error)

CreateWebToken return a token and session that can be used to authenticate a user.

func DecodeWebToken

func DecodeWebToken(context interface{}, webToken string) (sessionID string, token string, err error)

DecodeWebToken breaks a web token into its parts.

func GetUserWebToken

func GetUserWebToken(context interface{}, db *db.DB, publicID string) (string, error)

GetUserWebToken return a token if one exists and is valid.

func UpdateUser

func UpdateUser(context interface{}, db *db.DB, uu UpdUser) error

UpdateUser updates an existing user to the database.

func UpdateUserPassword

func UpdateUserPassword(context interface{}, db *db.DB, u *User, password string) error

UpdateUserPassword updates an existing user's password and token in the database.

func UpdateUserStatus

func UpdateUserStatus(context interface{}, db *db.DB, publicID string, status int) error

UpdateUserStatus changes the status of a user to make them active or disabled.

type NUser

type NUser struct {
    Status   int    `bson:"status" json:"status" validate:"required,ne=0"`
    FullName string `bson:"full_name" json:"full_name" validate:"required,min=8"`
    Email    string `bson:"email" json:"email" validate:"required,max=100,email"`
    Password string `bson:"password" json:"-" validate:"required,min=8"`
}

NUser is provided to create a new user value for use.

func (*NUser) Validate
func (nu *NUser) Validate() error

Validate performs validation on a NUser value before it is processed.

type UpdUser

type UpdUser struct {
    PublicID string `bson:"public_id" json:"public_id" validate:"required,uuid"`
    Status   int    `bson:"status" json:"status" validate:"required,ne=0"`
    FullName string `bson:"full_name" json:"full_name" validate:"required,min=8"`
    Email    string `bson:"email" json:"email" validate:"required,max=100,email"`
}

UpdUser is provided to update an existing user in the system.

func (*UpdUser) Validate
func (uu *UpdUser) Validate() error

Validate performs validation on a NewUser value before it is processed.

type User

type User struct {
    ID           bson.ObjectId `bson:"_id,omitempty" json:"-"`
    PublicID     string        `bson:"public_id" json:"public_id" validate:"required,uuid"`
    PrivateID    string        `bson:"private_id" json:"-" validate:"required,uuid"`
    Status       int           `bson:"status" json:"status" validate:"required,ne=0"`
    FullName     string        `bson:"full_name" json:"full_name" validate:"required,min=8"`
    Email        string        `bson:"email" json:"email" validate:"required,max=100,email"`
    Password     string        `bson:"password" json:"-" validate:"required,min=55"`
    IsDeleted    bool          `bson:"is_deleted" json:"-"`
    DateModified time.Time     `bson:"date_modified" json:"-"`
    DateCreated  time.Time     `bson:"date_created" json:"-"`
}

User model denotes a user entity for a tenant.

func GetUserByEmail
func GetUserByEmail(context interface{}, db *db.DB, email string, activeOnly bool) (*User, error)

GetUserByEmail retrieves a user record by using the provided email.

func GetUserByPublicID
func GetUserByPublicID(context interface{}, db *db.DB, publicID string, activeOnly bool) (*User, error)

GetUserByPublicID retrieves a user record by using the provided PublicID.

func LoginUser
func LoginUser(context interface{}, db *db.DB, email string, password string) (*User, error)

LoginUser authenticates the user and if successful returns the User value.

func NewUser
func NewUser(nu NUser) (*User, error)

NewUser creates a new user from a NewUser value.

func ValidateWebToken
func ValidateWebToken(context interface{}, db *db.DB, webToken string) (*User, error)

ValidateWebToken accepts a web token and validates its credibility. Returns a User value is the token is valid.

func (*User) IsPasswordValid
func (u *User) IsPasswordValid(password string) bool

IsPasswordValid compares the user provided password with what is in the db.

func (*User) Pwd
func (u *User) Pwd() ([]byte, error)

Pwd implements the secure entity interface.

func (*User) Salt
func (u *User) Salt() ([]byte, error)

Salt implements the secure entity interface.

func (*User) Validate
func (u *User) Validate() error

Validate performs validation on a CrtUser value before it is processed.

func (*User) WebToken
func (u *User) WebToken(sessionID string) (string, error)

WebToken returns a token ready for web use.


Generated by godoc2md

Documentation

Overview

Package auth package provides API's for managing users who will be accessing our web API's and applications. This includes all the CRUD related support for users and authentication. For now the user system is simple since users are pre-registered using our cli tool `kit`. In the future this can be expanded to provide more UI based support.

Users

A user is an entity that can be authenticated on the system and granted rights to the API's and applications that we build. From an authentication standpoint several fields from a User document are important:

PublicID : This is the users public identifier and can be shared with the world. It provides a unique id for each user. It is used to lookup users from the database. This is a randomlu generated UUID.

PrivateID : This is the users private identifier and must not be shared with the world. It is used in conjunction with the user supplied password to create an encrypted password. To authenticate with a password you need the users password and this private id. This is a randomlu generated UUID.

Password : This is a hased value based on a user provided string and the user's private identifier. These values are combined and encrypted to create a hash value that is stored in the user document as the password.

A user can be looked up by their public identifier or by email address. The email address can be used as a username and an index in the collection for users but make this field unique.

Sessions

A session is a document in the database tied to a user via their PublicID. Sessions provide a level of security for web tokens by giving them an expiration date and a lookup point for the user accessing the API. The SessionID is what is used to look up the user performing the web call. Though the user's PublicID is not private, it is not used directly.

Web Tokens

Access to the different web service API's using kit require sending a web token on every request. HTTP Basic Authorization is being used:

Authorization: Basic WebToken

A web token is a value that is not stored in the database but can be consistently generated by having a user document and a session identifier. It is made up of two parts, a SessionID and a Token which are concatinated together and then base64 encoded for use over HTTP:

base64Encode(SessionID:Token)

The SessionID is a randomly generated UUID and is recorded in the sessions collection. It is tied to a user via their PublicID and has an expiration date:

SessionID   string
PublicID    string
DateExpires time.Time
DateCreated time.Time

The Token is generated by using the following fields from the user document:

Password     string
PublicID     string
PrivateID    string
Email        string

The PublicID, PrivateID, Email fields are used to create a Salt that is combined with the Password to create a signed SHA256 hash value. This is a value that can be consistenly re-created when all the same values are present. If any of the fields used in this token change, the token will be invalidated.

Web Token Authentication

To make things as secure as possible, database lookups are performed as part of web token authentication. The user must keep their token secure.

Here are the steps to web token authentication:

  • Decode the web token and break it into its parts of SessionID and Token.
  • Retrieve the session document for the SessionID and validate it has not expired.
  • Retrieve the user document from the PublicID in the session document.
  • Validate the Token is valid by generating a new token from the retrieved user document.

If any of these steps fail, authorization fails.

User Login

This has not been coded yet.

Index

Constants

View Source
const (
	StatusUnknown = iota
	StatusActive
	StatusDisabled
)

Set of user status codes.

View Source
const Collection = "auth_users"

collection contains the name of the auth_users collection.

Variables

This section is empty.

Functions

func CreateUser

func CreateUser(context interface{}, db *db.DB, u *User) error

CreateUser adds a new user to the database.

func CreateWebToken

func CreateWebToken(context interface{}, db *db.DB, u *User, expires time.Duration) (string, error)

CreateWebToken return a token and session that can be used to authenticate a user.

func DecodeWebToken

func DecodeWebToken(context interface{}, webToken string) (sessionID string, token string, err error)

DecodeWebToken breaks a web token into its parts.

func GetUserWebToken

func GetUserWebToken(context interface{}, db *db.DB, publicID string) (string, error)

GetUserWebToken return a token if one exists and is valid.

func UpdateUser

func UpdateUser(context interface{}, db *db.DB, uu UpdUser) error

UpdateUser updates an existing user to the database.

func UpdateUserPassword

func UpdateUserPassword(context interface{}, db *db.DB, u *User, password string) error

UpdateUserPassword updates an existing user's password and token in the database.

func UpdateUserStatus

func UpdateUserStatus(context interface{}, db *db.DB, publicID string, status int) error

UpdateUserStatus changes the status of a user to make them active or disabled.

Types

type NUser

type NUser struct {
	Status   int    `bson:"status" json:"status" validate:"required,ne=0"`
	FullName string `bson:"full_name" json:"full_name" validate:"required,min=8"`
	Email    string `bson:"email" json:"email" validate:"required,max=100,email"`
	Password string `bson:"password" json:"-" validate:"required,min=8"`
}

NUser is provided to create a new user value for use.

func (*NUser) Validate

func (nu *NUser) Validate() error

Validate performs validation on a NUser value before it is processed.

type UpdUser

type UpdUser struct {
	PublicID string `bson:"public_id" json:"public_id" validate:"required,uuid"`
	Status   int    `bson:"status" json:"status" validate:"required,ne=0"`
	FullName string `bson:"full_name" json:"full_name" validate:"required,min=8"`
	Email    string `bson:"email" json:"email" validate:"required,max=100,email"`
}

UpdUser is provided to update an existing user in the system.

func (*UpdUser) Validate

func (uu *UpdUser) Validate() error

Validate performs validation on a NewUser value before it is processed.

type User

type User struct {
	ID           bson.ObjectId `bson:"_id,omitempty" json:"-"`
	PublicID     string        `bson:"public_id" json:"public_id" validate:"required,uuid"`
	PrivateID    string        `bson:"private_id" json:"-" validate:"required,uuid"`
	Status       int           `bson:"status" json:"status" validate:"required,ne=0"`
	FullName     string        `bson:"full_name" json:"full_name" validate:"required,min=8"`
	Email        string        `bson:"email" json:"email" validate:"required,max=100,email"`
	Password     string        `bson:"password" json:"-" validate:"required,min=55"`
	IsDeleted    bool          `bson:"is_deleted" json:"-"`
	DateModified time.Time     `bson:"date_modified" json:"-"`
	DateCreated  time.Time     `bson:"date_created" json:"-"`
}

User model denotes a user entity for a tenant.

func GetUserByEmail

func GetUserByEmail(context interface{}, db *db.DB, email string, activeOnly bool) (*User, error)

GetUserByEmail retrieves a user record by using the provided email.

func GetUserByPublicID

func GetUserByPublicID(context interface{}, db *db.DB, publicID string, activeOnly bool) (*User, error)

GetUserByPublicID retrieves a user record by using the provided PublicID.

func LoginUser

func LoginUser(context interface{}, db *db.DB, email string, password string) (*User, error)

LoginUser authenticates the user and if successful returns the User value.

func NewUser

func NewUser(nu NUser) (*User, error)

NewUser creates a new user from a NewUser value.

func ValidateWebToken

func ValidateWebToken(context interface{}, db *db.DB, webToken string) (*User, error)

ValidateWebToken accepts a web token and validates its credibility. Returns a User value is the token is valid.

func (*User) IsPasswordValid

func (u *User) IsPasswordValid(password string) bool

IsPasswordValid compares the user provided password with what is in the db.

func (*User) Pwd

func (u *User) Pwd() ([]byte, error)

Pwd implements the secure entity interface.

func (*User) Salt

func (u *User) Salt() ([]byte, error)

Salt implements the secure entity interface.

func (*User) Validate

func (u *User) Validate() error

Validate performs validation on a CrtUser value before it is processed.

func (*User) WebToken

func (u *User) WebToken(sessionID string) (string, error)

WebToken returns a token ready for web use.

Directories

Path Synopsis
Package crypto provides support for encrypting passwords and generating tokens for authentication support.
Package crypto provides support for encrypting passwords and generating tokens for authentication support.
Package session provides a level of security for web tokens by giving them an expiration date and a lookup point for the user accessing the API.
Package session provides a level of security for web tokens by giving them an expiration date and a lookup point for the user accessing the API.

Jump to

Keyboard shortcuts

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