-
Notifications
You must be signed in to change notification settings - Fork 11
/
app.js
213 lines (178 loc) · 5.31 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const env = require('dotenv');
const bodyParser = require('body-parser');
const fs = require('fs');
const morgan = require('morgan');
const cors = require('cors');
const passport = require('passport');
const helmet = require('helmet');
const { promisify } = require('es6-promisify');
const cookieParser = require('cookie-parser');
const flash = require('connect-flash');
const fileUpload = require('express-fileupload');
const Scheduler = require('./models/scheduledTasks');
const errorHandlers = require('./handlers/errorHandlers');
const helpers = require('./helpers');
const { getBreadcrumbs } = require('./handlers/breadcrumbs');
const compression = require('compression');
const csurf = require('csurf');
const { csrfProtection } = require('./middleware/csrfProtection');
env.config();
const PORT = process.env.PORT || 3000;
const { MONGO_URI } = process.env;
app.use(express.static(`${__dirname}/public`));
if (process.env.NODE_ENV !== 'test') {
app.use(morgan('combined'));
}
app.set('env', (process.env.NODE_ENV || process.env.ENV) || 'production');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.use(helmet());
app.disable('x-powered-by');
app.use(compression());
app.use(
fileUpload({
useTempFiles: true,
tempFileDir: '/tmp/',
}),
);
app.set('view engine', 'pug');
app.set('views', 'views');
require('./db');
app.use(cookieParser());
app.use(
session({
secret: process.env.SECRET_KEY,
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
}),
);
fs.readdirSync('models').forEach((file) => {
if (file.substr(-3) === '.js') {
// eslint-disable-next-line import/no-dynamic-require, global-require
require(`./models/${file}`);
}
});
// modelMigrations();
const Players = mongoose.model('players');
const Songs = mongoose.model('song');
const FeedItems = mongoose.model('feedItem');
const Songbooks = mongoose.model('songbook');
async function changePlayerImages() {
const players = await Players.find();
players.forEach(async (player) => {
const p = await Players.findById(player.id);
if (p.image) {
p.images.push(p.image);
p.image = undefined;
await p.save();
}
});
}
async function changeSongs() {
const songs = await Songs.find();
songs.forEach(async (song) => {
const s = await Songs.findById(song.id);
if (s.deleteLocal || s.deleteLocal === '') {
s.deleteLocal = undefined;
await s.save();
}
if (s.reference_title || s.reference_title === '') {
s.referenceTitle = s.reference_title;
s.reference_title = undefined;
await s.save();
}
if (s.reference_link || s.reference_link === '') {
s.referenceLink = s.reference_link;
s.reference_link = undefined;
await s.save();
}
if (s.player_id || s.player_id === '') {
s.playerId = s.player_id;
s.player_id = undefined;
await s.save();
}
});
}
async function changeFeedImagesUrlToUri() {
const feedItems = await FeedItems.find();
feedItems.forEach(async (feedItem) => {
const item = await FeedItems.findById(feedItem.id);
if (item.images) {
item.images.forEach((img) => {
if (!img.uri) {
img.uri = img.url;
}
img.url = img.uri;
});
}
item.save();
});
}
async function modelMigrations() {
await changePlayerImages();
await changeSongs();
await changeFeedImagesUrlToUri();
}
modelMigrations();
app.use(passport.initialize());
app.use(passport.session());
require('./handlers/passport');
app.use(flash());
let langs = process.env.INPUT_LANGUAGES;
if (!langs) {
langs = 'en';
}
langs = langs.split(',').map((lang) => lang.trim());
const randomId = Math
.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
app.use((req, res, next) => {
res.locals.h = helpers;
res.locals.currentUser = req.user || null;
res.locals.flashes = req.flash();
res.locals.langs = process.env.INPUT_LANGUAGES ? JSON.parse(process.env.INPUT_LANGUAGES) : ['en'];
res.locals.randomId = randomId;
next();
});
app.use((req, res, next) => {
req.login = promisify(req.login, req);
next();
});
const api = require('./routes/api');
app.use('/api', api);
const web = require('./routes/web');
app.use(csrfProtection)
app.use('/', (req, res, next) => {
res.locals.csrfToken = req.csrfToken();
next();
});
app.use('/', web);
app.use(errorHandlers.flashValidationErrors);
app.use(errorHandlers.notFound);
if (app.get('env') === 'development') {
app.use(errorHandlers.developmentErrors);
}
Scheduler.loadAllScheduledTasks();
// sample task creation:
// var task = {};
// task.creator = "maxgene@gmail.com";
// task.triggerAt = new Date(2019, 11, 14, 14, 41, 0);
// task.data = { "foo": "bar" };
// Scheduler.scheduleNewsPost(task);
app.use(errorHandlers.productionErrors);
app.listen(PORT, () => {
if (app.get('env') === 'development') {
// eslint-disable-next-line no-console
console.log(`app listening on http://localhost:${PORT}`);
} else {
// eslint-disable-next-line no-console
console.log('Express app is running');
}
});
module.exports = app;