Documentation
¶
Index ¶
- Constants
- func APIKeyClientIDHeader() simplehttp.MiddlewareFunc
- func AreSameTable(records []orm.DBRecord) bool
- func CopySettingsFromSureSQL(cnode suresql.SureSQLNode, config *simplehttp.Config)
- func CreateServer(cnode suresql.SureSQLNode) simplehttp.Server
- func DBLogging(db suresql.SureSQLDB, entry AccessLogTable) error
- func DecodeToken(tokenstring string, config *suresql.SureSQLDBMSConfig) (string, error)
- func HandleConnect(ctx simplehttp.Context) error
- func HandleCreateUser(ctx simplehttp.Context) error
- func HandleDBMSStatus(ctx simplehttp.Context) error
- func HandleDBStatus(ctx simplehttp.Context) error
- func HandleDeleteUser(ctx simplehttp.Context) error
- func HandleGetSchema(ctx simplehttp.Context) error
- func HandleInsert(ctx simplehttp.Context) error
- func HandleListUsers(ctx simplehttp.Context) error
- func HandleQuery(ctx simplehttp.Context) error
- func HandleRefresh(ctx simplehttp.Context) error
- func HandleSQLExecution(ctx simplehttp.Context) error
- func HandleSQLQuery(ctx simplehttp.Context) error
- func HandleUpdateUser(ctx simplehttp.Context) error
- func InitTokenMaps()
- func ListTableNames(records []orm.DBRecord) string
- func MiddlewareAPIKeyHeader() simplehttp.Middleware
- func MiddlwareTokenCheck() simplehttp.Middleware
- func RegisterInternalRoutes(server simplehttp.Server)
- func RegisterRoutes(server simplehttp.Server)
- func TokenValidationFromTTL() simplehttp.MiddlewareFunc
- type AccessLogTable
- type Credentials
- type EncryptedCredentials
- type HandlerState
- func (h *HandlerState) IsErrorLoggedInConsole() bool
- func (h *HandlerState) IsErrorLoggedInDB() bool
- func (h *HandlerState) IsSuccessLoggedInConsole() bool
- func (h *HandlerState) IsSuccessLoggedInDB() bool
- func (h *HandlerState) LogAndResponse(message string, data interface{}, logAgain bool) error
- func (h *HandlerState) OnlyLog(message string, data interface{}, restartTimer bool) error
- func (h *HandlerState) SaveStopTimer() float64
- func (h *HandlerState) SetError(msg string, err error, status int) *HandlerState
- func (h *HandlerState) SetSuccess(msg string, data interface{}) *HandlerState
- type TokenStoreStruct
- func (t TokenStoreStruct) GetAll() (map[string]interface{}, map[string]interface{})
- func (t TokenStoreStruct) RefreshTokenExist(token string) (*suresql.TokenTable, bool)
- func (t TokenStoreStruct) SaveToken(token suresql.TokenTable)
- func (t TokenStoreStruct) TokenExist(token string) (*suresql.TokenTable, bool)
- type UserTable
- type UserUpdateRequest
Constants ¶
const ( DECRYPT_FILLER = "." TOKEN_STRING = "token" TOKEN_LENGTH_MULTIPLIER = 3 // Controls token length/complexity )
Constant for auth related like token settings
const ( DEFAULT_HTTP_ENVIRONMENT = "./.env.suresql" LOG_RAW_QUERY = false // TODO : this one if on, currently only logging the results, instead of the queries. )
Define constants for token expiration and generation
const ( SUCCESS_EVENT = "success" ERROR_EVENT = "error" )
const ( API_KEY_STRING = "API_KEY" CLIENT_ID_STRING = "CLIENT_ID" TOKEN_TABLE_STRING = "token" )
const (
DEFAULT_INTERNAL_API = "/suresql"
)
Variables ¶
This section is empty.
Functions ¶
func APIKeyClientIDHeader ¶
func APIKeyClientIDHeader() simplehttp.MiddlewareFunc
func AreSameTable ¶
AreSameTable checks if all records are for the same table
func CopySettingsFromSureSQL ¶ added in v0.0.2
func CopySettingsFromSureSQL(cnode suresql.SureSQLNode, config *simplehttp.Config)
if DB settings is not there, get from environment. DB's settings table always wins
func CreateServer ¶
func CreateServer(cnode suresql.SureSQLNode) simplehttp.Server
func DecodeToken ¶
func DecodeToken(tokenstring string, config *suresql.SureSQLDBMSConfig) (string, error)
NOTE: maybe change this to just return empty string if error, then do checking if token=="" instead of error
func HandleConnect ¶
func HandleConnect(ctx simplehttp.Context) error
HandleConnect authenticates a user and returns tokens
func HandleCreateUser ¶
func HandleCreateUser(ctx simplehttp.Context) error
HandleCreateUser creates a new user in the system
func HandleDBMSStatus ¶
func HandleDBMSStatus(ctx simplehttp.Context) error
HandleGetSchema only for internal
func HandleDBStatus ¶
func HandleDBStatus(ctx simplehttp.Context) error
HandleDBStatus returns the current database status
func HandleDeleteUser ¶
func HandleDeleteUser(ctx simplehttp.Context) error
HandleDeleteUser deletes a user from the system
func HandleGetSchema ¶
func HandleGetSchema(ctx simplehttp.Context) error
HandleGetSchema only for internal
func HandleInsert ¶
func HandleInsert(ctx simplehttp.Context) error
HandleInsert processes record insertion requests
func HandleListUsers ¶
func HandleListUsers(ctx simplehttp.Context) error
HandleListUsers retrieves all users from the system (or filtered by username)
func HandleQuery ¶
func HandleQuery(ctx simplehttp.Context) error
HandleQuery processes data query requests
func HandleRefresh ¶
func HandleRefresh(ctx simplehttp.Context) error
HandleRefresh refreshes an existing token
func HandleSQLExecution ¶
func HandleSQLExecution(ctx simplehttp.Context) error
HandleSQLExecution processes SQL execution requests It is protected by both API Key (from AuthMiddleware) and Token (from TokenValidationMiddleware)
func HandleSQLQuery ¶
func HandleSQLQuery(ctx simplehttp.Context) error
HandleSQLExecution processes SQL execution requests It is protected by both API Key (from AuthMiddleware) and Token (from TokenValidationMiddleware)
func HandleUpdateUser ¶
func HandleUpdateUser(ctx simplehttp.Context) error
HandleUpdateUser updates an existing user
func InitTokenMaps ¶
func InitTokenMaps()
InitTokenMaps initializes the token maps with default TTLs
func ListTableNames ¶
Helper function to get a comma-separated list of table names NOTE: not used yet, maybe later for logging
func MiddlewareAPIKeyHeader ¶
func MiddlewareAPIKeyHeader() simplehttp.Middleware
AuthMiddleware verifies API key and client ID from request headers
func MiddlwareTokenCheck ¶
func MiddlwareTokenCheck() simplehttp.Middleware
TokenValidationMiddleware verifies that a valid token is present
func RegisterInternalRoutes ¶
func RegisterInternalRoutes(server simplehttp.Server)
Add these functions to your RegisterRoutes function in handler.go
func RegisterRoutes ¶
func RegisterRoutes(server simplehttp.Server)
RegisterRoutes sets up all the routes for the SureSQL API
func TokenValidationFromTTL ¶
func TokenValidationFromTTL() simplehttp.MiddlewareFunc
Types ¶
type AccessLogTable ¶
type AccessLogTable struct {
ID int `json:"id,omitempty" db:"id"`
Username string `json:"username,omitempty" db:"username"`
ActionType string `json:"action_type,omitempty" db:"action_type"`
Occurred time.Time `json:"occurred,omitempty" db:"occurred"`
Table string `json:"table_name,omitempty" db:"table_name"`
RawQuery string `json:"raw_query,omitempty" db:"raw_query"`
Result string `json:"result,omitempty" db:"result"`
ResultStatus string `json:"result_status,omitempty" db:"result_status"`
Error string `json:"error,omitempty" db:"error"`
Duration float64 `json:"duration,omitempty" db:"duration"`
Method string `json:"method,omitempty" db:"method"`
NodeNumber int `json:"node_number,omitempty" db:"node_number"`
Note string `json:"note,omitempty" db:"note"`
Description string `json:"description,omitempty" db:"description"`
ClientIP string `json:"client_ip,omitempty" db:"client_ip"`
ClientBrowser string `json:"client_browser,omitempty" db:"client_browser"`
ClientDevice string `json:"client_device,omitempty" db:"client_device"`
}
func (*AccessLogTable) DBLogging ¶
func (l *AccessLogTable) DBLogging(db *suresql.SureSQLDB) error
Save the logentry to log table
func (AccessLogTable) TableName ¶
func (l AccessLogTable) TableName() string
type Credentials ¶
func DecryptCredentials ¶
func DecryptCredentials(data string, apiKey, clientID string) (*Credentials, error)
type EncryptedCredentials ¶
type EncryptedCredentials struct {
Data string `json:"data"`
}
============= NOTE: this are not used at the moment, for future development where we encrypt the ============= data that is passed between request/response
If we want to encrypt the credential for DB connect, encapsulated in just a string 'data' Maybe the encrypt from client is using PGP hence the Front-END will encrypt using public key And Backend decrypt with PrivateKey, Then the encrypted "data" is SureSQLConfig json
type HandlerState ¶
type HandlerState struct {
Context simplehttp.Context
Header *simplehttp.RequestHeader // Please make sure that the HeaderParser middleware is used! If not it's nil.
Label string // This is used for logging, it's like the title/function name
User string // Mostly user that call make the request, could be also user that connect to DB?
LogMessage string // for success event logs
ErrorMessage string // for error event logs + Err?
ResponseMessage string // for handler response (API/Endpoint response)
Status int // http status usually
Err error // original error
Data interface{}
DBLogging bool
ConsoleLogging bool
DBLoggingEvent string // success,error - can be multiple. Which event is logged
ConsoleLoggingEvent string // success,error - can be multiple. Which event is logged
TableNames string // table in DB that is related, if applicable
TimerID int64 // if using timer, ie from Meda metrics
Duration float64 // if using timer, ie from Meda metrics
Token *suresql.TokenTable // for specific handlers that requires token
LogTable AccessLogTable // TODO: put them here but somewhat abstract?
}
Standardized handler state. NOTE: maybe next time move this to simplehttp. This is easier way to make end-points Which will always have: - binding the request parameter/body/file attachment? - logic - logging (optional) : can be console/log-files OR insert into DB - response back to caller
func NewHandlerState ¶
func NewHandlerState(ctx simplehttp.Context, user, label, table string) HandlerState
This is the configuration for logging for the project This is state status for basic handlers that do not require status
func NewHandlerTokenState ¶
func NewHandlerTokenState(ctx simplehttp.Context, label, table string) HandlerState
This is the state status for handlers that requires token.
func NewMiddlewareState ¶
func NewMiddlewareState(ctx simplehttp.Context, name string) HandlerState
This is the configuration for logging for the middleware
func (*HandlerState) IsErrorLoggedInConsole ¶
func (h *HandlerState) IsErrorLoggedInConsole() bool
Readibility for the state logging configuration
func (*HandlerState) IsErrorLoggedInDB ¶
func (h *HandlerState) IsErrorLoggedInDB() bool
func (*HandlerState) IsSuccessLoggedInConsole ¶
func (h *HandlerState) IsSuccessLoggedInConsole() bool
func (*HandlerState) IsSuccessLoggedInDB ¶
func (h *HandlerState) IsSuccessLoggedInDB() bool
func (*HandlerState) LogAndResponse ¶
func (h *HandlerState) LogAndResponse(message string, data interface{}, logAgain bool) error
Return response based on context, message and data is used for logging (not response) logAgain if want to run the logging once more and return (if not yet called)
func (*HandlerState) OnlyLog ¶
func (h *HandlerState) OnlyLog(message string, data interface{}, restartTimer bool) error
Implement this method according to the project logTable AND console logging Separate the Logging part and Response part (though it can be combined to make it faster) because sometimes the HandlerState is only for logging before returning anything. Like in the handler it has multiple log entries then at the end send back response
func (*HandlerState) SaveStopTimer ¶
func (h *HandlerState) SaveStopTimer() float64
Stopping the timer if not already stopped. This function is saved to be called multiple times!
func (*HandlerState) SetError ¶
func (h *HandlerState) SetError(msg string, err error, status int) *HandlerState
For chaining calls, this message in parameter is used for response
func (*HandlerState) SetSuccess ¶
func (h *HandlerState) SetSuccess(msg string, data interface{}) *HandlerState
For chaining calls, this message parameter is for response
type TokenStoreStruct ¶
type TokenStoreStruct struct {
TokenMap *medattlmap.TTLMap // For access tokens
RefreshTokenMap *medattlmap.TTLMap // For refresh tokens
}
Mini Redis like Key-Value storage based on MedaTTLMap
var ( // Instead of Redis, we use ttlmap is lighter // TokenMap *medattlmap.TTLMap // For access tokens // RefreshTokenMap *medattlmap.TTLMap // For refresh tokens TokenStore TokenStoreStruct )
Global variables
func NewTokenStore ¶
func NewTokenStore(exp, rexp time.Duration) TokenStoreStruct
func (TokenStoreStruct) GetAll ¶
func (t TokenStoreStruct) GetAll() (map[string]interface{}, map[string]interface{})
func (TokenStoreStruct) RefreshTokenExist ¶
func (t TokenStoreStruct) RefreshTokenExist(token string) (*suresql.TokenTable, bool)
Check if tokenExist, if it is, return the value of the TokenMap[token] - which is interface{} type
func (TokenStoreStruct) SaveToken ¶
func (t TokenStoreStruct) SaveToken(token suresql.TokenTable)
Check if tokenExist, if it is, return the value of the TokenMap[token] - which is interface{} type
func (TokenStoreStruct) TokenExist ¶
func (t TokenStoreStruct) TokenExist(token string) (*suresql.TokenTable, bool)
Check if tokenExist, if it is, return the value of the TokenMap[token] - which is interface{} type
type UserTable ¶
type UserTable struct {
ID int `json:"id,omitempty" db:"id"`
Username string `json:"username,omitempty" db:"username"`
Password string `json:"password,omitempty" db:"password"` // hashed
RoleName string `json:"role_name,omitempty" db:"role_name"`
CreatedAt time.Time `json:"created_at,omitempty" db:"created_at"`
}
UserTable struct representing a user from the database
type UserUpdateRequest ¶
type UserUpdateRequest struct {
Username string `json:"username"` // Required to identify the user
NewUsername string `json:"new_username,omitempty"` // Optional new username
NewPassword string `json:"new_password,omitempty"` // Optional new password
NewRoleName string `json:"new_role_name,omitempty"` // Optional new role
}
UserUpdateRequest represents the data for updating a user