-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
196 lines (160 loc) · 5.17 KB
/
app.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
require('use-strict');
const express = require('express');
const cookieParser = require('cookie-parser');
const createError = require('http-errors');
const logger = require('morgan');
const path = require('path');
const pogon = require('pogon.html');
const session = require('client-sessions');
const cachedConfigurationValues = require('./cachedConfigurationValues');
const db = require('./db');
const dbSchema = require('./dbSchema');
const recentPosts = require('./recentPosts');
const runtimeOptions = require('./runtimeOptions');
const setExpressOptions = require('./setExpressOptions');
const avatarRouter = require('./routes/avatar');
const backupRouter = require('./routes/backup');
const blogRouter = require('./routes/blog');
const changePasswordRouter = require('./routes/changePassword');
const configRouter = require('./routes/config');
const dashboardRouter = require('./routes/dashboard');
const draftsRouter = require('./routes/drafts');
const editRouter = require('./routes/edit');
const indexRouter = require('./routes/index');
const loginRouter = require('./routes/login');
const publishRouter = require('./routes/publish');
const previewRouter = require('./routes/preview');
const redirectsRouter = require('./routes/redirects');
const searchRouter = require('./routes/search');
async function startApp() {
await dbSchema.setupSchema();
await cachedConfigurationValues.ensureConnected();
const app = express();
setExpressOptions(app);
/*
// Uncomment to diagnose header issues
app.use((req, res, next) => {
console.log(JSON.stringify(req.headers));
next();
});
*/
app.use((req, res, next) => {
// https://github.com/mozilla/node-client-sessions/issues/101#issuecomment-165024320
if (req.secure) {
req.connection.proxySecure = true
}
next();
});
const isDevelopment = app.get('env') === 'development';
// Enable session keys on http in develop mode
// (Otherwise, they require https only)
const sessionConfig = await cachedConfigurationValues.getSession();
if (isDevelopment) {
sessionConfig.cookie.secure = false;
}
app.use(session(sessionConfig));
pogon.registerCustomTag('z3_recentPosts', recentPosts);
// Set up pogon as the view handler
app.set('views', './views') // specify the views directory
app.set('view engine', 'pogon.html') // register the template engine
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
const staticPath = path.join(__dirname, runtimeOptions.publicFolder);
app.use(express.static(staticPath));
const config = await cachedConfigurationValues.getConfig();
pogon.defaultTemplate = config.overrideTemplate;
app.use(async function(req, res, next) {
try {
res.locals.isLoggedIn = false;
if (req.session) {
if (req.session.isLoggedIn) {
res.locals.isLoggedIn = true;
}
}
res.locals.staticPages = await db.getAllStaticPages();
const config = await cachedConfigurationValues.getConfig();
res.locals.config = config;
const passwordRecord = await cachedConfigurationValues.getPassword();
// Private mode
if (passwordRecord == null) {
if (req.url != '/changePassword') {
res.redirect('/changePassword');
res.end();
return;
}
} else if (config.private && !req.session.isLoggedIn) {
if (req.url != '/login') {
res.redirect('/login');
res.end();
return;
}
}
next();
} catch (err) {
next(err);
}
});
// Admin pages do not use domain forcing
app.use('/changePassword/', changePasswordRouter);
app.use('/config/', configRouter);
app.use('/dashboard/', dashboardRouter);
app.use('/drafts/', draftsRouter);
app.use('/edit/', editRouter);
app.use('/login/', loginRouter);
app.use('/publish/', publishRouter);
app.use('/backup/', backupRouter);
// Globally-readable pages use domain forcing
app.use('/', redirectsRouter);
app.use('/', avatarRouter);
app.use('/blog/', blogRouter);
app.use('/preview/', previewRouter);
app.use('/search/', searchRouter);
app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use((req, res, next) => {
next(createError(404));
});
// error handler
app.use((err, req, res, next) => {
if (res.headersSent) {
return next(err);
}
if ((err instanceof db.PostNotFoundError) ||
(err instanceof db.DraftNotFoundError) ||
(err instanceof db.ImageNotFoundError)) {
res.status(404);
res.render(
'error', {
status: 404,
message: err.message
});
return;
} else if ((err instanceof db.UnknownStaticGroupError) ||
(err instanceof db.UnknownAfterPageIdError)) {
res.status(401);
res.render(
'error', {
status: 400,
message: err.message
});
return;
} else {
if (!(err.status)) {
console.error(`Unhandled error ${req.method} ${req.originalUrl}: ${err.stack}`);
}
const args = {};
// set locals, only providing error in development
args.message = isDevelopment ? err.message : '';
args.error = isDevelopment ? err : {};
args.status = err.status || 500;
args.url = req.url;
const viewFile = err.status == 401 ? '401' : 'error';
res.status(args.status);
res.render(viewFile, args);
}
});
return app;
}
module.exports = startApp;