This repository has been archived by the owner on Jan 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
app.js
227 lines (201 loc) · 7.1 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import Debug from 'debug';
import express from 'express';
import logger from 'morgan';
// import favicon from 'serve-favicon';
import path from 'path';
import lessMiddleware from 'less-middleware';
import session from 'express-session';
// import passport from 'passport';
import mongoose from 'mongoose';
import {isSuperAdmin, getClientIp } from './utils';
import adminRouter from './routes/admin';
import inviteRouter from './routes/invite';
import networkProxyRouter from './routes/network_proxy';
import discourseRouter from './auth/discourse';
import adminService from './service/admin';
import userService from './service/user';
import inviteService from './service/invite';
import networkProxyService from './service/network_proxy';
const appConfig = require('./configs/app');
const MIN_TRUST_LEVEL = parseInt(appConfig.trustLevel);
try {
mongoose.connect(appConfig.mongo)
.then(() => {
console.log('Connected to DB');
})
.catch(e => {
console.log(e);
throw e;
});
} catch (e) {
console.error(e);
throw e;
}
const app = express();
const debug = Debug('invites-manager:app');
// view engine setup
app.disable('etag');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(lessMiddleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
resave: false,
saveUninitialized: false,
secret: 'SAFE_NET_SECRET',
signed: true
}));
app.set('trust proxy', true);
// app.use('*', (req, res, next) => {
// let ipList = ['::1'];
// if (ipList.indexOf(getClientIp(req)) === -1) {
// return res.sendStatus(403);
// }
// next();
// });
// app.use(passport.initialize());
// app.use(passport.session());
app.use('/admin', adminRouter);
app.use('/invite', inviteRouter);
app.use('/networkProxy', networkProxyRouter);
app.use('/auth/discourse', discourseRouter);
app.use('/profile', (req, res) => {
if (req && req.session && req.session.passport && req.session.passport.user) {
const user = req.session.passport.user;
res.send({
role: req.session.user.role,
email: user.email,
id: user.id,
cip: getClientIp(req)
});
} else {
res.send({
cip: getClientIp(req)
});
}
});
app.use('/authUri/:testnet/:token', async (req, res) => {
if (!req.params.testnet || !req.params.token) {
return res.send(400, 'Invalid URI');
}
try {
const invite = await inviteService.get(req.params.testnet, req.params.token);
const ip = getClientIp(req);
if (!invite.ip) {
await inviteService.claim(req.params.testnet, ip, invite.token);
}
res.redirect(`/update_ip.html`);
} catch(e) {
res.send(400, e);
}
});
app.use('/clearDatabase', async (req, res) => {
try {
await inviteService.deleteAll(req.session.testnet);
await userService.deleteAll(req.session.testnet);
await networkProxyService.deleteAll(req.session.testnet);
res.sendStatus(200);
} catch (e) {
res.send(400, e);
}
});
app.use('/assignInvite/:id', async (req, res) => {
try {
let user = req.session.passport.user;
if (!isSuperAdmin(req) && !await adminService.isAdmin(user.userName)) {
return res.sendStatus(403);
}
let invite = await inviteService.findByAssignedTo(req.session.testnet, req.params.id);
if (invite) {
return res.send({ token: invite.token });
}
user = await userService.find(user.id, user.strategy);
invite = await inviteService.assignForUser(req.session.testnet, req.params.id, user._id);
return res.send({ testnet: req.session.testnet, token: invite.token });
} catch (e) {
console.log(e);
res.status(400).send(e.toString());
}
});
app.use('/testnet/:name', (req, res) => {
if (appConfig.testnets.indexOf(req.params.name) === -1) {
return res.status(400).send('Invalid testnet');
}
req.session.testnet = req.params.name;
res.redirect('/generateInvite');
});
app.use('/testnet', (req, res) => {
res.send(appConfig.testnets);
});
app.use('/generateInvite', async (req, res) => {
try {
let user = req.session.passport.user;
if (appConfig.msOnly === true && !user.email.endsWith('@maidsafe.net')) {
return res.redirect(`./auth_response.html?err=Under maintenenace, please try later.`);
}
const isSuperAdmin = appConfig.superAdmins.indexOf(user.email) > -1;
const isAdmin = await adminService.isAdmin(user.userName);
req.session.user = req.session.user || {};
req.session.user.role = isSuperAdmin ? 'SuperAdmin' : (isAdmin ? 'Admin' : 'User');
if (user.trustLevel < MIN_TRUST_LEVEL) {
return res.redirect(`./auth_response.html?err=Only users with trust level ${MIN_TRUST_LEVEL} or above can get an invite`);
}
user = await userService.find(user.id, user.strategy);
if (user) {
let invite = await inviteService.findByUserId(req.session.testnet, user._id);
if (!invite) {
invite = await inviteService.assignForUser(req.session.testnet, user._id);
}
if (!invite) {
return res.redirect(`./auth_response.html?err=No invites available`);
}
req.session.user.invite = invite.token;
res.redirect(`./update_ip.html?invite=${invite.token}`);
} else {
user = await userService.create(req.session.passport.user);
const invite = await inviteService.assignForUser(req.session.testnet, user._id);
if (!invite) {
return res.redirect(`./auth_response.html?err=No invites available`);
}
req.session.user.invite = invite.token;
res.redirect(`./update_ip.html?invite=${invite.token}`);
}
} catch (e) {
res.redirect(`./auth_response.html?err=${e}`);
}
});
app.use('/', (req, res) => {
res.redirect('/index.html');
});
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
/* eslint no-unused-vars: 0 */
app.use((err, req, res, next) => {
// set locals, only providing error in development
res.locals.message = err;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
// Handle uncaughtException
process.on('uncaughtException', (err) => {
debug('Caught exception: %j', err);
process.exit(1);
});
export default app;