Documentation ¶
Index ¶
- Constants
- func AddEndpoint(ep *Endpoint)
- func AddEndpoints(eps ...*Endpoint)
- func AskPassword(name string) (secret string)
- func AuditedSend(ctx echo.Context, res *Result) (err error)
- func AuditedSendSecret(ctx echo.Context, res *Result) (err error)
- func AuditedSendX(ctx echo.Context, data interface{}, res *Result) (err error)
- func Debug(module, fmtStr string, args ...interface{})
- func Decrypt(key []byte, text string) (decrypted string, err error)
- func DecryptStr(key string, text string) (decrypted string, err error)
- func DefMS(oprn string) (int, string)
- func DumpJSON(o interface{})
- func Encrypt(key []byte, text string) (encrypted string, err error)
- func EncryptStr(key string, text string) (encrypted string, err error)
- func ErrString(err error) string
- func Error(module, fmtStr string, args ...interface{}) (err error)
- func ExistsAsDir(path string) (yes bool)
- func ExistsAsFile(path string) (yes bool)
- func Fatal(module, fmtStr string, args ...interface{})
- func FirstValid(errs ...error) (err error)
- func GetAsJSON(o interface{}) (jstr string, err error)
- func GetConfig(key string, value interface{}) (found bool)
- func GetExecDir() (dirPath string)
- func GetFirstValidStr(strs ...string) (str string)
- func GetJWTKey() []byte
- func GetOffsetLimit(ctx echo.Context) (offset, limit int64, has bool)
- func GetQueryParam(ctx echo.Context, name string, def string) (val string)
- func GetRootPath() string
- func GetServiceStartCmd(serveFunc func(port int) error) *cli.Command
- func GetString(ctx echo.Context, key string) (value string)
- func GetStringConfig(key string) (value string)
- func GetToken(ctx echo.Context) (token *jwt.Token, err error)
- func GetUserIDPassword(params map[string]interface{}) (userID string, password string, err error)
- func HasConfig(key string) (yes bool)
- func HasError(module string, errs ...error) (has bool)
- func Hash(in string) (out string)
- func Info(module, fmtStr string, args ...interface{})
- func InitLogger(lc LoggerConfig)
- func InitServer(rootName string, apiVersion int)
- func IsAdmin(ctx echo.Context) (yes bool)
- func IsBasicType(rt reflect.Kind) bool
- func IsNormalUser(ctx echo.Context) (yes bool)
- func IsSuperUser(ctx echo.Context) (yes bool)
- func IsTime(val *reflect.Value) bool
- func LoadConfig(appName string)
- func LoadJSONFromArgs(ctx echo.Context, param string, out interface{}) (err error)
- func LogError(module string, err error) error
- func LogErrorX(module, msg string, err error, args ...interface{}) error
- func LogEvent(op string, userID string, userName string, success bool, err string, ...)
- func LogFatal(module string, err error)
- func LogJSON(level Level, module string, data interface{})
- func MergeCommands(cmdss ...[]*cli.Command) []*cli.Command
- func ModifiedHTTPErrorHandler(err error, c echo.Context)
- func Print(module, fmtStr string, args ...interface{})
- func PrintConfig()
- func SendAndAuditOnErr(ctx echo.Context, res *Result) (err error)
- func SendEmail(to, subject, meesage string) (err error)
- func SendVerificationMail(user *User) (err error)
- func Serve(port int) (err error)
- func SetEventAuditor(auditor EventAuditor)
- func SetLevel(level Level)
- func SetUserStorage(storage UserStorage)
- func ToFlatMap(obj interface{}, tagName string) (out map[string]interface{})
- func ToString(level Level) string
- func Trace(module, fmtStr string, args ...interface{})
- func UpdateUserInfo(user *User) (err error)
- func Walk(obj interface{}, config *WalkConfig)
- func Warn(module, fmtStr string, args ...interface{})
- type App
- func (app *App) AddModule(module *Module)
- func (app *App) Exec(gtx context.Context, args []string) (err error)
- func (app *App) FromAppDir(relPath string) (abs string)
- func (app *App) Init(gtx context.Context, admin *User, adminPass string, param M) (err error)
- func (app *App) Reset(gtx context.Context) (err error)
- func (app *App) Setup(gtx context.Context) (err error)
- type ArgGetter
- func (retriever *ArgGetter) GetIntOr(key string, def int) (val int)
- func (retriever *ArgGetter) GetOptionalInt(key string) (val int)
- func (retriever *ArgGetter) GetOptionalSecret(key string) (val string)
- func (retriever *ArgGetter) GetOptionalString(key string) (val string)
- func (retriever *ArgGetter) GetRequiredInt(key string) (val int)
- func (retriever *ArgGetter) GetRequiredSecret(key string) (val string)
- func (retriever *ArgGetter) GetRequiredString(key string) (val string)
- func (retriever *ArgGetter) GetSecretOr(key, def string) (val string)
- func (retriever *ArgGetter) GetStringOr(key, def string) (val string)
- type AsyncLogger
- type AuthLevel
- type Authenticator
- type Authorizer
- type BinderFunc
- type Client
- func (client *Client) CreateURL(access AuthLevel, args ...string) (str string)
- func (client *Client) Delete(access AuthLevel, urlArgs ...string) (rr *ResultReader)
- func (client *Client) Get(access AuthLevel, urlArgs ...string) (rr *ResultReader)
- func (client *Client) Login(userID, password string) (err error)
- func (client *Client) Post(content interface{}, access AuthLevel, urlArgs ...string) (rr *ResultReader)
- func (client *Client) Put(content interface{}, access AuthLevel, urlArgs ...string) (rr *ResultReader)
- type ConsoleWriter
- type CountList
- type DataStorage
- type DateRange
- type DirectLogger
- type EmailConfig
- type Endpoint
- type Event
- type EventAuditor
- type FieldNameRetriever
- type Filter
- type FilterSpec
- type FilterSpecList
- type FilterType
- type FilterVal
- type Group
- type Level
- type Logger
- type LoggerConfig
- type M
- type MatchStrategy
- type Matcher
- type Module
- type ModuleConfigFunc
- type NoOpAuditor
- type Pair
- type Param
- type ParamType
- type PropMatcher
- type Range
- type Result
- type ResultReader
- type SM
- type Session
- type StoredItemHandler
- type User
- type UserHandler
- func (uh *UserHandler) CreateInstance(by string) interface{}
- func (uh *UserHandler) DataType() string
- func (uh *UserHandler) GetKey(item interface{}) interface{}
- func (uh *UserHandler) PropNames() []string
- func (uh *UserHandler) SetModInfo(item interface{}, at time.Time, by string)
- func (uh *UserHandler) UniqueKeyField() string
- type UserState
- type UserStorage
- type Version
- type VisitorFunc
- type WalkConfig
- type WalkerState
- type Writer
Constants ¶
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 AddEndpoints ¶
func AddEndpoints(eps ...*Endpoint)
AddEndpoints - registers multiple REST categories
func AskPassword ¶
AskPassword - asks password, prints the given name before asking
func AuditedSend ¶
AuditedSend - sends result as JSON while logging it as event. The event data is same as the data present in the result
func AuditedSendSecret ¶
AuditedSendSecret - Sends result to client and logs everything other than the secret data field
func AuditedSendX ¶
AuditedSendX - sends result as JSON while logging it as event. This method logs event data which is seperate from result data
func DecryptStr ¶
DecryptStr - AES decrypts input text with given key string
func DumpJSON ¶
func DumpJSON(o interface{})
DumpJSON - dumps JSON representation of given data to stdout
func EncryptStr ¶
EncryptStr - AES encrypts input text with given key string
func ExistsAsDir ¶
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 ¶
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 FirstValid ¶
FirstValid - returns the first error that is not nil
func GetConfig ¶
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 ¶
GetFirstValidStr - gets first string that is not empty
func GetOffsetLimit ¶
GetOffsetLimit - retrieves offset and limit as integers provided in URL as query parameters. These parameters should have name - offset and limit respectively
func GetQueryParam ¶
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 ¶
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 GetStringConfig ¶
GetStringConfig - gets a value associated with config key
func GetUserIDPassword ¶
GetUserIDPassword - gets userID and password from parameter app, if not available a error is returned
func HasError ¶
HasError - logs the errors from the array that are not nil and return true if there were one or more non nil errors
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 ¶
InitServer - initializes all the registered endpoints
func IsBasicType ¶
IsBasicType - tells if the kind of data type is basic or composite
func IsNormalUser ¶
IsNormalUser - returns true if user is a normal user
func IsSuperUser ¶
IsSuperUser - returns true if user is a super user
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 ¶
LoadJSONFromArgs - decodes argument identified by 'param' to JSON and unmarshals it into the given 'out' structure
func LogErrorX ¶
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 MergeCommands ¶
func MergeCommands(cmdss ...[]*cli.Command) []*cli.Command
MergeCommands - merge commands from different arrays to single array
func ModifiedHTTPErrorHandler ¶
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 SendAndAuditOnErr ¶
SendAndAuditOnErr - sends the result to client and puts an audit record in audit log if the result is error OR sending failed
func SendEmail ¶
SendEmail - sends an email with given information. Uses the package level variable emainConfig for SMTP configuration - smtp.gmail.com:587
func SendVerificationMail ¶
SendVerificationMail - send mail with a link to user verification based on user email
func SetEventAuditor ¶
func SetEventAuditor(auditor EventAuditor)
SetEventAuditor - sets the event auditor
func SetUserStorage ¶
func SetUserStorage(storage UserStorage)
SetUserStorage - sets the user storage strategu
func ToFlatMap ¶
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 UpdateUserInfo ¶
UpdateUserInfo - updates common user fields
func Walk ¶
func Walk( obj interface{}, config *WalkConfig)
Walk - walk a given instance of struct/slice/map/basic type
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) FromAppDir ¶
FromAppDir - gives a absolute path from a path relative to app directory
func (*App) Init ¶
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.
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 ¶
GetIntOr - retrieves string int commandline, if not found returns given default
func (*ArgGetter) GetOptionalInt ¶
GetOptionalInt - retrieves int from commandline, if not provided it wont ask again from stdin
func (*ArgGetter) GetOptionalSecret ¶
GetOptionalSecret - reads 'secret' if provided in commandline, otherwise return empty string
func (*ArgGetter) GetOptionalString ¶
GetOptionalString - retrieves string from commandline, if not provided it wont ask again from stdin
func (*ArgGetter) GetRequiredInt ¶
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 ¶
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 ¶
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 ¶
GetSecretOr - retrieves password from commandline, if not found returns given default
func (*ArgGetter) GetStringOr ¶
GetStringOr - retrieves string from commandline, if not found returns given default
type AsyncLogger ¶
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
func NoOpAuthorizer ¶
NoOpAuthorizer - authorizer that does not do anything
type Authenticator ¶
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 ¶
Authorizer - a function that will be used authorize an user
type BinderFunc ¶
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 (*Client) CreateURL ¶
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 ¶
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
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
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
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 MergeEnpoints ¶
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
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 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 )
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 ¶
LoggerConfig - configuration that is used to initialize the logger
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 ¶
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 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 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 ¶
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 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
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
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
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