|
MantisBase v0.3.4
|
Namespaces | |
| namespace | logEntry |
| namespace | LogOrigin |
| Utility logger functions for each component/system. These functions automatically pass the origin parameter. | |
Classes | |
| class | AccessRule |
| Access control rule for entity permissions. More... | |
| class | Auth |
| JWT token creation and verification utilities. More... | |
| class | ContextStore |
| class | Database |
| Database connection and session management. More... | |
| class | DukCtx |
| class | Entity |
| Represents a database table/entity with schema and CRUD operations. More... | |
| class | EntitySchema |
| Builder class for creating and managing database table schemas. More... | |
| class | EntitySchemaField |
| Represents a single field in a database table schema. More... | |
| struct | Expr |
| Struct instance for handling evaluation of database access rules. More... | |
| class | Files |
| File management for entity file assets. More... | |
| class | FuncLogger |
| A class for tracing function execution [entry, exit] useful in following execution flow. More... | |
| class | KeyValStore |
| Manages application settings. More... | |
| class | LogDatabase |
| Manages SQLite database for application logs. More... | |
| class | Logger |
| class | MantisBase |
| MantisBase entry point. More... | |
| class | MantisContentReader |
More... | |
| class | MantisException |
| class | MantisLoggerImpl |
| Logger implementation for soci, allowing us to override the default logging behaviour with our own custom logger. More... | |
| class | MantisRequest |
A wrapper class around httplib::Request offering a consistent API and allowing for easy wrapper methods compatible with Duktape API requirements for scripting. More... | |
| class | MantisResponse |
| Wrapper around httplib::Response for consistent API. More... | |
| class | RealtimeDB |
| struct | RouteHandler |
| Struct encompassing the list of middlewares and the handler function registered to a specific route. More... | |
| struct | RouteKeyHash |
| class | Router |
| HTTP router for managing routes and request handling. More... | |
| class | RouteRegistry |
| class | RtDbWorker |
| class | SSEMgr |
| class | SSESession |
| class | Validators |
Typedefs | |
| using | json = nlohmann::json |
| Shorten JSON namespace. | |
| using | TokenMap = std::unordered_map< std::string, nlohmann::json > |
| typedef enum mb::LogLevel | LogLevel |
| using | Record = nlohmann::json |
| Single database record as JSON object. | |
| using | Records = std::vector< Record > |
| Collection of database records. | |
| using | RtCallback = std::function< void(const json &)> |
| using | HandlerResponse = httplib::Server::HandlerResponse |
| using | HandlerFn = std::function< void(MantisRequest &, MantisResponse &)> |
| |
| using | HandlerWithContentReaderFn = std::function< void(MantisRequest &, MantisResponse &, MantisContentReader &)> |
| |
| using | MiddlewareFn = std::function< HandlerResponse(MantisRequest &, MantisResponse &)> |
| |
| using | Middlewares = std::vector< MiddlewareFn > |
| |
| using | Method = std::string |
| |
| using | Path = std::string |
| |
| using | RouteKey = std::pair< Method, Path > |
| |
Enumerations | |
| enum class | LogLevel : uint8_t { TRACE = 0 , DEBUG , INFO , WARN , CRITICAL } |
Functions | |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> | getAuthToken () |
| Extract and validate JWT token from Authorization header. | |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> | hydrateContextData () |
| Hydrate request context with additional data. | |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> | hasAccess (const std::string &entity_name) |
| Check if request has access to entity based on access rules. | |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> | requireExprEval (const std::string &expr) |
| Require expression evaluation to pass. | |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> | requireGuestOnly () |
| Require guest-only access (no authentication). | |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> | requireAdminAuth () |
| Require admin authentication. | |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> | requireAdminOrEntityAuth (const std::string &entity_name) |
| Require admin OR entity authentication. | |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> | requireEntityAuth (const std::string &entity_name) |
| Require entity-specific authentication. | |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> | rateLimit (int max_requests, int window_seconds, bool use_user_id=false) |
| Rate limiting middleware to prevent abuse. | |
| soci::values | json2SociValue (const json &entity, const json &fields) |
| std::string | getColumnType (const std::string &column_name, const std::vector< json > &fields) |
| json | sociRow2Json (const soci::row &row, const std::vector< json > &entity_fields) |
| fs::path | joinPaths (const std::string &path1, const std::string &path2) |
| |
| fs::path | resolvePath (const std::string &input_path) |
| bool | createDirs (const fs::path &path) |
| Create directory, given a path. | |
| std::string | dirFromPath (const std::string &path) |
| Returns a created/existing directory from a path. | |
| void | toLowerCase (std::string &str) |
| Converts a string to its lowercase variant. | |
| void | toUpperCase (std::string &str) |
| Converts a string to its uppercase variant. | |
| std::string | trim (const std::string &s) |
| Trims leading and trailing whitespaces from a string. | |
| std::optional< json > | tryParseJsonStr (const std::string &json_str, std::optional< json > default_value=std::nullopt) |
| Attempt to parse a JSON string. | |
| bool | strToBool (const std::string &value) |
| Convert given string value to boolean type. | |
| std::string | generateTimeBasedId () |
| Generate a time base UUID. | |
| std::string | generateReadableTimeId () |
| Generates a readable time-based UUID. | |
| std::string | generateShortId (size_t length=16) |
| Generates a short UUID. | |
| std::vector< std::string > | splitString (const std::string &input, const std::string &delimiter) |
| Split given string based on given delimiter. | |
| std::string | getEnvOrDefault (const std::string &key, const std::string &defaultValue) |
| Retrieves a value from an environment variable or a default value if the env variable was not set. | |
| bool | invalidChar (unsigned char c) |
| Check if a character is invalid in a filename. | |
| void | sanitizeInPlace (std::string &s) |
| Sanitize a string in-place by removing or replacing invalid characters. | |
| std::string | sanitizeFilename (std::string_view original, std::size_t maxLen=50, std::size_t idLen=12, std::string_view idSep="_") |
| Sanitize a filename and ensure uniqueness. | |
| std::string | sanitizeFilename_JSWrapper (const std::string &original) |
| std::string | hashPassword (const std::string &password) |
| Digests user password + a generated salt to yield a hashed password. | |
| bool | verifyPassword (const std::string &password, const std::string &stored_hash) |
| Verifies user password if it matches the given hashed password. | |
| std::string | getCurrentTimestampUTC () |
| std::string | tmToStr (const std::tm &t) |
| Convert c++ std::tm date/time value to ISO formatted string. | |
| std::tm | strToTM (const std::string &value) |
| Convert ISO formatted datetime string to std::tm structure. | |
| std::string | dbDateToString (const soci::row &row, int index) |
| Convert database date value from SOCI row to string. | |
| int | safe_stoi (const std::string &s, const int default_val) |
| Safely convert string to integer with default fallback. | |
| bool | isValidIPv4 (const std::string &ip) |
| Validates if a string is a valid IPv4 address. | |
| bool | isValidIPv6 (const std::string &ip) |
| Validates if a string is a valid IPv6 address. | |
| bool | isValidIP (const std::string &ip) |
| Validates if a string is a valid IP address (IPv4 or IPv6). | |
| uint64_t | now_unix_ms () |
| std::string | to_hex_lower (const std::array< uint8_t, 16 > &b) |
| std::string | generate_uuidv7 () |
| void | registerUtilsToDuktapeEngine () |
| using mb::HandlerFn = typedef std::function<void(MantisRequest&, MantisResponse&)> |
Route Handler function shorthand
| using mb::HandlerResponse = typedef httplib::Server::HandlerResponse |
| using mb::HandlerWithContentReaderFn = typedef std::function<void(MantisRequest&, MantisResponse&, MantisContentReader&)> |
Route Handler function with content reader shorthand
| typedef nlohmann::json mb::json |
Shorten JSON namespace.
< Use shorthand fs to refer to the std::filesystem
| typedef enum mb::LogLevel mb::LogLevel |
Enum for the different logging levels.
| using mb::Method = typedef std::string |
Syntactic sugar for request method which is a std::string
| using mb::MiddlewareFn = typedef std::function<HandlerResponse(MantisRequest&, MantisResponse&)> |
Middleware shorthand for the function
| using mb::Middlewares = typedef std::vector<MiddlewareFn> |
Middleware function arrays
| using mb::Path = typedef std::string |
Syntactic sugar for request path which is a std::string
| using mb::Record = typedef nlohmann::json |
Single database record as JSON object.
| using mb::Records = typedef std::vector<Record> |
Collection of database records.
| using mb::RouteKey = typedef std::pair<Method, Path> |
Shorthand notation for the request's method, path pair.
| using mb::RtCallback = typedef std::function<void(const json &)> |
Callback invoked with a batch of change events (each event is a JSON object).
| using mb::TokenMap = typedef std::unordered_map<std::string, nlohmann::json> |
|
strong |
| bool mb::createDirs | ( | const fs::path & | path | ) |
Create directory, given a path.
Creates the target directory iteratively, including any missing parent directories. his ensures, any parent directory is set up before attempting to create a child directory.
| path | The directory path to create like /foo/bar. |
| std::string mb::dbDateToString | ( | const soci::row & | row, |
| int | index | ||
| ) |
Convert database date value from SOCI row to string.
| row | SOCI row containing the date value |
| index | Column index in the row |
| std::string mb::dirFromPath | ( | const std::string & | path | ) |
Returns a created/existing directory from a path.
Given a file path, it first gets the file parent directory and ensures the directory together with any missing parent directories are created first using the createDirs(...).
| path | The file path |
|
inline |
| std::string mb::generateReadableTimeId | ( | ) |
Generates a readable time-based UUID.
The first segment is the current time in ISO-formatted time + milliseconds + short random suffix. It is human-readable and sortable, just like
Sample Output: 20250531T221944517N3J
| std::string mb::generateShortId | ( | size_t | length = 16 | ) |
Generates a short UUID.
Similar to what platforms like YouTube use for videos, but in our case, making use of only alphanumeric characters.
Sample Output: Fz8xYc6a7LQw
| std::string mb::generateTimeBasedId | ( | ) |
Generate a time base UUID.
The first part is made up of milliseconds since epoch while the last 4 digits a random component. This makes it lexicographically sortable by time
Sample Output: 17171692041233276
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::getAuthToken | ( | ) |
Extract and validate JWT token from Authorization header.
Parses Bearer token from request headers and stores user info in context.
|
inline |
|
inline |
| std::string mb::getEnvOrDefault | ( | const std::string & | key, |
| const std::string & | defaultValue | ||
| ) |
Retrieves a value from an environment variable or a default value if the env variable was not set.
| key | Environment variable key. |
| defaultValue | A default value if the key is not set. |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::hasAccess | ( | const std::string & | entity_name | ) |
Check if request has access to entity based on access rules.
| entity_name | Entity/table name to check access for |
| std::string mb::hashPassword | ( | const std::string & | password | ) |
Digests user password + a generated salt to yield a hashed password.
| password | Password input to hash. |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::hydrateContextData | ( | ) |
Hydrate request context with additional data.
Populates context store with request metadata and user information.
| bool mb::invalidChar | ( | unsigned char | c | ) |
Check if a character is invalid in a filename.
Invalid characters typically include reserved symbols such as slashes, colons, question marks, etc. This function allows filtering and sanitization of filenames.
| c | Character to check. |
| bool mb::isValidIP | ( | const std::string & | ip | ) |
Validates if a string is a valid IP address (IPv4 or IPv6).
| ip | String to validate |
| bool mb::isValidIPv4 | ( | const std::string & | ip | ) |
Validates if a string is a valid IPv4 address.
Checks if the input string matches the IPv4 format (e.g., "192.168.1.1"). Does not validate the actual IP range, only the format.
| ip | String to validate as IPv4 address |
| bool mb::isValidIPv6 | ( | const std::string & | ip | ) |
Validates if a string is a valid IPv6 address.
Checks if the input string matches the IPv6 format (e.g., "2001:0db8::1"). Supports compressed notation (::).
| ip | String to validate as IPv6 address |
| fs::path mb::joinPaths | ( | const std::string & | path1, |
| const std::string & | path2 | ||
| ) |
JSON convenience for the nlomann::json namespace
Joins absolute path and a relative path, relative to the first path.
| path1 | The first absolute path or relative path |
| path2 | The relative path, subject to the first |
|
inline |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::rateLimit | ( | int | max_requests, |
| int | window_seconds, | ||
| bool | use_user_id = false |
||
| ) |
Rate limiting middleware to prevent abuse.
Limits the number of requests per time window. Can rate limit by IP address or by authenticated user ID. When the rate limit is exceeded, returns a 429 Too Many Requests response with rate limit headers.
| max_requests | Maximum number of requests allowed in the time window |
| window_seconds | Time window duration in seconds |
| use_user_id | If true, rate limit by authenticated user ID; if false, use IP address. Falls back to IP if user ID is not available. |
| void mb::registerUtilsToDuktapeEngine | ( | ) |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::requireAdminAuth | ( | ) |
Require admin authentication.
Only allows requests from users authenticated as admins.
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::requireAdminOrEntityAuth | ( | const std::string & | entity_name | ) |
Require admin OR entity authentication.
| entity_name | Entity name for entity-based auth |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::requireEntityAuth | ( | const std::string & | entity_name | ) |
Require entity-specific authentication.
| entity_name | Entity name to authenticate against |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::requireExprEval | ( | const std::string & | expr | ) |
Require expression evaluation to pass.
| expr | Expression string to evaluate |
| std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::requireGuestOnly | ( | ) |
Require guest-only access (no authentication).
Blocks authenticated users, only allows unauthenticated requests.
| fs::path mb::resolvePath | ( | const std::string & | input_path | ) |
Resolves given path as a string to an absolute path.
Given a relative path, relative to the cwd, we can resolve that path to the actual absolute path in our filesystem. This is needed for creating directories and files, especially for database and file-serving.
| input_path | The path to resolve |
| int mb::safe_stoi | ( | const std::string & | s, |
| const int | default_val | ||
| ) |
Safely convert string to integer with default fallback.
Attempts to convert a string to an integer. If conversion fails (invalid format, out of range, etc.), returns the default value instead of throwing an exception.
| s | String to convert |
| default_val | Default value to return if conversion fails |
| std::string mb::sanitizeFilename | ( | std::string_view | original, |
| std::size_t | maxLen = 50, |
||
| std::size_t | idLen = 12, |
||
| std::string_view | idSep = "_" |
||
| ) |
Sanitize a filename and ensure uniqueness.
Creates a safe filename from the given input. Invalid characters are replaced with underscores. The resulting filename is truncated to maxLen characters, and a short unique ID is appended to avoid collisions.
Example: Input: "my*illegal:file?.txt" Output: "my_illegal_file_txt_abC82xM01qP"
| original | Original filename (input). |
| maxLen | Maximum length of the sanitized name before adding ID. Default = 50. |
| idLen | Length of the unique ID suffix. Default = 12. |
| idSep | Separator inserted between the name and the ID. Default = "_". |
| std::string mb::sanitizeFilename_JSWrapper | ( | const std::string & | original | ) |
| void mb::sanitizeInPlace | ( | std::string & | s | ) |
Sanitize a string in-place by removing or replacing invalid characters.
This modifies the provided string directly. Characters deemed invalid by invalidChar() are replaced with an underscore (_).
| s | Reference to the string to sanitize. |
| std::vector< std::string > mb::splitString | ( | const std::string & | input, |
| const std::string & | delimiter | ||
| ) |
Split given string based on given delimiter.
| input | Input string to split. |
| delimiter | The string delimiter to use to split the input string. |
| bool mb::strToBool | ( | const std::string & | value | ) |
Convert given string value to boolean type.
By default, we check for true equivalents, anything else will be considered as a false value.
| value | String value to convert to bool |
| std::tm mb::strToTM | ( | const std::string & | value | ) |
Convert ISO formatted datetime string to std::tm structure.
| value | ISO formatted datetime string |
| std::string mb::tmToStr | ( | const std::tm & | t | ) |
Convert c++ std::tm date/time value to ISO formatted string.
| t | std::tm value |
|
inline |
| void mb::toLowerCase | ( | std::string & | str | ) |
Converts a string to its lowercase variant.
It converts the string in place.
| str | The string to convert. |
| void mb::toUpperCase | ( | std::string & | str | ) |
Converts a string to its uppercase variant.
It converts the string in place.
| str | The string to convert. |
| std::string mb::trim | ( | const std::string & | s | ) |
Trims leading and trailing whitespaces from a string.
| s | The string to trim. |
| std::optional< json > mb::tryParseJsonStr | ( | const std::string & | json_str, |
| std::optional< json > | default_value = std::nullopt |
||
| ) |
Attempt to parse a JSON string.
| json_str | JSON string to parse |
| default_value | Optional default value if conversion fails |
std::nullopt| bool mb::verifyPassword | ( | const std::string & | password, |
| const std::string & | stored_hash | ||
| ) |
Verifies user password if it matches the given hashed password.
Given a hashed password from the database (stored_hash), the method extracts the salt value, hashes the password value with the salt then compares the two hashes if they match.
| password | User password input. |
| stored_hash | Database stored hashed user password. |