users

package
v0.0.0-...-2bdc998 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2018 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AlgorithmHS256 = "HS256"
)

Algorithims

View Source
const Table = `users`
View Source
const TableActivation = `user_activation`
View Source
const TableBan = `user_bans`
View Source
const TableEvents = `user_events`

Variables

View Source
var Config = &Cfg{
	TokenExpirationTime: 7 * 24 * time.Hour,
	EncryptionLevel:     15,

	TokenSecret: secret.TokenSecret,

	EncryptionKey: secret.EncryptionKey,
}
View Source
var (
	// DefaultJWTConfig is the default JWT auth middleware config.
	DefaultJWTConfig = JWTConfig{
		Skipper: func(c echo.Context) bool {
			return false
		},
		SigningMethod: AlgorithmHS256,
		ContextKey:    "user",
		TokenLookup:   "header:" + echo.HeaderAuthorization,
	}
)
View Source
var Schema = []string{`
CREATE TABLE IF NOT EXISTS ` + Table + ` (
  id           SERIAL UNIQUE PRIMARY KEY,

  name         VARCHAR(25),
  username     VARCHAR(25) NOT NULL, -- 25 is more than enough -> 1234567890123456789012345 -> JetFuelCantMeltSteelBeams

  password     TEXT NOT NULL,
  email        VARCHAR(255) NOT NULL,

  deleted      BOOLEAN NOT NULL DEFAULT FALSE,
  activated    BOOLEAN NOT NULL DEFAULT FALSE,

  power        INTEGER NOT NULL DEFAULT 0,

  created      TIMESTAMP NOT NULL,
  seen         TIMESTAMP
);

`, `
CREATE TABLE IF NOT EXISTS ` + TableActivation + ` (
  id      SERIAL UNIQUE PRIMARY KEY,
  code    VARCHAR(255) NOT NULL,
  user_id INTEGER NOT NULL
);
`, `
CREATE TABLE IF NOT EXISTS ` + TableBan + ` (
  id        SERIAL UNIQUE PRIMARY KEY,
  user_id   INTEGER NOT NULL,
  state     BOOLEAN NOT NULL DEFAULT FALSE,
  temporary BOOLEAN NOT NULL DEFAULT FALSE,
  starts    TIMESTAMP,
  until     TIMESTAMP NOT NULL
);
`, `
CREATE TABLE IF NOT EXISTS ` + TableEvents + ` (
  id        SERIAL UNIQUE PRIMARY KEY,
  user_id   INTEGER NOT NULL,
  event     VARCHAR(255) NOT NULL,
  data      TEXT NULL,
  ip        INET NOT NULL,
  at        TIMESTAMP NOT NULL
);
`}

Schema is the database schema for users it runs everytime the application starts

View Source
var SchemaTest = []string{
	`TRUNCATE ` + Table + `, ` + TableActivation + `, ` + TableBan + `, ` + TableEvents + ` CASCADE;`,
}

SchemaTest is the database schema for testing the users table it runs before tests starts

Functions

func CheckCollection

func CheckCollection(c db.Collection, table string)

func Connect

func Connect() *errors.Error

Connect to the database

func Contact

func Contact()

func CreateToken

func CreateToken(hID interface{}, power string, encrypt bool) (string, error)

CreateToken creates a jwt token with a ID

func Disconnect

func Disconnect() *errors.Error

Disconnect from the database

func Exec

func Exec(list []string)

func FindExpressive

func FindExpressive(cond ...interface{}) db.Result

func GetID

func GetID(c echo.Context) (hide.Int64, error)

GetID gets the user's ID from the jwt and decrypts it

func GetUserID

func GetUserID(c echo.Context) (int64, error)

GetUserID decrypts the user id from the user token stored in echo's context

func HardDelete

func HardDelete()

func JWT

func JWT(key []byte) echo.MiddlewareFunc

JWT returns a JSON Web Token (JWT) auth middleware.

For valid token, it sets the user in context and calls next handler. For invalid token, it sends "401 - Unauthorized" response. For empty or invalid `Authorization` header, it sends "400 - Bad Request".

See: https://jwt.io/introduction

func JWTParse

func JWTParse(auth string, config JWTConfig) (*jwt.Token, error)

func JWTWithConfig

func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc

JWTWithConfig returns a JWT auth middleware from config. See: `JWT()`.

func Setup

func Setup() *errors.Error

func SoftDelete

func SoftDelete()

func WillTokenExpire

func WillTokenExpire(expAt int64) bool

WillTokenExpire checks if a token will expire the current range is 5-30 minutes

Types

type Activation

type Activation struct {
	ID     int64  `db:"id,omitempty" json:"id,string"`
	UserID int64  `db:"user_id"      json:"user_id,string"`
	Code   string `db:"code"         json:"code"`
}

Activation code for a user

type Ban

type Ban struct {
	ID     hide.Int64 `db:"id,omitempty" json:"id,string"`
	UserID hide.Int64 `db:"user_id"      json:"user_id,string"`

	State     bool `db:"state"           json:"state"`
	Temporary bool `db:"temporary"       json:"temporary"`

	Starts time.Time `db:"starts"        json:"starts"`
	Until  time.Time `db:"until"         json:"until"`
}

Ban information of a user

type ByCreated

type ByCreated []*User

ByCreated sorts users by the time that it was inserted into the database

func (ByCreated) Len

func (t ByCreated) Len() int

func (ByCreated) Less

func (t ByCreated) Less(i, j int) bool

func (ByCreated) Swap

func (t ByCreated) Swap(i, j int)

type Cfg

type Cfg struct {
	TokenExpirationTime time.Duration
	TokenSecret         []byte

	EncryptionLevel int
	EncryptionKey   string
}

type JUser

type JUser User

JUser prevents a loop in User.MarshalJSON()

type JWTConfig

type JWTConfig struct {
	// Skipper defines a function to skip middleware.
	Skipper middleware.Skipper

	// Signing key to validate token.
	// Required.
	SigningKey []byte `json:"signing_key"`

	// Signing method, used to check token signing method.
	// Optional. Default value HS256.
	SigningMethod string `json:"signing_method"`

	// Context key to store user information from the token into context.
	// Optional. Default value "user".
	ContextKey string `json:"context_key"`

	// TokenLookup is a string in the form of "<source>:<name>" that is used
	// to extract token from the request.
	// Optional. Default value "header:Authorization".
	// Possible values:
	// - "header:<name>"
	// - "query:<name>"
	TokenLookup string `json:"token_lookup"`
}

JWTConfig defines the config for JWT middleware.

type User

type User struct {
	ID hide.Int64 `db:"id,omitempty" json:"id,string"`

	Name     string `db:"name"       json:"name"               valid:"optional,length(3|20),alphanum"`
	Username string `db:"username"   json:"username"           valid:"optional,length(3|25),matches(^[a-zA-Z0-9_]+$)"`
	Password string `db:"password"   json:"password,omitempty" valid:"optional,length(3|255)"`
	Email    string `db:"email"      json:"email"              valid:"optional,length(6|255),email"`

	Token string `db:"-"             json:"token"` // jwt
	Power int    `db:"power"         json:"power"`

	Deleted bool      `db:"deleted"  json:"deleted"`
	Created time.Time `db:"created"  json:"created"`
	Seen    time.Time `db:"seen"     json:"seen"`

	LastName string `db:"last_name" valid:"optional,length(3|50),alphanum"`

	// cache, it will only look for activation codes
	// when this is set to false
	Activated bool `db:"activated"   json:"activated"`

	// other structs
	Banned     *Ban        `db:"-"   json:"banned"`
	Activation *Activation `db:"-"   json:"activation"`
}

User holds all needed user information also includes validation and db management

func Find

func Find(cond ...interface{}) ([]*User, *errors.Error)

Find gets all users in the database with the given condition

func NewUser

func NewUser() *User

NewUser creates a new user

func (*User) Auth

func (u *User) Auth(password string) (string, *errors.Error)

Auth authenticates a user and return a jwt token

func (*User) Ban

func (u *User) Ban(temporary bool, until time.Time) *errors.Error

Ban a user and save the state to the database it can be temporary or permanent

func (*User) ComparePassword

func (u *User) ComparePassword(password string) *errors.Error

ComparePassword checks if the given password is the same as the one in the database after hashing it, a u.Find() is required before using it when error is nil, means the passwords are equal

func (*User) Create

func (u *User) Create() (hide.Int64, *errors.Error)

Create validates and check if a user exists before inserting into the db

func (*User) Exists

func (u *User) Exists() (bool, *errors.Error)

Exists check if the user exists by counting the results found

func (*User) ExistsWithCond

func (u *User) ExistsWithCond(cond db.Cond) (bool, *errors.Error)

ExistsWithCond check if the user exists by using the given condition and counting the results found

func (*User) Find

func (u *User) Find() (bool, *errors.Error)

Find the user using the data on the struct id -> username -> email -> fail

func (*User) FindWithCond

func (u *User) FindWithCond(cond db.Cond) (bool, *errors.Error)

FindWithCond tries to find the user using the give conditions

func (*User) HardDelete

func (u *User) HardDelete() *errors.Error

HardDelete removes the user from the database use SoftDelete to disable a account

func (*User) Hash

func (u *User) Hash() *errors.Error

Hash the user's password

func (*User) IsBanned

func (u *User) IsBanned() (bool, *errors.Error)

IsBanned checks if a ban expired then removes the ban state and save to the database

func (*User) MarshalJSON

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

MarshalJSON hides the user password before transforming it into a json

func (*User) Replace

func (u *User) Replace(user *User)

Replace a user mem address

func (*User) Save

func (u *User) Save() *errors.Error

Save the user's data into the database aka update

func (*User) SaveWithCond

func (u *User) SaveWithCond(cond db.Cond) *errors.Error

SaveWithCond updates the user's data on the db with conditions

func (*User) SetIDFromString

func (u *User) SetIDFromString(id string) *errors.Error

SetIDFromString parses a user id from a string and insert it into the user

func (*User) SoftDelete

func (u *User) SoftDelete() *errors.Error

SoftDelete disables the account without removing it from the database

func (*User) Validate

func (u *User) Validate() (bool, *errors.Error)

Validate the user's struct only fields that aren't empty will be validaTed!

type UserPower

type UserPower int

UserPower is the level of power that a user can have access to

const (
	// Normal powers
	// UserPowerNone is the user that hasn't activaTed his account yet
	UserPowerNone UserPower = iota
	// UserPowerNormal is the user that activaTed his account
	UserPowerNormal
	// UserPowerPremium is the user that paid/donaTed
	UserPowerPremium

	// Limited powers
	// UserPowerMod has the powers to ban and warn users
	UserPowerMod
	// UserPowerBot has the power to read private information (email) but can not modify it
	UserPowerBot

	// All powers
	// UserPowerAdmin has the powers to make mods and edit users' information
	UserPowerAdmin
	// UserPowerOwner can make admins
	UserPowerOwner
	// UserPowerProgrammer can do everything and has access to db info
	UserPowerProgrammer
)

This is a list of user's power levels

func GetPower

func GetPower(c echo.Context) (UserPower, error)

GetPower gets the user's power from the jwt and decrypts it

type UserToken

type UserToken struct {
	UID   string `json:"id,string"`
	Power string `json:"power"`
	jwt.StandardClaims
}

UserToken holds a user id inside a jwt

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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