|
| 1 | +import NextAuth from "next-auth"; |
| 2 | +import { revalidateTag } from "next/cache"; |
| 3 | +import { cookies } from "next/headers"; |
| 4 | +import type { CollectionAfterLogoutHook } from "payload"; |
| 5 | +import { withPayload } from "../../../authjs/withPayload"; |
| 6 | +import { AUTHJS_STRATEGY_NAME } from "../../AuthjsAuthStrategy"; |
| 7 | +import type { AuthjsPluginConfig } from "../../plugin"; |
| 8 | + |
| 9 | +/** |
| 10 | + * Add logout hook to destroy the authjs session |
| 11 | + * |
| 12 | + * @see https://payloadcms.com/docs/hooks/collections#afterlogout |
| 13 | + * @see https://github.com/payloadcms/payload/blob/main/packages/payload/src/auth/operations/logout.ts |
| 14 | + */ |
| 15 | +export const logoutHook: ( |
| 16 | + pluginOptions: AuthjsPluginConfig, |
| 17 | +) => CollectionAfterLogoutHook = pluginOptions => { |
| 18 | + // Return the logout hook |
| 19 | + return async ({ req }) => { |
| 20 | + // Check if user is authenticated using the authjs strategy |
| 21 | + if (req.user?._strategy !== AUTHJS_STRATEGY_NAME) { |
| 22 | + return; |
| 23 | + } |
| 24 | + |
| 25 | + // Create authjs instance |
| 26 | + const { signOut } = NextAuth( |
| 27 | + withPayload(pluginOptions.authjsConfig, { |
| 28 | + payload: req.payload, |
| 29 | + userCollectionSlug: pluginOptions.userCollectionSlug, |
| 30 | + }), |
| 31 | + ); |
| 32 | + |
| 33 | + // Sign out and generate expired cookies using authjs |
| 34 | + const { cookies: authJsCookies } = (await signOut({ redirect: false })) as { |
| 35 | + cookies: { |
| 36 | + name: string; |
| 37 | + value: string; |
| 38 | + options: object; |
| 39 | + }[]; |
| 40 | + }; |
| 41 | + |
| 42 | + // Destroy the authjs session cookies |
| 43 | + const requestCookies = await cookies(); |
| 44 | + for (const cookie of authJsCookies) { |
| 45 | + requestCookies.set(cookie.name, cookie.value, cookie.options); |
| 46 | + } |
| 47 | + |
| 48 | + // Revalidate the cache for the payload session |
| 49 | + revalidateTag("payload-session"); |
| 50 | + }; |
| 51 | +}; |
0 commit comments