From 2defed11a387a541037aa9dc66bdb5bfa4f4de0d Mon Sep 17 00:00:00 2001 From: Michael Chan Date: Sun, 14 Jul 2024 21:15:29 -0700 Subject: [PATCH] add a logout button (probably not ideal) --- chan.dev/src/lib/authkit.ts | 10 +++++++++- chan.dev/src/pages/auth/callback.ts | 17 +++++++++++++++++ chan.dev/src/pages/dashboard.astro | 4 ++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/chan.dev/src/lib/authkit.ts b/chan.dev/src/lib/authkit.ts index 33872a4c..94f74b7b 100644 --- a/chan.dev/src/lib/authkit.ts +++ b/chan.dev/src/lib/authkit.ts @@ -1,7 +1,7 @@ import {sealData, unsealData} from 'iron-session' import {WorkOS} from '@workos-inc/node' import type {User} from '@workos-inc/node' -import {createRemoteJWKSet, jwtVerify} from 'jose' +import {createRemoteJWKSet, jwtVerify, decodeJwt} from 'jose' export const COOKIE_NAME = 'wos-session' @@ -51,6 +51,14 @@ export function getSignInURL() { }) } +export function getSignOutURL(sessionId: string) { + return workos.userManagement.getLogoutUrl({sessionId}) +} + +export function getSessionId(session: Session) { + return decodeJwt(session.accessToken).sid +} + export async function authenticateWithCode(code: string) { return await workos.userManagement.authenticateWithCode({ code, diff --git a/chan.dev/src/pages/auth/callback.ts b/chan.dev/src/pages/auth/callback.ts index de78b30c..eccd003d 100644 --- a/chan.dev/src/pages/auth/callback.ts +++ b/chan.dev/src/pages/auth/callback.ts @@ -22,4 +22,21 @@ export const GET: APIRoute = async ({ return redirect('/dashboard') } +export const POST: APIRoute = async ({cookies, redirect}) => { + const sessionId = String( + AUTHKIT.getSessionId( + await AUTHKIT.decryptSession( + cookies.get(AUTHKIT.COOKIE_NAME)! + ) + ) + ) + + cookies.delete( + AUTHKIT.COOKIE_NAME, + AUTHKIT.COOKIE_OPTIONS as AstroCookieSetOptions // critical that options be passed + ) + + return redirect(AUTHKIT.getSignOutURL(sessionId)) +} + export const prerender = false diff --git a/chan.dev/src/pages/dashboard.astro b/chan.dev/src/pages/dashboard.astro index 93e34be2..c8c936e7 100644 --- a/chan.dev/src/pages/dashboard.astro +++ b/chan.dev/src/pages/dashboard.astro @@ -10,4 +10,8 @@ export const prerender = false

Hello {session.user.lastName}! + +
+ +