-
Notifications
You must be signed in to change notification settings - Fork 217
/
express-init.js
185 lines (156 loc) · 5.86 KB
/
express-init.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
module.exports = function(crowi, app) {
const debug = require('debug')('growi:crowi:express-init');
const path = require('path');
const express = require('express');
const helmet = require('helmet');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const methodOverride = require('method-override');
const passport = require('passport');
const session = require('express-session');
const sanitizer = require('express-sanitizer');
const basicAuth = require('basic-auth-connect');
const flash = require('connect-flash');
const swig = require('swig-templates');
const webpackAssets = require('express-webpack-assets');
const i18next = require('i18next');
const i18nFsBackend = require('i18next-node-fs-backend');
const i18nSprintf = require('i18next-sprintf-postprocessor');
const i18nMiddleware = require('i18next-express-middleware');
const i18nUserSettingDetector = require('../util/i18nUserSettingDetector');
const env = crowi.node_env;
const middleware = require('../util/middlewares');
const toArrayIfNot = require('../../lib/util/toArrayIfNot');
const ErrorV3 = require('../util/ErrorV3');
// Old type config API
const config = crowi.getConfig();
const Config = crowi.model('Config');
// New type config API
const configManager = crowi.configManager;
const User = crowi.model('User');
const lngDetector = new i18nMiddleware.LanguageDetector();
lngDetector.addDetector(i18nUserSettingDetector);
i18next
.use(lngDetector)
.use(i18nFsBackend)
.use(i18nSprintf)
.init({
// debug: true,
fallbackLng: [User.LANG_EN_US],
whitelist: Object.keys(User.getLanguageLabels()).map((k) => { return User[k] }),
backend: {
loadPath: `${crowi.localeDir}{{lng}}/translation.json`,
},
detection: {
order: ['userSettingDetector', 'header', 'navigator'],
},
overloadTranslationOptionHandler: i18nSprintf.overloadTranslationOptionHandler,
// change nsSeparator from ':' to '::' because ':' is used in config keys and these are used in i18n keys
nsSeparator: '::',
});
app.use(helmet());
app.use((req, res, next) => {
const now = new Date();
const tzoffset = -(config.crowi['app:timezone'] || 9) * 60;
// for datez
const Page = crowi.model('Page');
const User = crowi.model('User');
const Config = crowi.model('Config');
app.set('tzoffset', tzoffset);
req.config = config;
req.csrfToken = null;
res.locals.req = req;
res.locals.baseUrl = configManager.getSiteUrl();
res.locals.config = config;
res.locals.env = env;
res.locals.now = now;
res.locals.tzoffset = tzoffset;
res.locals.consts = {
pageGrants: Page.getGrantLabels(),
userStatus: User.getUserStatusLabels(),
language: User.getLanguageLabels(),
restrictGuestMode: Config.getRestrictGuestModeLabels(),
registrationMode: Config.getRegistrationModeLabels(),
};
res.locals.local_config = Config.getLocalconfig(config); // config for browser context
next();
});
app.set('port', crowi.port);
const staticOption = (crowi.node_env === 'production') ? { maxAge: '30d' } : {};
app.use(express.static(crowi.publicDir, staticOption));
app.engine('html', swig.renderFile);
app.use(webpackAssets(
path.join(crowi.publicDir, 'manifest.json'),
{ devMode: (crowi.node_env === 'development') },
));
// app.set('view cache', false); // Default: true in production, otherwise undefined. -- 2017.07.04 Yuki Takei
app.set('view engine', 'html');
app.set('views', crowi.viewsDir);
app.use(methodOverride());
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(sanitizer());
app.use(cookieParser());
app.use(session(crowi.sessionConfig));
// Set basic auth middleware
app.use((req, res, next) => {
if (req.query.access_token || req.body.access_token) {
return next();
}
// FIXME:
// healthcheck endpoint exclude from basic authentication.
// however, hard coding is not desirable.
// need refactoring (ex. setting basic authentication for each routes)
if (req.path === '/_api/v3/healthcheck') {
return next();
}
const basicName = configManager.getConfig('crowi', 'security:basicName');
const basicSecret = configManager.getConfig('crowi', 'security:basicSecret');
if (basicName && basicSecret) {
return basicAuth(basicName, basicSecret)(req, res, next);
}
next();
});
// passport
if (Config.isEnabledPassport(config)) {
debug('initialize Passport');
app.use(passport.initialize());
app.use(passport.session());
}
app.use(flash());
app.use(middleware.swigFilters(crowi, app, swig));
app.use(middleware.swigFunctions(crowi, app));
app.use(middleware.csrfKeyGenerator(crowi, app));
// switch loginChecker
if (Config.isEnabledPassport(config)) {
app.use(middleware.loginCheckerForPassport(crowi, app));
}
else {
app.use(middleware.loginChecker(crowi, app));
}
app.use(i18nMiddleware.handle(i18next));
// add custom functions to express res
express.response.apiv3 = function(obj) { // not arrow function
// obj must be object
if (typeof obj !== 'object' || obj instanceof Array) {
throw new Error('invalid value supplied to res.apiv3');
}
this.json({ data: obj });
};
express.response.apiv3Err = function(_err, status = 400) { // not arrow function
if (!Number.isInteger(status)) {
throw new Error('invalid status supplied to res.apiv3Err');
}
let errors = toArrayIfNot(_err);
errors = errors.map((e) => {
if (e instanceof ErrorV3) {
return e;
}
if (typeof e === 'string') {
return { message: e };
}
throw new Error('invalid error supplied to res.apiv3Err');
});
this.status(status).json({ errors });
};
};