Created
September 4, 2020 11:13
-
-
Save jamesseanwright/aee5a1a12b688132b2108fd390b42a69 to your computer and use it in GitHub Desktop.
Authentication in Reno with a higher-order route handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { | |
| RouteHandler, | |
| AugmentedRequest, | |
| textResponse, | |
| createRouter, | |
| createRouteMap, | |
| } from "https://deno.land/x/[email protected]/reno/mod.ts"; | |
| import { Status } from "https://deno.land/[email protected]/http/mod.ts"; | |
| function hasValidSession(req: AugmentedRequest) { | |
| // Verify JWT, lookup session in database etc... | |
| } | |
| function unauthorised() { | |
| return textResponse("Unauthorised", {}, Status.Unauthorized); | |
| } | |
| function withAuth(handler: RouteHandler): RouteHandler { | |
| return (req) => hasValidSession(req) ? handler(req) : unauthorised(); | |
| } | |
| function profileRoute() { | |
| // Route handler for user profile | |
| } | |
| // Usage: | |
| // Protect an individual route | |
| const protectedProfile = withAuth(profileRoute); | |
| // Protect an entire router | |
| const userRouter = withAuth(createRouter(createRouteMap([ | |
| ["/profile", profileRoute], | |
| ]))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment