auth

package
v0.0.0-...-8afb70f Latest Latest
Warning

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

Go to latest
Published: May 19, 2015 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Sessions = sql.Table("sessions",
	sql.Column("key", sql.String{NotNull: true}),
	sql.ForeignKey("user_id", Users.C["id"], sql.Integer{NotNull: true}),
	sql.Column("expires", sql.Timestamp{WithTimezone: true, NotNull: true}),
	sql.PrimaryKey("key"),
)

Sessions is the postgres schema for sessions

View Source
var Tokens = sql.Table("tokens",
	sql.Column("key", sql.String{NotNull: true}),
	sql.ForeignKey(
		"user_id",
		Users.C["id"],
		sql.Integer{NotNull: true},
	).OnDelete(sql.Cascade),
	sql.Column("expires", sql.Timestamp{WithTimezone: true}),
	sql.Column("created_at", sql.Timestamp{NotNull: true, Default: pg.Now}),
	sql.PrimaryKey("key"),
)

Tokens is the postgres schema for user API tokens.

View Source
var Users = sql.Table("users",
	sql.Column("id", pg.Serial{NotNull: true}),
	sql.Column("email", sql.String{Length: 256, Unique: true, NotNull: true}),
	sql.Column("first_name", sql.String{Length: 64, NotNull: true}),
	sql.Column("last_name", sql.String{Length: 64, NotNull: true}),
	sql.Column("about", sql.String{Length: 512, NotNull: true}),
	sql.Column("photo", sql.String{Length: 512, NotNull: true}),
	sql.Column("is_active", sql.Boolean{NotNull: true, Default: sql.True}),
	sql.Column("is_superuser", sql.Boolean{NotNull: true, Default: sql.False}),
	sql.Column("password", sql.String{Length: 256, NotNull: true}),
	sql.Column("token", sql.String{Length: 256, NotNull: true}),
	sql.Column("token_set_at", sql.Timestamp{NotNull: true, Default: pg.Now}),
	sql.Column("created_at", sql.Timestamp{NotNull: true, Default: pg.Now}),
	sql.PrimaryKey("id"),
)

Users is the postgres schema for users

Functions

func CheckPassword

func CheckPassword(h Hasher, cleartext, encoded string) bool

CheckPassword verifies the given cleartext password against the given encoded string using the given hasher.

func ConstantTimeStringCompare

func ConstantTimeStringCompare(x, y string) bool

ConstantTimeStringCompare is wrapper around subtle.ConstantTimeCompare that takes two strings as parameters and returns a boolean instead of an int.

func EncodeBase64String

func EncodeBase64String(input []byte) string

EncodeBase64String is a wrapper around the standard base64 encoding call.

func MakePassword

func MakePassword(h Hasher, cleartext string) string

MakePassword hashes the given cleartext string using the given Hasher

func MockHasher

func MockHasher(name string, n int, digest func() hash.Hash) *mockHasher

func Pbkdf2

func Pbkdf2(cleartext, salt []byte, rounds int, h func() hash.Hash) []byte

func RandomBytes

func RandomBytes(n int) []byte

RandomBytes returns random bytes from the crypto/rand Reader or it panics.

func RandomKey

func RandomKey() string

RandomKey generates a new session key. It does so by producing 24 random bytes that are encoded in URL safe base64, for output of 32 chars.

func RandomKeyN

func RandomKeyN(n int) string

RandomKeyN generates a new Base 64 encoded random string. N is the length of the random bytes, not the final encoded string.

func RegisterHasher

func RegisterHasher(name string, hasher Hasher)

RegisterHasher adds a new Hasher to the registry with the given name.

func SetCookie

func SetCookie(w http.ResponseWriter, c config.CookieConfig, session Session)

SetCookie writes the cookie to the given http.ResponseWriter. The cookie's name is taken from the cookie configuration and its value is the given session key.

Types

type Auth

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

func Mock

func Mock(c config.Config, conn sql.Connection) *Auth

Mock creates a mock auth with mock users

func New

func New(c config.Config, conn sql.Connection) *Auth

New creates a new auth with users, sessions, and tokens

func (*Auth) ByPassword

func (auth *Auth) ByPassword(email, password string) (user User, err error)

ByPassword attempts to authenticate the given email using the given cleartext password. On failure, a specific error will be returned.

func (*Auth) BySession

func (auth *Auth) BySession(key string) (user User)

BySession returns an authenticated user if the given session is valid

func (*Auth) ByToken

func (auth *Auth) ByToken(id int64, key string) (user User)

ByToken returns an authenticated user if the given token is valid for the given user id. Tokens are used for API access.

func (*Auth) ByUserToken

func (auth *Auth) ByUserToken(id int64, key string) (user User, err error)

ByUserToken returns an authenticated user if the given user's token matches the given token. Companies are not added as this method is used only for password resets and initial account creation. The user token also is attached to the user's model, not the separate tokens table, which is used for API access.

func (*Auth) CookieName

func (auth *Auth) CookieName() string

CookieName returns the name of the cookie used by this auth

func (*Auth) CreateSession

func (auth *Auth) CreateSession(w http.ResponseWriter, user User) error

CreateSession creates a new session for the given user and redirects to the given next URL.

func (*Auth) CreateSessionAndRedirect

func (auth *Auth) CreateSessionAndRedirect(w http.ResponseWriter, r *http.Request, user User, next string) error

func (*Auth) CreateUser

func (auth *Auth) CreateUser(email, first, last, clear string) (User, error)

CreateUser creates a new user.

func (*Auth) Logout

func (auth *Auth) Logout(w http.ResponseWriter, r *http.Request) error

Logout removes the auth cookie's session key from the database

func (*Auth) MakePassword

func (auth *Auth) MakePassword(cleartext string) string

MakePassword returns an encrypted string of the given cleartext password using the auth user hasher.

func (*Auth) ResetUserToken

func (auth *Auth) ResetUserToken(user *User)

ResetUserToken generates a new user token and resets the token timestamp.

func (*Auth) Sessions

func (auth *Auth) Sessions() *SessionManager

Sessions returns the internal session manager

func (*Auth) Tokens

func (auth *Auth) Tokens() *TokenManager

Tokens returns the internal token manager

func (*Auth) Users

func (auth *Auth) Users() *UserManager

Users returns the internal user manager

type BaseHasher

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

BaseHasher is the parent of all included Hashers

func NewBaseHasher

func NewBaseHasher(algorithm string) BaseHasher

func (*BaseHasher) Algorithm

func (h *BaseHasher) Algorithm() string

Algorithm returns the algorithm of this Hasher

func (*BaseHasher) Salt

func (h *BaseHasher) Salt() string

Salt generates nine random bytes encoded to base64 for use as a salt.

type Hasher

type Hasher interface {
	Encode(string, string) string
	Salt() string
	Verify(string, string) bool
	Algorithm() string
}

Hasher is the target interface for included hashers.

func GetHasher

func GetHasher(name string) (Hasher, error)

GetHasher returns the Hasher in the registry with the given name.

type KeyFunc

type KeyFunc func() string

KeyFunc is the function type that will be used to generate new session keys.

type PBKDF2_Base

type PBKDF2_Base struct {
	BaseHasher
	// contains filtered or unexported fields
}

TODO declare private?

func NewPBKDF2Hasher

func NewPBKDF2Hasher(alg string, n int, digest func() hash.Hash) *PBKDF2_Base

func (*PBKDF2_Base) Encode

func (h *PBKDF2_Base) Encode(cleartext, salt string) string

func (*PBKDF2_Base) Verify

func (h *PBKDF2_Base) Verify(cleartext, encoded string) bool

type Session

type Session struct {
	Key     string    `db:"key"`
	UserID  int64     `db:"user_id"`
	Expires time.Time `db:"expires"`
	// contains filtered or unexported fields
}

Session is a database-backed user session.

func (Session) Delete

func (session Session) Delete() error

Delete removes the session with the given key from the database. It will return an error if the session does not have a key or the key was not deleted from the database. It will panic on any connection error.

func (Session) Exists

func (session Session) Exists() bool

Exists returns true if the session exists

type SessionManager

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

SessionManager is the internal manager of sessions

func NewSessions

func NewSessions(c config.CookieConfig, conn sql.Connection) *SessionManager

NewSessions will create a new internal session manager

func (*SessionManager) Create

func (m *SessionManager) Create(user User) (session Session)

Create creates a new session using a key generated for the given User

func (*SessionManager) Delete

func (m *SessionManager) Delete(key string) error

Delete removes the session with the given key from the database. It will return an error if the session key was not deleted from the database. It will panic on any connection error.

func (*SessionManager) Get

func (m *SessionManager) Get(key string) (session Session)

Get returns the session with the given key.

type Token

type Token struct {
	Key       string     `db:"key"`
	UserID    int64      `db:"user_id"`
	Expires   *time.Time `db:"expires"`
	CreatedAt time.Time  `db:"created_at,omitempty"`
	// contains filtered or unexported fields
}

Token is a database-backed user API token. The Expires field is nil if the token never expires.

func (Token) Delete

func (token Token) Delete() error

Delete removes the token with the given key from the database. It will return an error if the token does not have a key or the key was not deleted from the database. It will panic on any connection error.

func (Token) Exists

func (token Token) Exists() bool

Exists returns true if the token exists

type TokenManager

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

TokenManager is the internal manager of tokens

func NewTokens

func NewTokens(conn sql.Connection) *TokenManager

func (*TokenManager) All

func (m *TokenManager) All(id int64) (tokens []Token)

All returns all tokens for the given user ID

func (*TokenManager) Delete

func (m *TokenManager) Delete(key string) error

Delete removes the token with the given key from the database. It will return an error if the token does not have a key or the key was not deleted from the database. It will panic on any connection error.

func (*TokenManager) ForeverToken

func (m *TokenManager) ForeverToken(user User) (token Token)

Create creates a new token for the user. It will panic on error. The user ID must exist.

func (*TokenManager) Get

func (m *TokenManager) Get(key string) (token Token)

Get returns the token with the given key. Panic on database error.

type User

type User struct {
	ID          int64     `db:"id,omitempty"`
	Email       string    `db:"email"`
	FirstName   string    `db:"first_name"`
	LastName    string    `db:"last_name"`
	About       string    `db:"about"`
	Photo       string    `db:"photo"`
	IsActive    bool      `db:"is_active"`
	IsSuperuser bool      `db:"is_superuser"`
	Password    string    `db:"password"`
	Token       string    `db:"token"`
	TokenSetAt  time.Time `db:"token_set_at,omitempty"`
	CreatedAt   time.Time `db:"created_at,omitempty"`
	// contains filtered or unexported fields
}

User is a database-backed user.

func (User) Delete

func (user User) Delete() error

Delete removes the user with the given ID from the database. It will return an error if the user does not have an ID or the ID was not deleted from the database. It will panic on any connection error.

func (User) Exists

func (user User) Exists() bool

Exists returns true if the user has an assigned ID

func (User) Name

func (user User) Name() string

Name returns the concatenated first and last name

func (User) String

func (user User) String() string

String returns the user id and email

type UserManager

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

UserManager is the internal manager of users

func MockUsers

func MockUsers(conn sql.Connection) *UserManager

func NewUsers

func NewUsers(conn sql.Connection) *UserManager

func (*UserManager) Create

func (m *UserManager) Create(email, first, last, clear string) (User, error)

Create will create a new user with given email and cleartext password. It will panic on any crypto or database connection errors.

func (*UserManager) CreateSuperuser

func (m *UserManager) CreateSuperuser(email, first, last, clear string) (User, error)

CreateSuperuser will create a new superuser with given email and cleartext password. It will panic on any crypto or database connection errors.

func (*UserManager) Delete

func (m *UserManager) Delete(id int64) error

Delete removes the user with the given ID from the database. It will return an error if the ID was not deleted from the database. It will panic on any connection error.

func (*UserManager) GetByEmail

func (m *UserManager) GetByEmail(email string) (user User, err error)

GetByEmail returns the user with the given email.

func (*UserManager) GetByID

func (m *UserManager) GetByID(id int64) (user User, err error)

GetByID returns the user with the given id.

func (UserManager) Hasher

func (m UserManager) Hasher() Hasher

Hasher returns the hasher used by the UserManager

Jump to

Keyboard shortcuts

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