@opensaas/keystone-nextjs-auth 21.0.0 → 22.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # @opensaas-keystone/nextjs-auth
2
2
 
3
+ ## 22.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - 059d0cc: type fixes and and update user on login
8
+
9
+ ## 21.1.1
10
+
11
+ ### Patch Changes
12
+
13
+ - e48cb6c: Fix signin redirect error
14
+
15
+ ## 21.1.0
16
+
17
+ ### Minor Changes
18
+
19
+ - 9d35d01: Patch dependancies
20
+ - 4a593d7: dependancy updates
21
+
3
22
  ## 21.0.0
4
23
 
5
24
  ### Major Changes
@@ -11,7 +11,13 @@ declare type CoreNextAuthPageProps = {
11
11
  listKey: string;
12
12
  pages?: Partial<PagesOptions>;
13
13
  providers?: Provider[];
14
- resolver?: Function | undefined;
14
+ resolver?: (args: {
15
+ user: any;
16
+ profile: any;
17
+ account: any;
18
+ }) => {
19
+ [key: string]: boolean | string | number;
20
+ };
15
21
  sessionData: string | undefined;
16
22
  sessionSecret: string;
17
23
  };
@@ -1,3 +1,3 @@
1
- export declare const nextConfigTemplate: ({ keystonePath, }: {
1
+ export declare const nextConfigTemplate: ({ keystonePath }: {
2
2
  keystonePath: string;
3
3
  }) => string;
@@ -1,6 +1,26 @@
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';
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>;
23
+ };
4
24
  export declare type NextAuthSession = {
5
25
  listKey: string;
6
26
  itemId: string;
@@ -27,11 +47,17 @@ export declare type AuthConfig<GeneratedListTypes extends BaseListTypeInfo> = {
27
47
  identityField: GeneratedListTypes['fields'];
28
48
  /** Path for Keystone interface */
29
49
  keystonePath?: string;
30
- pages?: any;
50
+ pages?: Partial<PagesOptions>;
31
51
  /** Providers for Next Auth */
32
52
  providers: NextAuthProviders;
33
53
  /** Resolver for user to define their profile */
34
- resolver?: Function | undefined;
54
+ resolver?: (args: {
55
+ user: any;
56
+ profile: any;
57
+ account: any;
58
+ }) => Promise<{
59
+ [key: string]: boolean | string | number;
60
+ }>;
35
61
  /** Session data population */
36
62
  sessionData?: string | undefined;
37
63
  /** Next-Auth Session Secret */
@@ -5,8 +5,6 @@ Object.defineProperty(exports, '__esModule', { value: true });
5
5
  var _objectSpread = require('@babel/runtime/helpers/objectSpread2');
6
6
  var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
7
7
  var _includesInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/includes');
8
- var _indexOfInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/index-of');
9
- var _Object$values = require('@babel/runtime-corejs3/core-js-stable/object/values');
10
8
  var _mapInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/map');
11
9
  var _JSON$stringify = require('@babel/runtime-corejs3/core-js-stable/json/stringify');
12
10
  var _URL = require('@babel/runtime-corejs3/core-js-stable/url');
@@ -39,8 +37,6 @@ function _interopNamespace(e) {
39
37
  }
40
38
 
41
39
  var _includesInstanceProperty__default = /*#__PURE__*/_interopDefault(_includesInstanceProperty);
42
- var _indexOfInstanceProperty__default = /*#__PURE__*/_interopDefault(_indexOfInstanceProperty);
43
- var _Object$values__default = /*#__PURE__*/_interopDefault(_Object$values);
44
40
  var _mapInstanceProperty__default = /*#__PURE__*/_interopDefault(_mapInstanceProperty);
45
41
  var _JSON$stringify__default = /*#__PURE__*/_interopDefault(_JSON$stringify);
46
42
  var _URL__default = /*#__PURE__*/_interopDefault(_URL);
@@ -200,7 +196,7 @@ const authTemplate = ({
200
196
  return authOut;
201
197
  };
202
198
 
203
- const _excluded = ["get", "start"];
199
+ const _excluded = ["get"];
204
200
  /**
205
201
  * createAuth function
206
202
  *
@@ -239,8 +235,6 @@ function createAuth({
239
235
  context,
240
236
  isValidSession
241
237
  }) => {
242
- var _context;
243
-
244
238
  const {
245
239
  req,
246
240
  session
@@ -265,14 +259,14 @@ function createAuth({
265
259
  return;
266
260
  }
267
261
 
268
- if (_includesInstanceProperty__default["default"](pathname).call(pathname, '/_next/') || _includesInstanceProperty__default["default"](pathname).call(pathname, '/api/auth/')) {
262
+ 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)) {
269
263
  return;
270
264
  }
271
265
 
272
- if (!session && !_includesInstanceProperty__default["default"](pathname).call(pathname, `${customPath}/api/auth/`) && !(_indexOfInstanceProperty__default["default"](_context = _Object$values__default["default"](pages)).call(_context, pathname) > -1)) {
266
+ if (!session && !_includesInstanceProperty__default["default"](pathname).call(pathname, `${customPath}/api/auth/`)) {
273
267
  return {
274
268
  kind: 'redirect',
275
- to: `${customPath}/api/auth/signin`
269
+ to: (pages === null || pages === void 0 ? void 0 : pages.signIn) || `${customPath}/api/auth/signin`
276
270
  };
277
271
  }
278
272
  };
@@ -374,26 +368,16 @@ function createAuth({
374
368
 
375
369
 
376
370
  const withItemData = _sessionStrategy => {
377
- const {
378
- get,
379
- start
380
- } = _sessionStrategy,
381
- sessionStrategy = _objectWithoutProperties(_sessionStrategy, _excluded);
371
+ const sessionStrategy = _objectWithoutProperties(_sessionStrategy, _excluded);
382
372
 
383
373
  return _objectSpread(_objectSpread({}, sessionStrategy), {}, {
384
- start: async ({
385
- res
386
- }) => {
387
- console.log('start');
388
- const session = await start({
389
- res
390
- });
391
- return session;
374
+ start: async () => {
375
+ return 'false';
392
376
  },
393
377
  get: async ({
394
378
  req
395
379
  }) => {
396
- var _req$headers$authoriz;
380
+ var _req$headers, _req$headers$authoriz;
397
381
 
398
382
  const pathname = url__default["default"].parse(req === null || req === void 0 ? void 0 : req.url).pathname;
399
383
 
@@ -401,7 +385,7 @@ function createAuth({
401
385
  return;
402
386
  }
403
387
 
404
- if (((_req$headers$authoriz = req.headers.authorization) === null || _req$headers$authoriz === void 0 ? void 0 : _req$headers$authoriz.split(' ')[0]) === 'Bearer') {
388
+ 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') {
405
389
  var _token$data;
406
390
 
407
391
  const token = await jwt.getToken({
@@ -5,8 +5,6 @@ Object.defineProperty(exports, '__esModule', { value: true });
5
5
  var _objectSpread = require('@babel/runtime/helpers/objectSpread2');
6
6
  var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
7
7
  var _includesInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/includes');
8
- var _indexOfInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/index-of');
9
- var _Object$values = require('@babel/runtime-corejs3/core-js-stable/object/values');
10
8
  var _mapInstanceProperty = require('@babel/runtime-corejs3/core-js-stable/instance/map');
11
9
  var _JSON$stringify = require('@babel/runtime-corejs3/core-js-stable/json/stringify');
12
10
  require('@babel/runtime-corejs3/core-js-stable/url');
@@ -39,8 +37,6 @@ function _interopNamespace(e) {
39
37
  }
40
38
 
41
39
  var _includesInstanceProperty__default = /*#__PURE__*/_interopDefault(_includesInstanceProperty);
42
- var _indexOfInstanceProperty__default = /*#__PURE__*/_interopDefault(_indexOfInstanceProperty);
43
- var _Object$values__default = /*#__PURE__*/_interopDefault(_Object$values);
44
40
  var _mapInstanceProperty__default = /*#__PURE__*/_interopDefault(_mapInstanceProperty);
45
41
  var _JSON$stringify__default = /*#__PURE__*/_interopDefault(_JSON$stringify);
46
42
  var url__default = /*#__PURE__*/_interopDefault(url);
@@ -199,7 +195,7 @@ const authTemplate = ({
199
195
  return authOut;
200
196
  };
201
197
 
202
- const _excluded = ["get", "start"];
198
+ const _excluded = ["get"];
203
199
  /**
204
200
  * createAuth function
205
201
  *
@@ -238,8 +234,6 @@ function createAuth({
238
234
  context,
239
235
  isValidSession
240
236
  }) => {
241
- var _context;
242
-
243
237
  const {
244
238
  req,
245
239
  session
@@ -264,14 +258,14 @@ function createAuth({
264
258
  return;
265
259
  }
266
260
 
267
- if (_includesInstanceProperty__default["default"](pathname).call(pathname, '/_next/') || _includesInstanceProperty__default["default"](pathname).call(pathname, '/api/auth/')) {
261
+ 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)) {
268
262
  return;
269
263
  }
270
264
 
271
- if (!session && !_includesInstanceProperty__default["default"](pathname).call(pathname, `${customPath}/api/auth/`) && !(_indexOfInstanceProperty__default["default"](_context = _Object$values__default["default"](pages)).call(_context, pathname) > -1)) {
265
+ if (!session && !_includesInstanceProperty__default["default"](pathname).call(pathname, `${customPath}/api/auth/`)) {
272
266
  return {
273
267
  kind: 'redirect',
274
- to: `${customPath}/api/auth/signin`
268
+ to: (pages === null || pages === void 0 ? void 0 : pages.signIn) || `${customPath}/api/auth/signin`
275
269
  };
276
270
  }
277
271
  };
@@ -373,26 +367,16 @@ function createAuth({
373
367
 
374
368
 
375
369
  const withItemData = _sessionStrategy => {
376
- const {
377
- get,
378
- start
379
- } = _sessionStrategy,
380
- sessionStrategy = _objectWithoutProperties(_sessionStrategy, _excluded);
370
+ const sessionStrategy = _objectWithoutProperties(_sessionStrategy, _excluded);
381
371
 
382
372
  return _objectSpread(_objectSpread({}, sessionStrategy), {}, {
383
- start: async ({
384
- res
385
- }) => {
386
- console.log('start');
387
- const session = await start({
388
- res
389
- });
390
- return session;
373
+ start: async () => {
374
+ return 'false';
391
375
  },
392
376
  get: async ({
393
377
  req
394
378
  }) => {
395
- var _req$headers$authoriz;
379
+ var _req$headers, _req$headers$authoriz;
396
380
 
397
381
  const pathname = url__default["default"].parse(req === null || req === void 0 ? void 0 : req.url).pathname;
398
382
 
@@ -400,7 +384,7 @@ function createAuth({
400
384
  return;
401
385
  }
402
386
 
403
- if (((_req$headers$authoriz = req.headers.authorization) === null || _req$headers$authoriz === void 0 ? void 0 : _req$headers$authoriz.split(' ')[0]) === 'Bearer') {
387
+ 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') {
404
388
  var _token$data;
405
389
 
406
390
  const token = await jwt.getToken({
@@ -1,8 +1,6 @@
1
1
  import _objectSpread from '@babel/runtime/helpers/esm/objectSpread2';
2
2
  import _objectWithoutProperties from '@babel/runtime/helpers/esm/objectWithoutProperties';
3
3
  import _includesInstanceProperty from '@babel/runtime-corejs3/core-js-stable/instance/includes';
4
- import _indexOfInstanceProperty from '@babel/runtime-corejs3/core-js-stable/instance/index-of';
5
- import _Object$values from '@babel/runtime-corejs3/core-js-stable/object/values';
6
4
  import _mapInstanceProperty from '@babel/runtime-corejs3/core-js-stable/instance/map';
7
5
  import _JSON$stringify from '@babel/runtime-corejs3/core-js-stable/json/stringify';
8
6
  import _URL from '@babel/runtime-corejs3/core-js-stable/url';
@@ -165,7 +163,7 @@ const authTemplate = ({
165
163
  return authOut;
166
164
  };
167
165
 
168
- const _excluded = ["get", "start"];
166
+ const _excluded = ["get"];
169
167
  /**
170
168
  * createAuth function
171
169
  *
@@ -204,8 +202,6 @@ function createAuth({
204
202
  context,
205
203
  isValidSession
206
204
  }) => {
207
- var _context;
208
-
209
205
  const {
210
206
  req,
211
207
  session
@@ -230,14 +226,14 @@ function createAuth({
230
226
  return;
231
227
  }
232
228
 
233
- if (_includesInstanceProperty(pathname).call(pathname, '/_next/') || _includesInstanceProperty(pathname).call(pathname, '/api/auth/')) {
229
+ if (_includesInstanceProperty(pathname).call(pathname, '/_next/') || _includesInstanceProperty(pathname).call(pathname, '/api/auth/') || pages !== null && pages !== void 0 && pages.signIn && _includesInstanceProperty(pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.signIn) || pages !== null && pages !== void 0 && pages.error && _includesInstanceProperty(pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.error) || pages !== null && pages !== void 0 && pages.signOut && _includesInstanceProperty(pathname).call(pathname, pages === null || pages === void 0 ? void 0 : pages.signOut)) {
234
230
  return;
235
231
  }
236
232
 
237
- if (!session && !_includesInstanceProperty(pathname).call(pathname, `${customPath}/api/auth/`) && !(_indexOfInstanceProperty(_context = _Object$values(pages)).call(_context, pathname) > -1)) {
233
+ if (!session && !_includesInstanceProperty(pathname).call(pathname, `${customPath}/api/auth/`)) {
238
234
  return {
239
235
  kind: 'redirect',
240
- to: `${customPath}/api/auth/signin`
236
+ to: (pages === null || pages === void 0 ? void 0 : pages.signIn) || `${customPath}/api/auth/signin`
241
237
  };
242
238
  }
243
239
  };
@@ -339,26 +335,16 @@ function createAuth({
339
335
 
340
336
 
341
337
  const withItemData = _sessionStrategy => {
342
- const {
343
- get,
344
- start
345
- } = _sessionStrategy,
346
- sessionStrategy = _objectWithoutProperties(_sessionStrategy, _excluded);
338
+ const sessionStrategy = _objectWithoutProperties(_sessionStrategy, _excluded);
347
339
 
348
340
  return _objectSpread(_objectSpread({}, sessionStrategy), {}, {
349
- start: async ({
350
- res
351
- }) => {
352
- console.log('start');
353
- const session = await start({
354
- res
355
- });
356
- return session;
341
+ start: async () => {
342
+ return 'false';
357
343
  },
358
344
  get: async ({
359
345
  req
360
346
  }) => {
361
- var _req$headers$authoriz;
347
+ var _req$headers, _req$headers$authoriz;
362
348
 
363
349
  const pathname = url.parse(req === null || req === void 0 ? void 0 : req.url).pathname;
364
350
 
@@ -366,7 +352,7 @@ function createAuth({
366
352
  return;
367
353
  }
368
354
 
369
- if (((_req$headers$authoriz = req.headers.authorization) === null || _req$headers$authoriz === void 0 ? void 0 : _req$headers$authoriz.split(' ')[0]) === 'Bearer') {
355
+ 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') {
370
356
  var _token$data;
371
357
 
372
358
  const token = await getToken({
package/package.json CHANGED
@@ -1,27 +1,28 @@
1
1
  {
2
2
  "name": "@opensaas/keystone-nextjs-auth",
3
- "version": "21.0.0",
3
+ "version": "22.0.0",
4
4
  "repository": "https://github.com/opensaasau/keystone-nextjs-auth",
5
5
  "license": "MIT",
6
6
  "main": "dist/opensaas-keystone-nextjs-auth.cjs.js",
7
7
  "module": "dist/opensaas-keystone-nextjs-auth.esm.js",
8
8
  "dependencies": {
9
- "@babel/runtime": "^7.17.8",
10
- "@babel/runtime-corejs3": "^7.17.8",
9
+ "@babel/runtime": "^7.17.9",
10
+ "@babel/runtime-corejs3": "^7.17.9",
11
11
  "@types/ejs": "^3.1.0",
12
- "cookie": "^0.4.2",
12
+ "cookie": "^0.5.0",
13
13
  "cross-fetch": "^3.1.5",
14
- "ejs": "^3.1.6",
14
+ "ejs": "^3.1.7",
15
15
  "fast-deep-equal": "^3.1.3",
16
- "graphql": "^15.8.0",
17
- "next-auth": "^4.3.1"
16
+ "next-auth": "^4.3.4"
18
17
  },
19
18
  "devDependencies": {
20
19
  "@keystone-6/core": "^1.1.0",
20
+ "next": "12.1.0",
21
21
  "react": "^17.0.2"
22
22
  },
23
23
  "peerDependencies": {
24
24
  "@keystone-6/core": "^1.1.0",
25
+ "next": "12.1.0",
25
26
  "react": "^17.0.2"
26
27
  },
27
28
  "engines": {
@@ -3,12 +3,10 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var _objectSpread = require('@babel/runtime/helpers/objectSpread2');
6
- var _JSON$stringify = require('@babel/runtime-corejs3/core-js-stable/json/stringify');
7
6
  var NextAuth = require('next-auth');
8
7
 
9
8
  function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
10
9
 
11
- var _JSON$stringify__default = /*#__PURE__*/_interopDefault(_JSON$stringify);
12
10
  var NextAuth__default = /*#__PURE__*/_interopDefault(NextAuth);
13
11
 
14
12
  async function findMatchingIdentity(identityField, identity, queryAPI) {
@@ -70,9 +68,7 @@ function NextAuthPage(props) {
70
68
  resolver,
71
69
  sessionData,
72
70
  sessionSecret
73
- } = props; // TODO: (v1.1). https://github.com/ijsto/keystone-6-oauth/projects/1#card-78602004
74
-
75
- console.log('NextAuthPages... ', pages);
71
+ } = props;
76
72
 
77
73
  if (!query) {
78
74
  console.error('NextAuthPage got no query.');
@@ -123,26 +119,42 @@ function NextAuthPage(props) {
123
119
 
124
120
  if (!result.success) {
125
121
  if (!autoCreate) {
126
- console.log('`autoCreate` if set to `false`, skipping user auto-creation');
122
+ console.log('`autoCreate` is set to `false`, skipping user auto-creation');
127
123
  return false;
128
124
  }
129
125
 
130
- console.log('`autoCreate` if set to `true`, auto-creating a new user');
126
+ console.log('`autoCreate` is set to `true`, auto-creating a new user');
131
127
  const createUser = await list.createOne({
132
128
  data
133
129
  }).then(returned => {
134
- console.log('User Created', _JSON$stringify__default["default"](returned));
135
- return true;
130
+ return {
131
+ success: true,
132
+ user: returned
133
+ };
136
134
  }).catch(error => {
137
135
  console.log(error);
138
136
  throw new Error(error);
139
137
  });
140
138
  console.log('Created User', createUser);
141
- return createUser;
142
- } // await list.updateOne({where: {id: result.item.id}, data});
143
-
139
+ return createUser.success;
140
+ }
144
141
 
145
- return result.success;
142
+ console.log('Data', data);
143
+ const updateUser = await list.updateOne({
144
+ where: {
145
+ id: result.item.id
146
+ },
147
+ data
148
+ }).then(returned => {
149
+ return {
150
+ success: true,
151
+ user: returned
152
+ };
153
+ }).catch(error => {
154
+ console.log(error);
155
+ throw new Error(error);
156
+ });
157
+ return updateUser.success;
146
158
  },
147
159
 
148
160
  async redirect({
@@ -3,12 +3,10 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var _objectSpread = require('@babel/runtime/helpers/objectSpread2');
6
- var _JSON$stringify = require('@babel/runtime-corejs3/core-js-stable/json/stringify');
7
6
  var NextAuth = require('next-auth');
8
7
 
9
8
  function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
10
9
 
11
- var _JSON$stringify__default = /*#__PURE__*/_interopDefault(_JSON$stringify);
12
10
  var NextAuth__default = /*#__PURE__*/_interopDefault(NextAuth);
13
11
 
14
12
  async function findMatchingIdentity(identityField, identity, queryAPI) {
@@ -70,9 +68,7 @@ function NextAuthPage(props) {
70
68
  resolver,
71
69
  sessionData,
72
70
  sessionSecret
73
- } = props; // TODO: (v1.1). https://github.com/ijsto/keystone-6-oauth/projects/1#card-78602004
74
-
75
- console.log('NextAuthPages... ', pages);
71
+ } = props;
76
72
 
77
73
  if (!query) {
78
74
  console.error('NextAuthPage got no query.');
@@ -123,26 +119,42 @@ function NextAuthPage(props) {
123
119
 
124
120
  if (!result.success) {
125
121
  if (!autoCreate) {
126
- console.log('`autoCreate` if set to `false`, skipping user auto-creation');
122
+ console.log('`autoCreate` is set to `false`, skipping user auto-creation');
127
123
  return false;
128
124
  }
129
125
 
130
- console.log('`autoCreate` if set to `true`, auto-creating a new user');
126
+ console.log('`autoCreate` is set to `true`, auto-creating a new user');
131
127
  const createUser = await list.createOne({
132
128
  data
133
129
  }).then(returned => {
134
- console.log('User Created', _JSON$stringify__default["default"](returned));
135
- return true;
130
+ return {
131
+ success: true,
132
+ user: returned
133
+ };
136
134
  }).catch(error => {
137
135
  console.log(error);
138
136
  throw new Error(error);
139
137
  });
140
138
  console.log('Created User', createUser);
141
- return createUser;
142
- } // await list.updateOne({where: {id: result.item.id}, data});
143
-
139
+ return createUser.success;
140
+ }
144
141
 
145
- return result.success;
142
+ console.log('Data', data);
143
+ const updateUser = await list.updateOne({
144
+ where: {
145
+ id: result.item.id
146
+ },
147
+ data
148
+ }).then(returned => {
149
+ return {
150
+ success: true,
151
+ user: returned
152
+ };
153
+ }).catch(error => {
154
+ console.log(error);
155
+ throw new Error(error);
156
+ });
157
+ return updateUser.success;
146
158
  },
147
159
 
148
160
  async redirect({
@@ -1,5 +1,4 @@
1
1
  import _objectSpread from '@babel/runtime/helpers/esm/objectSpread2';
2
- import _JSON$stringify from '@babel/runtime-corejs3/core-js-stable/json/stringify';
3
2
  import NextAuth from 'next-auth';
4
3
 
5
4
  async function findMatchingIdentity(identityField, identity, queryAPI) {
@@ -61,9 +60,7 @@ function NextAuthPage(props) {
61
60
  resolver,
62
61
  sessionData,
63
62
  sessionSecret
64
- } = props; // TODO: (v1.1). https://github.com/ijsto/keystone-6-oauth/projects/1#card-78602004
65
-
66
- console.log('NextAuthPages... ', pages);
63
+ } = props;
67
64
 
68
65
  if (!query) {
69
66
  console.error('NextAuthPage got no query.');
@@ -114,26 +111,42 @@ function NextAuthPage(props) {
114
111
 
115
112
  if (!result.success) {
116
113
  if (!autoCreate) {
117
- console.log('`autoCreate` if set to `false`, skipping user auto-creation');
114
+ console.log('`autoCreate` is set to `false`, skipping user auto-creation');
118
115
  return false;
119
116
  }
120
117
 
121
- console.log('`autoCreate` if set to `true`, auto-creating a new user');
118
+ console.log('`autoCreate` is set to `true`, auto-creating a new user');
122
119
  const createUser = await list.createOne({
123
120
  data
124
121
  }).then(returned => {
125
- console.log('User Created', _JSON$stringify(returned));
126
- return true;
122
+ return {
123
+ success: true,
124
+ user: returned
125
+ };
127
126
  }).catch(error => {
128
127
  console.log(error);
129
128
  throw new Error(error);
130
129
  });
131
130
  console.log('Created User', createUser);
132
- return createUser;
133
- } // await list.updateOne({where: {id: result.item.id}, data});
134
-
131
+ return createUser.success;
132
+ }
135
133
 
136
- return result.success;
134
+ console.log('Data', data);
135
+ const updateUser = await list.updateOne({
136
+ where: {
137
+ id: result.item.id
138
+ },
139
+ data
140
+ }).then(returned => {
141
+ return {
142
+ success: true,
143
+ user: returned
144
+ };
145
+ }).catch(error => {
146
+ console.log(error);
147
+ throw new Error(error);
148
+ });
149
+ return updateUser.success;
137
150
  },
138
151
 
139
152
  async redirect({
@@ -17,10 +17,7 @@ export function getBaseAuthSchema({
17
17
  resolveType: (root, context) => context.session?.listKey,
18
18
  }),
19
19
  resolve(root, args, { session, db }) {
20
- if (
21
- typeof session?.itemId === 'string' &&
22
- typeof session.listKey === 'string'
23
- ) {
20
+ if (typeof session?.itemId === 'string' && typeof session.listKey === 'string') {
24
21
  return db[session.listKey].findOne({
25
22
  where: { id: session.itemId },
26
23
  });
package/src/index.ts CHANGED
@@ -5,8 +5,8 @@ import {
5
5
  KeystoneConfig,
6
6
  KeystoneContext,
7
7
  AdminUIConfig,
8
- SessionStrategy,
9
8
  BaseKeystoneTypeInfo,
9
+ SessionStrategy,
10
10
  } from '@keystone-6/core/types';
11
11
  import { getSession } from 'next-auth/react';
12
12
  import { getToken } from 'next-auth/jwt';
@@ -17,7 +17,7 @@ import * as cookie from 'cookie';
17
17
  import { nextConfigTemplate } from './templates/next-config';
18
18
  // import * as Path from 'path';
19
19
 
20
- import { AuthConfig, KeystoneOAuthConfig, NextAuthSession } from './types';
20
+ import { AuthConfig, KeystoneOAuthConfig, NextAuthSession, AuthSessionStrategy } from './types';
21
21
  import { getSchemaExtension } from './schema';
22
22
  import { authTemplate } from './templates/auth';
23
23
 
@@ -56,31 +56,38 @@ export function createAuth<GeneratedListTypes extends BaseListTypeInfo>({
56
56
  * - to the init page when initFirstItem is configured, and there are no user in the database
57
57
  * - to the signin page when no valid session is present
58
58
  */
59
- const pageMiddleware: AdminUIConfig<BaseKeystoneTypeInfo>['pageMiddleware'] =
60
- async ({ context, isValidSession }) => {
61
- const { req, session } = context;
62
- const pathname = url.parse(req?.url!).pathname!;
59
+ const pageMiddleware: AdminUIConfig<BaseKeystoneTypeInfo>['pageMiddleware'] = async ({
60
+ context,
61
+ isValidSession,
62
+ }) => {
63
+ const { req, session } = context;
64
+ const pathname = url.parse(req?.url!).pathname!;
63
65
 
64
- if (isValidSession) {
65
- if (pathname === `${customPath}/api/auth/signin`) {
66
- return { kind: 'redirect', to: `${customPath}` };
67
- }
68
- if (customPath !== '' && pathname === '/') {
69
- return { kind: 'redirect', to: `${customPath}` };
70
- }
71
- return;
72
- }
73
- if (pathname.includes('/_next/') || pathname.includes('/api/auth/')) {
74
- return;
66
+ if (isValidSession) {
67
+ if (pathname === `${customPath}/api/auth/signin`) {
68
+ return { kind: 'redirect', to: `${customPath}` };
75
69
  }
76
- if (
77
- !session &&
78
- !pathname.includes(`${customPath}/api/auth/`) &&
79
- !(Object.values(pages).indexOf(pathname) > -1)
80
- ) {
81
- return { kind: 'redirect', to: `${customPath}/api/auth/signin` };
70
+ if (customPath !== '' && pathname === '/') {
71
+ return { kind: 'redirect', to: `${customPath}` };
82
72
  }
83
- };
73
+ return;
74
+ }
75
+ if (
76
+ pathname.includes('/_next/') ||
77
+ pathname.includes('/api/auth/') ||
78
+ (pages?.signIn && pathname.includes(pages?.signIn)) ||
79
+ (pages?.error && pathname.includes(pages?.error)) ||
80
+ (pages?.signOut && pathname.includes(pages?.signOut))
81
+ ) {
82
+ return;
83
+ }
84
+ if (!session && !pathname.includes(`${customPath}/api/auth/`)) {
85
+ return {
86
+ kind: 'redirect',
87
+ to: pages?.signIn || `${customPath}/api/auth/signin`,
88
+ };
89
+ }
90
+ };
84
91
 
85
92
  /**
86
93
  * getAdditionalFiles
@@ -181,23 +188,20 @@ export function createAuth<GeneratedListTypes extends BaseListTypeInfo>({
181
188
  - [ ] We could support additional where input to validate item sessions (e.g an isEnabled boolean)
182
189
  */
183
190
  const withItemData = (
184
- _sessionStrategy: SessionStrategy<Record<string, any>>
185
- ): SessionStrategy<NextAuthSession | undefined> => {
186
- const { get, start, ...sessionStrategy } = _sessionStrategy;
191
+ _sessionStrategy: AuthSessionStrategy<Record<string, any>>
192
+ ): AuthSessionStrategy<NextAuthSession | never> => {
193
+ const { get, ...sessionStrategy } = _sessionStrategy;
187
194
  return {
188
195
  ...sessionStrategy,
189
- start: async ({ res }) => {
190
- console.log('start');
191
-
192
- const session = await start({ res });
193
- return session;
196
+ start: async () => {
197
+ return 'false';
194
198
  },
195
199
  get: async ({ req }) => {
196
200
  const pathname = url.parse(req?.url!).pathname!;
197
201
  if (pathname.includes('/api/auth')) {
198
202
  return;
199
203
  }
200
- if (req.headers.authorization?.split(' ')[0] === 'Bearer') {
204
+ if (req.headers?.authorization?.split(' ')[0] === 'Bearer') {
201
205
  const token = (await getToken({
202
206
  req,
203
207
  secret: sessionSecret,
@@ -252,13 +256,9 @@ export function createAuth<GeneratedListTypes extends BaseListTypeInfo>({
252
256
  ui = {
253
257
  ...keystoneConfig.ui,
254
258
  publicPages: [...(keystoneConfig.ui.publicPages || []), ...publicPages],
255
- getAdditionalFiles: [
256
- ...(keystoneConfig.ui?.getAdditionalFiles || []),
257
- getAdditionalFiles,
258
- ],
259
- pageMiddleware: async (args) =>
260
- (await pageMiddleware(args)) ??
261
- keystoneConfig?.ui?.pageMiddleware?.(args),
259
+ getAdditionalFiles: [...(keystoneConfig.ui?.getAdditionalFiles || []), getAdditionalFiles],
260
+ pageMiddleware: async args =>
261
+ (await pageMiddleware(args)) ?? keystoneConfig?.ui?.pageMiddleware?.(args),
262
262
  enableSessionItem: true,
263
263
  isAccessAllowed: async (context: KeystoneContext) => {
264
264
  const { req } = context;
@@ -286,9 +286,8 @@ export function createAuth<GeneratedListTypes extends BaseListTypeInfo>({
286
286
  };
287
287
  }
288
288
 
289
- if (!keystoneConfig.session)
290
- throw new TypeError('Missing .session configuration');
291
- const session = withItemData(keystoneConfig.session);
289
+ if (!keystoneConfig.session) throw new TypeError('Missing .session configuration');
290
+ const session = withItemData(keystoneConfig.session) as SessionStrategy<any>;
292
291
 
293
292
  const existingExtendGraphQLSchema = keystoneConfig.extendGraphqlSchema;
294
293
  return {
@@ -307,7 +306,7 @@ export function createAuth<GeneratedListTypes extends BaseListTypeInfo>({
307
306
  generateNodeAPI: true,
308
307
  },
309
308
  extendGraphqlSchema: existingExtendGraphQLSchema
310
- ? (schema) => existingExtendGraphQLSchema(extendGraphqlSchema(schema))
309
+ ? schema => existingExtendGraphQLSchema(extendGraphqlSchema(schema))
311
310
  : extendGraphqlSchema,
312
311
  };
313
312
  };
@@ -4,10 +4,7 @@ export async function findMatchingIdentity(
4
4
  identityField: string,
5
5
  identity: string | number,
6
6
  queryAPI: any
7
- ): Promise<
8
- | { success: false; code: AuthTokenRequestErrorCode }
9
- | { success: true; item: any }
10
- > {
7
+ ): Promise<{ success: false; code: AuthTokenRequestErrorCode } | { success: true; item: any }> {
11
8
  const item = await queryAPI.findOne({
12
9
  where: { [identityField]: identity },
13
10
  });
@@ -1,14 +1,9 @@
1
- import NextAuth, {
2
- CookiesOptions,
3
- EventCallbacks,
4
- PagesOptions,
5
- } from 'next-auth';
1
+ import NextAuth, { CookiesOptions, EventCallbacks, PagesOptions } from 'next-auth';
6
2
  import type { KeystoneListsAPI } from '@keystone-6/core/types';
7
3
  import { Provider } from 'next-auth/providers';
8
4
  import { JWTOptions } from 'next-auth/jwt';
9
5
  import { validateNextAuth } from '../lib/validateNextAuth';
10
6
 
11
- // TODO: See if possible to merge with `type AuthConfig`
12
7
  type CoreNextAuthPageProps = {
13
8
  autoCreate: boolean;
14
9
  cookies?: Partial<CookiesOptions>;
@@ -18,7 +13,9 @@ type CoreNextAuthPageProps = {
18
13
  listKey: string;
19
14
  pages?: Partial<PagesOptions>;
20
15
  providers?: Provider[];
21
- resolver?: Function | undefined;
16
+ resolver?: (args: { user: any; profile: any; account: any }) => {
17
+ [key: string]: boolean | string | number;
18
+ };
22
19
  sessionData: string | undefined;
23
20
  sessionSecret: string;
24
21
  };
@@ -45,8 +42,6 @@ export default function NextAuthPage(props: NextAuthPageProps) {
45
42
  sessionData,
46
43
  sessionSecret,
47
44
  } = props;
48
- // TODO: (v1.1). https://github.com/ijsto/keystone-6-oauth/projects/1#card-78602004
49
- console.log('NextAuthPages... ', pages);
50
45
 
51
46
  if (!query) {
52
47
  console.error('NextAuthPage got no query.');
@@ -79,16 +74,9 @@ export default function NextAuthPage(props: NextAuthPageProps) {
79
74
  } else {
80
75
  identity = 0;
81
76
  }
82
- const userInput = resolver
83
- ? await resolver({ user, account, profile })
84
- : {};
77
+ const userInput = resolver ? await resolver({ user, account, profile }) : {};
85
78
 
86
- const result = await validateNextAuth(
87
- identityField,
88
- identity,
89
- protectIdentities,
90
- queryAPI
91
- );
79
+ const result = await validateNextAuth(identityField, identity, protectIdentities, queryAPI);
92
80
  // ID
93
81
  const data: any = {
94
82
  [identityField]: identity,
@@ -97,30 +85,35 @@ export default function NextAuthPage(props: NextAuthPageProps) {
97
85
 
98
86
  if (!result.success) {
99
87
  if (!autoCreate) {
100
- console.log(
101
- '`autoCreate` if set to `false`, skipping user auto-creation'
102
- );
88
+ console.log('`autoCreate` is set to `false`, skipping user auto-creation');
103
89
  return false;
104
90
  }
105
- console.log(
106
- '`autoCreate` if set to `true`, auto-creating a new user'
107
- );
91
+ console.log('`autoCreate` is set to `true`, auto-creating a new user');
108
92
 
109
93
  const createUser = await list
110
94
  .createOne({ data })
111
- .then((returned) => {
112
- console.log('User Created', JSON.stringify(returned));
113
- return true;
95
+ .then(returned => {
96
+ return { success: true, user: returned };
114
97
  })
115
- .catch((error) => {
98
+ .catch(error => {
116
99
  console.log(error);
117
100
  throw new Error(error);
118
101
  });
119
102
  console.log('Created User', createUser);
120
- return createUser;
103
+ return createUser.success;
121
104
  }
122
- // await list.updateOne({where: {id: result.item.id}, data});
123
- return result.success;
105
+ console.log('Data', data);
106
+
107
+ const updateUser = await list
108
+ .updateOne({ where: { id: result.item.id }, data })
109
+ .then(returned => {
110
+ return { success: true, user: returned };
111
+ })
112
+ .catch(error => {
113
+ console.log(error);
114
+ throw new Error(error);
115
+ });
116
+ return updateUser.success;
124
117
  },
125
118
  async redirect({ url }) {
126
119
  return url;
@@ -167,5 +160,4 @@ export default function NextAuthPage(props: NextAuthPageProps) {
167
160
  });
168
161
  }
169
162
 
170
- export const getNextAuthPage = (props: NextAuthPageProps) => () =>
171
- NextAuthPage({ ...props });
163
+ export const getNextAuthPage = (props: NextAuthPageProps) => () => NextAuthPage({ ...props });
package/src/schema.ts CHANGED
@@ -9,13 +9,11 @@ export const getSchemaExtension = ({
9
9
  identityField: string;
10
10
  listKey: string;
11
11
  }): ExtendGraphqlSchema =>
12
- graphql.extend((base) => {
12
+ graphql.extend(base => {
13
13
  const baseSchema = getBaseAuthSchema({
14
14
  listKey,
15
15
  base,
16
16
  });
17
17
 
18
- return [baseSchema.extension].filter(
19
- (x): x is Exclude<typeof x, undefined> => x !== undefined
20
- );
18
+ return [baseSchema.extension].filter((x): x is Exclude<typeof x, undefined> => x !== undefined);
21
19
  });
@@ -56,11 +56,7 @@ module.exports = withPreconstruct({
56
56
  <% } %>
57
57
  });
58
58
  `;
59
- export const nextConfigTemplate = ({
60
- keystonePath,
61
- }: {
62
- keystonePath: string;
63
- }) => {
59
+ export const nextConfigTemplate = ({ keystonePath }: { keystonePath: string }) => {
64
60
  const nextConfigOut = ejs.render(template, { keystonePath });
65
61
 
66
62
  return nextConfigOut;
package/src/types.ts CHANGED
@@ -1,6 +1,27 @@
1
- import { BaseListTypeInfo, KeystoneConfig } from '@keystone-6/core/types';
2
- import { CookiesOptions, PagesOptions } from 'next-auth';
1
+ import type { ServerResponse, IncomingMessage } from 'http';
2
+ import type { NextRequest } from 'next/server';
3
3
  import { Provider } from 'next-auth/providers';
4
+ import { CookiesOptions, PagesOptions } from 'next-auth';
5
+ import { BaseListTypeInfo, KeystoneConfig, CreateContext } from '@keystone-6/core/types';
6
+
7
+ type NextAuthResponse = IncomingMessage & NextRequest;
8
+
9
+ export declare type AuthSessionStrategy<StoredSessionData> = {
10
+ start: (args: {
11
+ res: ServerResponse;
12
+ data: any;
13
+ createContext: CreateContext;
14
+ }) => Promise<string>;
15
+ end: (args: {
16
+ req: IncomingMessage;
17
+ res: ServerResponse;
18
+ createContext: CreateContext;
19
+ }) => Promise<void>;
20
+ get: (args: {
21
+ req: NextAuthResponse;
22
+ createContext: CreateContext;
23
+ }) => Promise<StoredSessionData | undefined>;
24
+ };
4
25
 
5
26
  export type NextAuthSession = { listKey: string; itemId: string; data: any };
6
27
 
@@ -15,9 +36,7 @@ type NextAuthOptions = {
15
36
  resolver: any;
16
37
  };
17
38
 
18
- export type KeystoneOAuthConfig = KeystoneConfig &
19
- KeytoneOAuthOptions &
20
- NextAuthOptions;
39
+ export type KeystoneOAuthConfig = KeystoneConfig & KeytoneOAuthOptions & NextAuthOptions;
21
40
 
22
41
  export type AuthConfig<GeneratedListTypes extends BaseListTypeInfo> = {
23
42
  /** Auth Create users in Keystone DB from Auth Provider */
@@ -31,20 +50,20 @@ export type AuthConfig<GeneratedListTypes extends BaseListTypeInfo> = {
31
50
  /** Path for Keystone interface */
32
51
  keystonePath?: string;
33
52
  // Custom pages for different NextAuth events
34
- pages?: any; // TODO: Fix types
53
+ pages?: Partial<PagesOptions>;
35
54
  /** Providers for Next Auth */
36
55
  providers: NextAuthProviders;
37
56
  /** Resolver for user to define their profile */
38
- resolver?: Function | undefined;
57
+ resolver?: (args: { user: any; profile: any; account: any }) => Promise<{
58
+ [key: string]: boolean | string | number;
59
+ }>;
39
60
  /** Session data population */
40
61
  sessionData?: string | undefined;
41
62
  /** Next-Auth Session Secret */
42
63
  sessionSecret: string;
43
64
  };
44
65
 
45
- export type AuthTokenRequestErrorCode =
46
- | 'IDENTITY_NOT_FOUND'
47
- | 'MULTIPLE_IDENTITY_MATCHES';
66
+ export type AuthTokenRequestErrorCode = 'IDENTITY_NOT_FOUND' | 'MULTIPLE_IDENTITY_MATCHES';
48
67
 
49
68
  export type PasswordAuthErrorCode =
50
69
  | AuthTokenRequestErrorCode