|
| 1 | +import NextAuth from "next-auth"; |
| 2 | +import { CollectionConfig, Forbidden, type CollectionRefreshHook } from "payload"; |
| 3 | +import { withPayload } from "../../../authjs/withPayload"; |
| 4 | +import type { AuthjsPluginConfig } from "../../plugin"; |
| 5 | +import { getAllVirtualFields } from "../../utils/getAllVirtualFields"; |
| 6 | +import { getUserAttributes } from "../../utils/getUserAttributes"; |
| 7 | + |
| 8 | +/** |
| 9 | + * Add refresh hook to override the refresh endpoint to refresh the session with authjs |
| 10 | + * |
| 11 | + * @see https://payloadcms.com/docs/hooks/collections#refresh |
| 12 | + * @see https://github.com/payloadcms/payload/blob/main/packages/payload/src/auth/operations/refresh.ts |
| 13 | + */ |
| 14 | +export const refreshHook: ( |
| 15 | + collection: CollectionConfig, |
| 16 | + pluginOptions: AuthjsPluginConfig, |
| 17 | +) => CollectionRefreshHook | undefined = (collection, pluginOptions) => { |
| 18 | + // Get all virtual fields |
| 19 | + const virtualFields = getAllVirtualFields(collection.fields); |
| 20 | + |
| 21 | + // Return the refresh hook |
| 22 | + return async ({ args: { req }, user }) => { |
| 23 | + // Get session from authjs |
| 24 | + const { auth } = NextAuth( |
| 25 | + withPayload(pluginOptions.authjsConfig, { |
| 26 | + payload: req.payload, |
| 27 | + userCollectionSlug: pluginOptions.userCollectionSlug, |
| 28 | + }), |
| 29 | + ); |
| 30 | + let session = await auth(); |
| 31 | + |
| 32 | + // If no session user, throw forbidden |
| 33 | + if (!session?.user) { |
| 34 | + throw new Forbidden(req.t); |
| 35 | + } |
| 36 | + |
| 37 | + // Get user virtual fields |
| 38 | + const virtualSessionFields = getUserAttributes(session.user, virtualFields); |
| 39 | + |
| 40 | + // Return user to payload cms |
| 41 | + return { |
| 42 | + exp: Math.floor(new Date(session.expires).getTime() / 1000), |
| 43 | + setCookie: undefined, |
| 44 | + refreshedToken: undefined as unknown as string, |
| 45 | + strategy: user._strategy, |
| 46 | + user: { |
| 47 | + ...user, |
| 48 | + ...virtualSessionFields, |
| 49 | + }, |
| 50 | + }; |
| 51 | + }; |
| 52 | +}; |
0 commit comments