/
middleware.js
108 lines (96 loc) · 2.69 KB
/
middleware.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
import dedent from 'dedent';
import { validationResult } from 'express-validator';
import { createValidatorErrorFormatter } from './create-handled-error.js';
import {
getAccessTokenFromRequest,
removeCookies
} from './getSetAccessToken.js';
import { getRedirectParams } from './redirection';
export function ifNoUserRedirectHome(message, type = 'errors') {
return function (req, res, next) {
const { path } = req;
if (req.user) {
return next();
}
const { origin } = getRedirectParams(req);
req.flash(type, message || `You must be signed in to access ${path}`);
return res.redirect(origin);
};
}
export function ifNoUserSend(sendThis) {
return function (req, res, next) {
if (req.user) {
return next();
}
return res.status(200).send(sendThis);
};
}
export function ifNoUser401(req, res, next) {
if (req.user) {
return next();
}
return res.status(401).end();
}
export function ifNotVerifiedRedirectToUpdateEmail(req, res, next) {
const { user } = req;
if (!user) {
return next();
}
if (!user.emailVerified) {
req.flash(
'danger',
dedent`
We do not have your verified email address on record,
please add it in the settings to continue with your request.
`
);
return res.redirect('/settings');
}
return next();
}
export function ifUserRedirectTo(status) {
status = status === 301 ? 301 : 302;
return (req, res, next) => {
const { accessToken } = getAccessTokenFromRequest(req);
const { returnTo } = getRedirectParams(req);
if (req.user && accessToken) {
return res.status(status).redirect(returnTo);
}
if (req.user && !accessToken) {
// This request has an active auth session
// but there is no accessToken attached to the request
// perhaps the user cleared cookies?
// we need to remove the zombie auth session
removeCookies(req, res);
delete req.session.passport;
}
return next();
};
}
export function ifNotMobileRedirect() {
return (req, res, next) => {
//
// Todo: Use the below check once we have done more research on usage
//
// const isMobile = /(iPhone|iPad|Android)/.test(req.headers['user-agent']);
// if (!isMobile) {
// res.json({ error: 'not from mobile' });
// } else {
// next();
// }
next();
};
}
// for use with express-validator error formatter
export const createValidatorErrorHandler =
(...args) =>
(req, res, next) => {
const validation = validationResult(req).formatWith(
createValidatorErrorFormatter(...args)
);
if (!validation.isEmpty()) {
const errors = validation.array();
return next(errors.pop());
}
return next();
};