forked from FAForever/website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpress.js
257 lines (216 loc) · 8.26 KB
/
express.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
// Simulate config options from your production environment by
// customising the .env file in your project's root folder.
require('dotenv').load();
let express = require('express');
let middleware = require('./routes/middleware');
let expressValidator = require('express-validator');
let bodyParser = require('body-parser');
let passport = require('passport');
let OAuth2Strategy = require('passport-oauth2');
const showdown = require('showdown');
const fs = require('fs');
let app = express();
//Define environment variables with default values
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
process.env.WP_URL = process.env.WP_URL || 'https://direct.faforever.com/wp-json';
process.env.CHALLONGE_USERNAME = process.env.CHALLONGE_USERNAME || 'joe';
process.env.CHALLONGE_APIKEY = process.env.CHALLONGE_APIKEY || '12345';
process.env.PORT = process.env.PORT || '4000';
process.env.GOOGLE_CALENDAR_API_KEY = process.env.GOOGLE_CALENDAR_API_KEY || '12345';
process.env.API_URL = process.env.API_URL || 'https://api.test.faforever.com';
process.env.OAUTH_CLIENT_ID = process.env.OAUTH_CLIENT_ID || '12345';
process.env.OAUTH_CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET || '12345';
process.env.HOST = process.env.HOST || 'http://localhost';
process.env.SESSION_SECRET_KEY = process.env.SESSION_SECRET_KEY || '12345';
process.env.TWITCH_CLIENT_ID = process.env.TWITCH_CLIENT_ID || '12345';
process.env.TWITCH_LIVESTREAM_URL = process.env.TWITCH_LIVESTREAM_URL || 'https://api.twitch.tv/kraken/streams/?game=Supreme%20Commander:%20Forged%20Alliance';
//Execute middleware before each request...
app.use(middleware.initLocals);
app.use(middleware.getLatestClientRelease);
app.use(middleware.clientChecks);
//Set static public directory path
app.use(express.static('public', {
immutable: true,
maxAge: 4 * 60 * 60 * 1000 // 4 hours
}));
app.use(bodyParser.urlencoded({extended: false}));
app.use(expressValidator({
customValidators: {
isEqual: function (value1, value2) {
return value1 === value2;
}
}
}));
app.use(require('express-session')({
secret: process.env.SESSION_SECRET_KEY,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 3600000 * 12 //an api token is valid for 12h
}
}));
//Authentication on pages
app.use(passport.initialize());
app.use(passport.session());
app.use(middleware.username);
//Initialize values for default configs
app.set('views', 'templates/views');
app.set('view engine', 'pug');
app.set('port', process.env.PORT);
//Variable to hold routing path
let routes = './routes/views/';
//Define routes
app.get('/', require(routes + 'index'));
function loggedIn(req, res, next) {
let fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
req.session.referral = fullUrl;
if (req.isAuthenticated()) {
res.locals.username = req.user.data.attributes.login;
next();
} else {
res.redirect('/login');
}
}
// ToS and Privacy Statement
function markdown(template) {
let html = new showdown.Converter().makeHtml(fs.readFileSync(template, 'utf-8'));
return (req, res) => {
res.render('markdown', {content: html});
}
}
app.get('/privacy', markdown("templates/views/privacy.md"))
app.get('/tos', markdown("templates/views/tos.md"))
//Account routes
app.get('/account/register', require(routes + 'accounts/get/register'));
app.post('/account/register', require(routes + 'accounts/post/register'));
app.get('/account/link', loggedIn, require(routes + 'accounts/get/linkSteam'));
app.get('/account/connect', loggedIn, require(routes + 'accounts/get/connectSteam'));
app.get('/account/password/reset', require(routes + 'accounts/get/resetPassword'));
app.post('/account/password/reset', require(routes + 'accounts/post/resetPassword'));
app.get('/account/password/change', loggedIn, require(routes + 'accounts/get/changePassword'));
app.post('/account/password/change', loggedIn, require(routes + 'accounts/post/changePassword'));
app.get('/account/username/change', loggedIn, require(routes + 'accounts/get/changeUsername'));
app.post('/account/username/change', loggedIn, require(routes + 'accounts/post/changeUsername'));
app.get('/account/email/change', loggedIn, require(routes + 'accounts/get/changEmail'));
app.post('/account/email/change', loggedIn, require(routes + 'accounts/post/changEmail'));
app.get('/account_activated', require(routes + 'accounts/get/register'));
app.get('/password_resetted', require(routes + 'accounts/get/resetPassword'));
app.get('/client', require(routes + 'client'));
app.get('/livestream', require(routes + 'livestream'));
app.get('/contribution', require(routes + 'contribution'));
app.get('/calendar', require(routes + 'calendar'));
app.get('/competitive/tournaments', require(routes + 'tournaments'));
app.get('/competitive/leaderboards/1v1', require(routes + '1v1'));
app.get('/competitive/leaderboards/global', require(routes + 'global'));
app.get('/competitive/leaderboards/leagues', (function(){
let updateLeagues = require("./scripts/updateLeagues");
let ladderData = {};
let updateFunction = function(){
try {
updateLeagues.run(ladderData).then(function(ladderUpdatedData){
ladderData = ladderUpdatedData;
});
} catch (e) {
console.error("Error while updating ladder week!", e);
};
};
setInterval(
updateFunction
, 60 * 60 * 1000); /// Every 60 minutes
updateFunction();
return function(res, req){
require(routes + 'leagues')(res, req, ladderData);
}
})()
);
app.get('/news/', require(routes + 'blog'));
app.get('/category/:category/page/:page', require(routes + 'blog'));
app.get('/news/search/:search/page/:page', require(routes + 'blog'));
app.get('/tag/:tag/page/:page', require(routes + 'blog'));
app.get('/author/:author/page/:page', require(routes + 'blog'));
app.get('/news/page/:page', require(routes + 'blog'));
app.get('/:year/:month/:slug', require(routes + 'post'));
app.get('/logout', function (req, res) {
req.logout();
res.redirect('/');
});
app.get('/login', passport.authenticate('faforever', {
failureRedirect: '/login',
failureFlash: true
}), function (req, res) {
req.logout();
res.redirect('/');
});
passport.use('faforever', new OAuth2Strategy({
tokenURL: process.env.API_URL + '/oauth/token',
authorizationURL: process.env.API_URL + '/oauth/authorize',
clientID: process.env.OAUTH_CLIENT_ID,
clientSecret: process.env.OAUTH_CLIENT_SECRET,
callbackURL: process.env.HOST + '/callback',
scope: ['write_account_data', 'public_profile']
},
function (accessToken, refreshToken, profile, done) {
let request = require('request');
request.get(
{url: process.env.API_URL + '/me', headers: {'Authorization': 'Bearer ' + accessToken}},
function (e, r, body) {
if (r.statusCode != 200) {
return done(null);
}
let user = JSON.parse(body);
user.data.attributes.token = accessToken;
return done(null, user);
}
);
}
));
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (id, done) {
done(null, id);
});
app.get('/callback', passport.authenticate('faforever', {
failureRedirect: '/login',
failureFlash: true
}), function (req, res, next) {
res.redirect(req.session.referral ? req.session.referral : '/');
req.session.referral = null;
});
//404 Error Handler
app.use(function (req, res, next) {
res.status(404).render('errors/404');
});
//Display 500 Error Handler if in development mode.
if (process.env.NODE_ENV === 'development') {
app.enable('verbose errors');
//500 Error Handler
app.use(function (err, req, res, next) {
res.status(500).render('errors/500', {error: err});
});
}
let extractor = require("./scripts/extractor");
let getLatestClientRelease = require("./scripts/getLatestClientRelease");
// Run scripts initially on startup
extractor.run();
getLatestClientRelease.run();
// Run leaderboard extractor every minute
setTimeout(() => {
try {
extractor.run();
} catch (e) {
console.error("Error while updating leaderboards!", e);
}
}, 60 * 1000);
// Run client release fetcher every 15 minutes
setTimeout(() => {
try {
getLatestClientRelease.run();
} catch (e) {
console.error("Error while fetching latest client release!", e);
}
}, 15 * 60 * 1000);
//Start and listen on port
app.listen(process.env.PORT, function () {
console.log('Express listening on port ' + process.env.PORT);
});