utils

package
v0.0.0-...-a0ef6a5 Latest Latest
Warning

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

Go to latest
Published: Jan 9, 2022 License: GPL-3.0 Imports: 18 Imported by: 0

Documentation

Overview

Utility functions for logging messages, errors, etc.

Utility functions used be `site/site.go` and `tools/databaseTools.go`. Functions in `web.go` should generally not interrupt the flow of the application by exiting on error. Instead, they should return their error status to be handled by the calling function.

Index

Constants

View Source
const (
	Error   logType = 0
	Warning logType = 1
	Info    logType = 2
	List    logType = 3
	Done    logType = 4
	Debug   logType = 5

	EXIT_SUCCESS int = 0
	ERR_GENERIC  int = 1

	ERR_USAGE     int = 10
	ERR_INPUT     int = 11
	ERR_UUID      int = 12
	ERR_FILE_READ int = 13

	ERR_CONNECTION int = 30
	ERR_WRITE      int = 31
	ERR_BYTES      int = 32
)
View Source
const (
	DatabaseFilename string = "pwnts.db" // default

	ERR_DATABASE_INVALID int = 20
	ERR_STATEMENT        int = 21
	ERR_QUERY            int = 22
	ERR_SCAN             int = 23
)
View Source
const (
	MaxCallbackTime   time.Duration = 15 * time.Minute
	MaxTeamNameLength int           = 64
)

Variables

View Source
var (
	CurrentDirectory, _        = os.Getwd()
	DatabaseFilepath    string = CurrentDirectory + "/server/" + DatabaseFilename // default
)
View Source
var (
	JWTSigningKey []byte = []byte("supersecretsecret")
)
View Source
var MapTypesToPrefix = map[logType]string{
	Error:   MapTypesToColor[Error].Sprint("[!]"),
	Warning: MapTypesToColor[Warning].Sprint("[-]"),
	Info:    MapTypesToColor[Info].Sprint("[*]"),
	List:    MapTypesToColor[List].Sprint("[^]"),
	Done:    MapTypesToColor[Done].Sprint("[+]"),
	Debug:   MapTypesToColor[Debug].Sprint("[?]"),
}

Functions

func CalculateCallbackPoints

func CalculateCallbackPoints(timeDifference time.Duration, targetValue int) int

func CheckError

func CheckError(messageType logType, err error, messages ...string) bool

`LogError()` if present and return `err == nil`.

func CheckErrorExit

func CheckErrorExit(messageType logType, err error, errCode int, messages ...string)

Same as CheckError() but exit on error.

func CheckWebError

func CheckWebError(writer http.ResponseWriter, request *http.Request, err error, errorMessage string) bool

Handle any errors encountered when trying to serve a web page by setting the the response status to 500: Internal Server Error.

func ClearAuthCookieAndRedirect

func ClearAuthCookieAndRedirect(writer http.ResponseWriter, request *http.Request, err error)

func Close

func Close(closable io.Closer)

Utiliy to close an object that implements the `io.Closer` interface. Used over `object.Close()` for automatic error checking.

func GenerateJWT

func GenerateJWT(db *sql.DB, username string, teamID int) (tokenStirng string, err error)

func GetAuthClaims

func GetAuthClaims(writer http.ResponseWriter, request *http.Request) (authClaims jwt.MapClaims, err error)

Parses the JSON Web Token "auth" cookie and returns its claims as jwt.MapClaims.

func GetDatabaseHandle

func GetDatabaseHandle() *sql.DB

Return a handle to the application database.

Currently hardcoded to open utils.sqlite.DatabaseFilepath.

func GetFormDataSingle

func GetFormDataSingle(writer http.ResponseWriter, request *http.Request, dataName string) (dataSingle string)

Extract the first value from the specified form field. Automatically runs ValidateFormData to check for errors.

func GetHostIP

func GetHostIP() (hostIP net.IP)

Get preferred outbound IP address of this machine

func GetJWTClaims

func GetJWTClaims(jwtCookie *http.Cookie, writer http.ResponseWriter, request *http.Request) (tokenClaims jwt.MapClaims, err error)

Parses the provided JSON Web Token cookie and returns its claims as jwt.MapClaims.

func GetTeamName

func GetTeamName(db *sql.DB, teamID int) (teamName string, err error)

func GetTeamNames

func GetTeamNames(db *sql.DB) ([]string, error)

func GetUserIP

func GetUserIP(request *http.Request) string

func GetUserInfo

func GetUserInfo(db *sql.DB, username string) (teamId int, name string, passwordHash string, createdDateUnix int, err error)

Returns the teamId, name, password_hash, and created_date_unix for the specified username, as well as an err if needed.

If user does not exist, err = sql.ErrNoRows If backend server error, err = some error Else, err = nil

func HashPassword

func HashPassword(password string) (string, error)

func Log

func Log(messageType logType, messages ...string)

Log a timestamped message with a given logType.

func LogError

func LogError(messageType logType, err error, messages ...string)

Log the message, then print the error string

func LogIP

func LogIP(messageType logType, request *http.Request, messages ...string)

Log the IP address of the request with the specified error level and message.

func LogPlain

func LogPlain(messageType logType, messages ...string)

`Log()` without a timestamp.

func LogPlainExit

func LogPlainExit(messageType logType, errCode int, messages ...string)

Same as `LogPlain()`, but exit after logging.

func LogReturn

func LogReturn(messageType logType, messages ...string) string

Return the `log()` string instead of printing it.

func PromptFileDownload

func PromptFileDownload(writer http.ResponseWriter, request *http.Request, filePath string, fileName string)

func RegisterAgent

func RegisterAgent(db *sql.DB, agentUUID string, teamID int) bool

func RegisterTeam

func RegisterTeam(db *sql.DB, teamName string, teamPasswordHash string) error

Register a new Team by its name and password hash.

Returns `EXIT_SUCCESS` upon successful Team creation.

Otherwise, upon error, returns one of `ERR_INPUT` (team name too long), `ERR_STATEMENT`, or `ERR_QUERY`.

func ReturnStatusJSON

func ReturnStatusJSON(writer http.ResponseWriter, request *http.Request, message string, isError bool)

func ReturnStatusServerError

func ReturnStatusServerError(writer http.ResponseWriter, request *http.Request, message string)

func ReturnStatusSuccess

func ReturnStatusSuccess(writer http.ResponseWriter, request *http.Request, message string)

func ReturnStatusUserError

func ReturnStatusUserError(writer http.ResponseWriter, request *http.Request, message string)

func ValidateDatabase

func ValidateDatabase(db *sql.DB) bool

TODO: validate table names, not just number of tables.

Count the number of tables in the database and ensure it equals the
expected value.

func ValidateDatabaseExit

func ValidateDatabaseExit(db *sql.DB)

Same as `ValidateDatabase(db)`, but exit when invalid.

func ValidateFormData

func ValidateFormData(writer http.ResponseWriter, request *http.Request, formData []string, minObjects int, maxObjects int) bool

Ensure that the form field contains the expected number of objects.

func ValidatePasswordHash

func ValidatePasswordHash(password string, hash string) bool

Types

type ReturnMessage

type ReturnMessage struct {
	Message string `json:"message"`
	Error   bool   `json:"error"`
}

https://pkg.go.dev/encoding/json#Marshal

Jump to

Keyboard shortcuts

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