teak

package module
v0.0.0-...-8e695b4 Latest Latest
Warning

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

Go to latest
Published: May 1, 2021 License: MIT Imports: 34 Imported by: 3

README

teak

A attempt to improve Vaali.

Intended changes are:

Details will be added later.

Note

This repo is expected to be broken for some time

Documentation

Index

Constants

View Source
const InfiniteDepth int = -1

InfiniteDepth - used to indicate that Walk should continue till all the nodes in the heirarchy are visited

Variables

This section is empty.

Functions

func AddEndpoint

func AddEndpoint(ep *Endpoint)

AddEndpoint - registers an REST endpoint

func AddEndpoints

func AddEndpoints(eps ...*Endpoint)

AddEndpoints - registers multiple REST categories

func AskPassword

func AskPassword(name string) (secret string)

AskPassword - asks password, prints the given name before asking

func AuditedSend

func AuditedSend(ctx echo.Context, res *Result) (err error)

AuditedSend - sends result as JSON while logging it as event. The event data is same as the data present in the result

func AuditedSendSecret

func AuditedSendSecret(ctx echo.Context, res *Result) (err error)

AuditedSendSecret - Sends result to client and logs everything other than the secret data field

func AuditedSendX

func AuditedSendX(ctx echo.Context, data interface{}, res *Result) (err error)

AuditedSendX - sends result as JSON while logging it as event. This method logs event data which is seperate from result data

func Debug

func Debug(module, fmtStr string, args ...interface{})

Debug - debug logs

func Decrypt

func Decrypt(key []byte, text string) (decrypted string, err error)

Decrypt - decrypts input text with given key using AES algo

func DecryptStr

func DecryptStr(key string, text string) (decrypted string, err error)

DecryptStr - AES decrypts input text with given key string

func DefMS

func DefMS(oprn string) (int, string)

DefMS - gives default message and status, used for convenience

func DumpJSON

func DumpJSON(o interface{})

DumpJSON - dumps JSON representation of given data to stdout

func Encrypt

func Encrypt(key []byte, text string) (encrypted string, err error)

Encrypt - encrypts input text with given key using AES algo

func EncryptStr

func EncryptStr(key string, text string) (encrypted string, err error)

EncryptStr - AES encrypts input text with given key string

func ErrString

func ErrString(err error) string

ErrString - returns the error string if the given error is not nil

func Error

func Error(module, fmtStr string, args ...interface{}) (err error)

Error - error logs

func ExistsAsDir

func ExistsAsDir(path string) (yes bool)

ExistsAsDir - checks if a directory exists at given path. If a error occurs while stating whatever exists at given location, false is returned

func ExistsAsFile

func ExistsAsFile(path string) (yes bool)

ExistsAsFile - checks if a regular file exists at given path. If a error occurs while stating whatever exists at given location, false is returned

func Fatal

func Fatal(module, fmtStr string, args ...interface{})

Fatal - error logs

func FirstValid

func FirstValid(errs ...error) (err error)

FirstValid - returns the first error that is not nil

func GetAsJSON

func GetAsJSON(o interface{}) (jstr string, err error)

GetAsJSON - converts given data to JSON and returns as pretty printed

func GetConfig

func GetConfig(key string, value interface{}) (found bool)

GetConfig - retrieves config value for the given key and populates the value argument given. If the key does not exist in the config map or if its not possible to populate value arg from retrieved value and error is returned

func GetExecDir

func GetExecDir() (dirPath string)

GetExecDir - gives absolute path of the directory in which the executable for the current application is present

func GetFirstValidStr

func GetFirstValidStr(strs ...string) (str string)

GetFirstValidStr - gets first string that is not empty

func GetJWTKey

func GetJWTKey() []byte

GetJWTKey - gives a unique JWT key

func GetOffsetLimit

func GetOffsetLimit(ctx echo.Context) (offset, limit int64, has bool)

GetOffsetLimit - retrieves offset and limit as integers provided in URL as query parameters. These parameters should have name - offset and limit respectively

func GetQueryParam

func GetQueryParam(ctx echo.Context, name string, def string) (val string)

GetQueryParam - get query param if present otherwise return the default

func GetRootPath

func GetRootPath() string

GetRootPath - get base URL of the configured application's REST Endpoints

func GetServiceStartCmd

func GetServiceStartCmd(serveFunc func(port int) error) *cli.Command

GetServiceStartCmd - creates a command to service start, if serveFunc is not nil then that function is invoked at the end of command, otherwise default serve is used

func GetString

func GetString(ctx echo.Context, key string) (value string)

GetString - retrieves property with key from context

func GetStringConfig

func GetStringConfig(key string) (value string)

GetStringConfig - gets a value associated with config key

func GetToken

func GetToken(ctx echo.Context) (token *jwt.Token, err error)

GetToken - gets token from context or from header

func GetUserIDPassword

func GetUserIDPassword(params map[string]interface{}) (
	userID string, password string, err error)

GetUserIDPassword - gets userID and password from parameter app, if not available a error is returned

func HasConfig

func HasConfig(key string) (yes bool)

HasConfig - checks if a value exists in config for a key

func HasError

func HasError(module string, errs ...error) (has bool)

HasError - logs the errors from the array that are not nil and return true if there were one or more non nil errors

func Hash

func Hash(in string) (out string)

Hash - creates a SHA1 hash of input string

func Info

func Info(module, fmtStr string, args ...interface{})

Info - information logs

func InitLogger

func InitLogger(lc LoggerConfig)

InitLogger - initializes the logger with non default options. If you want default behavior, no need to call any init functions

func InitServer

func InitServer(rootName string, apiVersion int)

InitServer - initializes all the registered endpoints

func IsAdmin

func IsAdmin(ctx echo.Context) (yes bool)

IsAdmin - returns true if user associated with request is an admin

func IsBasicType

func IsBasicType(rt reflect.Kind) bool

IsBasicType - tells if the kind of data type is basic or composite

func IsNormalUser

func IsNormalUser(ctx echo.Context) (yes bool)

IsNormalUser - returns true if user is a normal user

func IsSuperUser

func IsSuperUser(ctx echo.Context) (yes bool)

IsSuperUser - returns true if user is a super user

func IsTime

func IsTime(val *reflect.Value) bool

IsTime - tells if a reflected value is time

func LoadConfig

func LoadConfig(appName string)

LoadConfig - loads configuration for app with given appName. Searches for configuration file in standard locations and loads based all of them. If same config values is present in different files, value for the file that is loaded last is kept

func LoadJSONFromArgs

func LoadJSONFromArgs(ctx echo.Context, param string, out interface{}) (
	err error)

LoadJSONFromArgs - decodes argument identified by 'param' to JSON and unmarshals it into the given 'out' structure

func LogError

func LogError(module string, err error) error

LogError - error log

func LogErrorX

func LogErrorX(module, msg string, err error, args ...interface{}) error

LogErrorX - checks if the provide err is not null, and logs it along with the given message

func LogEvent

func LogEvent(
	op string,
	userID string,
	userName string,
	success bool,
	err string,
	data interface{})

LogEvent - logs an event using the registered audit function

func LogFatal

func LogFatal(module string, err error)

LogFatal - logs before exit

func LogJSON

func LogJSON(level Level, module string, data interface{})

LogJSON - logs data as JSON

func MergeCommands

func MergeCommands(cmdss ...[]*cli.Command) []*cli.Command

MergeCommands - merge commands from different arrays to single array

func ModifiedHTTPErrorHandler

func ModifiedHTTPErrorHandler(err error, c echo.Context)

ModifiedHTTPErrorHandler is the default HTTP error handler. It sends a JSON response with status code. [Modefied from echo.DefaultHTTPErrorHandler]

func Print

func Print(module, fmtStr string, args ...interface{})

Print - prints the message on console

func PrintConfig

func PrintConfig()

PrintConfig - prints the configuration

func SendAndAuditOnErr

func SendAndAuditOnErr(ctx echo.Context, res *Result) (err error)

SendAndAuditOnErr - sends the result to client and puts an audit record in audit log if the result is error OR sending failed

func SendEmail

func SendEmail(to, subject, meesage string) (err error)

SendEmail - sends an email with given information. Uses the package level variable emainConfig for SMTP configuration - smtp.gmail.com:587

func SendVerificationMail

func SendVerificationMail(user *User) (err error)

SendVerificationMail - send mail with a link to user verification based on user email

func Serve

func Serve(port int) (err error)

Serve - start the server

func SetEventAuditor

func SetEventAuditor(auditor EventAuditor)

SetEventAuditor - sets the event auditor

func SetLevel

func SetLevel(level Level)

SetLevel - sets the filter level

func SetUserStorage

func SetUserStorage(storage UserStorage)

SetUserStorage - sets the user storage strategu

func ToFlatMap

func ToFlatMap(obj interface{}, tagName string) (out map[string]interface{})

ToFlatMap - converts given composite data structure into a map of string to interfaces. The heirarchy of types are flattened into single level. The keys of the map indicate the original heirarchy

func ToString

func ToString(level Level) string

ToString - maps level to a string

func Trace

func Trace(module, fmtStr string, args ...interface{})

Trace - trace logs

func UpdateUserInfo

func UpdateUserInfo(user *User) (err error)

UpdateUserInfo - updates common user fields

func Walk

func Walk(
	obj interface{},
	config *WalkConfig)

Walk - walk a given instance of struct/slice/map/basic type

func Warn

func Warn(module, fmtStr string, args ...interface{})

Warn - warning logs

Types

type App

type App struct {
	cli.App
	// contains filtered or unexported fields
}

App - the application itself

func GetAppReference

func GetAppReference(ctx *cli.Context) (vapp *App)

GetAppReference - gets instance of teak.App which is stored inside cli.App.Metadata

func NewApp

func NewApp(
	name string,
	appVersion Version,
	apiVersion int,
	desc string,
	authtr Authenticator,
	authzr Authorizer,
	uStorage UserStorage,
	genStorage DataStorage) (app *App)

NewApp - creates a new application with default options

func (*App) AddModule

func (app *App) AddModule(module *Module)

AddModule - registers a module with the app

func (*App) Exec

func (app *App) Exec(gtx context.Context, args []string) (err error)

Exec - runs the applications

func (*App) FromAppDir

func (app *App) FromAppDir(relPath string) (abs string)

FromAppDir - gives a absolute path from a path relative to app directory

func (*App) Init

func (app *App) Init(
	gtx context.Context, admin *User, adminPass string, param M) (err error)

Init - initializes the application and the registered module. This needs to be called when app/module configuration changes. For example: This is the place where mongoDB indices are expected to be created.

func (*App) Reset

func (app *App) Reset(gtx context.Context) (err error)

Reset - resets the application and module configuration and data. USE WITH CAUTION

func (*App) Setup

func (app *App) Setup(gtx context.Context) (err error)

Setup - Setup the application for the first time

type ArgGetter

type ArgGetter struct {
	Err error
	// contains filtered or unexported fields
}

ArgGetter - this struct and its method are helpers to combine getting args from commandline arguments or from reading from console. Also handles errors when required arguments are not provided

func NewArgGetter

func NewArgGetter(ctx *cli.Context) (argtr *ArgGetter)

NewArgGetter - creates a new argument retriever with given context

func (*ArgGetter) GetIntOr

func (retriever *ArgGetter) GetIntOr(key string, def int) (val int)

GetIntOr - retrieves string int commandline, if not found returns given default

func (*ArgGetter) GetOptionalInt

func (retriever *ArgGetter) GetOptionalInt(key string) (val int)

GetOptionalInt - retrieves int from commandline, if not provided it wont ask again from stdin

func (*ArgGetter) GetOptionalSecret

func (retriever *ArgGetter) GetOptionalSecret(key string) (val string)

GetOptionalSecret - reads 'secret' if provided in commandline, otherwise return empty string

func (*ArgGetter) GetOptionalString

func (retriever *ArgGetter) GetOptionalString(key string) (val string)

GetOptionalString - retrieves string from commandline, if not provided it wont ask again from stdin

func (*ArgGetter) GetRequiredInt

func (retriever *ArgGetter) GetRequiredInt(key string) (val int)

GetRequiredInt - gives a Integer argument either from commandline or from blocking user input, this method sets the error if required arg-val is empty

func (*ArgGetter) GetRequiredSecret

func (retriever *ArgGetter) GetRequiredSecret(key string) (val string)

GetRequiredSecret - gives a string argument either from commandline or from blocking user input, this method sets the error if required arg-val is empty

func (*ArgGetter) GetRequiredString

func (retriever *ArgGetter) GetRequiredString(key string) (val string)

GetRequiredString - gives a string argument either from commandline or from blocking user input, this method sets the error if required arg-val is empty

func (*ArgGetter) GetSecretOr

func (retriever *ArgGetter) GetSecretOr(key, def string) (val string)

GetSecretOr - retrieves password from commandline, if not found returns given default

func (*ArgGetter) GetStringOr

func (retriever *ArgGetter) GetStringOr(key, def string) (val string)

GetStringOr - retrieves string from commandline, if not found returns given default

type AsyncLogger

type AsyncLogger struct {
	sync.Mutex
	// contains filtered or unexported fields
}

AsyncLogger - logger that uses goroutine for dispatching

func NewAsyncLogger

func NewAsyncLogger() *AsyncLogger

NewAsyncLogger - creates a new DirectLogger instace

func (*AsyncLogger) GetWriter

func (al *AsyncLogger) GetWriter(uniqueID string) (writer Writer)

GetWriter - gives the writer with given ID

func (*AsyncLogger) Log

func (al *AsyncLogger) Log(level Level,
	module string,
	fmtstr string,
	args ...interface{})

Log - logs a message with given level and module

func (*AsyncLogger) RegisterWriter

func (al *AsyncLogger) RegisterWriter(writer Writer)

RegisterWriter - registers a writer

func (*AsyncLogger) RemoveWriter

func (al *AsyncLogger) RemoveWriter(uniqueID string)

RemoveWriter - removes a writer with given ID

type AuthLevel

type AuthLevel int

AuthLevel - authorization of an user

const (
	//Super - super user
	Super AuthLevel = iota

	//Admin - application admin
	Admin

	//Normal - normal user
	Normal

	//Monitor - readonly user
	Monitor

	//Public - no authentication required
	Public
)

func NoOpAuthorizer

func NoOpAuthorizer(gtx context.Context, userID string) (AuthLevel, error)

NoOpAuthorizer - authorizer that does not do anything

func (AuthLevel) String

func (a AuthLevel) String() string

type Authenticator

type Authenticator func(
	gtx context.Context, params map[string]interface{}) (*User, error)

Authenticator - a function that is used to authenticate an user. The function takes map of parameters contents of which will differ based on actual function used

type Authorizer

type Authorizer func(gtx context.Context, userID string) (AuthLevel, error)

Authorizer - a function that will be used authorize an user

type BinderFunc

type BinderFunc func(ctx echo.Context) (interface{}, error)

BinderFunc - a function that binds data struct to response body

type Client

type Client struct {
	http.Client
	Address    string
	VersionStr string
	BaseURL    string
	Token      string
	User       *User
}

Client - client for orek service

func NewClient

func NewClient(address, appName, versionStr string) *Client

NewClient - creates a new rest client

func (*Client) CreateURL

func (client *Client) CreateURL(
	access AuthLevel,
	args ...string) (str string)

CreateURL - constructs URL from base URL, access level and the given path components

func (*Client) Delete

func (client *Client) Delete(
	access AuthLevel,
	urlArgs ...string) (rr *ResultReader)

Delete - performs a delete request

func (*Client) Get

func (client *Client) Get(
	access AuthLevel,
	urlArgs ...string) (rr *ResultReader)

Get - performs a get request

func (*Client) Login

func (client *Client) Login(userID, password string) (err error)

Login - login to a teak based service with userID and password. If successful client will have the session information and can perform REST calls that needs authentication

func (*Client) Post

func (client *Client) Post(
	content interface{},
	access AuthLevel,
	urlArgs ...string) (rr *ResultReader)

Post - performs a post request

func (*Client) Put

func (client *Client) Put(
	content interface{},
	access AuthLevel,
	urlArgs ...string) (rr *ResultReader)

Put - performs a put request

type ConsoleWriter

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

ConsoleWriter - Log writer that writes to console

func NewConsoleWriter

func NewConsoleWriter() *ConsoleWriter

NewConsoleWriter - creates a new console writer

func (*ConsoleWriter) Enable

func (cw *ConsoleWriter) Enable(value bool)

Enable - enables or disables console logger based on the passed value

func (*ConsoleWriter) IsEnabled

func (cw *ConsoleWriter) IsEnabled() (value bool)

IsEnabled - tells if the writer is enabled

func (*ConsoleWriter) UniqueID

func (cw *ConsoleWriter) UniqueID() string

UniqueID - identifier for console writer

func (*ConsoleWriter) Write

func (cw *ConsoleWriter) Write(message string)

Write - writes message to console

type CountList

type CountList struct {
	TotalCount int64       `json:"total" db:"total"`
	Data       interface{} `json:"data" db:"data"`
}

CountList - paginated list returned from mongoDB along with total number of items in the list counted without pagination

type DataStorage

type DataStorage interface {
	Name() string
	Count(
		gtx context.Context,
		dtype string,
		filter *Filter) (count int64, err error)
	Create(
		gtx context.Context,
		dataType string,
		data interface{}) error
	Update(
		gtx context.Context,
		dataType string,
		keyField string,
		key interface{},
		data interface{}) error
	Delete(
		gtx context.Context,
		dataType string,
		keyField string,
		key interface{}) error
	RetrieveOne(
		gtx context.Context,
		dataType string,
		keyField string,
		key interface{},
		data interface{}) error
	Retrieve(
		gtx context.Context,
		dtype string,
		sortFiled string,
		offset int64,
		limit int64,
		filter *Filter,
		out interface{}) error
	RetrieveWithCount(
		gtx context.Context,
		dtype string,
		sortFiled string,
		offset int64,
		limit int64,
		filter *Filter,
		out interface{}) (count int64, err error)
	GetFilterValues(
		gtx context.Context,
		dtype string,
		specs FilterSpecList) (values M, err error)
	GetFilterValuesX(
		gtx context.Context,
		dtype string,
		field string,
		specs FilterSpecList,
		filter *Filter) (values M, err error)

	IsSetup(gtx context.Context) (yes bool, err error)
	Setup(gtx context.Context, admin *User, adminPass string, param M) error
	Init(gtx context.Context, params M) error
	Reset(gtx context.Context) error
	Destroy(gtx context.Context) error
	Wrap(cmd *cli.Command) *cli.Command
}

DataStorage - defines a data storage

func GetStore

func GetStore() DataStorage

GetStore - get the data store

type DateRange

type DateRange struct {
	// Name string    `json:"name" bson:"name"`
	From time.Time `json:"from" db:"from"`
	To   time.Time `json:"to" db:"to"`
}

DateRange - represents date ranges

func (*DateRange) IsValid

func (r *DateRange) IsValid() bool

IsValid - returns true if both From and To dates are non-zero

type DirectLogger

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

DirectLogger - logger that writes directly to all registered writers

func NewDirectLogger

func NewDirectLogger() *DirectLogger

NewDirectLogger - creates a new DirectLogger instace

func (*DirectLogger) GetWriter

func (dl *DirectLogger) GetWriter(uniqueID string) (writer Writer)

GetWriter - gives the writer with given ID

func (*DirectLogger) Log

func (dl *DirectLogger) Log(level Level,
	module string,
	fmtstr string,
	args ...interface{})

Log - logs a message with given level and module

func (*DirectLogger) RegisterWriter

func (dl *DirectLogger) RegisterWriter(writer Writer)

RegisterWriter - registers a writer

func (*DirectLogger) RemoveWriter

func (dl *DirectLogger) RemoveWriter(uniqueID string)

RemoveWriter - removes a writer with given ID

type EmailConfig

type EmailConfig struct {
	AppEMail         string `json:"appEMail"`
	AppEMailPassword string `json:"appEMailPassword"`
	SMTPHost         string `json:"smtpHost"`
	SMTPPort         int    `json:"smtpPort"`
}

EmailConfig - configuration for sending email

type Endpoint

type Endpoint struct {
	Method   string      `json:"method"`
	URL      string      `json:"url"`
	Access   AuthLevel   `json:"access"`
	Category string      `json:"cateogry"`
	Route    *echo.Route `json:"route"`
	Comment  string      `json:"Comment"`
	Func     echo.HandlerFunc
}

Endpoint - represents a REST endpoint with associated metadata

func Merge

func Merge(epss ...[]*Endpoint) (eps []*Endpoint)

Merge - merges multple endpoint arrays

func MergeEnpoints

func MergeEnpoints(epss ...[]*Endpoint) []*Endpoint

MergeEnpoints - merge endpoints from different arrays to single array

type Event

type Event struct {
	Op       string      `json:"op" db:"op"`
	UserID   string      `json:"userID" db:"user_id"`
	UserName string      `json:"userName" db:"user_name"`
	Success  bool        `json:"success" db:"success"`
	Error    string      `json:"error" db:"error"`
	Time     time.Time   `json:"time" db:"time"`
	Data     interface{} `json:"data" db:"data"`
}

Event - represents a event initiated by a user while performing an operation

type EventAuditor

type EventAuditor interface {
	//LogEvent - logs given event into storage
	LogEvent(event *Event)

	//GetEvents - retrieves event entries based on filters
	GetEvents(offset, limit int64,
		filter *Filter) (
		total int64,
		events []*Event,
		err error)

	//CreateIndices - creates mongoDB indeces for tables used for event logs
	CreateIndices() (err error)

	//CleanData - cleans event related data from database
	CleanData() (err error)
}

EventAuditor - handles application events for audit purposes

func GetAuditor

func GetAuditor() EventAuditor

GetAuditor - gets the event auditor

type FieldNameRetriever

type FieldNameRetriever func(field *reflect.StructField) (name string)

FieldNameRetriever - retrieves name for the field from given

type Filter

type Filter struct {
	Props    map[string]Matcher     `json:"props" db:"props"`
	Bools    map[string]interface{} `json:"bools" db:"bools"`
	Dates    map[string]DateRange   `json:"dates" db:"dates"`
	Lists    map[string]Matcher     `json:"lists" db:"lists"`
	Searches map[string]Matcher     `json:"searches" db:"searches"`
}

Filter - generic filter used to filter data in any mongodb collection

type FilterSpec

type FilterSpec struct {
	Field string     `json:"field" db:"field"`
	Name  string     `json:"name" db:"name"`
	Type  FilterType `json:"type" db:"type"`
}

FilterSpec - filter specification

type FilterSpecList

type FilterSpecList []*FilterSpec

FilterSpecList - alias for array of filter specs

type FilterType

type FilterType string

FilterType - Type of filter item

const Array FilterType = "array'"

Array - filter for an array

const Boolean FilterType = "boolean"

Boolean - filter for boolean field

const Constant FilterType = "constant"

Constant - constant filter value

const Date FilterType = "dateRange"

Date - filter for data range

const Prop FilterType = "prop"

Prop - filter for a value

const Search FilterType = "search"

Search - filter for search text field

const Static FilterType = "static"

Static - constant filter value

type FilterVal

type FilterVal struct {
	Name  string `json:"name" db:"name"`
	Count int    `json:"count" db:"count"`
}

FilterVal - values for filter along with the count

type Group

type Group struct {
	Name  string   `json:"name" db:"name"`
	Users []string `json:"users" db:"users"`
}

Group - group of users

type Level

type Level int

Level - gives log level

const (
	//TraceLevel - low level debug message
	TraceLevel Level = 1

	//DebugLevel - a debug message
	DebugLevel Level = 2

	//InfoLevel - information message
	InfoLevel Level = 3

	//WarnLevel - warning message
	WarnLevel Level = 4

	//ErrorLevel - error message
	ErrorLevel Level = 5

	//FatalLevel - fatal messages
	FatalLevel Level = 6

	//PrintLevel - prints a output message
	PrintLevel Level = 7
)

func GetLevel

func GetLevel() (level Level)

GetLevel - gets the filter level

func (Level) String

func (level Level) String() string

type Logger

type Logger interface {
	//Log - logs a message with given level and module
	Log(level Level,
		module string,
		fmtstr string,
		args ...interface{})

	//RegisterWriter - registers a writer
	RegisterWriter(writer Writer)

	//RemoveWriter - removes a writer with given ID
	RemoveWriter(uniqueID string)

	//GetWriter - gives the writer with given ID
	GetWriter(uniqueID string) (writer Writer)
}

Logger - interface that defines a logger implementation

type LoggerConfig

type LoggerConfig struct {
	Logger      Logger
	LogConsole  bool
	FilterLevel Level
}

LoggerConfig - configuration that is used to initialize the logger

type M

type M map[string]interface{}

M - map of string to any

type MatchStrategy

type MatchStrategy string

MatchStrategy - strategy to match multiple fields passed as part of the filters

const MatchAll MatchStrategy = "all"

MatchAll - match all provided values while executing filter

const MatchNone MatchStrategy = "none"

MatchNone - match values that are not part of the provided list while executing filter

const MatchOne MatchStrategy = "one"

MatchOne - match atleast one of the provided values while executing filter

type Matcher

type Matcher struct {
	Strategy MatchStrategy `json:"strategy" db:"strategy"`
	Fields   []interface{} `json:"fields" db:"fields"`
}

Matcher - matches the given fields. If multiple fileds are given the; the joining condition is decided by the MatchStrategy given

type Module

type Module struct {
	Name         string              `json:"name" db:"name"`
	Description  string              `json:"desc" db:"desc"`
	Endpoints    []*Endpoint         `json:"endpoints" db:"endpoints"`
	ItemHandlers []StoredItemHandler `json:"itemHandlers" db:"item_handlers"`
	Commands     []*cli.Command
	Initialize   ModuleConfigFunc
	Setup        ModuleConfigFunc
	Reset        ModuleConfigFunc
}

Module - represents an application module

type ModuleConfigFunc

type ModuleConfigFunc func(gtx context.Context, app *App) (err error)

ModuleConfigFunc Signature used by functions that are used to configure a module. Some config callbacks include - initialize, setup, reset etc

type NoOpAuditor

type NoOpAuditor struct{}

NoOpAuditor - doesnt do anything, it's a dummy auditor

func (*NoOpAuditor) CleanData

func (n *NoOpAuditor) CleanData() (err error)

CleanData - there's nothing to clean

func (*NoOpAuditor) CreateIndices

func (n *NoOpAuditor) CreateIndices() (err error)

CreateIndices - creates nothing

func (*NoOpAuditor) GetEvents

func (n *NoOpAuditor) GetEvents(
	offset, limit int, filter *Filter) (
	total int, events []*Event, err error)

GetEvents - gives an empty list of events

func (*NoOpAuditor) LogEvent

func (n *NoOpAuditor) LogEvent(event *Event)

LogEvent - logs event to console

type Pair

type Pair struct {
	Key   string `json:"key" db:"key"`
	Value string `json:"value" db:"value"`
}

Pair - association of key and value

type Param

type Param struct {
	Name    string      `json:"name" db:"name"`
	Type    ParamType   `json:"type" db:"type"`
	Desc    string      `json:"desc" db:"desc"`
	Range   Range       `json:"range" db:"range"`
	Choices []Pair      `json:"choices" db:"choices"`
	Default interface{} `json:"def" db:"def"`
}

Param - represents generic parameter

type ParamType

type ParamType int

ParamType - type of the parameter

const (
	//Bool - bool parameter
	Bool ParamType = iota

	//NumberRange - number range parameter
	NumberRange

	//Choice - parameter with choices
	Choice

	//Text - arbitrary string
	Text
)

type PropMatcher

type PropMatcher []interface{}

PropMatcher - matches props

type Range

type Range struct {
	Min int `json:"min" db:"min"`
	Max int `json:"max" db:"max"`
}

Range - integer range

type Result

type Result struct {
	Status int         `json:"status"`
	Op     string      `json:"op"`
	Msg    string      `json:"msg"`
	OK     bool        `json:"ok"`
	Err    string      `json:"error"`
	Data   interface{} `json:"data"`
}

Result - result of an API call

type ResultReader

type ResultReader struct {
	RawData []byte
	Err     error
	Res     Result
}

ResultReader - proto result, use it to read the Result with proper data struct

func NewResultReader

func NewResultReader(r *http.Response) (reader *ResultReader)

NewResultReader - creates a new result-reader from response body

func (*ResultReader) Finish

func (rr *ResultReader) Finish() (err error)

Finish - decodes the server response and returns error if it failed. Use this method if data is not expected from server call

func (*ResultReader) Read

func (rr *ResultReader) Read(data interface{}) (err error)

Read - read result data from reader. The provided data object will be populatd with result's data field

type SM

type SM map[string]string

SM - map of string to string

type Session

type Session struct {
	UserID   string    `json:"userID"`
	UserName string    `json:"userName"`
	UserType string    `json:"userType"`
	Valid    bool      `json:"valid"`
	Role     AuthLevel `json:"role"`
}

Session - container for retrieving session & user information from JWT

func RetrieveSessionInfo

func RetrieveSessionInfo(ctx echo.Context) (uinfo Session, err error)

RetrieveSessionInfo - retrieves session information from JWT token

type StoredItemHandler

type StoredItemHandler interface {
	DataType() string
	UniqueKeyField() string
	GetKey(item interface{}) interface{}
	SetModInfo(item interface{}, at time.Time, by string)
	CreateInstance(by string) interface{}
	PropNames() []string
}

StoredItemHandler - needs to be implemented for any data type that is expected to work with generic crud system

func GetItemHandler

func GetItemHandler(dtype string) StoredItemHandler

GetItemHandler - get the item handler for given data type

type User

type User struct {
	UserID     string      `json:"userID" db:"userID"`
	Email      string      `json:"email" db:"email"`
	Auth       AuthLevel   `json:"auth" db:"auth"`
	FirstName  string      `json:"firstName" db:"first_name"`
	LastName   string      `json:"lastName" db:"last_name"`
	Title      string      `json:"title" db:"title"`
	FullName   string      `json:"fullName" db:"full_name"`
	State      UserState   `json:"state" db:"state"`
	VerID      string      `json:"ver_id" db:"ver_id"`
	PwdExpiry  time.Time   `json:"pwdExpiry" db:"pwd_expiry"`
	CreatedAt  time.Time   `json:"createdAt" db:"created_at"`
	CreatedBy  string      `json:"createdBy" db:"created_by"`
	ModifiedAt time.Time   `json:"modifiedAt" db:"modified_at"`
	ModifiedBy string      `json:"modifiedBy" db:"modified_by"`
	VerfiedAt  time.Time   `json:"verifiedAt" db:"verified_at"`
	Props      interface{} `json:"props,omitempty" db:"props,omitempty"`
}

User - represents an user

func DefaultAuthenticator

func DefaultAuthenticator(gtx context.Context, params map[string]interface{}) (
	user *User, err error)

DefaultAuthenticator - authenticator that uses applications UserStorage to authenticate a user

func DoLogin

func DoLogin(
	gtx context.Context, userID string, password string) (*User, error)

DoLogin - performs login using username and password

func NoOpAuthenticator

func NoOpAuthenticator(
	gtx context.Context, params map[string]interface{}) (*User, error)

NoOpAuthenticator - authenticator that does not do anything

type UserHandler

type UserHandler struct{}

UserHandler - CRUD support for User data type

func (*UserHandler) CreateInstance

func (uh *UserHandler) CreateInstance(by string) interface{}

CreateInstance - create instance of the data type for which the handler is written

func (*UserHandler) DataType

func (uh *UserHandler) DataType() string

DataType - type of data for which this handler is written

func (*UserHandler) GetKey

func (uh *UserHandler) GetKey(item interface{}) interface{}

GetKey - get the uniquely identifying key for the given item

func (*UserHandler) PropNames

func (uh *UserHandler) PropNames() []string

PropNames - get prop names of Users

func (*UserHandler) SetModInfo

func (uh *UserHandler) SetModInfo(item interface{}, at time.Time, by string)

SetModInfo - set the modifincation information for the data

func (*UserHandler) UniqueKeyField

func (uh *UserHandler) UniqueKeyField() string

UniqueKeyField - gives the field which uniquely identifies the user

type UserState

type UserState string

UserState - state of the user account

var Active UserState = "active"

Active - user is active

var Disabled UserState = "disabled"

Disabled - user account is disabled by an admin

var Flagged UserState = "flagged"

Flagged - user account is flagged by a user

var Verfied UserState = "verified"

Verfied - user account is verified by the user

type UserStorage

type UserStorage interface {
	//CreateUser - creates user in database, returns the has of the user ID
	// This returns hash of the user ID which should be used for subsequent
	// uses
	CreateUser(gtx context.Context, user *User) (idHash string, err error)

	//UpdateUser - updates user in database
	UpdateUser(gtx context.Context, user *User) (err error)

	//DeleteUser - deletes user with given user ID
	DeleteUser(gtx context.Context, userID string) (err error)

	//GetUser - gets details of the user corresponding to ID
	GetUser(gtx context.Context, userID string) (user *User, err error)

	//GetAllUsers - gets all users based on offset and limit
	GetUsers(
		gtx context.Context,
		offset,
		limit int64,
		filter *Filter) (users []*User, err error)

	//GetCount - gives the number of user selected by given filter
	GetCount(gtx context.Context, filter *Filter) (count int64, err error)

	//GetUsersWithCount - gives a list of users paged with total count
	GetUsersWithCount(
		gtx context.Context,
		offset,
		limit int64,
		filter *Filter) (total int64, users []*User, err error)

	//ResetPassword - sets password of a unauthenticated user
	ResetPassword(
		gtx context.Context, userID, oldPwd, newPwd string) (err error)

	//SetPassword - sets password of a already authenticated user, old password
	//is not required
	SetPassword(gtx context.Context, userID, newPwd string) (err error)

	//ValidateUser - validates user ID and password
	ValidateUser(gtx context.Context, userID, password string) (err error)

	//GetUserAuthLevel - gets user authorization level
	GetUserAuthLevel(gtx context.Context, userID string) (
		level AuthLevel, err error)

	//SetAuthLevel - sets the auth level for the user
	SetAuthLevel(gtx context.Context, userID string, authLevel AuthLevel) (err error)

	//SetUserState - sets state of an user account
	SetUserState(gtx context.Context, userID string, state UserState) (err error)

	//VerifyUser - sets state of an user account to verified based on userID
	//and verification ID
	VerifyUser(gtx context.Context, userID, verID string) (err error)

	//UpdateProfile - updates user details - this should be used when user
	//logged in is updating own user account
	UpdateProfile(gtx context.Context, user *User) (err error)
}

UserStorage - interface representing strategy to store and manage user information

func GetUserStorage

func GetUserStorage() UserStorage

GetUserStorage - get the configured user storage

type Version

type Version struct {
	Major int `json:"major" db:"major"`
	Minor int `json:"minor" db:"minor"`
	Patch int `json:"patch" db:"patch"`
}

Version - represents version of the application

func Ver

func Ver(major, minor, patch int) Version

Ver - quick and dirty way to create a version object

func (Version) String

func (v Version) String() string

String - version to string

type VisitorFunc

type VisitorFunc func(state *WalkerState) (cont bool)

VisitorFunc - function that will be called on each value of reflected type. The return value decides whether to continue with depth search in current branch

type WalkConfig

type WalkConfig struct {
	Visitor            VisitorFunc        //visitor function
	FieldNameRetriever FieldNameRetriever //func to get name from struct field
	MaxDepth           int                //Stop walk at this depth
	IgnoreContainers   bool               //Ignore slice and map parent objects
	VisitPrivate       bool               //Visit private fields
	VisitRootStruct    bool               //Visit the root struct thats passed
}

WalkConfig - determines how Walk is carried out

type WalkerState

type WalkerState struct {
	Depth   int
	Field   *reflect.StructField
	Path    string
	Parent  *reflect.Value
	Current *reflect.Value
}

WalkerState - current state of the walk

type Writer

type Writer interface {
	UniqueID() string
	Write(message string)
	Enable(value bool)
	IsEnabled() (value bool)
}

Writer - interface that takes a message and writes it based on the implementation

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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