models

package
v0.0.26 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2022 License: MIT Imports: 34 Imported by: 2

Documentation

Index

Constants

View Source
const (
	NoCacheExpiration       time.Duration = -1
	DefaultLongExpiration                 = 24 * time.Hour
	DefaultMediumExpiration               = time.Hour
	DefaultShortExpiration                = time.Second * 15
	DefaultCleanInterval                  = time.Minute
)
View Source
const APP_NAME_KEY = "APP_NAME"
View Source
const APP_USER_KEY = "APP_USER"
View Source
const DEFAULT_APP_NAME string = ""
View Source
const DEFAULT_ENV_NAME string = ""
View Source
const DEFAULT_ENV_URL string = "http://config"
View Source
const ENV_NAME_KEY = "APP_ENV_NAME"
View Source
const ENV_URL_KEY = "APP_ENV_ROOT_URL"
View Source
const JWT_REFRESH = "__REFRESH__"
View Source
const (
	RequestAuthKey ctxRequestKey
)

Variables

View Source
var ErrUserUnverified = errors.New("user is not verified")

Functions

func CheckPassword

func CheckPassword(hash, password string) bool

func ExecuteSQL

func ExecuteSQL(ctx context.Context, db DbConn, sql string, optionsAndArgs ...any) ([]map[string]any, error)

func GetAccessToken

func GetAccessToken(r *http.Request) (string, error)

func HashPassword

func HashPassword(password string) string

Types

type APIClient

type APIClient struct {
	*HTTPClient
	// contains filtered or unexported fields
}

func APIClientFromConfig

func APIClientFromConfig(config map[string]any) *APIClient

func NewAPIClient

func NewAPIClient(rootURL, accessURL, refreshURL, clientID, clientSecret string,
	timeout int, maxIdleConns int, maxPerHost int) *APIClient

func (*APIClient) Do

func (self *APIClient) Do(req *http.Request, err error) (*http.Response, error)

func (*APIClient) Get

func (self *APIClient) Get(path string, values url.Values) (*http.Response, error)

func (*APIClient) LoadToken

func (self *APIClient) LoadToken() error

func (*APIClient) PostJSON

func (self *APIClient) PostJSON(path string, data any) (*http.Response, error)

func (*APIClient) PostObject

func (self *APIClient) PostObject(path string, obj any) (*http.Response, error)

func (*APIClient) PostValues

func (self *APIClient) PostValues(path string, form *url.Values) (*http.Response, error)

func (*APIClient) RefreshToken

func (self *APIClient) RefreshToken() error

type Auth

type Auth interface {
	JWTIssuer

	GetCookieMaxAge() int
	GenerateRandomUUID() uuid.UUID
	CreatePayload(context.Context, string) (JWTPayload, error)
	CheckRefresh(context.Context, string, string) (JWTPayload, error)
	CreateClientCred(context.Context, string) (*ClientCredential, error)
	CheckClientCred(context.Context, *ClientCredential) (JWTPayload, error)
	CreateLogin(context.Context, *Login, string) (string, error)
	CheckLogin(context.Context, *Login) (JWTPayload, error)
	UpsertUser(context.Context, *AuthUser, bool) (string, error)
	GetProfile(context.Context, string) (*Profile, error)
	Logout(context.Context, JWTPayload) (bool, error)
	CleanAuthSessions(context.Context) error
	CreateAuthCode(context.Context, string, string, string, string, time.Duration) error
	CheckAuthCode(context.Context, string, string, string) error
	CheckPhone(context.Context, string, string) (JWTPayload, error)
	CreateEmailVerification(context.Context, uuid.UUID, string) (string, error)
	CheckEmailVerification(context.Context, string) (JWTPayload, error)
	Message(context.Context, *AuthMessage) error

	IsActiveSession(context.Context, JWTPayload) (bool, error)
	IsLoggedIn(http.HandlerFunc) http.HandlerFunc

	AddRole(context.Context, string) error
	RemoveRole(context.Context, string) error
	AddEntitlement(context.Context, string, string) (bool, error)
	RemoveEntitlement(context.Context, string, string) (bool, error)
	DumpEntitlements(context.Context) (map[string]map[string]bool, error)
}

func AuthFromConfig

func AuthFromConfig(
	db DbConn,
	config map[string]any,
	secretGetter func() []byte,
) Auth

type AuthDbImpl

type AuthDbImpl struct {
	JWTIssuer

	MaxAge          int           `json:"max_age"`
	MaxFailCount    int           `json:"max_fail_count"`
	FailCountExpiry time.Duration `json:"fail_count_expiry"`
	SessionExpiry   time.Duration `json:"session_expiry"`
	AllowUnverified bool          `json:"allow_unverified"`
	// contains filtered or unexported fields
}

func (*AuthDbImpl) AddEntitlement

func (self *AuthDbImpl) AddEntitlement(ctx context.Context, email, roleName string) (bool, error)

func (*AuthDbImpl) AddRole

func (self *AuthDbImpl) AddRole(ctx context.Context, roleName string) error

func (*AuthDbImpl) CheckAuthCode added in v0.0.10

func (self *AuthDbImpl) CheckAuthCode(ctx context.Context, authMethod, authId, code string) error

func (*AuthDbImpl) CheckClientCred

func (self *AuthDbImpl) CheckClientCred(ctx context.Context, cred *ClientCredential) (JWTPayload, error)

func (*AuthDbImpl) CheckEmailVerification added in v0.0.10

func (self *AuthDbImpl) CheckEmailVerification(ctx context.Context, verificationCode string) (JWTPayload, error)

func (*AuthDbImpl) CheckLogin

func (self *AuthDbImpl) CheckLogin(ctx context.Context, cred *Login) (JWTPayload, error)

func (*AuthDbImpl) CheckPhone added in v0.0.10

func (self *AuthDbImpl) CheckPhone(ctx context.Context, phone, code string) (JWTPayload, error)

func (*AuthDbImpl) CheckRefresh

func (self *AuthDbImpl) CheckRefresh(ctx context.Context, id string, token string) (JWTPayload, error)

func (*AuthDbImpl) CleanAuthSessions

func (self *AuthDbImpl) CleanAuthSessions(ctx context.Context) error

func (*AuthDbImpl) CreateAuthCode added in v0.0.10

func (self *AuthDbImpl) CreateAuthCode(ctx context.Context,
	authMethod, authId, code, ipAddress string, duration time.Duration) error

func (*AuthDbImpl) CreateClientCred

func (self *AuthDbImpl) CreateClientCred(ctx context.Context, id string) (*ClientCredential, error)

func (*AuthDbImpl) CreateEmailVerification added in v0.0.10

func (self *AuthDbImpl) CreateEmailVerification(ctx context.Context, entityUUID uuid.UUID, ipAddress string) (string, error)

func (*AuthDbImpl) CreateLogin added in v0.0.10

func (self *AuthDbImpl) CreateLogin(ctx context.Context, cred *Login, ipAddress string) (string, error)

func (*AuthDbImpl) CreatePayload

func (self *AuthDbImpl) CreatePayload(ctx context.Context, email string) (JWTPayload, error)

func (*AuthDbImpl) DumpEntitlements

func (self *AuthDbImpl) DumpEntitlements(ctx context.Context) (map[string]map[string]bool, error)

func (*AuthDbImpl) GenerateRandomUUID

func (self *AuthDbImpl) GenerateRandomUUID() uuid.UUID

func (*AuthDbImpl) GetCookieMaxAge

func (s *AuthDbImpl) GetCookieMaxAge() int

func (*AuthDbImpl) GetProfile

func (self *AuthDbImpl) GetProfile(ctx context.Context, id string) (*Profile, error)

func (*AuthDbImpl) IsActiveSession

func (self *AuthDbImpl) IsActiveSession(ctx context.Context, p JWTPayload) (bool, error)

func (*AuthDbImpl) IsLoggedIn

func (self *AuthDbImpl) IsLoggedIn(handler http.HandlerFunc) http.HandlerFunc

func (*AuthDbImpl) Logout

func (self *AuthDbImpl) Logout(ctx context.Context, p JWTPayload) (bool, error)

func (*AuthDbImpl) Message added in v0.0.10

func (self *AuthDbImpl) Message(ctx context.Context, msg *AuthMessage) error

func (*AuthDbImpl) RemoveEntitlement

func (self *AuthDbImpl) RemoveEntitlement(ctx context.Context, email, roleName string) (bool, error)

func (*AuthDbImpl) RemoveRole

func (self *AuthDbImpl) RemoveRole(ctx context.Context, roleName string) error

func (*AuthDbImpl) UpsertUser

func (self *AuthDbImpl) UpsertUser(ctx context.Context, u *AuthUser, forceNew bool) (string, error)

type AuthMessage added in v0.0.10

type AuthMessage struct {
	ContactName string         `json:"name"`
	Email       string         `json:"email"`
	Subject     string         `json:"subject"`
	Body        string         `json:"body"`
	Details     map[string]any `json:"details,omitempty"`
}

type AuthUser

type AuthUser struct {
	EntityType       EntityType
	EntityUUID       uuid.UUID
	DisplayName      string
	Details          map[string]any
	EntityStatus     UserStatus
	Email            string
	AuthMethod       string
	Validation       string
	HashedValidation string
}

type Cache

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

func NewCache

func NewCache(ctx context.Context,
	expireAfterRead, expireAfterWrite, cleanInterval time.Duration,
	maxSize, evictSize int,
) *Cache

func (Cache) Clear

func (c Cache) Clear()

func (Cache) Count

func (c Cache) Count() int

func (Cache) Delete

func (c Cache) Delete(k any)

Delete an item from the cache. Does nothing if the key is not in the cache.

func (Cache) DeleteExpired

func (c Cache) DeleteExpired()

func (Cache) Get

func (c Cache) Get(k any) (any, bool)

func (Cache) Info

func (c Cache) Info() map[string]int64

func (Cache) Items

func (c Cache) Items() map[any]any

func (Cache) OnEvicted

func (c Cache) OnEvicted(f func(any, any))

func (Cache) Set

func (c Cache) Set(k any, x any)

type CacheItem

type CacheItem struct {
	Object     any
	Expiration int64
}

func (CacheItem) IsExpired

func (item CacheItem) IsExpired() bool

type ClientCredential

type ClientCredential struct {
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
}

type ClientError

type ClientError struct {
	StatusCode int
	Message    string
	Request    *http.Request
}

func (*ClientError) Error

func (self *ClientError) Error() string

type DbConn

type DbConn interface {
	Begin(ctx context.Context) (pgx.Tx, error)
	Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, error)
	Query(ctx context.Context, sql string, optionsAndArgs ...interface{}) (pgx.Rows, error)
	QueryRow(ctx context.Context, sql string, optionsAndArgs ...interface{}) pgx.Row
}

func NewDbConn added in v0.0.18

func NewDbConn(ctx context.Context, config map[string]any) (DbConn, error)

type EmailClient added in v0.0.10

type EmailClient struct {
	From         string `json:"from,omitempty"`
	To           string `json:"to,omitempty"`
	SMTPHost     string `json:"smtp_host,omitempty"`
	SMTPPort     int    `json:"smtp_port,omitempty"`
	SMTPUser     string `json:"smtp_user,omitempty"`
	SMTPPassword string `json:"smtp_password,omitempty"`
	// contains filtered or unexported fields
}

func EmailClientFromConfig added in v0.0.10

func EmailClientFromConfig(config map[string]any) *EmailClient

func (*EmailClient) Send added in v0.0.10

func (self *EmailClient) Send(_ context.Context, to, subject, body string) error

type EntityType

type EntityType string
const (
	UserEntityType EntityType = "user"
)

type Environment

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

func DefaultEnvironment

func DefaultEnvironment() *Environment

func NewEnvironment

func NewEnvironment(name, env, rootURL string) *Environment

func (*Environment) GetConfig

func (self *Environment) GetConfig(parts []string) (map[string]any, error)

func (*Environment) GetUser

func (self *Environment) GetUser() string

type HTTPClient

type HTTPClient struct {
	Client *http.Client
	// contains filtered or unexported fields
}

func NewHTTPClient

func NewHTTPClient(rootURL string, timeout int, maxIdleConns int, maxPerHost int) *HTTPClient

func (*HTTPClient) CheckStatusCode

func (self *HTTPClient) CheckStatusCode(req *http.Request, resp *http.Response, err error) (*http.Response, error)

func (*HTTPClient) Do

func (self *HTTPClient) Do(req *http.Request, err error) (*http.Response, error)

func (*HTTPClient) Get

func (self *HTTPClient) Get(path string, values url.Values) (*http.Response, error)

func (*HTTPClient) GetGetRequest

func (self *HTTPClient) GetGetRequest(path string, values url.Values) (*http.Request, error)

func (*HTTPClient) GetPostJSONRequest

func (self *HTTPClient) GetPostJSONRequest(path string, data any) (*http.Request, error)

func (*HTTPClient) GetPostObjectRequest

func (self *HTTPClient) GetPostObjectRequest(path string, obj any) (*http.Request, error)

func (*HTTPClient) GetPostValuesRequest

func (self *HTTPClient) GetPostValuesRequest(path string, form *url.Values) (*http.Request, error)

func (*HTTPClient) PostJSON

func (self *HTTPClient) PostJSON(path string, data any) (*http.Response, error)

func (*HTTPClient) PostObject

func (self *HTTPClient) PostObject(path string, obj any) (*http.Response, error)

func (*HTTPClient) PostValues

func (self *HTTPClient) PostValues(path string, form *url.Values) (*http.Response, error)

func (*HTTPClient) ToBytes

func (self *HTTPClient) ToBytes(resp *http.Response, err error) ([]byte, error)

func (*HTTPClient) ToJSON

func (self *HTTPClient) ToJSON(resp *http.Response, err error) (map[string]any, error)

type JWTIssuer

type JWTIssuer interface {
	NewJWT() *jwt.Token
	JWTKeyFunc(token *jwt.Token) (any, error)
	CreateAccessToken(payload JWTPayload) (string, error)
	CreateRefreshToken(JWTPayload) (string, error)
	LoadJWT(*http.Request) (JWTPayload, error)
	HasRole(JWTPayload, string) bool
	IsValidJWT(http.HandlerFunc) http.HandlerFunc
	ValidateJWT(http.Handler) http.Handler
	IsAdmin(http.HandlerFunc) http.HandlerFunc
}

func NewJWTIssuer

func NewJWTIssuer(secretGetter func() []byte) JWTIssuer

type JWTPayload

type JWTPayload interface {
	GetID() string
	GetSession() string
	GetRoles() string
}

type JWTTransformer

type JWTTransformer interface {
	GetPayload(*jwt.Token) (JWTPayload, error)
	PutPayloadInAccess(*jwt.Token, JWTPayload) error
	PutPayloadInRefresh(*jwt.Token, JWTPayload) error
}

type Login

type Login struct {
	Email    string `json:"email,omitempty"`
	Password string `json:"password,omitempty"`
	Name     string `json:"name,omitempty"`
}

type Profile

type Profile struct {
	Email       string         `json:"email"`
	DisplayName string         `json:"display_name"`
	UserStatus  UserStatus     `json:"user_status"`
	Details     map[string]any `json:"details"`
	FailCount   int            `json:"fail_count"`
}

type SMSClient added in v0.0.4

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

func SMSFromConfig added in v0.0.4

func SMSFromConfig(config map[string]any, emailClient *EmailClient) (*SMSClient, error)

func (*SMSClient) GetCountryCode added in v0.0.26

func (self *SMSClient) GetCountryCode(country string) (string, error)

func (*SMSClient) GetSMSGatewayCountries added in v0.0.25

func (self *SMSClient) GetSMSGatewayCountries() map[string]SMSGatewayCountry

func (*SMSClient) GetSMSServer added in v0.0.26

func (self *SMSClient) GetSMSServer(country, gateway string) (string, error)

func (*SMSClient) Send added in v0.0.4

func (self *SMSClient) Send(msg *SMSMessage) error

type SMSGatewayCountry added in v0.0.25

type SMSGatewayCountry struct {
	CountryCode string              `json:"code"`
	Gateways    map[string]struct{} `json:"gateways"`
}

type SMSGateways added in v0.0.25

type SMSGateways struct {
	Countries map[string]SMSGatewayCountry `json:"countries"`
	Gateways  map[string]map[string]string `json:"gateways"`
}

type SMSMessage added in v0.0.25

type SMSMessage struct {
	Phone   string `json:"phone"`
	Body    string `json:"body,omitempty"`
	Gateway string `json:"gateway,omitempty"`
	Country string `json:"country,omitempty"`
}

func (*SMSMessage) GetEmail added in v0.0.26

func (self *SMSMessage) GetEmail(client *SMSClient) (string, error)

func (*SMSMessage) GetPhone added in v0.0.25

func (self *SMSMessage) GetPhone(client *SMSClient, withCountryCode bool) (string, error)

type Scanner

type Scanner interface {
	Scan(...interface{}) error
}

type ServerError

type ServerError struct {
	StatusCode int
	Message    string
	Request    *http.Request
}

func (*ServerError) Error

func (self *ServerError) Error() string

type SimpleJWTIssuer

type SimpleJWTIssuer struct {
	JWTTransformer
	// contains filtered or unexported fields
}

func (*SimpleJWTIssuer) CreateAccessToken

func (self *SimpleJWTIssuer) CreateAccessToken(payload JWTPayload) (string, error)

func (*SimpleJWTIssuer) CreateRefreshToken

func (self *SimpleJWTIssuer) CreateRefreshToken(payload JWTPayload) (string, error)

func (*SimpleJWTIssuer) HasRole added in v0.0.10

func (self *SimpleJWTIssuer) HasRole(payload JWTPayload, role string) bool

func (*SimpleJWTIssuer) IsAdmin

func (self *SimpleJWTIssuer) IsAdmin(handler http.HandlerFunc) http.HandlerFunc

func (*SimpleJWTIssuer) IsValidJWT

func (self *SimpleJWTIssuer) IsValidJWT(handler http.HandlerFunc) http.HandlerFunc

func (*SimpleJWTIssuer) JWTKeyFunc

func (self *SimpleJWTIssuer) JWTKeyFunc(token *jwt.Token) (any, error)

func (*SimpleJWTIssuer) LoadJWT added in v0.0.10

func (self *SimpleJWTIssuer) LoadJWT(r *http.Request) (JWTPayload, error)

func (*SimpleJWTIssuer) NewJWT

func (self *SimpleJWTIssuer) NewJWT() *jwt.Token

func (*SimpleJWTIssuer) ValidateJWT

func (self *SimpleJWTIssuer) ValidateJWT(next http.Handler) http.Handler

type SimpleJWTTransformer

type SimpleJWTTransformer struct {
	AccessExpiry  time.Duration `json:"access_expiry"`
	RefreshExpiry time.Duration `json:"refresh_expiry"`
}

func (*SimpleJWTTransformer) GetPayload

func (self *SimpleJWTTransformer) GetPayload(token *jwt.Token) (JWTPayload, error)

func (*SimpleJWTTransformer) PutPayloadInAccess

func (self *SimpleJWTTransformer) PutPayloadInAccess(token *jwt.Token, payload JWTPayload) error

func (*SimpleJWTTransformer) PutPayloadInRefresh

func (self *SimpleJWTTransformer) PutPayloadInRefresh(token *jwt.Token, payload JWTPayload) error

type SimplePayload

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

func (*SimplePayload) GetID

func (self *SimplePayload) GetID() string

func (*SimplePayload) GetRoles

func (self *SimplePayload) GetRoles() string

func (*SimplePayload) GetRolesMap

func (self *SimplePayload) GetRolesMap() map[string]bool

func (*SimplePayload) GetSession

func (self *SimplePayload) GetSession() string

type Tenure

type Tenure int
const (
	TenureShort Tenure
	TenureMedium
	TenureLong
	TenureForever
	TenureNever
)

type TenureCache

type TenureCache struct {
	Long    *Cache
	Medium  *Cache
	Short   *Cache
	Forever *Cache
}

func BuildTenureCache

func BuildTenureCache(ctx context.Context, config map[string]any) *TenureCache

func NewTenureCache

func NewTenureCache(ctx context.Context) *TenureCache

func (*TenureCache) Clear

func (c *TenureCache) Clear(tenure Tenure)

func (*TenureCache) ClearAll

func (c *TenureCache) ClearAll()

func (*TenureCache) Delete

func (c *TenureCache) Delete(tenure Tenure, k string)

func (*TenureCache) Get

func (c *TenureCache) Get(tenure Tenure, k string) (any, bool)

func (*TenureCache) Info

func (c *TenureCache) Info() map[string]map[string]int64

func (*TenureCache) Set

func (c *TenureCache) Set(tenure Tenure, k string, v any)

type UnknownError

type UnknownError struct {
	StatusCode int
	Message    string
	Request    *http.Request
}

func (*UnknownError) Error

func (self *UnknownError) Error() string

type UserStatus

type UserStatus string
const (
	UserStatusVerified   UserStatus = "verified"
	UserStatusUnverified            = "unverified"
)

Jump to

Keyboard shortcuts

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