![]() |
MantisBase v0.4.9
|
Namespaces | |
| namespace | smtp_detail |
Classes | |
| struct | ApiKeyResult |
| class | MbApiKeyMgr |
| Create, list, revoke, and resolve API keys for entity users and admins. More... | |
| class | MbAuth |
| JWT token creation and verification utilities. More... | |
| class | MbContextStore |
| class | MbDatabase |
| MbDatabase connection and session management. More... | |
| class | MbLoggerImpl |
| MbLogger implementation for soci, allowing us to override the default logging behaviour with our own custom logger. More... | |
| struct | MbSmtpConfig |
| struct | MbEmailMsg |
| struct | MbRateLimitEntry |
| class | MbMailer |
| class | MbException |
| Application exception carrying an HTTP status code and messages. More... | |
| struct | Expr |
| Struct instance for handling evaluation of database access rules. More... | |
| class | MbFilesMgr |
| File management for entity file assets. More... | |
| struct | MbFormDataItem |
| class | MbRequest |
| HTTP request wrapper bound to a MantisBase instance. More... | |
| class | MbResponse |
| HTTP response wrapper bound to a MantisBase instance. More... | |
| class | MbKVStore |
| Manages application settings. More... | |
| class | MbLogDatabase |
| Manages SQLite database for application logs. More... | |
| class | MbLogger |
| struct | MbAccessEvalContext |
| class | MbAccessRule |
| Access control rule for entity permissions. More... | |
| struct | MbAuthMethods |
| struct | EntityListPage |
| class | MbEntity |
| Represents a database table/entity with schema and CRUD operations. More... | |
| class | MbEntitySchema |
| Builder class for creating and managing database table schemas. More... | |
| struct | IndexDefinition |
| class | MbEntitySchemaField |
| class | MbValidators |
| Static validators for schema definitions and CRUD request bodies. More... | |
| class | MbOAuthMgr |
| OAuth provider registry, entity enablement, and login/link flows. More... | |
| class | MbRealtimeDB |
| class | MbRtDbWorker |
| struct | RealtimeAuthSnapshot |
| MbAuth state captured at connect or subscribe time. More... | |
| struct | TopicAccessResult |
| struct | RealtimeWsSession |
| struct | MbRouteKeyHash |
| struct | MbRouteHandler |
| class | MbRouteRegistry |
| Thread-local route registry backing the MantisBase router. More... | |
| class | MbRouter |
| Central HTTP router and schema cache for a MantisBase instance. More... | |
| class | MbSSESession |
| Per-client SSE session state and async stream writer. More... | |
| class | MbSSEMgr |
| Manages SSE routes, sessions, broadcast, and shared WebSocket cleanup. More... | |
| class | MbAppMixin |
| Non-owning access to the active MantisBase from DI-aware types. More... | |
| class | MbWSMgr |
| Tracks WebSocket connections, topic indexes, and broadcasts change events. More... | |
| class | MbRealtimeWSController |
| Drogon WebSocket controller for the realtime endpoint. More... | |
| class | MantisBase |
| MantisBase entry point. More... | |
| struct | MbScriptJson |
Typedefs | |
| using | json = nlohmann::json |
| Shorten JSON namespace. | |
| typedef enum mb::MbLogLevel | MbLogLevel |
| Log severity levels mirrored in spdlog and the log database. | |
| 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 | MbHandlerFn = std::function<void(MbRequest&, MbResponse&)> |
| Standard route handler (request, response). | |
| using | MbMiddlewareFn = std::function<MbHandlerResponse(MbRequest&, MbResponse&)> |
| using | MbMiddlewares = std::vector<MbMiddlewareFn> |
| using | MbMethod = std::string |
| using | MbPath = std::string |
| using | MbRouteKey = std::pair<MbMethod, MbPath> |
| Route lookup key: HTTP method + path pattern. | |
Enumerations | |
| enum class | MbLogLevel : uint8_t { TRACE = 0 , DEBUG , INFO , WARN , CRITICAL } |
| Log severity levels mirrored in spdlog and the log database. More... | |
| enum class | MbAccessEvalResult { Allow , DenyUnauthenticated , DenyForbidden , DenyUnknownRule } |
| enum class | MbIntPrecision { I8 , I16 , I32 , I64 , U8 , U16 , U32 , U64 } |
| enum class | MbAuthUpgradeResult { Applied , Unchanged , DeniedSwitch , DeniedDowngrade } |
| enum class | MbHandlerResponse { Handled , Unhandled } |
| Middleware short-circuit result: stop or continue the chain. More... | |
Functions | |
| MANTISBASE_API MbMiddlewareFn | getAuthToken () |
| Extract JWT or API key from the Authorization header. | |
| MANTISBASE_API MbMiddlewareFn | hydrateContextData () |
| Hydrate request context with additional data. | |
| MANTISBASE_API MbMiddlewareFn | resolveSchema () |
| Resolve schema from :schema_name_or_id path param and validate it exists. | |
| MANTISBASE_API MbMiddlewareFn | resolveAuthEntity () |
| Resolve auth entity from :entity_name path param. | |
| MANTISBASE_API MbMiddlewareFn | resolveEntity () |
| Resolve entity from :entity_name path param and validate it is API-accessible. | |
| MANTISBASE_API MbMiddlewareFn | rejectViewMutations () |
| Reject POST, PATCH, and DELETE requests against view-type entities. | |
| MANTISBASE_API MbMiddlewareFn | hasEntityAccess () |
| Check access rules for the entity named in the :entity_name path param. | |
| MANTISBASE_API MbMiddlewareFn | hasAccess (const std::string &entity_name) |
| Check if request has access to entity based on access rules. | |
| MANTISBASE_API MbMiddlewareFn | requireExprEval (const std::string &expr) |
| Require expression evaluation to pass. | |
| MANTISBASE_API MbMiddlewareFn | requireGuestOnly () |
| Require guest-only access (no authentication). | |
| MANTISBASE_API MbMiddlewareFn | requireAdminAuth () |
| Require admin authentication. | |
| MANTISBASE_API MbMiddlewareFn | envGateMiddleware (const std::string &env_var, bool block_when_truthy) |
| Block the request when an environment variable matches a truthy state. | |
| MANTISBASE_API MbMiddlewareFn | settingsFeatureGate (const std::string &setting_key) |
| Block the request when an app-settings flag is truthy. | |
| MANTISBASE_API MbMiddlewareFn | requireAdminOrEntityAuth (const std::string &entity_name) |
| Require admin OR entity authentication. | |
| MANTISBASE_API MbMiddlewareFn | requireEntityAuth (const std::string &entity_name) |
| Require entity-specific authentication. | |
| MANTISBASE_API MbMiddlewareFn | rateLimit (int max_requests, int window_seconds, bool use_user_id=false) |
| Rate limiting middleware to prevent abuse. | |
| MANTISBASE_API bool | isGuestAuth (const nlohmann::json &auth) |
| MANTISBASE_API bool | isAdminAuth (const nlohmann::json &auth) |
| MANTISBASE_API bool | isUserAuth (const nlohmann::json &auth) |
| MANTISBASE_API MbAccessEvalResult | evaluateAccessRule (const MbAccessRule &rule, const MbAccessEvalContext &ctx) |
| MANTISBASE_API nlohmann::json | buildAccessExprVars (const MbRequest &req, const nlohmann::json &auth) |
| MANTISBASE_API nlohmann::json | buildAccessExprVars (const nlohmann::json &auth, const std::string &remote_addr, int remote_port, const std::string &local_addr, int local_port, const nlohmann::json &body=nlohmann::json::object()) |
| MANTISBASE_API std::pair< int, std::string > | accessEvalHttpError (MbAccessEvalResult result, const MbAccessRule &rule=MbAccessRule{}) |
| MbHandlerFn | entityGetManyHandler () |
| MbHandlerFn | entityGetOneHandler () |
| MbHandlerFn | entityPostHandler () |
| MbHandlerFn | entityPatchHandler () |
| MbHandlerFn | entityDeleteHandler () |
| void | registerAdminEntityRoutes (const MantisBase &app) |
| MbHandlerFn | schemaGetManyHandler () |
| MbHandlerFn | schemaGetOneHandler () |
| MbHandlerFn | schemaPostHandler () |
| MbHandlerFn | schemaPatchHandler () |
| MbHandlerFn | schemaDeleteHandler () |
| MANTISBASE_API MbIntPrecision | defaultIntPrecision () |
| MANTISBASE_API bool | isUnsignedIntPrecision (MbIntPrecision precision) |
| MANTISBASE_API std::string | intPrecisionToString (MbIntPrecision precision) |
| MANTISBASE_API MbIntPrecision | intPrecisionFromString (const std::string &token) |
| MANTISBASE_API MbIntPrecision | intPrecisionFromField (const nlohmann::json &field) |
| MANTISBASE_API soci::db_type | intPrecisionToSociType (MbIntPrecision precision) |
| MANTISBASE_API std::pair< int64_t, int64_t > | intPrecisionSignedRange (MbIntPrecision precision) |
| MANTISBASE_API std::pair< uint64_t, uint64_t > | intPrecisionUnsignedRange (MbIntPrecision precision) |
| MANTISBASE_API std::optional< std::string > | validateIntPrecisionToken (const std::string &token) |
| MANTISBASE_API std::optional< std::string > | validateIntFieldValue (const nlohmann::json &value, MbIntPrecision precision) |
| MANTISBASE_API std::optional< std::string > | validateIntConstraintBounds (const nlohmann::json &field) |
| MANTISBASE_API void | bindIntFieldValue (soci::values &vals, const std::string &field_name, const nlohmann::json &value, MbIntPrecision precision) |
| MANTISBASE_API nlohmann::json | readIntFieldValue (const soci::row &row, size_t index, MbIntPrecision precision) |
| MANTISBASE_API RealtimeAuthSnapshot | makeGuestAuthSnapshot () |
| MANTISBASE_API std::string | resolveRealtimeToken (const drogon::HttpRequestPtr &req) |
| Resolve bearer/API-key token from a realtime HTTP upgrade or SSE request. | |
| MANTISBASE_API RealtimeAuthSnapshot | resolveRealtimeAuth (const MantisBase &app, const std::string &token) |
| Hydrate auth from a JWT or mb_sk_ API key. | |
| MANTISBASE_API TopicAccessResult | filterAuthorizedTopics (const MantisBase &app, const std::vector< std::string > &topics, const RealtimeAuthSnapshot &snap) |
| Filter topics by entity access rules. | |
| MANTISBASE_API MbAuthUpgradeResult | tryUpgradeAuth (RealtimeAuthSnapshot &session, const RealtimeAuthSnapshot &incoming) |
| Apply incoming auth to an existing session (subscribe-time upgrade). | |
| MANTISBASE_API std::string | generateRealtimeClientId (std::string_view prefix) |
| Generate a unique realtime client/session ID. | |
| MANTISBASE_API bool | isAuthExpired (const RealtimeAuthSnapshot &snap, const MantisBase &app) |
| MANTISBASE_API bool | isAuthenticatedSnapshot (const RealtimeAuthSnapshot &snap) |
| MANTISBASE_API void | touchWsSession (RealtimeWsSession &session) |
| MANTISBASE_API bool | initWolfSsl () |
| MANTISBASE_API std::string | generateSecureRandom (size_t length) |
| MANTISBASE_API std::string | sha256Hex (const std::string &input) |
| MANTISBASE_API std::string | base64UrlEncode (const std::vector< uint8_t > &data) |
| MANTISBASE_API std::string | base64UrlEncode (const std::string &data) |
| MANTISBASE_API std::vector< uint8_t > | base64UrlDecode (const std::string &encoded) |
| MANTISBASE_API std::string | generatePKCEVerifier (size_t length=43) |
| MANTISBASE_API std::string | generatePKCEChallenge (const std::string &verifier) |
| MANTISBASE_API std::string | aes256GcmEncrypt (const std::string &plaintext, const std::string &key) |
| MANTISBASE_API std::string | aes256GcmDecrypt (const std::string &ciphertext, const std::string &key) |
| MANTISBASE_API soci::values | json2SociValue (const json &entity, const json &fields) |
| Bind a JSON entity payload to SOCI values using field metadata. | |
| MANTISBASE_API MbIntPrecision | getColumnIntPrecision (const std::string &column_name, const std::vector< json > &fields) |
| MANTISBASE_API std::string | getColumnType (const std::string &column_name, const std::vector< json > &fields) |
| MANTISBASE_API json | sociRow2Json (const std::string &db_type, const soci::row &row, const std::vector< json > &entity_fields) |
| Convert a SOCI result row to JSON using entity field metadata. | |
| MANTISBASE_API fs::path | joinPaths (const std::string &path1, const std::string &path2) |
| Joins absolute path and a relative path, relative to the first path. | |
| MANTISBASE_API fs::path | resolvePath (const std::string &input_path) |
| MANTISBASE_API bool | createDirs (const fs::path &path) |
| Create directory, given a path. | |
| MANTISBASE_API std::string | dirFromPath (const std::string &path) |
| Returns a created/existing directory from a path. | |
| MANTISBASE_API void | toLowerCase (std::string &str) |
| Converts a string to its lowercase variant. | |
| MANTISBASE_API void | toUpperCase (std::string &str) |
| Converts a string to its uppercase variant. | |
| MANTISBASE_API std::string | trim (const std::string &s) |
| Trims leading and trailing whitespaces from a string. | |
| MANTISBASE_API std::string | sqlIdentifier (const std::string &ident) |
| Validate a string as a safe SQL identifier and return it unchanged. | |
| MANTISBASE_API std::pair< json, std::string > | tryParseJsonStr (const std::string &json_str) |
| Try parsing a string to a JSON object and return the object and any error if parsing failed. | |
| MANTISBASE_API bool | strToBool (const std::string &value) |
| Convert given string value to boolean type. | |
| MANTISBASE_API std::string | generateTimeBasedId () |
| Generate a time base UUID. | |
| MANTISBASE_API std::string | generateReadableTimeId () |
| Generates a readable time-based UUID. | |
| MANTISBASE_API std::string | generateShortId (size_t length=16) |
| Generates a short UUID. | |
| MANTISBASE_API std::vector< std::string > | splitString (const std::string &input, const std::string &delimiter) |
| Split given string based on given delimiter. | |
| MANTISBASE_API 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. | |
| MANTISBASE_API bool | invalidChar (unsigned char c) |
| Check if a character is invalid in a filename. | |
| MANTISBASE_API void | sanitizeInPlace (std::string &s) |
| Sanitize a string in-place by removing or replacing invalid characters. | |
| MANTISBASE_API 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) |
| MANTISBASE_API bool | isAllowedFileExtension (const std::string &extension) |
| MANTISBASE_API std::string | safeContentType (const std::string &extension) |
| MANTISBASE_API std::string | hashPassword (const std::string &password) |
| Digests user password + a generated salt to yield a hashed password. | |
| MANTISBASE_API bool | verifyPassword (const std::string &password, const std::string &stored_hash) |
| Verifies user password if it matches the given hashed password. | |
| MANTISBASE_API std::tm | toUtcTime (std::time_t t) |
| Thread-safe conversion of an epoch time to a UTC std::tm. | |
| MANTISBASE_API std::tm | toLocalTime (std::time_t t) |
| Thread-safe conversion of an epoch time to a local-time std::tm. | |
| MANTISBASE_API std::string | getCurrentTimestampUTC () |
| MANTISBASE_API std::string | tmToStr (const std::tm &t) |
| Convert c++ std::tm date/time value to ISO formatted string. | |
| MANTISBASE_API std::tm | strToTM (const std::string &value) |
| Convert ISO formatted datetime string to std::tm structure. | |
| MANTISBASE_API std::string | dbDateToString (const std::string &db_type, 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. | |
| MANTISBASE_API bool | isValidIPv4 (const std::string &ip) |
| Validates if a string is a valid IPv4 address. | |
| MANTISBASE_API bool | isValidIPv6 (const std::string &ip) |
| Validates if a string is a valid IPv6 address. | |
| MANTISBASE_API 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 () |
| Generate a UUID v7 string. | |
Variables | |
| constexpr char | kAuthTokenCookieName [] = "mb_token" |
| HttpOnly cookie name used for JWT session tokens on login/refresh responses. | |
| constexpr int | MAX_LIST_PAGE_SIZE = 500 |
| constexpr int | kRealtimeNoTopicGraceSeconds = 60 |
| constexpr int | kRealtimeIdleTimeoutMinutes = 10 |
| constexpr int | kRealtimeCleanupIntervalSeconds = 30 |
| using mb::json = nlohmann::json |
Shorten JSON namespace.
< Use shorthand fs to refer to the std::filesystem
| using mb::MbHandlerFn = std::function<void(MbRequest&, MbResponse&)> |
Standard route handler (request, response).
The single handler signature for all methods including PUT/PATCH/POST. Body handling (JSON and multipart/file uploads) is available directly on MbRequest via jsonBody(), formData(), filesMetadata(), parseFormDataToEntity(), and writeFiles().
| typedef enum mb::MbLogLevel mb::MbLogLevel |
Log severity levels mirrored in spdlog and the log database.
| using mb::MbMethod = std::string |
| using mb::MbMiddlewareFn = std::function<MbHandlerResponse(MbRequest&, MbResponse&)> |
| using mb::MbMiddlewares = std::vector<MbMiddlewareFn> |
| using mb::MbPath = std::string |
| using mb::MbRouteKey = std::pair<MbMethod, MbPath> |
Route lookup key: HTTP method + path pattern.
| using mb::Record = nlohmann::json |
Single database record as JSON object.
| using mb::Records = std::vector<Record> |
Collection of database records.
| using mb::RtCallback = std::function<void(const json &)> |
Callback invoked with a batch of change events (each event is a JSON object).
|
strong |
Outcome of evaluateAccessRule for HTTP, SSE, and WebSocket checks.
|
strong |
Outcome of applying incoming credentials to an existing realtime session.
|
strong |
|
strong |
|
strong |
|
nodiscard |
| std::string mb::aes256GcmDecrypt | ( | const std::string & | ciphertext, |
| const std::string & | key ) |
AES-256-GCM decrypt counterpart to aes256GcmEncrypt.
| std::string mb::aes256GcmEncrypt | ( | const std::string & | plaintext, |
| const std::string & | key ) |
AES-256-GCM encrypt; ciphertext includes IV + tag. Key must be 32 bytes.
| std::vector< uint8_t > mb::base64UrlDecode | ( | const std::string & | encoded | ) |
Base64url decode; returns empty vector on invalid input.
| std::string mb::base64UrlEncode | ( | const std::string & | data | ) |
| std::string mb::base64UrlEncode | ( | const std::vector< uint8_t > & | data | ) |
Base64url encode without padding (JWT/PKCE safe alphabet).
| void mb::bindIntFieldValue | ( | soci::values & | vals, |
| const std::string & | field_name, | ||
| const nlohmann::json & | value, | ||
| MbIntPrecision | precision ) |
Bind an int JSON value into SOCI vals using the correct width/type.
|
nodiscard |
Build expression variables from an HTTP request and auth block (custom rules).
|
nodiscard |
Build expression variables for non-HTTP contexts (SSE/WS, tests).
| 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 std::string & | db_type, |
| const soci::row & | row, | ||
| int | index ) |
Convert database date value from SOCI row to string.
| db_type | database type, ie sqlite3 |
| row | SOCI row containing the date value |
| index | Column index in the row |
|
nodiscard |
| 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 |
| MbHandlerFn mb::entityDeleteHandler | ( | ) |
DELETE /api/v1/entities/:entity_name/:id — delete one record.
| MbHandlerFn mb::entityGetManyHandler | ( | ) |
GET /api/v1/entities/:entity_name — cursor-paginated list.
| MbHandlerFn mb::entityGetOneHandler | ( | ) |
GET /api/v1/entities/:entity_name/:id — read one record.
| MbHandlerFn mb::entityPatchHandler | ( | ) |
PATCH /api/v1/entities/:entity_name/:id — partial update (supports multipart).
| MbHandlerFn mb::entityPostHandler | ( | ) |
POST /api/v1/entities/:entity_name — create (supports multipart/file fields).
| MbMiddlewareFn mb::envGateMiddleware | ( | const std::string & | env_var, |
| bool | block_when_truthy ) |
Block the request when an environment variable matches a truthy state.
Reads env_var at request time. If strToBool(getEnvOrDefault(env_var, "")) equals block_when_truthy, responds with HTTP 503 and stops the middleware chain. Otherwise the request continues to the route handler.
Example: envGateMiddleware("MB_DISABLE_ADMIN_MUTATIONS", true) blocks admin account mutations when MB_DISABLE_ADMIN_MUTATIONS is set to true, 1, on, or yes.
Example: envGateMiddleware("MB_DISABLE_CONFIG_MUTATIONS", true) blocks PATCH on /api/v1/sys/settings/config when MB_DISABLE_CONFIG_MUTATIONS is truthy.
| env_var | Environment variable name |
| block_when_truthy | Truthy env value that triggers the 503 block |
|
nodiscard |
Evaluate rule against ctx (auth, verification, optional request).
|
nodiscard |
Filter topics by entity access rules.
MbEntity-only topics use the list rule; entity:row_id topics use the get rule.
| app | Application instance (entity schema lookup). |
| topics | Requested topic strings. |
| snap | Current session auth snapshot. |
|
inline |
Generate a UUID v7 string.
Thread-local RNG; counter increments within the same millisecond to reduce collision risk.
| std::string mb::generatePKCEChallenge | ( | const std::string & | verifier | ) |
| std::string mb::generatePKCEVerifier | ( | size_t | length = 43 | ) |
| 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
|
nodiscard |
Generate a unique realtime client/session ID.
| prefix | "rt_sse" or "rt_ws". |
| std::string mb::generateSecureRandom | ( | size_t | length | ) |
| 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
| MbMiddlewareFn mb::getAuthToken | ( | ) |
Extract JWT or API key from the Authorization header.
Parses Authorization: Bearer <token> or the mb_token HttpOnly cookie. Bearer is preferred when both are present. Tokens starting with mb_sk_ are treated as API keys and resolved through MbApiKeyMgr; JWTs are verified on later middleware. Sets auth and verification request attributes consumed by requireEntityAuth() and access-rule checks.
|
inline |
Resolve int precision for a column by matching field name in schema metadata.
|
inline |
Look up declared field type string for a column name.
| on | unknown column. |
|
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. |
| MbMiddlewareFn mb::hasAccess | ( | const std::string & | entity_name | ) |
Check if request has access to entity based on access rules.
| entity_name | MbEntity/table name to check access for |
| MbMiddlewareFn mb::hasEntityAccess | ( | ) |
Check access rules for the entity named in the :entity_name path param.
| std::string mb::hashPassword | ( | const std::string & | password | ) |
Digests user password + a generated salt to yield a hashed password.
| password | Password input to hash. |
| MbMiddlewareFn mb::hydrateContextData | ( | ) |
Hydrate request context with additional data.
Populates context store with request metadata and user information.
| bool mb::initWolfSsl | ( | ) |
Initialize wolfSSL once per process. Windows builds fault in HMAC and the RNG until this runs. Safe to call more than once.
|
nodiscard |
Parse precision from a field JSON object. Accepts string tokens (i8, u32, …) or legacy numeric bit widths (8, 16, 32, 64) as signed.
|
nodiscard |
Parse a precision token; throws on unknown input.
|
nodiscard |
|
nodiscard |
Map precision to the SOCI indicator type used for bind/read.
|
nodiscard |
|
nodiscard |
| 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. |
|
nodiscard |
auth represents an mb_admins session. | bool mb::isAllowedFileExtension | ( | const std::string & | extension | ) |
extension is on the upload allow-list.
|
nodiscard |
|
nodiscard |
|
nodiscard |
auth represents an unauthenticated guest.
|
nodiscard |
|
nodiscard |
auth represents a regular entity user session. | 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 ) |
Joins absolute path and a relative path, relative to the first path.
JSON convenience for the nlomann::json namespace
| path1 | The first absolute path or relative path |
| path2 | The relative path, subject to the first |
|
inline |
Bind a JSON entity payload to SOCI values using field metadata.
| entity | Record JSON keyed by field name. |
| fields | Schema field array (name, type, constraints, …). |
| std::invalid_argument | if fields is not an array. |
|
nodiscard |
|
inline |
| MbMiddlewareFn 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. |
|
nodiscard |
Read an int column from a SOCI row into JSON using the field precision.
| void mb::registerAdminEntityRoutes | ( | const MantisBase & | app | ) |
Register built-in admin entity routes (mb_admins, etc.) on the app router.
| MbMiddlewareFn mb::rejectViewMutations | ( | ) |
Reject POST, PATCH, and DELETE requests against view-type entities.
| MbMiddlewareFn mb::requireAdminAuth | ( | ) |
Require admin authentication.
Only allows requests from users authenticated as admins.
| MbMiddlewareFn mb::requireAdminOrEntityAuth | ( | const std::string & | entity_name | ) |
Require admin OR entity authentication.
Requires a valid JWT or API key. Allows mb_admins or users whose auth.entity matches entity_name. Missing/invalid credentials → 401; authenticated but wrong entity → 403.
| entity_name | MbEntity name for entity-based auth |
| MbMiddlewareFn mb::requireEntityAuth | ( | const std::string & | entity_name | ) |
Require entity-specific authentication.
Requires a valid JWT or API key for entity_name only. Admins from other entities are rejected. Missing/invalid credentials → 401; wrong entity → 403.
| entity_name | MbEntity name to authenticate against |
| MbMiddlewareFn mb::requireExprEval | ( | const std::string & | expr | ) |
Require expression evaluation to pass.
Evaluates expr with auth and req variables (same context as entity custom access rules). Does not require authentication upfront — the expression decides. Returns 403 with "Access denied!" when false.
| expr | Expression string to evaluate (auth.id, @auth.id, req.body, etc.) |
| MbMiddlewareFn mb::requireGuestOnly | ( | ) |
Require guest-only access (no authentication).
Blocks authenticated users, only allows unauthenticated requests.
| MbMiddlewareFn mb::resolveAuthEntity | ( | ) |
Resolve auth entity from :entity_name path param.
Returns 404 when the entity is missing, not auth type, is a system/admin entity, or has API disabled.
| MbMiddlewareFn mb::resolveEntity | ( | ) |
Resolve entity from :entity_name path param and validate it is API-accessible.
Returns 404 when the entity does not exist, is a system entity, or has API disabled.
| 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 |
|
nodiscard |
Hydrate auth from a JWT or mb_sk_ API key.
| app | Application instance (for verification and user hydration). |
| token | Raw token; empty yields guest. Invalid/expired tokens yield guest. |
|
nodiscard |
Resolve bearer/API-key token from a realtime HTTP upgrade or SSE request.
| req | Drogon request (?token= wins over Authorization: Bearer). |
| MbMiddlewareFn mb::resolveSchema | ( | ) |
Resolve schema from :schema_name_or_id path param and validate it exists.
Returns 404 when the schema id/name is invalid or not found.
| 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::safeContentType | ( | const std::string & | extension | ) |
Map a file extension to a safe MIME type for Content-Type headers.
| 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 | ) |
Duktape/JS wrapper around sanitizeFilename (string arguments).
| 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. |
| MbHandlerFn mb::schemaDeleteHandler | ( | ) |
DELETE /api/v1/schemas/:id — drop schema and underlying table.
| MbHandlerFn mb::schemaGetManyHandler | ( | ) |
GET /api/v1/schemas — list entity schemas.
| MbHandlerFn mb::schemaGetOneHandler | ( | ) |
GET /api/v1/schemas/:id — fetch one schema by id or name.
| MbHandlerFn mb::schemaPatchHandler | ( | ) |
PATCH /api/v1/schemas/:id — update schema metadata/fields.
| MbHandlerFn mb::schemaPostHandler | ( | ) |
POST /api/v1/schemas — create a new entity schema and table.
| MbMiddlewareFn mb::settingsFeatureGate | ( | const std::string & | setting_key | ) |
Block the request when an app-settings flag is truthy.
Reads setting_key from settings().configs() at request time (default false). When the value is truthy per strToBool, responds with HTTP 503 and stops the chain.
Used for production safety toggles such as allowRegistration (when true, blocks admin API signup) and disableSchemaMutations (when true, blocks schema POST/PATCH/DELETE).
| std::string mb::sha256Hex | ( | const std::string & | input | ) |
|
inline |
Convert a SOCI result row to JSON using entity field metadata.
| db_type | Active database type string (affects date formatting). |
| row | SOCI row from a SELECT. |
| entity_fields | Schema fields array for type lookup. |
| 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. |
| std::string mb::sqlIdentifier | ( | const std::string & | ident | ) |
Validate a string as a safe SQL identifier and return it unchanged.
This is the single choke point that every query builder must route interpolated identifiers (table and column names) through, since those cannot be passed as bound parameters. Only 1..64 characters of [A-Za-z0-9_] are accepted, which makes identifier-based SQL injection impossible (no quotes, whitespace or semicolons can appear). Column and row values must still be bound via soci::use — this is only for identifiers.
| ident | Candidate identifier. |
| MbException(400) | if the identifier is not a valid SQL identifier. |
| 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 |
Format 16 raw bytes as lowercase UUID string with hyphen separators.
| std::tm mb::toLocalTime | ( | std::time_t | t | ) |
Thread-safe conversion of an epoch time to a local-time std::tm.
std::localtime returns a pointer to a shared static std::tm. This fills a private std::tm with localtime_s / localtime_r so request threads do not share that buffer.
Prefer toUtcTime() for anything persisted to the database; this is only for values intended to be rendered in the server's local timezone.
| t | Epoch time value. |
| 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::touchWsSession | ( | RealtimeWsSession & | session | ) |
Update last_activity on a WebSocket session to the current time.
| 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::tm mb::toUtcTime | ( | std::time_t | t | ) |
Thread-safe conversion of an epoch time to a UTC std::tm.
std::gmtime returns a pointer to a shared static std::tm. Concurrent calls from the server thread and a request thread race on that buffer, and on Windows the race faults. This fills a private std::tm with gmtime_s / gmtime_r. UTC is the canonical timezone for persisted timestamps so values stay stable across local timezone and DST.
| t | Epoch time value. |
| std::string mb::trim | ( | const std::string & | s | ) |
Trims leading and trailing whitespaces from a string.
| s | The string to trim. |
| std::pair< json, std::string > mb::tryParseJsonStr | ( | const std::string & | json_str | ) |
Try parsing a string to a JSON object and return the object and any error if parsing failed.
| json_str | JSON string to parse |
|
nodiscard |
Apply incoming auth to an existing session (subscribe-time upgrade).
| session | Session snapshot to update when upgrade is allowed. |
| incoming | MbAuth resolved from the subscribe request. |
|
nodiscard |
Validate min/max constraint keys on an int field definition.
|
nodiscard |
|
nodiscard |
| 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 | MbDatabase stored hashed user password. |
|
inlineconstexpr |
HttpOnly cookie name used for JWT session tokens on login/refresh responses.
|
inlineconstexpr |
Background cleanup loop interval for SSE and WebSocket stale sessions.
|
inlineconstexpr |
Idle timeout for sessions that have active topic subscriptions.
|
inlineconstexpr |
Grace period before closing a connect-only session with no subscribed topics.
|
inlineconstexpr |
Upper bound on the number of records returned by a single list() page. Requests larger than this are clamped so one request cannot force an unbounded query or response allocation.