jester icon indicating copy to clipboard operation
jester copied to clipboard

Better support for authentication

Open ekarlso opened this issue 10 years ago • 1 comments

It would be nice to have a better way to do authentication vs having to write the same code pr route over and over.

ekarlso avatar Mar 10 '15 11:03 ekarlso

So this is super old, you probably already have a work-around, and this doesn't really add support in Jester, but for posterity, here is one way to write an auth handler.

type Session = ref object ... # session state

# look up session based on cookie, some other mechanism, etc.
proc lookupSession(req: Request): Session = ...

# whatever logic for managing if the user has the requested permission
proc userHasPermission(session: Session, permission: string): bool = ...

const page401: string = ... # whatever you want to return for 401

# for use within a routes: block
template withPermission(permission: string, body: untyped): untyped =
  let session {.inject.}: Session =  lookupSession(req)
  if not session.isNil and userHasPermission(session, permission):
    body
  else: resp(Http401, page401, "text/html")

Then use like:

routes:
  get "/restricted/resource": withPermission("canReadStuff"):
    resp("secret stuff")

  post "/restricted/new-thing": withPermission("canCreateThings"):
    # add the thing
    resp(Http201, "I made the thing")

jdbernard avatar Apr 25 '17 15:04 jdbernard