auth

package
v0.1.13 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2021 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package auth provides a standard auth for your website. Multiple providers can be added.

Index

Constants

View Source
const (
	ParamLogin    = "login"
	ParamPassword = "password"
	ParamToken    = "token"
	ParamProvider = "provider"
	KeyClaim      = "claim"
	KeyNavigation = "navigation"
	KeyLanguages  = "languages"
)

predefined http parameter and return keys.

View Source
const (
	LOGIN                 = "Login"
	RefreshedToken        = "RefreshToken"
	RefreshedTokenInvalid = "RefreshTokenInvalid"
	LOGOUT                = "Logout"
	ResetPasswordToken    = "ResetPasswordToken"
	LOCKED                = "Locked"
	INACTIVE              = "Inactive"
	WrongPassword         = "WrongPassword"
	ChangedPassword       = "ChangedPassword"
)

Pre-defined Protocol keys.

Variables

View Source
var (
	ErrUserOption   = "auth: option %s was not found"
	ErrUserLocked   = errors.New("auth: your user is locked because of too many login attempts")
	ErrUserInactive = errors.New("auth: your user is inactive")
)

Error messages.

View Source
var (
	ErrProvider = "auth: provider %s is not registered or configured"
)

Error messages.

View Source
var ErrRefreshTokenNotValid = errors.New("auth: refresh token is not valid")

Functions

func AddNavigationPoint

func AddNavigationPoint(name string, fn func([]string, controller.Interface) ([]Navigation, error))

AddNavigationPoint to the database navigation. Navigations points can be added to any level. To access a child navigation point use a dot notation. Example: Settings.Accounts

func AddProtocol

func AddProtocol(login string, key string, value ...string) error

AddProtocol is a helper to log a key, value(optional) for the given user id.

func BuildRouteGuard

func BuildRouteGuard() error

BuildRouteGuard is creating a map[PATTERN][HTTPMethod][]roles. The map is used in the RBAC Allowed method.

func ChangePassword

func ChangePassword(login string, pwUser string) error

ChangePassword will change the password and delete the pw token.

func ChangePasswordTokenValid

func ChangePasswordTokenValid(login string, token string) error

ChangePasswordTokenValid will check if the token was signed the last 15 minutes and if the user is still valid.

func ConfigureProvider

func ConfigureProvider(provider string, options map[string]interface{}) error

ConfigureProvider will config the provider an add it to a local cache. Error will return if the provider is not allowed by server configuration or it was not registered.

func DeleteUserToken

func DeleteUserToken(login string, rt string) error

func JWTGenerateCallback

func JWTGenerateCallback(w http.ResponseWriter, r *http.Request, c jwt.Claimer, refreshToken string) error

JWTGenerateCallback will generate the user claim for the frontend.

func JWTRefreshCallback

func JWTRefreshCallback(w http.ResponseWriter, r *http.Request, c jwt.Claimer) error

JWTRefreshCallback will check if the refresh token is existing and still valid. If so, it will delete the refresh token and generate a new one incl. jwt token. TODO dont delete the rf token each time.

func RandomPassword

func RandomPassword(length int) string

RandomPassword generates a random password with the given length.

func Register

func Register(name string, provider providerFn) error

Register a new cache provider by name.

Types

type Base

type Base struct {
	orm.Model
	ID int
}

Base model is a helper for the default cache and builder.

func (Base) DefaultBuilder

func (b Base) DefaultBuilder() query.Builder

DefaultBuilder of the models.

func (Base) DefaultCache

func (b Base) DefaultCache() (cache.Manager, time.Duration)

DefaultCache of the models.

type Claim

type Claim struct {
	jwt.Claim

	UID     int
	Name    string
	Surname string
	Login   string
	Roles   []string

	Options map[string]string
}

Claim will hold the user information.

func (Claim) Render

func (c Claim) Render() interface{}

Render will only return the needed data to the frontend.

func (Claim) UserID

func (c Claim) UserID() interface{}

type Interface

type Interface interface {
	Login(p controller.Interface) (Schema, error)
	Logout(p controller.Interface) error

	ForgotPassword(p controller.Interface) error
	ChangePassword(p controller.Interface) error
	RegisterAccount(p controller.Interface) error
}

Interface for the providers.

func New

func New(provider string) (Interface, error)

New will return the configured provider. Error will return if the provider is not registered or configured.

type Navigation struct {
	Base

	Title    string
	Position int

	RouteID query.NullInt
	Icon    query.NullString
	Note    query.NullString
	Route   server.Route `orm:"relation:belongsTo"`

	Children []Navigation
}

Navigation struct

func (n *Navigation) EndpointsByRoles(roles []string, controller controller.Interface) ([]Navigation, error)

EndpointsByRoles will return all nav endpoints which are allowed for the given roles. The nav-points are fetched from the navigation database table. Additional navigation points can be added manually - see AddNavigationPoint function. The manually added navigation points have to be added on an early stage (before server.Start()).

type Option

type Option struct {
	Base
	UserID int
	Key    string
	Value  string
	Hide   bool
}

Option model.

func (Option) DefaultTableName

func (o Option) DefaultTableName() string

type Protocol

type Protocol struct {
	Base

	UserID int
	Key    string
	Value  query.NullString
}

Protocol struct to log user actions.

func (Protocol) DefaultTableName

func (p Protocol) DefaultTableName() string

DefaultTableName of the protocol model.

type Rbac

type Rbac struct {
}

func (Rbac) Allowed

func (r Rbac) Allowed(pattern string, HTTPMethod string, claims interface{}) bool

type RefreshToken

type RefreshToken struct {
	Base

	Token  string
	UserID int
	Expire query.NullTime
}

func (*RefreshToken) DeleteExpired

func (r *RefreshToken) DeleteExpired() error

DeleteExpired refresh tokens of the user account.

func (*RefreshToken) Valid

func (r *RefreshToken) Valid(login string, refreshToken string) error

Valid checks if the given refresh token is still valid.

type Role

type Role struct {
	Base

	Name        string           `json:",omitempty"`
	Description query.NullString `json:",omitempty"`

	Children []Role         `json:",omitempty"`
	Backend  []server.Route `orm:"relation:m2m;poly:Route;poly_value:Backend;join_table:role_routes;join_fk:role_id" json:",omitempty"`
	Frontend []server.Route `orm:"relation:m2m;poly:Route;poly_value:Frontend;join_table:role_routes;join_fk:role_id" json:",omitempty"`
}

Role struct is holding the permission for frontend and backend routes. Roles are self referenced.

type Schema

type Schema struct {
	Provider string
	UID      string

	Login      string
	Name       string
	Surname    string
	Salutation string

	Options []Option
}

Schema should be used as a return value for the providers. Login will be mandatory and should be the E-Mail address of the user. Additional Options can be added which (will be saved as user options in the database - not implemented yet).

type User

type User struct {
	Base

	Login      string           `json:",omitempty"`
	Salutation string           `json:",omitempty"`
	Name       query.NullString `json:",omitempty"`
	Surname    query.NullString `json:",omitempty"`
	Email      string           `json:",omitempty"`

	State           string         `json:",omitempty"`
	LastLogin       query.NullTime `json:",omitempty"`
	FailedLogins    query.NullInt  `json:",omitempty"`
	LastFailedLogin query.NullTime `json:",omitempty"`

	RefreshTokens []RefreshToken `json:",omitempty"`
	Roles         []Role         `orm:"relation:m2m" json:",omitempty" validate:"min=1"`
	Options       []Option       `json:",omitempty"`
	// contains filtered or unexported fields
}

User model

func UserByLogin

func UserByLogin(login string) (*User, error)

UserByLogin will return the user. Error will return if the user does not exist.

func (*User) ComparePassword

func (u *User) ComparePassword(hash string, pw string) error

ComparePassword checks the given password with the hashed password.

func (*User) IncreaseFailedLogin

func (u *User) IncreaseFailedLogin() error

IncreaseFailedLogin will increase the failed logins counter and set the last failed login timestamp.

func (*User) IsInactive

func (u *User) IsInactive() bool

IsInactive is a helper to check if a user is inactive because the duration of the last login is too big.

func (*User) IsLocked

func (u *User) IsLocked() bool

IsLocked is a helper to check if the user is locked because of too many login attempts.

func (*User) Option

func (u *User) Option(key string) (*Option, error)

Option will return the option by key. Error will return if the option does not exist.

func (User) OptionsToMap

func (u User) OptionsToMap() map[string]string

OptionsToMap is a helper to export all user options which are not hidden. This is used for the user claim.

func (*User) SetSecureConfig

func (u *User) SetSecureConfig() error

SetSecureConfig is adding the lock/inactivity and allowed failed logins.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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