@opensaas/keystone-nextjs-auth 21.1.1 → 22.2.0

Sign up to get free protection for your applications and to get access to all the features.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # @opensaas-keystone/nextjs-auth
2
2
 
3
+ ## 22.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 4a2f20a: Allow custom session `get`, `start` and `end`
8
+
9
+ ### Patch Changes
10
+
11
+ - 4a2f20a: Set prisma and query on global in dev to prevent instantiating extra `PrismaClient` instances
12
+
13
+ ## 22.1.0
14
+
15
+ ### Minor Changes
16
+
17
+ - b89f4e7: Invalidate user when deleted from database
18
+
19
+ ### Patch Changes
20
+
21
+ - b89f4e7: signin pages error fix
22
+
23
+ ## 22.0.0
24
+
25
+ ### Major Changes
26
+
27
+ - 059d0cc: type fixes and and update user on login
28
+
3
29
  ## 21.1.1
4
30
 
5
31
  ### Patch Changes
@@ -1,11 +1,11 @@
1
- import { BaseListTypeInfo, KeystoneConfig } from "@keystone-6/core/types";
2
- import { AuthConfig, KeystoneOAuthConfig } from "./types";
1
+ import { BaseListTypeInfo, KeystoneConfig } from '@keystone-6/core/types';
2
+ import { AuthConfig, KeystoneOAuthConfig } from './types';
3
3
  /**
4
4
  * createAuth function
5
5
  *
6
6
  * Generates config for Keystone to implement standard auth features.
7
7
  */
8
- export type { NextAuthProviders, KeystoneOAuthConfig } from "./types";
8
+ export type { NextAuthProviders, KeystoneOAuthConfig } from './types';
9
9
  export declare function createAuth<GeneratedListTypes extends BaseListTypeInfo>({ autoCreate, cookies, identityField, listKey, keystonePath, pages, resolver, providers, sessionData, sessionSecret, }: AuthConfig<GeneratedListTypes>): {
10
10
  withAuth: (keystoneConfig: KeystoneConfig) => KeystoneOAuthConfig;
11
11
  };
@@ -2,24 +2,29 @@ import { CookiesOptions, EventCallbacks, PagesOptions } from 'next-auth';
2
2
  import type { KeystoneListsAPI } from '@keystone-6/core/types';
3
3
  import { Provider } from 'next-auth/providers';
4
4
  import { JWTOptions } from 'next-auth/jwt';
5
- declare type CoreNextAuthPageProps = {
5
+ export declare type NextAuthTemplateProps = {
6
6
  autoCreate: boolean;
7
- cookies?: Partial<CookiesOptions>;
8
- events?: Partial<EventCallbacks>;
9
7
  identityField: string;
10
- jwt?: Partial<JWTOptions>;
11
8
  listKey: string;
12
- pages?: Partial<PagesOptions>;
13
- providers?: Provider[];
14
- resolver?: Function | undefined;
15
9
  sessionData: string | undefined;
16
10
  sessionSecret: string;
17
11
  };
18
- declare type NextAuthGglProps = {
19
- mutationName?: string;
20
- query?: KeystoneListsAPI<any>;
12
+ export declare type CoreNextAuthPageProps = {
13
+ cookies?: Partial<CookiesOptions>;
14
+ events?: Partial<EventCallbacks>;
15
+ jwt?: Partial<JWTOptions>;
16
+ pages?: Partial<PagesOptions>;
17
+ providers: Provider[];
18
+ resolver?: (args: {
19
+ user: any;
20
+ profile: any;
21
+ account: any;
22
+ }) => Promise<{
23
+ [key: string]: boolean | string | number;
24
+ }>;
25
+ } & NextAuthTemplateProps;
26
+ export declare type NextAuthPageProps = CoreNextAuthPageProps & {
27
+ query: KeystoneListsAPI<any>;
21
28
  };
22
- export declare type NextAuthPageProps = CoreNextAuthPageProps & NextAuthGglProps;
23
29
  export default function NextAuthPage(props: NextAuthPageProps): any;
24
30
  export declare const getNextAuthPage: (props: NextAuthPageProps) => () => any;
25
- export {};
@@ -1,4 +1,2 @@
1
- import { NextAuthPageProps } from '../pages/NextAuthPage';
2
- declare type AuthTemplateOptions = NextAuthPageProps;
3
- export declare const authTemplate: ({ autoCreate, identityField, listKey, sessionData, sessionSecret, }: AuthTemplateOptions) => string;
4
- export {};
1
+ import { NextAuthTemplateProps } from '../pages/NextAuthPage';
2
+ export declare const authTemplate: ({ autoCreate, identityField, listKey, sessionData, sessionSecret, }: NextAuthTemplateProps) => string;
@@ -1,3 +1,3 @@
1
- export declare const nextConfigTemplate: ({ keystonePath, }: {
1
+ export declare const nextConfigTemplate: ({ keystonePath }: {
2
2
  keystonePath: string;
3
3
  }) => string;
@@ -1,10 +1,25 @@
1
- import { BaseListTypeInfo, KeystoneConfig } from '@keystone-6/core/types';
2
- import { CookiesOptions, PagesOptions } from 'next-auth';
1
+ /// <reference types="node" />
2
+ import type { ServerResponse, IncomingMessage } from 'http';
3
+ import type { NextRequest } from 'next/server';
3
4
  import { Provider } from 'next-auth/providers';
4
- export declare type NextAuthSession = {
5
- listKey: string;
6
- itemId: string;
7
- data: any;
5
+ import { CookiesOptions, PagesOptions } from 'next-auth';
6
+ import { BaseListTypeInfo, KeystoneConfig, CreateContext } from '@keystone-6/core/types';
7
+ declare type NextAuthResponse = IncomingMessage & NextRequest;
8
+ export declare type AuthSessionStrategy<StoredSessionData> = {
9
+ start: (args: {
10
+ res: ServerResponse;
11
+ data: any;
12
+ createContext: CreateContext;
13
+ }) => Promise<string>;
14
+ end: (args: {
15
+ req: IncomingMessage;
16
+ res: ServerResponse;
17
+ createContext: CreateContext;
18
+ }) => Promise<void>;
19
+ get: (args: {
20
+ req: NextAuthResponse;
21
+ createContext: CreateContext;
22
+ }) => Promise<StoredSessionData | undefined>;
8
23
  };
9
24
  export declare type NextAuthProviders = Provider[];
10
25
  declare type KeytoneOAuthOptions = {
@@ -27,11 +42,17 @@ export declare type AuthConfig<GeneratedListTypes extends BaseListTypeInfo> = {
27
42
  identityField: GeneratedListTypes['fields'];
28
43
  /** Path for Keystone interface */
29
44
  keystonePath?: string;
30
- pages?: any;
45
+ pages?: Partial<PagesOptions>;
31
46
  /** Providers for Next Auth */
32
47
  providers: NextAuthProviders;
33
48
  /** Resolver for user to define their profile */
34
- resolver?: Function | undefined;
49
+ resolver?: (args: {
50
+ user: any;
51
+ profile: any;
52
+ account: any;
53
+ }) => Promise<{
54
+ [key: string]: boolean | string | number;
55
+ }>;
35
56
  /** Session data population */
36
57
  sessionData?: string | undefined;
37
58
  /** Next-Auth Session Secret */
@@ -164,8 +164,17 @@ const getSchemaExtension = ({
164
164
 
165
165
  const template = `
166
166
  import getNextAuthPage from '@opensaas/keystone-nextjs-auth/pages/NextAuthPage';
167
- import { query } from '.keystone/api';
168
167
  import keystoneConfig from '../../../../../keystone';
168
+ import { PrismaClient } from '.prisma/client';
169
+ import { createQueryAPI } from '@keystone-6/core/___internal-do-not-use-will-break-in-patch/node-api';
170
+
171
+ const prisma = global.prisma || PrismaClient
172
+
173
+ if (process.env.NODE_ENV !== 'production') global.prisma = prisma
174
+
175
+ const query = global.query || createQueryAPI(keystoneConfig, prisma);
176
+
177
+ if (process.env.NODE_ENV !== 'production') global.query = query
169
178
 
170
179
  export default getNextAuthPage({
171
180
  autoCreate: <%= autoCreate %>,
@@ -196,7 +205,7 @@ const authTemplate = ({
196
205
  return authOut;
197
206
  };
198
207
 
199
- const _excluded = ["get", "start"];
208
+ const _excluded = ["get", "end"];
200
209
  /**
201
210
  * createAuth function
202
211
  *
@@ -219,7 +228,7 @@ function createAuth({
219
228
  // part of the createAuth API (in which case its use cases need to be documented and tested)
220
229
  // or whether always being true is what we want, in which case we can refactor our code
221
230
  // to match this. -TL
222
- const customPath = !keystonePath || keystonePath === "/" ? "" : keystonePath;
231
+ const customPath = !keystonePath || keystonePath === '/' ? '' : keystonePath;
223
232
  /**
224
233
  * pageMiddleware
225
234
  *
@@ -242,16 +251,16 @@ function createAuth({
242
251
  const pathname = url__default["default"].parse(req === null || req === void 0 ? void 0 : req.url).pathname;
243
252
 
244
253
  if (isValidSession) {
245
- if (pathname === `${customPath}/api/auth/signin`) {
254
+ if (pathname === `${customPath}/api/auth/signin` || pages !== null && pages !== void 0 && pages.signIn && _includesInstanceProperty__default["default"](pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.signIn)) {
246
255
  return {
247
- kind: "redirect",
256
+ kind: 'redirect',
248
257
  to: `${customPath}`
249
258
  };
250
259
  }
251
260
 
252
- if (customPath !== "" && pathname === "/") {
261
+ if (customPath !== '' && pathname === '/') {
253
262
  return {
254
- kind: "redirect",
263
+ kind: 'redirect',
255
264
  to: `${customPath}`
256
265
  };
257
266
  }
@@ -259,13 +268,13 @@ function createAuth({
259
268
  return;
260
269
  }
261
270
 
262
- if (_includesInstanceProperty__default["default"](pathname).call(pathname, "/_next/") || _includesInstanceProperty__default["default"](pathname).call(pathname, "/api/auth/") || _includesInstanceProperty__default["default"](pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.signIn) || _includesInstanceProperty__default["default"](pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.error) || _includesInstanceProperty__default["default"](pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.signOut)) {
271
+ if (_includesInstanceProperty__default["default"](pathname).call(pathname, '/_next/') || _includesInstanceProperty__default["default"](pathname).call(pathname, '/api/auth/') || pages !== null && pages !== void 0 && pages.signIn && _includesInstanceProperty__default["default"](pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.signIn) || pages !== null && pages !== void 0 && pages.error && _includesInstanceProperty__default["default"](pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.error) || pages !== null && pages !== void 0 && pages.signOut && _includesInstanceProperty__default["default"](pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.signOut)) {
263
272
  return;
264
273
  }
265
274
 
266
275
  if (!session && !_includesInstanceProperty__default["default"](pathname).call(pathname, `${customPath}/api/auth/`)) {
267
276
  return {
268
- kind: "redirect",
277
+ kind: 'redirect',
269
278
  to: (pages === null || pages === void 0 ? void 0 : pages.signIn) || `${customPath}/api/auth/signin`
270
279
  };
271
280
  }
@@ -282,8 +291,8 @@ function createAuth({
282
291
 
283
292
  const getAdditionalFiles = () => {
284
293
  const filesToWrite = [{
285
- mode: "write",
286
- outputPath: "pages/api/auth/[...nextauth].js",
294
+ mode: 'write',
295
+ outputPath: 'pages/api/auth/[...nextauth].js',
287
296
  src: authTemplate({
288
297
  autoCreate,
289
298
  identityField,
@@ -292,8 +301,8 @@ function createAuth({
292
301
  sessionSecret
293
302
  })
294
303
  }, {
295
- mode: "write",
296
- outputPath: "next.config.js",
304
+ mode: 'write',
305
+ outputPath: 'next.config.js',
297
306
  src: nextConfigTemplate({
298
307
  keystonePath: customPath
299
308
  })
@@ -370,64 +379,70 @@ function createAuth({
370
379
  const withItemData = _sessionStrategy => {
371
380
  const {
372
381
  get,
373
- start
382
+ end
374
383
  } = _sessionStrategy,
375
384
  sessionStrategy = _objectWithoutProperties(_sessionStrategy, _excluded);
376
385
 
377
386
  return _objectSpread(_objectSpread({}, sessionStrategy), {}, {
378
- start: async ({
379
- res
380
- }) => {
381
- console.log("start");
382
- const session = await start({
383
- res
384
- });
385
- return session;
386
- },
387
387
  get: async ({
388
- req
388
+ req,
389
+ createContext
389
390
  }) => {
390
- var _req$headers$authoriz;
391
+ var _req$headers, _req$headers$authoriz;
391
392
 
393
+ const session = await get({
394
+ req,
395
+ createContext
396
+ });
397
+ const sudoContext = createContext({
398
+ sudo: true
399
+ });
392
400
  const pathname = url__default["default"].parse(req === null || req === void 0 ? void 0 : req.url).pathname;
401
+ let nextSession;
393
402
 
394
- if (_includesInstanceProperty__default["default"](pathname).call(pathname, "/api/auth")) {
403
+ if (_includesInstanceProperty__default["default"](pathname).call(pathname, '/api/auth')) {
395
404
  return;
396
405
  }
397
406
 
398
- if (((_req$headers$authoriz = req.headers.authorization) === null || _req$headers$authoriz === void 0 ? void 0 : _req$headers$authoriz.split(" ")[0]) === "Bearer") {
399
- var _token$data;
400
-
401
- const token = await jwt.getToken({
407
+ if (((_req$headers = req.headers) === null || _req$headers === void 0 ? void 0 : (_req$headers$authoriz = _req$headers.authorization) === null || _req$headers$authoriz === void 0 ? void 0 : _req$headers$authoriz.split(' ')[0]) === 'Bearer') {
408
+ nextSession = await jwt.getToken({
402
409
  req,
403
410
  secret: sessionSecret
404
411
  });
405
-
406
- if (token !== null && token !== void 0 && (_token$data = token.data) !== null && _token$data !== void 0 && _token$data.id) {
407
- return token;
408
- }
412
+ } else {
413
+ nextSession = await react.getSession({
414
+ req
415
+ });
409
416
  }
410
417
 
411
- const nextSession = await react.getSession({
412
- req
413
- });
414
-
415
- if (nextSession) {
416
- return nextSession;
418
+ if (!nextSession || !nextSession.listKey || nextSession.listKey !== listKey || !nextSession.itemId || !sudoContext.query[listKey] || !nextSession.itemId) {
419
+ return;
417
420
  }
421
+
422
+ return _objectSpread(_objectSpread({}, nextSession), {}, {
423
+ data: nextSession.data,
424
+ listKey: nextSession.listKey,
425
+ itemId: nextSession.itemId
426
+ }, session);
418
427
  },
419
428
  end: async ({
420
429
  res,
421
- req
430
+ req,
431
+ createContext
422
432
  }) => {
423
- const TOKEN_NAME = process.env.NODE_ENV === "production" ? "__Secure-next-auth.session-token" : "next-auth.session-token";
424
- res.setHeader("Set-Cookie", cookie__namespace.serialize(TOKEN_NAME, "", {
433
+ await end({
434
+ res,
435
+ req,
436
+ createContext
437
+ });
438
+ const TOKEN_NAME = process.env.NODE_ENV === 'production' ? '__Secure-next-auth.session-token' : 'next-auth.session-token';
439
+ res.setHeader('Set-Cookie', cookie__namespace.serialize(TOKEN_NAME, '', {
425
440
  maxAge: 0,
426
441
  expires: new Date(),
427
442
  httpOnly: true,
428
- secure: process.env.NODE_ENV === "production",
429
- path: "/",
430
- sameSite: "lax",
443
+ secure: process.env.NODE_ENV === 'production',
444
+ path: '/',
445
+ sameSite: 'lax',
431
446
  // TODO: Update parse to URL
432
447
  domain: url__default["default"].parse(req.url).hostname
433
448
  }));
@@ -472,12 +487,12 @@ function createAuth({
472
487
  } = context;
473
488
  const pathname = url__default["default"].parse(req === null || req === void 0 ? void 0 : req.url).pathname; // Allow nextjs scripts and static files to be accessed without auth
474
489
 
475
- if (_includesInstanceProperty__default["default"](pathname).call(pathname, "/_next/")) {
490
+ if (_includesInstanceProperty__default["default"](pathname).call(pathname, '/_next/')) {
476
491
  return true;
477
492
  } // Allow keystone to access /api/__keystone_api_build for hot reloading
478
493
 
479
494
 
480
- if (process.env.NODE_ENV !== "production" && ((_context$req = context.req) === null || _context$req === void 0 ? void 0 : _context$req.url) !== undefined && new _URL__default["default"](context.req.url, "http://example.com").pathname === `${customPath}/api/__keystone_api_build`) {
495
+ if (process.env.NODE_ENV !== 'production' && ((_context$req = context.req) === null || _context$req === void 0 ? void 0 : _context$req.url) !== undefined && new _URL__default["default"](context.req.url, 'http://example.com').pathname === `${customPath}/api/__keystone_api_build`) {
481
496
  return true;
482
497
  }
483
498
 
@@ -486,7 +501,7 @@ function createAuth({
486
501
  });
487
502
  }
488
503
 
489
- if (!keystoneConfig.session) throw new TypeError("Missing .session configuration");
504
+ if (!keystoneConfig.session) throw new TypeError('Missing .session configuration');
490
505
  const session = withItemData(keystoneConfig.session);
491
506
  const existingExtendGraphQLSchema = keystoneConfig.extendGraphqlSchema;
492
507
  return _objectSpread(_objectSpread({}, keystoneConfig), {}, {
@@ -163,8 +163,17 @@ const getSchemaExtension = ({
163
163
 
164
164
  const template = `
165
165
  import getNextAuthPage from '@opensaas/keystone-nextjs-auth/pages/NextAuthPage';
166
- import { query } from '.keystone/api';
167
166
  import keystoneConfig from '../../../../../keystone';
167
+ import { PrismaClient } from '.prisma/client';
168
+ import { createQueryAPI } from '@keystone-6/core/___internal-do-not-use-will-break-in-patch/node-api';
169
+
170
+ const prisma = global.prisma || PrismaClient
171
+
172
+ if (process.env.NODE_ENV !== 'production') global.prisma = prisma
173
+
174
+ const query = global.query || createQueryAPI(keystoneConfig, prisma);
175
+
176
+ if (process.env.NODE_ENV !== 'production') global.query = query
168
177
 
169
178
  export default getNextAuthPage({
170
179
  autoCreate: <%= autoCreate %>,
@@ -195,7 +204,7 @@ const authTemplate = ({
195
204
  return authOut;
196
205
  };
197
206
 
198
- const _excluded = ["get", "start"];
207
+ const _excluded = ["get", "end"];
199
208
  /**
200
209
  * createAuth function
201
210
  *
@@ -218,7 +227,7 @@ function createAuth({
218
227
  // part of the createAuth API (in which case its use cases need to be documented and tested)
219
228
  // or whether always being true is what we want, in which case we can refactor our code
220
229
  // to match this. -TL
221
- const customPath = !keystonePath || keystonePath === "/" ? "" : keystonePath;
230
+ const customPath = !keystonePath || keystonePath === '/' ? '' : keystonePath;
222
231
  /**
223
232
  * pageMiddleware
224
233
  *
@@ -241,16 +250,16 @@ function createAuth({
241
250
  const pathname = url__default["default"].parse(req === null || req === void 0 ? void 0 : req.url).pathname;
242
251
 
243
252
  if (isValidSession) {
244
- if (pathname === `${customPath}/api/auth/signin`) {
253
+ if (pathname === `${customPath}/api/auth/signin` || pages !== null && pages !== void 0 && pages.signIn && _includesInstanceProperty__default["default"](pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.signIn)) {
245
254
  return {
246
- kind: "redirect",
255
+ kind: 'redirect',
247
256
  to: `${customPath}`
248
257
  };
249
258
  }
250
259
 
251
- if (customPath !== "" && pathname === "/") {
260
+ if (customPath !== '' && pathname === '/') {
252
261
  return {
253
- kind: "redirect",
262
+ kind: 'redirect',
254
263
  to: `${customPath}`
255
264
  };
256
265
  }
@@ -258,13 +267,13 @@ function createAuth({
258
267
  return;
259
268
  }
260
269
 
261
- if (_includesInstanceProperty__default["default"](pathname).call(pathname, "/_next/") || _includesInstanceProperty__default["default"](pathname).call(pathname, "/api/auth/") || _includesInstanceProperty__default["default"](pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.signIn) || _includesInstanceProperty__default["default"](pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.error) || _includesInstanceProperty__default["default"](pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.signOut)) {
270
+ if (_includesInstanceProperty__default["default"](pathname).call(pathname, '/_next/') || _includesInstanceProperty__default["default"](pathname).call(pathname, '/api/auth/') || pages !== null && pages !== void 0 && pages.signIn && _includesInstanceProperty__default["default"](pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.signIn) || pages !== null && pages !== void 0 && pages.error && _includesInstanceProperty__default["default"](pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.error) || pages !== null && pages !== void 0 && pages.signOut && _includesInstanceProperty__default["default"](pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.signOut)) {
262
271
  return;
263
272
  }
264
273
 
265
274
  if (!session && !_includesInstanceProperty__default["default"](pathname).call(pathname, `${customPath}/api/auth/`)) {
266
275
  return {
267
- kind: "redirect",
276
+ kind: 'redirect',
268
277
  to: (pages === null || pages === void 0 ? void 0 : pages.signIn) || `${customPath}/api/auth/signin`
269
278
  };
270
279
  }
@@ -281,8 +290,8 @@ function createAuth({
281
290
 
282
291
  const getAdditionalFiles = () => {
283
292
  const filesToWrite = [{
284
- mode: "write",
285
- outputPath: "pages/api/auth/[...nextauth].js",
293
+ mode: 'write',
294
+ outputPath: 'pages/api/auth/[...nextauth].js',
286
295
  src: authTemplate({
287
296
  autoCreate,
288
297
  identityField,
@@ -291,8 +300,8 @@ function createAuth({
291
300
  sessionSecret
292
301
  })
293
302
  }, {
294
- mode: "write",
295
- outputPath: "next.config.js",
303
+ mode: 'write',
304
+ outputPath: 'next.config.js',
296
305
  src: nextConfigTemplate({
297
306
  keystonePath: customPath
298
307
  })
@@ -369,64 +378,70 @@ function createAuth({
369
378
  const withItemData = _sessionStrategy => {
370
379
  const {
371
380
  get,
372
- start
381
+ end
373
382
  } = _sessionStrategy,
374
383
  sessionStrategy = _objectWithoutProperties(_sessionStrategy, _excluded);
375
384
 
376
385
  return _objectSpread(_objectSpread({}, sessionStrategy), {}, {
377
- start: async ({
378
- res
379
- }) => {
380
- console.log("start");
381
- const session = await start({
382
- res
383
- });
384
- return session;
385
- },
386
386
  get: async ({
387
- req
387
+ req,
388
+ createContext
388
389
  }) => {
389
- var _req$headers$authoriz;
390
+ var _req$headers, _req$headers$authoriz;
390
391
 
392
+ const session = await get({
393
+ req,
394
+ createContext
395
+ });
396
+ const sudoContext = createContext({
397
+ sudo: true
398
+ });
391
399
  const pathname = url__default["default"].parse(req === null || req === void 0 ? void 0 : req.url).pathname;
400
+ let nextSession;
392
401
 
393
- if (_includesInstanceProperty__default["default"](pathname).call(pathname, "/api/auth")) {
402
+ if (_includesInstanceProperty__default["default"](pathname).call(pathname, '/api/auth')) {
394
403
  return;
395
404
  }
396
405
 
397
- if (((_req$headers$authoriz = req.headers.authorization) === null || _req$headers$authoriz === void 0 ? void 0 : _req$headers$authoriz.split(" ")[0]) === "Bearer") {
398
- var _token$data;
399
-
400
- const token = await jwt.getToken({
406
+ if (((_req$headers = req.headers) === null || _req$headers === void 0 ? void 0 : (_req$headers$authoriz = _req$headers.authorization) === null || _req$headers$authoriz === void 0 ? void 0 : _req$headers$authoriz.split(' ')[0]) === 'Bearer') {
407
+ nextSession = await jwt.getToken({
401
408
  req,
402
409
  secret: sessionSecret
403
410
  });
404
-
405
- if (token !== null && token !== void 0 && (_token$data = token.data) !== null && _token$data !== void 0 && _token$data.id) {
406
- return token;
407
- }
411
+ } else {
412
+ nextSession = await react.getSession({
413
+ req
414
+ });
408
415
  }
409
416
 
410
- const nextSession = await react.getSession({
411
- req
412
- });
413
-
414
- if (nextSession) {
415
- return nextSession;
417
+ if (!nextSession || !nextSession.listKey || nextSession.listKey !== listKey || !nextSession.itemId || !sudoContext.query[listKey] || !nextSession.itemId) {
418
+ return;
416
419
  }
420
+
421
+ return _objectSpread(_objectSpread({}, nextSession), {}, {
422
+ data: nextSession.data,
423
+ listKey: nextSession.listKey,
424
+ itemId: nextSession.itemId
425
+ }, session);
417
426
  },
418
427
  end: async ({
419
428
  res,
420
- req
429
+ req,
430
+ createContext
421
431
  }) => {
422
- const TOKEN_NAME = "__Secure-next-auth.session-token" ;
423
- res.setHeader("Set-Cookie", cookie__namespace.serialize(TOKEN_NAME, "", {
432
+ await end({
433
+ res,
434
+ req,
435
+ createContext
436
+ });
437
+ const TOKEN_NAME = '__Secure-next-auth.session-token' ;
438
+ res.setHeader('Set-Cookie', cookie__namespace.serialize(TOKEN_NAME, '', {
424
439
  maxAge: 0,
425
440
  expires: new Date(),
426
441
  httpOnly: true,
427
- secure: "production" === "production",
428
- path: "/",
429
- sameSite: "lax",
442
+ secure: "production" === 'production',
443
+ path: '/',
444
+ sameSite: 'lax',
430
445
  // TODO: Update parse to URL
431
446
  domain: url__default["default"].parse(req.url).hostname
432
447
  }));
@@ -471,7 +486,7 @@ function createAuth({
471
486
  } = context;
472
487
  const pathname = url__default["default"].parse(req === null || req === void 0 ? void 0 : req.url).pathname; // Allow nextjs scripts and static files to be accessed without auth
473
488
 
474
- if (_includesInstanceProperty__default["default"](pathname).call(pathname, "/_next/")) {
489
+ if (_includesInstanceProperty__default["default"](pathname).call(pathname, '/_next/')) {
475
490
  return true;
476
491
  } // Allow keystone to access /api/__keystone_api_build for hot reloading
477
492
 
@@ -480,7 +495,7 @@ function createAuth({
480
495
  });
481
496
  }
482
497
 
483
- if (!keystoneConfig.session) throw new TypeError("Missing .session configuration");
498
+ if (!keystoneConfig.session) throw new TypeError('Missing .session configuration');
484
499
  const session = withItemData(keystoneConfig.session);
485
500
  const existingExtendGraphQLSchema = keystoneConfig.extendGraphqlSchema;
486
501
  return _objectSpread(_objectSpread({}, keystoneConfig), {}, {