Added ProjectDef parsing code. Unit test for , authentication logic.

This commit is contained in:
Jonathan Bernard
2017-04-24 16:31:58 -05:00
parent 053ac8dc14
commit ec967ec2bf
4 changed files with 162 additions and 43 deletions

View File

@ -1,6 +1,7 @@
import asyncdispatch, bcrypt, jester, json, jwt, os, osproc, sequtils, tempfile,
times, unittest
import asyncdispatch, bcrypt, jester, json, jwt, os, osproc, sequtils,
strutils, tempfile, times, unittest
import logging
import ./configuration, ./core, private/util
type Worker = object
@ -47,7 +48,7 @@ proc toJWT*(cfg: StrawBossConfig, session: Session): string =
jwt.sign(cfg.authSecret)
result = $jwt
proc fromJWT*(cfg: StrawBossConfig, strTok: string): Session =
proc fromJWT*(cfg: StrawBossConfig, strTok: string): Session =
let jwt = toJWT(strTok)
var secret = cfg.authSecret
if not jwt.verify(secret): raiseEx "Unable to verify auth token."
@ -66,11 +67,15 @@ proc fromJWT*(cfg: StrawBossConfig, strTok: string): Session =
proc extractSession(cfg: StrawBossConfig, request: Request): Session =
# Find the auth header
if not request.headers.hasKey("Authentication"):
if not request.headers.hasKey("Authorization"):
raiseEx "No auth token."
# Read and verify the JWT token
result = fromJWT(cfg, request.headers["Authentication"])
let headerVal = request.headers["Authorization"]
if not headerVal.startsWith("Bearer "):
raiseEx "Invalid Authentication type (only 'Bearer' is supported)."
result = fromJWT(cfg, headerVal[7..^1])
proc spawnWorker(req: RunRequest): Worker =
let dir = mkdtemp()
@ -101,10 +106,19 @@ proc makeAuthToken*(cfg: StrawBossConfig, uname, pwd: string): string =
if not validatePwd(user, pwd): raiseEx "invalid username or password"
result = toJWT(cfg, newSession(user))
template requireAuth() =
template withSession(body: untyped): untyped =
var session {.inject.}: Session
try: session = extractSession(givenCfg, request)
except: resp(Http401, makeJsonResp(Http401), "application/json")
var authed = false
try:
session = extractSession(givenCfg, request)
authed = true
except:
debug "Auth failed: " & getCurrentExceptionMsg()
resp(Http401, makeJsonResp(Http401), "application/json")
if authed: body
proc start*(givenCfg: StrawBossConfig): void =
@ -116,18 +130,22 @@ proc start*(givenCfg: StrawBossConfig): void =
appName = "/api"
routes:
get "/ping":
resp($(%*"pong"), "application/json")
get "/auth-token":
echo $request.params
try:
let authToken = makeAuthToken(givenCfg, @"username", @"password")
resp("\"" & $authToken & "\"", "application/json")
except: resp(Http401, makeJsonResp(Http401, getCurrentExceptionMsg()))
get "/projects":
requireAuth()
get "/verify-auth": withSession:
resp(Http200, $(%*{
"username": session.user.name
}), "application/json")
get "/projects": withSession:
resp($(%(givenCfg.projects)), "application/json")
post "/project/@projectName/@stepName/run/@buildRef?":