Skip to content

Commit 9400c13

Browse files
committed
refactor: Refactor custom logout endpoint to be closer on original payload code
1 parent 66e50fc commit 9400c13

File tree

1 file changed

+70
-53
lines changed
  • packages/payload-authjs/src/payload/collection/endpoints

1 file changed

+70
-53
lines changed
Lines changed: 70 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import NextAuth from "next-auth";
2+
import type { Endpoint, PayloadRequest } from "payload";
3+
import { generateExpiredPayloadCookie, headersWithCors, logoutOperation } from "payload";
4+
25
import { NextResponse } from "next/server";
3-
import { APIError, type Endpoint, generateExpiredPayloadCookie, headersWithCors } from "payload";
46
import { withPayload } from "../../../authjs/withPayload";
57
import { AUTHJS_STRATEGY_NAME } from "../../AuthjsAuthStrategy";
68
import type { AuthjsPluginConfig } from "../../plugin";
@@ -17,72 +19,87 @@ export const logoutEndpoint: (pluginOptions: AuthjsPluginConfig) => Endpoint = p
1719
method: "post",
1820
path: "/logout",
1921
handler: async req => {
20-
const { config: collection } = getRequestCollection(req);
22+
// --- Payload cms default logic ---
23+
const collection = getRequestCollection(req);
24+
const { t } = req;
25+
const result = await logoutOperation({
26+
collection,
27+
req,
28+
});
2129

22-
if (!req.user) {
23-
throw new APIError("No User", 400);
24-
}
30+
const headers = headersWithCors({
31+
headers: new Headers(),
32+
req,
33+
});
2534

26-
if (req.user.collection !== collection.slug) {
27-
throw new APIError("Incorrect collection", 403);
35+
if (!result) {
36+
return Response.json(
37+
{
38+
message: t("error:logoutFailed"),
39+
},
40+
{
41+
headers,
42+
status: 500,
43+
},
44+
);
2845
}
2946

30-
// Create response with cors headers
47+
const expiredCookie = generateExpiredPayloadCookie({
48+
collectionAuthConfig: collection.config.auth,
49+
config: req.payload.config,
50+
cookiePrefix: req.payload.config.cookiePrefix,
51+
});
52+
53+
headers.set("Set-Cookie", expiredCookie);
54+
3155
const response = NextResponse.json(
3256
{
33-
message: req.t("authentication:logoutSuccessful"),
57+
message: t("authentication:logoutSuccessful"),
3458
},
3559
{
36-
headers: headersWithCors({
37-
headers: new Headers(),
38-
req,
39-
}),
60+
headers,
61+
status: 200,
4062
},
4163
);
4264

43-
if (req.user._strategy === AUTHJS_STRATEGY_NAME) {
44-
// Generate expired cookies using authjs
45-
const { signOut } = NextAuth(
46-
withPayload(pluginOptions.authjsConfig, {
47-
payload: req.payload,
48-
userCollectionSlug: pluginOptions.userCollectionSlug,
49-
}),
50-
);
51-
const { cookies } = (await signOut({ redirect: false })) as {
52-
cookies: {
53-
name: string;
54-
value: string;
55-
options: object;
56-
}[];
57-
};
58-
59-
// Set cookies on response
60-
for (const cookie of cookies) {
61-
response.cookies.set(cookie.name, cookie.value, cookie.options);
62-
}
63-
} else {
64-
// Generate an expired cookie using payload cms
65-
const expiredCookie = generateExpiredPayloadCookie({
66-
collectionAuthConfig: collection.auth,
67-
config: req.payload.config,
68-
cookiePrefix: req.payload.config.cookiePrefix,
69-
});
65+
// --- Custom logic ---
7066

71-
// Set cookie on response
72-
response.headers.set("Set-Cookie", expiredCookie);
73-
}
74-
75-
// Execute afterLogout hooks
76-
if (collection.hooks?.afterLogout?.length) {
77-
for (const hook of collection.hooks.afterLogout) {
78-
await hook({
79-
collection,
80-
context: req.context,
81-
req,
82-
});
83-
}
67+
// If the user is authenticated using authjs, we need to destroy the authjs session cookie
68+
if (req.user?._strategy === AUTHJS_STRATEGY_NAME) {
69+
await destroyAuthjsSessionCookie(req, response, pluginOptions);
8470
}
8571

8672
return response;
8773
},
8874
});
75+
76+
/**
77+
* Destroy the authjs session cookie
78+
*/
79+
const destroyAuthjsSessionCookie = async (
80+
req: PayloadRequest,
81+
response: NextResponse,
82+
pluginOptions: AuthjsPluginConfig,
83+
) => {
84+
// Create authjs instance
85+
const { signOut } = NextAuth(
86+
withPayload(pluginOptions.authjsConfig, {
87+
payload: req.payload,
88+
userCollectionSlug: pluginOptions.userCollectionSlug,
89+
}),
90+
);
91+
92+
// Generate expired cookies using authjs
93+
const { cookies } = (await signOut({ redirect: false })) as {
94+
cookies: {
95+
name: string;
96+
value: string;
97+
options: object;
98+
}[];
99+
};
100+
101+
// Set cookies on response
102+
for (const cookie of cookies) {
103+
response.cookies.set(cookie.name, cookie.value, cookie.options);
104+
}
105+
};

0 commit comments

Comments
 (0)