Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
331 lines (310 loc) · 11.8 KB
/
Copy pathindex.ts
File metadata and controls
331 lines (310 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import url from 'url';
import {
AdminFileToWrite,
BaseListTypeInfo,
KeystoneConfig,
KeystoneContext,
AdminUIConfig,
SessionStrategy,
BaseKeystoneTypeInfo,
} from '@keystone-6/core/types';
import { password, timestamp } from '@keystone-6/core/fields';
import { AuthConfig, AuthGqlNames } from './types';
import { getSchemaExtension } from './schema';
import { signinTemplate } from './templates/signin';
import { initTemplate } from './templates/init';
/**
* createAuth function
*
* Generates config for Keystone to implement standard auth features.
*/
export function createAuth<ListTypeInfo extends BaseListTypeInfo>({
listKey,
secretField,
initFirstItem,
identityField,
magicAuthLink,
passwordResetLink,
sessionData = 'id',
}: AuthConfig<ListTypeInfo>) {
const gqlNames: AuthGqlNames = {
// Core
authenticateItemWithPassword: `authenticate${listKey}WithPassword`,
ItemAuthenticationWithPasswordResult: `${listKey}AuthenticationWithPasswordResult`,
ItemAuthenticationWithPasswordSuccess: `${listKey}AuthenticationWithPasswordSuccess`,
ItemAuthenticationWithPasswordFailure: `${listKey}AuthenticationWithPasswordFailure`,
// Initial data
CreateInitialInput: `CreateInitial${listKey}Input`,
createInitialItem: `createInitial${listKey}`,
// Password reset
sendItemPasswordResetLink: `send${listKey}PasswordResetLink`,
SendItemPasswordResetLinkResult: `Send${listKey}PasswordResetLinkResult`,
validateItemPasswordResetToken: `validate${listKey}PasswordResetToken`,
ValidateItemPasswordResetTokenResult: `Validate${listKey}PasswordResetTokenResult`,
redeemItemPasswordResetToken: `redeem${listKey}PasswordResetToken`,
RedeemItemPasswordResetTokenResult: `Redeem${listKey}PasswordResetTokenResult`,
// Magic auth
sendItemMagicAuthLink: `send${listKey}MagicAuthLink`,
SendItemMagicAuthLinkResult: `Send${listKey}MagicAuthLinkResult`,
redeemItemMagicAuthToken: `redeem${listKey}MagicAuthToken`,
RedeemItemMagicAuthTokenResult: `Redeem${listKey}MagicAuthTokenResult`,
RedeemItemMagicAuthTokenSuccess: `Redeem${listKey}MagicAuthTokenSuccess`,
RedeemItemMagicAuthTokenFailure: `Redeem${listKey}MagicAuthTokenFailure`,
};
/**
* fields
*
* Fields added to the auth list.
*/
const fieldConfig = {
access: () => false,
ui: {
createView: { fieldMode: 'hidden' },
itemView: { fieldMode: 'hidden' },
listView: { fieldMode: 'hidden' },
},
} as const;
// These field names have to follow this format so that for e.g
// validateAuthToken() behaves correctly.
const tokenFields = (tokenType: 'passwordReset' | 'magicAuth') => ({
[`${tokenType}Token`]: password({ ...fieldConfig }),
[`${tokenType}IssuedAt`]: timestamp({ ...fieldConfig }),
[`${tokenType}RedeemedAt`]: timestamp({ ...fieldConfig }),
});
const fields = {
...(passwordResetLink && tokenFields('passwordReset')),
...(magicAuthLink && tokenFields('magicAuth')),
};
/**
* pageMiddleware
*
* Should be added to the ui.pageMiddleware stack.
*
* Redirects:
* - from the signin or init pages to the index when a valid session is present
* - to the init page when initFirstItem is configured, and there are no user in the database
* - to the signin page when no valid session is present
*/
const pageMiddleware: AdminUIConfig<BaseKeystoneTypeInfo>['pageMiddleware'] = async ({
context,
isValidSession,
}) => {
const { req, session } = context;
const pathname = url.parse(req!.url!).pathname!;
if (isValidSession) {
if (pathname === '/signin' || (initFirstItem && pathname === '/init')) {
return { kind: 'redirect', to: '/' };
}
return;
}
if (!session && initFirstItem) {
const count = await context.sudo().query[listKey].count({});
if (count === 0) {
if (pathname !== '/init') {
return { kind: 'redirect', to: '/init' };
}
return;
}
}
if (!session && pathname !== '/signin') {
let to = pathname === '/' ? '/signin' : `/signin?from=${encodeURIComponent(req!.url!)}`;
return { kind: 'redirect', to };
}
};
/**
* getAdditionalFiles
*
* This function adds files to be generated into the Admin UI build. Must be added to the
* ui.getAdditionalFiles config.
*
* The signin page is always included, and the init page is included when initFirstItem is set
*/
const getAdditionalFiles = () => {
let filesToWrite: AdminFileToWrite[] = [
{
mode: 'write',
src: signinTemplate({ gqlNames, identityField, secretField }),
outputPath: 'pages/signin.js',
},
];
if (initFirstItem) {
filesToWrite.push({
mode: 'write',
src: initTemplate({ listKey, initFirstItem }),
outputPath: 'pages/init.js',
});
}
return filesToWrite;
};
/**
* publicAuthPages
*
* Must be added to the ui.publicPages config
*/
const publicPages = ['/signin'];
if (initFirstItem) {
publicPages.push('/init');
}
/**
* extendGraphqlSchema
*
* Must be added to the extendGraphqlSchema config. Can be composed.
*/
const extendGraphqlSchema = getSchemaExtension({
identityField,
listKey,
secretField,
gqlNames,
initFirstItem,
passwordResetLink,
magicAuthLink,
sessionData,
});
/**
* validateConfig
*
* Validates the provided auth config; optional step when integrating auth
*/
const validateConfig = (keystoneConfig: KeystoneConfig) => {
const listConfig = keystoneConfig.lists[listKey];
if (listConfig === undefined) {
const msg = `A createAuth() invocation specifies the list "${listKey}" but no list with that key has been defined.`;
throw new Error(msg);
}
// TODO: Check for String-like typing for identityField? How?
// TODO: Validate that the identifyField is unique.
// TODO: If this field isn't required, what happens if I try to log in as `null`?
const identityFieldConfig = listConfig.fields[identityField];
if (identityFieldConfig === undefined) {
const i = JSON.stringify(identityField);
const msg = `A createAuth() invocation for the "${listKey}" list specifies ${i} as its identityField but no field with that key exists on the list.`;
throw new Error(msg);
}
// TODO: We could make the secret field optional to disable the standard id/secret auth and password resets (ie. magic links only)
const secretFieldConfig = listConfig.fields[secretField];
if (secretFieldConfig === undefined) {
const s = JSON.stringify(secretField);
const msg = `A createAuth() invocation for the "${listKey}" list specifies ${s} as its secretField but no field with that key exists on the list.`;
throw new Error(msg);
}
// TODO: Could also validate initFirstItem.itemData keys?
for (const field of initFirstItem?.fields || []) {
if (listConfig.fields[field] === undefined) {
const f = JSON.stringify(field);
const msg = `A createAuth() invocation for the "${listKey}" list specifies the field ${f} in initFirstItem.fields array but no field with that key exist on the list.`;
throw new Error(msg);
}
}
};
/**
* withItemData
*
* Automatically injects a session.data value with the authenticated item
*/
/* TODO:
- [ ] We could support additional where input to validate item sessions (e.g an isEnabled boolean)
*/
const withItemData = (
_sessionStrategy: SessionStrategy<Record<string, any>>
): SessionStrategy<{ listKey: string; itemId: string; data: any }> => {
const { get, ...sessionStrategy } = _sessionStrategy;
return {
...sessionStrategy,
get: async ({ req, createContext }) => {
const session = await get({ req, createContext });
const sudoContext = createContext({ sudo: true });
if (
!session ||
!session.listKey ||
session.listKey !== listKey ||
!session.itemId ||
!sudoContext.query[session.listKey]
) {
return;
}
try {
const data = await sudoContext.query[listKey].findOne({
where: { id: session.itemId },
query: sessionData,
});
if (!data) return;
return { ...session, itemId: session.itemId, listKey, data };
} catch (e) {
// TODO: the assumption is this should only be from an invalid sessionData configuration
// it could be something else though, either way, result is a bad session
return;
}
},
};
};
/**
* withAuth
*
* Automatically extends config with the correct auth functionality. This is the easiest way to
* configure auth for keystone; you should probably use it unless you want to extend or replace
* the way auth is set up with custom functionality.
*
* It validates the auth config against the provided keystone config, and preserves existing
* config by composing existing extendGraphqlSchema functions and ui config.
*/
const withAuth = (keystoneConfig: KeystoneConfig): KeystoneConfig => {
validateConfig(keystoneConfig);
let ui = keystoneConfig.ui;
if (!keystoneConfig.ui?.isDisabled) {
ui = {
...keystoneConfig.ui,
publicPages: [...(keystoneConfig.ui?.publicPages || []), ...publicPages],
getAdditionalFiles: [...(keystoneConfig.ui?.getAdditionalFiles || []), getAdditionalFiles],
pageMiddleware: async args =>
(await pageMiddleware(args)) ?? keystoneConfig?.ui?.pageMiddleware?.(args),
isAccessAllowed: async (context: KeystoneContext) => {
// Allow access to the adminMeta data from the /init path to correctly render that page
// even if the user isn't logged in (which should always be the case if they're seeing /init)
const headers = context.req?.headers;
const host = headers ? headers['x-forwarded-host'] || headers['host'] : null;
const url = headers?.referer ? new URL(headers.referer) : undefined;
const accessingInitPage =
url?.pathname === '/init' &&
url?.host === host &&
(await context.sudo().query[listKey].count({})) === 0;
return (
accessingInitPage ||
(keystoneConfig.ui?.isAccessAllowed
? keystoneConfig.ui.isAccessAllowed(context)
: context.session !== undefined)
);
},
};
}
if (!keystoneConfig.session) throw new TypeError('Missing .session configuration');
const session = withItemData(keystoneConfig.session);
const existingExtendGraphQLSchema = keystoneConfig.extendGraphqlSchema;
const listConfig = keystoneConfig.lists[listKey];
return {
...keystoneConfig,
ui,
session,
// Add the additional fields to the references lists fields object
// TODO: The fields we're adding here shouldn't naively replace existing fields with the same key
// Leaving existing fields in place would allow solution devs to customise these field defs (eg. access control,
// work factor for the tokens, etc.) without abandoning the withAuth() interface
lists: {
...keystoneConfig.lists,
[listKey]: { ...listConfig, fields: { ...listConfig.fields, ...fields } },
},
extendGraphqlSchema: existingExtendGraphQLSchema
? schema => existingExtendGraphQLSchema(extendGraphqlSchema(schema))
: extendGraphqlSchema,
};
};
return {
withAuth,
// In the future we may want to return the following so that developers can
// roll their own. This is pending a review of the use cases this might be
// appropriate for, along with documentation and testing.
// ui: { pageMiddleware, getAdditionalFiles, publicPages },
// fields,
// extendGraphqlSchema,
// validateConfig,
};
}