/
index.js
345 lines (322 loc) · 10.1 KB
/
index.js
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
module.exports = {
extend: '@apostrophecms/piece-type',
options: {
alias: 'redirect',
label: 'aposRedirect:label',
pluralLabel: 'aposRedirect:pluralLabel',
searchable: false,
editRole: 'editor',
publishRole: 'editor',
withType: '@apostrophecms/page',
localized: false,
quickCreate: false,
statusCode: 302,
i18n: {
ns: 'aposRedirect',
browser: true
},
openGraph: false, // Disables @apostrophecms/open-graph for redirects
seoFields: false, // Disables @apostrophecms/seo for redirects
skip: [ /\/api\/v1\/.*/ ],
before: null
},
init(self) {
self.addUnlocalizedMigration();
self.addTargetLocaleMigration();
self.createIndexes();
},
handlers(self) {
return {
beforeSave: {
slugPrefix(req, doc) {
doc.slug = 'redirect-' + doc.redirectSlug;
if (!doc.title) {
doc.title = doc.redirectSlug;
}
},
setCurrentLocale(req, doc) {
const internalPage = doc._newPage && doc._newPage[0];
// Watch out for unlocalized types and missing documents
doc.targetLocale = (doc.urlType === 'internal' && internalPage?.aposLocale)
? internalPage.aposLocale.replace(/:.*$/, '')
: null;
}
}
};
},
fields(self, options) {
const remove = [
'visibility'
];
const add = {
redirectSlug: {
// This is *not* type: 'slug' because we want to let you match any
// nonsense the old site had in there, including mixed case.
type: 'string',
label: 'aposRedirect:originalSlug',
help: 'aposRedirect:originalSlugHelp',
required: true
},
title: {
label: 'aposRedirect:title',
type: 'string',
required: true
},
urlType: {
label: 'aposRedirect:urlType',
type: 'select',
choices: [
{
label: 'aposRedirect:urlTypeInternal',
value: 'internal'
},
{
label: 'aposRedirect:urlTypeExternal',
value: 'external'
}
],
def: 'internal'
},
ignoreQueryString: {
label: 'aposRedirect:ignoreQuery',
type: 'boolean',
def: false
},
forwardQueryString: {
label: 'aposRedirect:forwardQuery',
type: 'boolean',
def: false
},
_newPage: {
type: 'relationship',
label: 'aposRedirect:newPage',
withType: '@apostrophecms/page',
if: {
urlType: 'internal'
},
builders: {
// Editors+ set up redirects, so it's OK for non-admins to follow
// them anywhere (they won't actually get access without logging in)
project: {
slug: 1,
title: 1,
_url: 1,
aposLocale: 1
}
},
max: 1
},
externalUrl: {
label: 'aposRedirect:external',
type: 'url',
if: {
urlType: 'external'
}
},
statusCode: {
label: 'aposRedirect:statusCode',
type: 'radio',
htmlHelp: 'aposRedirect:statusCodeHtmlHelp',
choices: [
{
label: 'aposRedirect:302',
value: '302'
},
{
label: 'aposRedirect:301',
value: '301'
}
],
def: '302'
}
};
const group = {
basics: {
label: 'apostrophe:basics',
fields: [
'title',
'redirectSlug',
'urlType',
'_newPage',
'externalUrl',
'statusCode',
'ignoreQueryString',
'forwardQueryString'
]
}
};
if (options.statusCode.toString() === '301') {
add.statusCode.def = options.statusCode.toString();
}
add._newPage.withType = options.withType;
return {
add,
remove,
group
};
},
middleware(self, options) {
return {
checkRedirect: {
before: self.options.before,
async middleware(req, res, next) {
try {
if (self.options.skip.find((regExp) => regExp.test(req.originalUrl))) {
return next();
}
} catch (e) {
self.apos.util.error('Error checking redirect allow list: ', e);
}
try {
const slug = req.originalUrl;
const [ pathOnly, queryString ] = slug.split('?');
const results = await self
.find(req, { $or: [ { redirectSlug: slug }, { redirectSlug: pathOnly } ] })
.currentLocaleTarget(false)
.relationships(false)
.project({
_id: 1,
redirectSlug: 1,
targetLocale: 1,
externalUrl: 1,
urlType: 1,
ignoreQueryString: 1,
forwardQueryString: 1,
statusCode: 1
})
.toArray();
if (!results.length) {
return await emitAndRedirectOrNext();
}
const foundTarget = results.find(({ redirectSlug }) => redirectSlug === slug) ||
results.find(({
redirectSlug,
ignoreQueryString
}) => redirectSlug === pathOnly && ignoreQueryString);
if (!foundTarget) {
// Query will produce a match if the path matches, but we need
// to implement ignoreQueryString: false properly
return await emitAndRedirectOrNext();
}
const shouldForwardQueryString = foundTarget && foundTarget.forwardQueryString;
const localizedReq = (
(foundTarget.urlType === 'internal') &&
Object.keys(self.apos.i18n.locales).includes(foundTarget.targetLocale) &&
(req.locale !== foundTarget.targetLocale)
)
? req.clone({ locale: foundTarget.targetLocale })
: req;
const target = foundTarget.urlType === 'internal'
? await self.find(localizedReq, { _id: foundTarget._id }).toObject()
: foundTarget;
if (!target) {
return await emitAndRedirectOrNext();
}
const parsedCode = parseInt(target.statusCode);
const status = (parsedCode && !isNaN(parsedCode)) ? parsedCode : 302;
const qs = shouldForwardQueryString && queryString ? `?${queryString}` : '';
if (target.urlType === 'internal' && target._newPage && target._newPage[0]) {
return redirect(status, target._newPage[0]._url + qs);
} else if (target.urlType === 'external' && target.externalUrl.length) {
return redirect(status, target.externalUrl + qs);
}
return await emitAndRedirectOrNext();
} catch (e) {
self.apos.util.error(e);
return res.status(500).send('error');
}
async function redirect(status, url, redirectMethod = 'rawRedirect') {
const result = {
status,
url
};
await self.emit('beforeRedirect', req, result);
return res[redirectMethod](result.status, result.url);
}
async function emitAndRedirectOrNext() {
const result = { status: 302 };
await self.emit('noMatch', req, result);
if (result.redirect) {
return redirect(result.status, result.redirect, 'redirect');
}
if (result.rawRedirect) {
return redirect(result.status, result.rawRedirect);
}
return next();
}
}
}
};
},
queries(self, query) {
return {
builders: {
currentLocaleTarget: {
def: true,
launder(val) {
return self.apos.launder.booleanOrNull(val);
},
finalize() {
const active = query.get('currentLocaleTarget');
const { locale } = query.req;
if (active && locale) {
query.and({ $or: [ { targetLocale: null }, { targetLocale: locale } ] });
}
}
}
}
};
},
methods(self) {
return {
addUnlocalizedMigration() {
self.apos.migration.add('@apostrophecms/redirect:unlocalized', async () => {
const redirects = await self.apos.doc.db.find({
type: self.name,
aposMode: 'published'
}).toArray();
for (const redirect of redirects) {
delete redirect.aposLocale;
delete redirect.aposMode;
delete redirect.lastPublishedAt;
redirect._id = redirect._id.split(':')[0];
if (redirect.aposDocId) {
await self.apos.doc.db.removeMany({
aposDocId: redirect.aposDocId
});
await self.apos.doc.db.insertOne(redirect);
}
}
});
},
addTargetLocaleMigration() {
self.apos.migration.add('@apostrophecms/redirect:addTargetLocale', async () => {
await self.apos.migration.eachDoc({
type: self.__meta.name,
urlType: 'internal',
targetLocale: {
$exists: 0
}
}, async redirect => {
await self.apos.doc.db.updateOne({
_id: redirect._id
}, {
$set: {
// It is in the nature of the original bug that we can't tell exactly
// what locale this should have been (relationships use aposDocId which
// is cross-locale and we were not saving any information about the
// target locale). However the default locale is the most
// likely to be useful and prevents a crash, and if it is not useful
// the user can just edit or remove the redirect
targetLocale: self.apos.i18n.defaultLocale
}
});
});
});
},
createIndexes() {
self.apos.doc.db.createIndex({ redirectSlug: 1 });
}
};
}
};