all repos — litestore @ 9962f44318cea9aceea765e78ed1048ef6cca54c

A minimalist nosql document store.

Updates.
h3rald h3rald@h3rald.com
Thu, 20 Feb 2020 17:54:19 +0100
commit

9962f44318cea9aceea765e78ed1048ef6cca54c

parent

29cea5eaa9b68472dc79beda9a40998931236970

3 files changed, 33 insertions(+), 24 deletions(-)

jump to
M src/litestorepkg/lib/api_v6.nimsrc/litestorepkg/lib/api_v6.nim

@@ -1036,7 +1036,7 @@ discard ctx.duk_put_prop_string(api_idx, "head")

discard ctx.duk_put_global_string("$store") proc jError(ctx: DTContext): LSResponse = - return resError(Http500, $ctx.duk_safe_to_string(-1)) + return resError(Http500, "Middleware Error: " & $ctx.duk_safe_to_string(-1)) proc getMiddleware*(LS: LiteStore, id: string): string = if not LS.middleware.hasKey(id):

@@ -1047,34 +1047,36 @@ result = doc.data

else: result = LS.middleware[id] -proc getMiddlewareSeq(resource, id: string): seq[string] = +proc getMiddlewareSeq(resource, id, meth: string): seq[string] = result = newSeq[string]() if LS.config.kind != JObject or not LS.config.hasKey("resources"): return - var reqUri = resource & "/" & id + var reqUri = "/" & resource & "/" & id if reqUri[^1] == '/': reqUri.removeSuffix({'/'}) let parts = reqUri.split("/") - let ancestors = parts[0..parts.len-2] + let ancestors = parts[1..parts.len-2] var currentPath = "/" + var currentPaths = "" for p in ancestors: - currentPath &= p & "/*" - if LS.config["resources"].hasKey(currentPath) and LS.config["resources"][currentPath].hasKey("middleware"): - let mw = LS.config["resources"][currentPath]["middleware"] + currentPath &= p + currentPaths = currentPath & "/*" + if LS.config["resources"].hasKey(currentPaths) and LS.config["resources"][currentPaths].hasKey(meth) and LS.config["resources"][currentPaths][meth].hasKey("middleware"): + let mw = LS.config["resources"][currentPaths][meth]["middleware"] if (mw.kind == JArray): for m in mw: result.add m.getStr - if LS.config["resources"].hasKey(reqUri) and LS.config["resources"][reqUri].hasKey("middleware"): - let mw = LS.config["resources"][reqUri]["middleware"] + if LS.config["resources"].hasKey(reqUri) and LS.config["resources"][reqUri].hasKey(meth) and LS.config["resources"][reqUri][meth].hasKey("middleware"): + let mw = LS.config["resources"][reqUri][meth]["middleware"] if (mw.kind == JArray): for m in mw: result.add m.getStr proc execute*(req: var LSRequest, LS: LiteStore, resource, id: string): LSResponse = - let middleware = getMiddlewareSeq(resource, id) + let middleware = getMiddlewareSeq(resource, id, $req.reqMethod) var jReq = $(%* req) - var jRes = """ - { + echo jReq + var jRes = """{ "code": 200, "content": "", "final": false,

@@ -1084,22 +1086,20 @@ "Access-Control-Allow-Headers": "Authorization, Content-Type",

"Server": "$1", "Content-Type": "application/json" } - } - """ % [LS.appname & "/" & LS.appversion] + }""" % [LS.appname & "/" & LS.appversion] var context = "{}" - ###### # Create execution context var ctx = duk_create_heap_default() duk_console_init(ctx) duk_print_alert_init(ctx) LS.registerStoreApi(ctx, resource, id) - if ctx.duk_peval_string("JSON.parse($1);" % jReq) != 0: + if ctx.duk_peval_string("JSON.parse('$1');" % jReq) != 0: return jError(ctx) discard ctx.duk_put_global_string("$req") - if ctx.duk_peval_string("JSON.parse($1);" % jRes) != 0: + if ctx.duk_peval_string("JSON.parse('$1');" % jRes.replace("\n", "")) != 0: return jError(ctx) discard ctx.duk_put_global_string("$res") - if ctx.duk_peval_string("JSON.parse($1);" % context) != 0: + if ctx.duk_peval_string("JSON.parse('$1');" % context) != 0: return jError(ctx) discard ctx.duk_put_global_string("$ctx") # Middleware-specific functions

@@ -1130,14 +1130,16 @@ abort = ctx.duk_get_boolean(-1)

if next != 1: return resError(Http500, "Middleware does not explicitly call $next().") let code = LS.getMiddleware(middleware[i]) + echo "evaluating code" if ctx.duk_peval_string(code) != 0: + echo "error!" return jError(ctx) i.inc # Retrieve response, and request if ctx.duk_peval_string("JSON.stringify($res);") != 0: return jError(ctx) let fRes = parseJson($(ctx.duk_get_string(-1))).newLSResponse - if ctx.duk_peval_string("JSON.stringify($req;") != 0: + if ctx.duk_peval_string("JSON.stringify($req);") != 0: return jError(ctx) let fReq = parseJson($(ctx.duk_get_string(-1))).newLSRequest() ctx.duk_destroy_heap();
M src/litestorepkg/lib/server.nimsrc/litestorepkg/lib/server.nim

@@ -49,7 +49,7 @@ echo ""

LOG.info("Exiting...") quit() -template auth(uri: string): void = +template auth(uri: string, jwt: JWT): void = let cfg = access[uri] if cfg.hasKey(reqMethod): LOG.debug("Authenticating: " & reqMethod & " " & uri)

@@ -58,7 +58,7 @@ return resError(Http401, "Unauthorized - No token")

let token = req.headers["Authorization"].replace(peg"^ 'Bearer '", "") # Validate token try: - let jwt = token.toJwt() + jwt = token.toJwt() let parts = token.split(".") var sig = LS.auth["signature"].getStr discard verifySignature(parts[0] & "." & parts[1], decodeUrlSafe(parts[2]), sig)

@@ -87,6 +87,7 @@ var reqUri = "/" & info.resource & "/" & info.id

if reqUri[^1] == '/': reqUri.removeSuffix({'/'}) let reqMethod = $req.reqMethod + var jwt: JWT # Authentication/Authorization if LS.auth != newJNull(): var uri = reqUri

@@ -94,12 +95,12 @@ let access = LS.auth["access"]

while true: # Match exact url if access.hasKey(uri): - auth(uri) + auth(uri, jwt) break # Match exact url adding /* (e.g. /docs would match also /docs/* in auth.json) elif uri[^1] != '*' and uri[^1] != '/': if access.hasKey(uri & "/*"): - auth(uri & "/*") + auth(uri & "/*", jwt) break var parts = uri.split("/") if parts[^1] == "*":

@@ -112,11 +113,13 @@ else:

# If at the end of the URL, check generic URL uri = "/*" if access.hasKey(uri): - auth(uri) + auth(uri, jwt) break if info.version == "v6": if info.resource.match(peg"^docs / info / tags / indexes$"): var nReq = req + if jwt.signature.len != 0: + nReq.jwt = jwt return api_v6.execute(nReq, LS, info.resource, info.id) elif info.resource.match(peg"^dir$"): if LS.directory.len > 0:
M src/litestorepkg/lib/types.nimsrc/litestorepkg/lib/types.nim

@@ -6,6 +6,7 @@ uri,

pegs, json, strtabs, + jwt, tables import config

@@ -96,6 +97,7 @@ reqMethod*: HttpMethod

headers*: HttpHeaders protocol*: tuple[orig: string, major, minor: int] url*: Uri + jwt*: JWT hostname*: string body*: string LSResponse* = object

@@ -160,11 +162,13 @@

proc newLSResponse*(res: JsonNode): LSResponse = result.code = HttpCode(res["code"].getInt) result.content = res["content"].getStr + result.headers = newHttpHeaders() for k, v in res["headers"].pairs: result.headers[k] = v.getStr proc newLSRequest*(req: JsonNode): LSRequest = result.reqMethod = httpMethod(req["method"].getStr) + result.headers = newHttpHeaders() for k, v in req["headers"].pairs: result.headers[k] = v.getStr result.protocol = to(req["protocol"], tuple[orig: string, major, minor: int])