Skip to content

Instantly share code, notes, and snippets.

@jamesseanwright
Created September 4, 2020 11:13
Show Gist options
  • Select an option

  • Save jamesseanwright/aee5a1a12b688132b2108fd390b42a69 to your computer and use it in GitHub Desktop.

Select an option

Save jamesseanwright/aee5a1a12b688132b2108fd390b42a69 to your computer and use it in GitHub Desktop.
Authentication in Reno with a higher-order route handler
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