Session routes in Kitura?

186 views Asked by At

In Vapor, I can easily secure routes in a login session with this:

drop.group(protect) {
    secure in
    secure.get("secureRoute", handler: )
    secure.post("securePostRoute", handler: )
    //and so forth
}

And the handler proceeds as usual, no checking for sessions, as it's already done by drop.group(protect).

However, in Kitura, it seems as though if I want to achieve the same thing, I'd have to do this:

router.get("/") {
    request, response, next in

    //Get the current session
    sess = request.session

    //Check if we have a session and it has a value for email
    if let sess = sess, let email = sess["email"].string {
        try response.send(fileName: pathToFile).end()
    } else {
       try response.send(fileName: pathToAnotherFile).end()
    }
}

I'll have to manually check for the session in every secure route. This will end up being very redundant.

Is there any solution as elegant as Vapor's?

1

There are 1 answers

0
Youming Lin On BEST ANSWER

If you have common logic that is needed in multiple routes, you can set up a middleware and have it execute before each route. Kitura supports Node express-style route handling; you can register middleware in sequence, and the middleware will be processed (assuming their mount paths match the request URL) in the same order that they were registered.

For example:

router.get("/private/*", handler: handler1)
router.get("/private/helloworld", handler: handler2)

In this case, a request matching "/private/helloworld" will be processed by handler1 and then by handler2, as long as handler1 invokes next() at the end of its processing.