MantisBase v0.3.4
Loading...
Searching...
No Matches
mb Namespace Reference

router.h More...

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
 

‍Middleware shorthand for the content reader

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 &)>
 

‍Route Handler function shorthand


 
using HandlerWithContentReaderFn = std::function< void(MantisRequest &, MantisResponse &, MantisContentReader &)>
 

‍Route Handler function with content reader shorthand


 
using MiddlewareFn = std::function< HandlerResponse(MantisRequest &, MantisResponse &)>
 

‍Middleware shorthand for the function


 
using Middlewares = std::vector< MiddlewareFn >
 

‍Middleware function arrays


 
using Method = std::string
 

‍Syntactic sugar for request method which is a std::string


 
using Path = std::string
 

‍Syntactic sugar for request path which is a std::string


 
using RouteKey = std::pair< Method, Path >
 

‍Shorthand notation for the request's method, path pair.


 

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)
 

‍JSON convenience for the nlomann::json namespace


 
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< jsontryParseJsonStr (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 ()
 

Detailed Description

router.h

Router file for higher level route registration and removal *

Typedef Documentation

◆ HandlerFn

using mb::HandlerFn = typedef std::function<void(MantisRequest&, MantisResponse&)>

‍Route Handler function shorthand

◆ HandlerResponse

using mb::HandlerResponse = typedef httplib::Server::HandlerResponse

◆ HandlerWithContentReaderFn

‍Route Handler function with content reader shorthand

◆ json

typedef nlohmann::json mb::json

Shorten JSON namespace.

< Use shorthand fs to refer to the std::filesystem

◆ LogLevel

typedef enum mb::LogLevel mb::LogLevel

Enum for the different logging levels.

◆ Method

using mb::Method = typedef std::string

‍Syntactic sugar for request method which is a std::string

◆ MiddlewareFn

using mb::MiddlewareFn = typedef std::function<HandlerResponse(MantisRequest&, MantisResponse&)>

‍Middleware shorthand for the function

◆ Middlewares

using mb::Middlewares = typedef std::vector<MiddlewareFn>

‍Middleware function arrays

◆ Path

using mb::Path = typedef std::string

‍Syntactic sugar for request path which is a std::string

◆ Record

using mb::Record = typedef nlohmann::json

Single database record as JSON object.

◆ Records

using mb::Records = typedef std::vector<Record>

Collection of database records.

◆ RouteKey

using mb::RouteKey = typedef std::pair<Method, Path>

‍Shorthand notation for the request's method, path pair.

◆ RtCallback

using mb::RtCallback = typedef std::function<void(const json &)>

Callback invoked with a batch of change events (each event is a JSON object).

◆ TokenMap

using mb::TokenMap = typedef std::unordered_map<std::string, nlohmann::json>

Enumeration Type Documentation

◆ LogLevel

enum class mb::LogLevel : uint8_t
strong

Enum for the different logging levels.

Enumerator
TRACE 
DEBUG 

‍Trace logging level

INFO 

‍Debug Logging Level

WARN 

‍Info Logging Level

CRITICAL 

‍Warning Logging Level

‍Critical Logging Level

Function Documentation

◆ createDirs()

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.

Parameters
pathThe directory path to create like /foo/bar.
Returns
True if creation was successful. If the directory exists, it returns false.

◆ dbDateToString()

std::string mb::dbDateToString ( const soci::row &  row,
int  index 
)

Convert database date value from SOCI row to string.

Parameters
rowSOCI row containing the date value
indexColumn index in the row
Returns
String representation of the date

◆ dirFromPath()

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(...).

See also
createDirs() for creating directories.
Parameters
pathThe file path
Returns
Returns the directory path if successful, else an empty string.

◆ generate_uuidv7()

std::string mb::generate_uuidv7 ( )
inline

◆ generateReadableTimeId()

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

Returns
A readable-time based UUID
See also
generateTimeBasedId() For a time-based UUID.
generateShortId() For a short UUID.

◆ generateShortId()

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

Returns
A short alphanumeric UUID
See also
generateTimeBasedId() For a time-based UUID.
generateReadableTimeId() For a readable time-based UUID.

◆ generateTimeBasedId()

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

Returns
A time based UUID
See also
generateReadableTimeId() For a readable time-based UUID.
generateShortId() For a short UUID.

◆ getAuthToken()

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.

Returns
Middleware function

◆ getColumnType()

std::string mb::getColumnType ( const std::string &  column_name,
const std::vector< json > &  fields 
)
inline

◆ getCurrentTimestampUTC()

std::string mb::getCurrentTimestampUTC ( )
inline

◆ getEnvOrDefault()

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.

Parameters
keyEnvironment variable key.
defaultValueA default value if the key is not set.
Returns
The env value if found, else the default value passed in.

◆ hasAccess()

std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::hasAccess ( const std::string &  entity_name)

Check if request has access to entity based on access rules.

Parameters
entity_nameEntity/table name to check access for
Returns
Middleware function that validates access rules
router.Get("/api/v1/posts", handler, {hasAccess("posts")});
std::function< HandlerResponse(MantisRequest &, MantisResponse &)> hasAccess(const std::string &entity_name)
Check if request has access to entity based on access rules.
Definition middlewares.cpp:85

◆ hashPassword()

std::string mb::hashPassword ( const std::string &  password)

Digests user password + a generated salt to yield a hashed password.

Parameters
passwordPassword input to hash.
Returns
A hash string representation of the password + salt.

◆ hydrateContextData()

std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::hydrateContextData ( )

Hydrate request context with additional data.

Populates context store with request metadata and user information.

Returns
Middleware function

◆ invalidChar()

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.

Parameters
cCharacter to check.
Returns
true if the character is invalid in a filename, false otherwise.

◆ isValidIP()

bool mb::isValidIP ( const std::string &  ip)

Validates if a string is a valid IP address (IPv4 or IPv6).

Parameters
ipString to validate
Returns
true if valid IPv4 or IPv6, false otherwise

◆ isValidIPv4()

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.

Parameters
ipString to validate as IPv4 address
Returns
true if the string is a valid IPv4 format, false otherwise
if (isValidIPv4("192.168.1.1")) {
// Valid IPv4 format
}
bool isValidIPv4(const std::string &ip)
Validates if a string is a valid IPv4 address.
Definition string_utils.cpp:199

◆ isValidIPv6()

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 (::).

Parameters
ipString to validate as IPv6 address
Returns
true if the string is a valid IPv6 format, false otherwise

◆ joinPaths()

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.

Parameters
path1The first absolute path or relative path
path2The relative path, subject to the first
Returns
An absolute path if successfully joined, else an empty path.

◆ json2SociValue()

soci::values mb::json2SociValue ( const json entity,
const json fields 
)
inline

◆ now_unix_ms()

uint64_t mb::now_unix_ms ( )
inline

◆ rateLimit()

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.

Parameters
max_requestsMaximum number of requests allowed in the time window
window_secondsTime window duration in seconds
use_user_idIf true, rate limit by authenticated user ID; if false, use IP address. Falls back to IP if user ID is not available.
Returns
Middleware function that enforces rate limits
Note
The login endpoint uses this middleware with 5 requests per 60 seconds by IP.
Rate limit headers are included in responses: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, and Retry-After.
// Rate limit by IP: 100 requests per minute
router.Get("/api/v1/data", handler, {rateLimit(100, 60, false)});
// Rate limit by user: 10 requests per second
router.Post("/api/v1/upload", handler, {rateLimit(10, 1, true)});
// Login endpoint: 5 attempts per minute per IP (prevents brute force)
router.Post("/api/v1/auth/login", loginHandler, {rateLimit(5, 60, false)});
std::function< HandlerResponse(MantisRequest &, MantisResponse &)> rateLimit(int max_requests, int window_seconds, bool use_user_id=false)
Rate limiting middleware to prevent abuse.
Definition middlewares.cpp:404

◆ registerUtilsToDuktapeEngine()

void mb::registerUtilsToDuktapeEngine ( )

◆ requireAdminAuth()

std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::requireAdminAuth ( )

Require admin authentication.

Only allows requests from users authenticated as admins.

Returns
Middleware function

◆ requireAdminOrEntityAuth()

std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::requireAdminOrEntityAuth ( const std::string &  entity_name)

Require admin OR entity authentication.

Parameters
entity_nameEntity name for entity-based auth
Returns
Middleware function that allows admins or entity users

◆ requireEntityAuth()

std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::requireEntityAuth ( const std::string &  entity_name)

Require entity-specific authentication.

Parameters
entity_nameEntity name to authenticate against
Returns
Middleware function that validates entity auth

◆ requireExprEval()

std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::requireExprEval ( const std::string &  expr)

Require expression evaluation to pass.

Parameters
exprExpression string to evaluate
Returns
Middleware function that evaluates expression

◆ requireGuestOnly()

std::function< HandlerResponse(MantisRequest &, MantisResponse &)> mb::requireGuestOnly ( )

Require guest-only access (no authentication).

Blocks authenticated users, only allows unauthenticated requests.

Returns
Middleware function

◆ resolvePath()

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.

Parameters
input_pathThe path to resolve
Returns
Returns an absolute filesystem path.

◆ safe_stoi()

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.

Parameters
sString to convert
default_valDefault value to return if conversion fails
Returns
Converted integer or default value
int page = safe_stoi(req.getQueryParam("page"), 1); // Defaults to 1 if invalid
int limit = safe_stoi(req.getQueryParam("limit"), 100); // Defaults to 100 if invalid
int safe_stoi(const std::string &s, const int default_val)
Safely convert string to integer with default fallback.
Definition string_utils.cpp:191

◆ sanitizeFilename()

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"

Parameters
originalOriginal filename (input).
maxLenMaximum length of the sanitized name before adding ID. Default = 50.
idLenLength of the unique ID suffix. Default = 12.
idSepSeparator inserted between the name and the ID. Default = "_".
Returns
Sanitized filename with appended unique ID.

◆ sanitizeFilename_JSWrapper()

std::string mb::sanitizeFilename_JSWrapper ( const std::string &  original)

◆ sanitizeInPlace()

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 (_).

Parameters
sReference to the string to sanitize.

◆ sociRow2Json()

json mb::sociRow2Json ( const soci::row &  row,
const std::vector< json > &  entity_fields 
)
inline

◆ splitString()

std::vector< std::string > mb::splitString ( const std::string &  input,
const std::string &  delimiter 
)

Split given string based on given delimiter.

Parameters
inputInput string to split.
delimiterThe string delimiter to use to split the input string.
Returns
A vector of strings.
auto parts = splitString("Hello, John!", ",");
std::cout << parts.size() << std::endl;
// > Should be a vector of two strings `Hello` and ` World`
std::vector< std::string > splitString(const std::string &input, const std::string &delimiter)
Split given string based on given delimiter.
Definition string_utils.cpp:93

◆ strToBool()

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.

Parameters
valueString value to convert to bool
Returns
true or false value

◆ strToTM()

std::tm mb::strToTM ( const std::string &  value)

Convert ISO formatted datetime string to std::tm structure.

Parameters
valueISO formatted datetime string
Returns
std::tm structure representing the datetime

◆ tmToStr()

std::string mb::tmToStr ( const std::tm &  t)

Convert c++ std::tm date/time value to ISO formatted string.

Parameters
tstd::tm value
Returns
ISO formatted datetime value

◆ to_hex_lower()

std::string mb::to_hex_lower ( const std::array< uint8_t, 16 > &  b)
inline

◆ toLowerCase()

void mb::toLowerCase ( std::string &  str)

Converts a string to its lowercase variant.

It converts the string in place.

Parameters
strThe string to convert.
See also
toUpperCase() To convert string to uppercase.

◆ toUpperCase()

void mb::toUpperCase ( std::string &  str)

Converts a string to its uppercase variant.

It converts the string in place.

Parameters
strThe string to convert.
See also
toLowerCase() To convert string to lowercase.

◆ trim()

std::string mb::trim ( const std::string &  s)

Trims leading and trailing whitespaces from a string.

Parameters
sThe string to trim.
Returns
String with all leading and trailing whitespaces removed.

◆ tryParseJsonStr()

std::optional< json > mb::tryParseJsonStr ( const std::string &  json_str,
std::optional< json default_value = std::nullopt 
)

Attempt to parse a JSON string.

Parameters
json_strJSON string to parse
default_valueOptional default value if conversion fails
Returns
A JSON Object if successful, else a std::nullopt
auto user = tryParseJsonStr("{\"name\": \"John Doe\"}");
if(user.has_value()) {
// Do something ...
}
std::optional< json > tryParseJsonStr(const std::string &json_str, std::optional< json > default_value=std::nullopt)
Attempt to parse a JSON string.
Definition string_utils.cpp:7

◆ verifyPassword()

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.

Parameters
passwordUser password input.
stored_hashDatabase stored hashed user password.
Returns
boolean indicating whether the verification was successful or not.