router

package
v0.0.0-...-4518a5d Latest Latest
Warning

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

Go to latest
Published: May 17, 2019 License: Apache-2.0 Imports: 11 Imported by: 1

Documentation

Index

Constants

View Source
const KeyForReqHeaderEditorToken = "X-Custom-Editor-Token"

KeyForReqHeaderEditorToken key untuk editor token. token untuk mengindari double submit

Variables

View Source
var CORSAllowedPaths = make(map[string][]string)

CORSAllowedPaths path yang di injinkan cors

View Source
var DefaultEditorTokenValidationChecker = func(editorToken string, username string, objectName string, businessObjectName string, db *gorm.DB, baseLogEntry *log.Entry, req *http.Request) (ok bool, errorCode string, errFinal error) {
	if len(editorToken) == 0 {
		return false, "TOKEN_PARAM_EMPTY", fmt.Errorf("Token parameter was not found on the request")
	}
	if len(username) == 0 {
		return false, "USERNAME_EMPTY", fmt.Errorf("Username was not found on request.this request is not allowed")
	}
	logEntry := baseLogEntry.WithField("editorToken", editorToken)

	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		errFinal = err
		errorCode = "START_DB_TRANSACTION_FAILED"
		logEntry.WithError(err).Errorf("Unable to start database transaction , reported error: %s", err.Error())
		return
	}
	var theToken coremodel.EditDataToken
	dbRead := tx.Where(&coremodel.EditDataToken{Token: editorToken}).First(&theToken)
	if dbRead.RowsAffected == 0 {
		errMsg := fmt.Sprintf(MessageTemplateUnableToFindEditorToken, editorToken)
		logEntry.Errorf(errMsg)
		tx.Rollback()
		return false, "TOKEN_NOT_FOUND", fmt.Errorf(errMsg)
	}

	if theToken.ActiveFlag != "Y" {
		errorCode = "TOKEN_NOT_ACTIVE"
		errMsg := fmt.Sprintf(MessageTemplateEditorTokenNotActive, editorToken)
		logEntry.Errorf(errMsg)
		errFinal = fmt.Errorf(errMsg)
		tx.Rollback()
		return
	}
	if theToken.CreatedAt == nil {
		logEntry.Errorf("Token[%s]created at is null. ignored", editorToken)
		errorCode = "TOKEN_EXPIRED"
		errMsg := fmt.Sprintf(MessageTemplateEditorTokenExpired, editorToken)
		logEntry.Errorf(errMsg)
		errFinal = fmt.Errorf(errMsg)
		tx.Rollback()
		return
	}
	if duration := int32(time.Since(*theToken.CreatedAt).Seconds()); duration > MaxEditorTokenAgeSecond {
		logEntry.Errorf("Token[%s]Max duration is %d. token duration is %d", editorToken, MaxEditorTokenAgeSecond, duration)
		errorCode = "TOKEN_EXPIRED"
		errMsg := fmt.Sprintf(MessageTemplateEditorTokenExpired, editorToken)
		logEntry.Errorf(errMsg)
		errFinal = fmt.Errorf(errMsg)
		tx.Rollback()
		return
	}
	theToken.ActiveFlag = "N"
	skr := time.Now()
	if errUpd := tx.Save(theToken).Error; errUpd != nil {
		tx.Rollback()
		errFinal = errUpd
		logEntry.WithError(errUpd).Errorf("Fail to update token for id %s, reported error : %s", editorToken, errUpd.Error())
		errorCode = "FAIL_UPDATE_TOKEN_DATA"
		tx.Rollback()
		return
	}
	theToken.UpdatedAt = &(skr)
	errFinal = tx.Commit().Error
	ok = true
	return
}

DefaultEditorTokenValidationChecker default checker for editor token valid state Parameters: - username = username current request. this will be cross check to token owner

View Source
var DefaultGetterEditorToken = GetEditorTokenOnRequestHeader

DefaultGetterEditorToken default get editor token

View Source
var MaxEditorTokenAgeSecond = int32(900)

MaxEditorTokenAgeSecond max duration of editor token(in seconds),default = 15 minutes( 900 secons)

View Source
var MessageTemplateEditorTokenExpired = "Editor token (%s) already expired. You need to re-open the data "

MessageTemplateEditorTokenExpired template for message token exceed duration

View Source
var MessageTemplateEditorTokenNotActive = "Editor token (%s) is not active. This request probably is double submit "

MessageTemplateEditorTokenNotActive templae message for token not flag active

View Source
var MessageTemplateUnableToFindEditorToken = "Unable to find token with id: %s "

MessageTemplateUnableToFindEditorToken template message for token not found passed parameter: - index 0 = id of token

Functions

func AppendAllowedRequestHeader

func AppendAllowedRequestHeader(headerKey string)

AppendAllowedRequestHeader add allowed key to header

func AssignCustomDaoAndLoggerAttributeGenerator

func AssignCustomDaoAndLoggerAttributeGenerator(f CustomDaoAndLoggerAttributeGeneratorFunction)

AssignCustomDaoAndLoggerAttributeGenerator replace custom dao attribute generator for example on multi tenant database, you need to set user data with user schema name

func AssignDefaultLoggerPredefinedParameterFiller

func AssignDefaultLoggerPredefinedParameterFiller(f LoggerPredefinedParameterFiller)

AssignDefaultLoggerPredefinedParameterFiller replace log entry filler

func AssignFlushLogCommand

func AssignFlushLogCommand(command func())

AssignFlushLogCommand assign flush log command

func GetEditorTokenOnRequestHeader

func GetEditorTokenOnRequestHeader(logEntry *log.Entry, req *http.Request) (editorToken string)

GetEditorTokenOnRequestHeader getter editor token on request header. The key for editor token is specified on variable KeyForReqHeaderEditorToken

func RegisterAllowedCORDomain

func RegisterAllowedCORDomain(domains ...string)

RegisterAllowedCORDomain register domain to allowed cors

func RegisterAllowedCORDomains

func RegisterAllowedCORDomains(domains []string)

RegisterAllowedCORDomains register domain to allowed cors

func RegisterDeleteJSONHandler

func RegisterDeleteJSONHandler(param RegisterDeleteJSONHandlerParam) *mux.Route

RegisterDeleteJSONHandler register method delete

func RegisterGetJSONHandler

func RegisterGetJSONHandler(param RegisterGetJSONHandlerParam) *mux.Route

RegisterGetJSONHandler register get handler

func RegisterPostJSONHandler

func RegisterPostJSONHandler(param RegisterPostJSONHandlerParameter) *mux.Route

RegisterPostJSONHandler register post route handler routePath = path of route to serve

func RegisterPutJSONHandler

func RegisterPutJSONHandler(param RegisterPutJSONHandlerParam) *mux.Route

RegisterPutJSONHandler register put http handler

func RegisterRouteHandlers

func RegisterRouteHandlers(routeParameter Parameter, routeManager HandlerManagerFunction)

RegisterRouteHandlers register semua handlers pada maanager

func SetDisableGzipResponse

func SetDisableGzipResponse(disable bool)

SetDisableGzipResponse disable/enable gzip response

Types

type CustomDaoAndLoggerAttributeGeneratorFunction

type CustomDaoAndLoggerAttributeGeneratorFunction func(executionID string, routePath string, req *http.Request, routeParameter Parameter, username string, userUUID string, baseLogEntry *log.Entry) (logEntry *log.Entry, daoAttribute map[string]interface{})

CustomDaoAndLoggerAttributeGeneratorFunction used for var customDaoAndLoggerAttributeGenerator. this to put additional parameter on log and on dao . Log need entries to ease logging . for example on multi tenant scenario, this will put tenant id etc on data log same sample case for dao. app relied on gorm database. for case multi tenant database, table name will be prefixed with schema name for example

type DelHandlerFunction

type DelHandlerFunction func(parameter HTTPDeleteParameter) (result interface{}, error common.ErrorWithCodeData)

DelHandlerFunction handler http delete request

type DeleteRouterDefinition

type DeleteRouterDefinition struct {
	//RoutePath path route
	RoutePath string
	//Secured flag secured request atau tidak
	Secured bool
	//DisableGzip disable gzip response. per request. ini bisa di override pada level app
	DisableGzip bool
	//Handler request handler
	Handler DelHandlerFunction

	//DoNotAllowCORS default false, set to true to disable CORS for this path ( post)
	DoNotAllowCORS bool
	//CheckForDoubleSubmit check for request that double submit. scan by editor token data
	CheckForDoubleSubmit *NeedDoubleSubmitProtectionDefinition
}

DeleteRouterDefinition handler http delete request

type EditorTokenValidationCheckerFunction

type EditorTokenValidationCheckerFunction func(editorToken string, username string, objectName string, businessObjectName string, db *gorm.DB, logEntry *log.Entry, req *http.Request) (ok bool, errorCode string, err error)

EditorTokenValidationCheckerFunction checker for double submit method will check to table is key exists , expired or not - objectName is model name. technical name to be compare on checking token. token to edit must came same as data token on db - businessObjectName business name of object. to notify user what wrong

type GetEditorTokenFunction

type GetEditorTokenFunction func(logEntry *log.Entry, req *http.Request) (editorToken string)

GetEditorTokenFunction defintion of method to get editor data token. will be used to stop double submit on form data

type GetHandlerFunction

type GetHandlerFunction func(parameter HTTPGetParameter) (result interface{}, error common.ErrorWithCodeData)

GetHandlerFunction route handler function

type GetRouterDefinition

type GetRouterDefinition struct {
	//RoutePath path route
	RoutePath string
	//Secured flag secured request atau tidak
	Secured bool
	//DisableGzip disable gzip response. per request. ini bisa di override pada level app
	DisableGzip bool
	//Handler request handler
	Handler GetHandlerFunction

	//DoNotAllowCORS default false, set to true to disable CORS for this path ( post)
	DoNotAllowCORS bool
	//CheckForDoubleSubmit check for request that double submit. scan by editor token data
	CheckForDoubleSubmit *NeedDoubleSubmitProtectionDefinition
}

GetRouterDefinition definisi route

type HTTPCommonParameter

type HTTPCommonParameter struct {
	//Username username dari current
	Username string
	//UserUUID auth user uuid(firebase thing)
	UserUUID string
	//IPAddress ip address current user
	IPAddress string
	//RequestPath path request
	RequestPath string
	//RawRequest raw reqest parameter
	RawRequest *http.Request
	//DatabaseReference reference to GORM
	DatabaseReference *gorm.DB
	//LogEntry log entry untuk kemudahan logging. common item di inject di awal
	LogEntry *log.Entry
	//PathParameters parameter dalam path. misal path = /alpha/{omega}, parameter omega akan di taruh dalam map
	PathParameters map[string]string
}

HTTPCommonParameter common http parameter

type HTTPDeleteParameter

type HTTPDeleteParameter struct {
	HTTPCommonParameter
}

HTTPDeleteParameter parameter for delete

type HTTPGetParameter

type HTTPGetParameter struct {
	HTTPCommonParameter
}

HTTPGetParameter parameter for http( GET)

type HTTPPostParameter

type HTTPPostParameter struct {
	HTTPCommonParameter
}

HTTPPostParameter parameter for post method

type HTTPPutParameter

type HTTPPutParameter struct {
	HTTPCommonParameter
}

HTTPPutParameter parameter for put request

type HandlerManagerFunction

type HandlerManagerFunction func() (getHandlers []GetRouterDefinition, postHandlers []PostRouterDefinition, putHandlers []PutRouterDefinition, delHandlers []DeleteRouterDefinition)

HandlerManagerFunction producer route handler. untuk register route

type LoggerPredefinedParameterFiller

type LoggerPredefinedParameterFiller func(executionID string, routePath string, req *http.Request, routeParameter Parameter, username string, userUUID string, logEntry *log.Entry) (modifiedLogEntry *log.Entry)

LoggerPredefinedParameterFiller filler log data. for generic logger data filler

type LoginInformationProviderFunction

type LoginInformationProviderFunction func(DatabaseReference *gorm.DB, logEntry *log.Entry, req *http.Request) (userData common.SimpleUserData, err common.ErrorWithCodeData)

LoginInformationProviderFunction login handler definition

type NeedDoubleSubmitProtectionDefinition

type NeedDoubleSubmitProtectionDefinition struct {
	//ObjectName object name(mostly model name of top level model name)
	ObjectName string
	//BusinessObjectName business name of object
	BusinessObjectName string
	//CustomChecker if checker need custom check. for example custom name etc. this use to override definition
	CustomChecker *EditorTokenValidationCheckerFunction
}

NeedDoubleSubmitProtectionDefinition definition of route that need double submit protection

type Parameter

type Parameter struct {
	//CORSEnabledDomains domain yang di ijinkan CORS
	CORSEnabledDomains []string
	//DatabaseReference reference to GORM
	DatabaseReference *gorm.DB
	//MuxRouter mux router untuk register path
	MuxRouter *mux.Router
	//LoginInformationProvider provider logi information
	LoginInformationProvider LoginInformationProviderFunction
}

Parameter register route parameter

func (*Parameter) Clone

func (p *Parameter) Clone(db *gorm.DB) (cloneResult Parameter)

Clone clone data except for database reference

type PostHandlerFunction

type PostHandlerFunction func(parameter HTTPPostParameter) (result interface{}, error common.ErrorWithCodeData)

PostHandlerFunction handler http post request

type PostRouterDefinition

type PostRouterDefinition struct {
	//RoutePath path route
	RoutePath string
	//Secured flag secured request atau tidak
	Secured bool
	//DisableGzip disable gzip response. per request. ini bisa di override pada level app
	DisableGzip bool
	//Handler request handler
	Handler PostHandlerFunction

	//DoNotAllowCORS default false, set to true to disable CORS for this path ( post)
	DoNotAllowCORS bool
	//CheckForDoubleSubmit check for request that double submit. scan by editor token data
	CheckForDoubleSubmit *NeedDoubleSubmitProtectionDefinition
}

PostRouterDefinition definisi post router

type PutHandlerFunction

type PutHandlerFunction func(parameter HTTPPutParameter) (result interface{}, error common.ErrorWithCodeData)

PutHandlerFunction handler http put function

type PutRouterDefinition

type PutRouterDefinition struct {
	//RoutePath path route
	RoutePath string
	//Secured flag secured request atau tidak
	Secured bool
	//DisableGzip disable gzip response. per request. ini bisa di override pada level app
	DisableGzip bool
	//Handler request handler
	Handler PutHandlerFunction

	//DoNotAllowCORS default false, set to true to disable CORS for this path ( post)
	DoNotAllowCORS bool
	//CheckForDoubleSubmit check for request that double submit. scan by editor token data
	CheckForDoubleSubmit *NeedDoubleSubmitProtectionDefinition
}

PutRouterDefinition definisi http put method

type RegisterDeleteJSONHandlerParam

type RegisterDeleteJSONHandlerParam struct {
	//route data
	RouteParameter Parameter
	//RoutePath path of route
	RoutePath string
	//DisableGzip disable gzip response. per request. ini bisa di override pada level app
	DisableGzip bool
	//Secured secured flag. if no user then request is rejected
	Secured bool
	//DoNotAllowCORS default false, set to true to disable CORS for this path ( post)
	DoNotAllowCORS bool
	//Handler handler post task
	Handler DelHandlerFunction
	///CheckForDoubleSubmit check for request that double submit. scan by editor token data
	CheckForDoubleSubmit *NeedDoubleSubmitProtectionDefinition
}

RegisterDeleteJSONHandlerParam parameter JSON delete

type RegisterGetJSONHandlerParam

type RegisterGetJSONHandlerParam struct {
	//RouteParameter param route
	RouteParameter Parameter
	//RoutePath path route
	RoutePath string
	//Secured flag secured request atau tidak
	Secured bool
	//DisableGzip disable gzip response. per request. ini bisa di override pada level app
	DisableGzip bool
	//Handler request handler
	Handler GetHandlerFunction

	//DoNotAllowCORS default false, set to true to disable CORS for this path ( post)
	DoNotAllowCORS bool
	//CheckForDoubleSubmit check for request that double submit. scan by editor token data
	CheckForDoubleSubmit *NeedDoubleSubmitProtectionDefinition
}

RegisterGetJSONHandlerParam Param get

type RegisterPostJSONHandlerParameter

type RegisterPostJSONHandlerParameter struct {
	//route data
	RouteParameter Parameter
	//RoutePath path of route
	RoutePath string
	//Secured secured flag. if no user then request is rejected
	Secured bool
	//DisableGzip disable gzip response. per request. ini bisa di override pada level app
	DisableGzip bool
	//Handler handler post task
	Handler PostHandlerFunction

	//DoNotAllowCORS default false, set to true to disable CORS for this path ( post)
	DoNotAllowCORS bool
	//CheckForDoubleSubmit check for request that double submit. scan by editor token data
	CheckForDoubleSubmit *NeedDoubleSubmitProtectionDefinition
}

RegisterPostJSONHandlerParameter parameter post

type RegisterPutJSONHandlerParam

type RegisterPutJSONHandlerParam struct {
	//route data
	RouteParameter Parameter
	//RoutePath path of route
	RoutePath string
	//Secured secured flag. if no user then request is rejected
	Secured bool
	//DisableGzip disable gzip response. per request. ini bisa di override pada level app
	DisableGzip bool
	//Handler handler put task
	Handler func(parameter HTTPPutParameter) (interface{}, common.ErrorWithCodeData)
	//DoNotAllowCORS default false, set to true to disable CORS for this path ( post)
	DoNotAllowCORS bool
	//CheckForDoubleSubmit check for request that double submit. scan by editor token data
	CheckForDoubleSubmit *NeedDoubleSubmitProtectionDefinition
}

RegisterPutJSONHandlerParam parameter put

type ResultJSONOKWrapper

type ResultJSONOKWrapper struct {
	HaveError bool        `json:"haveError"`
	Data      interface{} `json:"data"`
}

ResultJSONOKWrapper wrapper for result OK

type RouteLoggerPredefinedParameterFiller

type RouteLoggerPredefinedParameterFiller func(executionID string, routePath string, req *http.Request, routeParameter Parameter, username string, userUUID string, logEntry *log.Entry) (modifiedLogEntry *log.Entry)

RouteLoggerPredefinedParameterFiller parameter filler custom. ini mungkin akan spesifik pada app. executionID = id eksekusi. dalam kasus dengan cloud function ini akan di isi dengan id dari function routePath = path of handled http

Jump to

Keyboard shortcuts

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