api: WIP CORS supoport

This commit is contained in:
Jonathan Bernard 2019-09-24 22:41:25 -05:00
parent 0a8f701c3c
commit cf60793395
6 changed files with 22 additions and 8 deletions

View File

@ -34,6 +34,10 @@ proc loadConfig*(args: Table[string, docopt.Value] = initTable[string, docopt.Va
warn "Cannot read configuration file \"" & filePath & "\":\n\t" &
getCurrentExceptionMsg()
let knownOriginsArray =
if json.hasKey("knownOrigins"): json["knownOrigins"]
else: newJArray()
let cfg = CombinedConfig(docopt: args, json: json)
result = PMApiConfig(
@ -41,7 +45,8 @@ proc loadConfig*(args: Table[string, docopt.Value] = initTable[string, docopt.Va
dbConnString: cfg.getVal("db-conn-string"),
debug: "true".startsWith(cfg.getVal("debug", "false").toLower()),
port: parseInt(cfg.getVal("port", "8080")),
pwdCost: cast[int8](parseInt(cfg.getVal("pwd-cost", "11"))))
pwdCost: cast[int8](parseInt(cfg.getVal("pwd-cost", "11"))),
knownOrigins: toSeq(knownOriginsArray).mapIt(it.getStr))
proc initContext(args: Table[string, docopt.Value]): PMApiContext =

View File

@ -32,10 +32,21 @@ template halt(code: HttpCode,
result.matched = true
break allRoutes
template jsonResp(code: HttpCode, details: string = "", headers: RawHeaders = @{:} ) =
template jsonResp(code: HttpCode, details: string = "", headersToSend: RawHeaders = @{:} ) =
let reqOrigin = $(request.headers["Origin"])
let corsHeaders =
if ctx.cfg.knownOrigins.contains(reqOrigin):
@{
"Access-Control-Allow-Origin": reqOrigin,
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": $(request.reqMeth)
}
else: @{:}
halt(
code,
headers & @{
headersToSend & corsHeaders & @{
"Content-Type": JSON,
"Cache-Control": "no-cache"
},

View File

@ -9,6 +9,7 @@ type
debug*: bool
port*: int
pwdCost*: int8
knownOrigins*: seq[string]
PMApiContext* = object
cfg*: PMApiConfig
@ -23,7 +24,8 @@ proc `%`*(cfg: PMApiConfig): JsonNode =
"dbConnString": cfg.dbConnString,
"debug": cfg.debug,
"port": cfg.port,
"pwdCost": cfg.pwdCost }
"pwdCost": cfg.pwdCost,
"knownOrigins": cfg.knownOrigins }
template raiseEx*(errorType: type, reason: string): void =
raise newException(errorType, reason)

View File

@ -1 +0,0 @@
{"Modules":[{"Key":"","Source":"","Dir":"."},{"Key":"dev_env","Source":"./deployed_env","Dir":"deployed_env"},{"Key":"prod_env","Source":"./deployed_env","Dir":"deployed_env"}]}

View File

@ -1,3 +0,0 @@
{
"aws": "7b0461a9e1bb61eb2b58ee46d67d51a2f59d4b0fe6137025c82b4f5060477d2f"
}