From 096a1235b5b8115b87f056e452afc5b7f2f6024f Mon Sep 17 00:00:00 2001 From: Michael Wolf Date: Sun, 11 Jan 2026 15:31:59 -0600 Subject: [PATCH] Add basic logout --- express/basic/logout.ts | 38 +++++++++++++++++++++++++++++++++++ express/basic/routes.ts | 2 ++ express/routes.ts | 1 + templates/basic/home.html.njk | 2 ++ 4 files changed, 43 insertions(+) create mode 100644 express/basic/logout.ts diff --git a/express/basic/logout.ts b/express/basic/logout.ts new file mode 100644 index 0000000..a1f7dc8 --- /dev/null +++ b/express/basic/logout.ts @@ -0,0 +1,38 @@ +import { SESSION_COOKIE_NAME } from "../auth/token"; +import { services } from "../services"; +import type { Call, Result, Route } from "../types"; +import { redirect } from "../util"; + +const logoutHandler = async (call: Call): Promise => { + // Extract token from cookie and invalidate the session + const token = services.auth.extractToken(call.request); + if (token) { + await services.auth.logout(token); + } + + // Clear the cookie and redirect to login + const redirectResult = redirect("/login"); + redirectResult.cookies = [ + { + name: SESSION_COOKIE_NAME, + value: "", + options: { + httpOnly: true, + secure: false, + sameSite: "lax", + maxAge: 0, + path: "/", + }, + }, + ]; + + return redirectResult; +}; + +const logoutRoute: Route = { + path: "/logout", + methods: ["GET", "POST"], + handler: logoutHandler, +}; + +export { logoutRoute }; diff --git a/express/basic/routes.ts b/express/basic/routes.ts index a27b6cd..d5b1f20 100644 --- a/express/basic/routes.ts +++ b/express/basic/routes.ts @@ -3,6 +3,7 @@ import { services } from "../services"; import type { Call, Result, Route } from "../types"; import { html, render } from "../util"; import { loginRoute } from "./login"; +import { logoutRoute } from "./logout"; const routes: Record = { hello: { @@ -29,6 +30,7 @@ const routes: Record = { }, }, login: loginRoute, + logout: logoutRoute, }; export { routes }; diff --git a/express/routes.ts b/express/routes.ts index ba3688a..8fa77ca 100644 --- a/express/routes.ts +++ b/express/routes.ts @@ -28,6 +28,7 @@ const routes: Route[] = [ basicRoutes.home, basicRoutes.hello, basicRoutes.login, + basicRoutes.logout, { path: "/slow", methods: ["GET"], diff --git a/templates/basic/home.html.njk b/templates/basic/home.html.njk index 3dd682d..20af87f 100644 --- a/templates/basic/home.html.njk +++ b/templates/basic/home.html.njk @@ -5,7 +5,9 @@ home

+ {{ email }}

+ logout