-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
579 lines (542 loc) · 17.7 KB
/
index.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
const hogan = require('hogan-express');
const express = require('express');
const session = require('cookie-session');
const favicon = require('serve-favicon');
const sqlite3 = require('sqlite3')
const passport = require('passport')
const fetch = require('node-fetch')
var OIDCStrategy = require('passport-azure-ad').OIDCStrategy;
var cookieParser = require('cookie-parser');
const atob = require('atob');
const config = require('./config');
require('dotenv').config()
const { BASE_PROTO } = process.env;
const baseURL = process.env.BASE_URL;
if (!baseURL || !BASE_PROTO) {
console.error("ERROR: Cannot find base URL or protocol, exiting...");
return;
} else {
console.log(`Running at ${BASE_PROTO}://${baseURL}`)
}
console.log("Node env: ", process.env.NODE_ENV)
var db = new sqlite3.Database(process.env.DB_FILE, sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
process.exit(1);
}
})
var app = express();
var server = app.listen(9215, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Listening on port %s', port);
});
app.set('view engine', 'html');
app.set('views', require('path').join(__dirname, '/view'));
app.engine('html', hogan);
const partials = {
smallNavbar: 'components/smallNavbar',
fullNavbar: 'components/fullNavbar',
footer: 'components/footer',
}
// Create a session-store to be used by both the express-session
// middleware and the keycloak middleware.
function getRandomURL() {
const length = 6;
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
const secret = process.env.COOKIE_KEY || "secret";
app.use(session({
secret: secret,
}));
function isDefinedRoute(name) {
// prevent the user from using well-defined routes as a short URL
app._router.stack.forEach(function(r){
if (r.route && r.route.path && r.route.path == `/${name}`){
return true
}
})
return false;
}
//-----------------------------------------------------------------------------
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.
//-----------------------------------------------------------------------------
passport.serializeUser(function (user, done) {
done(null, user.oid);
});
passport.deserializeUser(function (oid, done) {
findByOid(oid, function (err, user) {
done(err, user);
});
});
// array to hold logged in users
var users = [];
var findByOid = function (oid, fn) {
for (var i = 0, len = users.length; i < len; i++) {
var user = users[i];
if (user.oid === oid) {
return fn(null, user);
}
}
return fn(null, null);
};
getUserGroups = async (oid, accessToken) => {
const headers = {
"Authorization": `Bearer ${accessToken}`,
"Content-Type": "application/json"
};
const requestOptions = {
method: 'GET',
headers: headers,
redirect: 'follow'
};
return await fetch(`https://graph.microsoft.com/v1.0/users/${oid}/transitiveMemberOf/microsoft.graph.group?$select=displayName`, requestOptions)
.then(response => response.json())
.then(result => {
let groups;
let cleanGroups;
try {
groups = result.value;
cleanGroups = groups.map(x => x["displayName"])
return cleanGroups
} catch (e) {
console.error(e);
return [];
}
})
.catch(error => console.log('error', error));
}
var gat = "";
passport.use(new OIDCStrategy(config.creds,
function (iss, sub, profile, accessToken, refreshToken, done) {
if (!profile.oid) {
return done(new Error("No oid found"), null);
}
// asynchronous verification, for effect...
process.nextTick(function () {
findByOid(profile.oid, async function (err, user) {
if (err) {
return done(err);
}
gat = accessToken;
profile._json.groups = await getUserGroups(profile.oid, accessToken)
users.push(profile);
return done(null, profile);
});
});
}
));
app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));
app.use(express.json())
app.use(passport.initialize());
app.use(passport.session());
app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use('/static', express.static('public'))
async function ensureAuthenticated(req, res, next) {
if (!req.user) { return res.redirect('/login'); }
req.user._json.groups = await getUserGroups(req.user.oid, gat);
const intserect = validateArray(config.groups_permitted, req.user._json.groups);
const intersect2 = validateArray(config.admin_groups, req.user._json.groups)
if (!intserect && !intersect2) {
return res.status(401).redirect("/unauthorized");
}
next();
};
function checkIfAdmin(req) {
const userGroups = new Set(req.user._json.groups !== undefined ? req.user._json.groups : []);
const adminGroups = new Set(config.admin_groups);
for (const key of userGroups) {
if (adminGroups.has(key)) {
return true;
}
}
return false;
}
function ensureAdmin(req, res, next) {
if (!req.isAuthenticated()) { return res.redirect("/login"); }
if (checkIfAdmin(req)) { return next() }
return res.redirect('/unauthorized')
};
async function addURLToDB(name, url, email, groups) {
console.log("adding", name, url, email, groups)
return new Promise(function (resolve, reject) {
db.serialize(function () {
const stmt = db.prepare("INSERT INTO urlData (name, url, email, groups) VALUES (?, ?, ?, ?)");
stmt.run([name, url, email, groups], function (err) {
if (err) {
reject(err)
} else {
resolve({ name, url, email })
}
})
})
})
}
async function getDataForEmail(email) {
return new Promise(function (resolve, reject) {
db.serialize(function () {
const stmt = db.prepare("SELECT * FROM urlData WHERE email=?");
stmt.all([email], function (err, data) {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
})
}
async function getAllLinks() {
return new Promise(function (resolve, reject) {
db.serialize(function () {
const stmt = db.prepare("SELECT * FROM urlData");
stmt.all([], function (err, data) {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
})
}
async function getDelegatedLinks(userGroups) {
return new Promise(function (resolve, reject) {
db.serialize(function () {
const stmt = db.prepare("SELECT * FROM urlData;");
stmt.all([], function (err, allData) {
if (err) {
reject(err)
} else {
allData = allData.map(item => {
if (item.groups === null) {
return item;
}
item.groups = item.groups.split(',');
return item;
})
const data = allData.filter(item => {
let compareGroups = []
if (item.groups !== null) {
compareGroups = item.groups
}
const mergedArray = userGroups.filter(value => compareGroups.includes(value));
return mergedArray.length > 0
})
resolve(data)
}
})
})
})
}
async function removeURLfromDB(name) {
return new Promise(function (resolve, reject) {
db.serialize(function () {
const stmt = db.prepare("DELETE FROM urlData WHERE name=?");
stmt.run([name], function (err) {
if (err) {
reject(err)
} else {
resolve(name)
}
})
})
})
}
async function getRedirectURL(name) {
return new Promise(function (resolve, reject) {
db.serialize(function () {
const stmt = db.prepare("SELECT url FROM urlData WHERE name=?");
stmt.all([name], function (err, data) {
if (err) {
reject(err)
} else {
resolve(data)
}
})
})
})
}
async function updateRecord(name, url) {
return new Promise(function (resolve, reject) {
db.serialize(function () {
const stmt = db.prepare("UPDATE urlData SET url=?, name=? WHERE name=?");
stmt.run([url, name, name], function (err) {
if (err) {
reject(err)
} else {
resolve({ name, url })
}
})
})
})
}
app.get('/login',
function (req, res, next) {
passport.authenticate('azuread-openidconnect',
{
response: res, // required
resourceURL: config.resourceURL, // optional. Provide a value if you want to specify the resource.
customState: 'my_state', // optional. Provide a value if you want to provide custom state value.
failureRedirect: '/error',
domain_hint: config.branding.domainHint,
prompt: 'select_account'
}
)(req, res, next);
},
function (req, res) {
res.redirect('/');
});
app.get('/error', (req, res) => {
res.status(500).send("An error occurred.")
});
app.get('/unauthorized', (req, res) => {
return res.status(401).render('unauthorized.html', { partials, productName: config.branding.title, logoPath: config.branding.logoPath, copyrightOwner: config.branding.copyrightOwner, statusURL: config.branding.statusURL, orgHome: config.branding.orgHome, groups: config.groups_permitted.toString().replaceAll(",", "<br />"), adminGroups: config.admin_groups.toString().replaceAll(",", "<br />") });
});
// 'POST returnURL'
// `passport.authenticate` will try to authenticate the content returned in
// body (such as authorization code). If authentication fails, user will be
// redirected to '/' (home page); otherwise, it passes to the next middleware.
app.post('/auth/openid/return',
function (req, res, next) {
passport.authenticate('azuread-openidconnect',
{
response: res, // required
resourceURL: config.resourceURL, // optional. Provide a value if you want to specify the resource.
customState: 'my_state', // optional. Provide a value if you want to provide custom state value.
failureRedirect: '/error',
domain_hint: config.branding.domainHint,
prompt: 'select_account'
}
)(req, res, next);
},
function (req, res) {
res.redirect('/create');
});
// 'logout' route, logout from passport, and destroy the session with AAD.
app.get('/logout', function (req, res) {
res.clearCookie('connect.sid', { path: '/' });
res.clearCookie('session', { path: '/' });
res.clearCookie('session.sig', { path: '/' });
req.session = null;
res.redirect('/');
});
function validateArray(userGroups, accessGroups) {
for (const item of userGroups) {
if (accessGroups.includes(item)) {
return true;
}
}
return false;
}
app.use('/admin/', ensureAdmin)
app.get('/', async function (req, res) {
if (req.isAuthenticated()) { return res.redirect('/create') }
res.render('home.html', { partials, productName: config.branding.title, logoPath: config.branding.logoPath, copyrightOwner: config.branding.copyrightOwner, statusURL: config.branding.statusURL, orgHome: config.branding.orgHome, loginProvider: config.branding.loginProvider });
return
})
app.get('/create', ensureAuthenticated, async function (req, res) {
res.render('index.html', {
partials,
productName: config.branding.title,
logoPath: config.branding.logoPath,
copyrightOwner: config.branding.copyrightOwner,
statusURL: config.branding.statusURL,
orgHome: config.branding.orgHome,
email: req.user._json.preferred_username,
name: req.user.displayName,
baseURL,
userGroups: req.user._json.groups !== undefined ? req.user._json.groups.map((item) => { return { group: item } }) : {},
isAdminUser: checkIfAdmin(req)
})
return
})
app.post('/addURL', ensureAuthenticated, async function (req, res) {
const email = req.user._json.preferred_username;
const url = req.query.url;
const name = req.query.name;
const groups = req.body.groups
if (isDefinedRoute(name)) {
return res.status(409).json({
message: "This short URL is reserved by the system. Please try another."
})
}
if (url.indexOf(baseURL) > -1) {
return res.json({
message: `The origin URL cannot be a path of ${baseURL}`
})
}
if (url === undefined || name === undefined) {
res.status(400).json({
message: "Either url or name was not provided."
})
return
}
addURLToDB(name, url, email, groups).then((obj) => {
res.json({
url: obj.url,
shortURL: `${config.branding.externalDomain}/${obj.name}`,
email: obj.email,
groups: groups
});
}).catch((err) => {
if (err.errno == 19) {
res.status(409).json({
message: "This short URL has already been taken. Please try another."
})
} else {
res.status(500).json({
message: "The short URL could not be added. Please try again."
})
}
})
return
});
app.get('/mylinks', ensureAuthenticated, async function (req, res) {
const email = req.user._json.preferred_username;
const name = req.user.displayName;
const userGroups = req.user._json.groups !== undefined ? req.user._json.groups : [];
let data = await getDataForEmail(email).catch(() => { res.status(500).render('500', { productName: config.branding.title, logoPath: config.branding.logoPath, copyrightOwner: config.branding.copyrightOwner, statusURL: config.branding.statusURL, }); return });
data = data.map((item) => {
const d = item;
d.url = atob(d.url);
d.groups = d.groups.replace(',', "<br />")
return d;
})
let delegatedLinks = await getDelegatedLinks(userGroups).catch(() => { res.status(500).render('500', { productName: config.branding.title, logoPath: config.branding.logoPath, copyrightOwner: config.branding.copyrightOwner, statusURL: config.branding.statusURL, }); return });
delegatedLinks = delegatedLinks.map((item) => {
const d = item;
d.url = atob(d.url);
return d;
})
delegatedLinks = delegatedLinks.filter(word => word.email != email);
res.render('mylinks', {
partials,
productName: config.branding.title,
logoPath: config.branding.logoPath,
copyrightOwner: config.branding.copyrightOwner,
statusURL: config.branding.statusURL,
orgHome: config.branding.orgHome,
data,
name,
email,
baseURL,
delegatedLinks,
productName: config.branding.title,
isAdminUser: checkIfAdmin(req)
})
})
app.get('/admin/links', ensureAuthenticated, async function (req, res) {
const email = req.user._json.preferred_username;
const name = req.user.displayName;
const userGroups = req.user._json.groups !== undefined ? req.user._json.groups : [];
let data = await getAllLinks().catch(() => { res.status(500).render('500', { productName: config.branding.title, logoPath: config.branding.logoPath, copyrightOwner: config.branding.copyrightOwner, statusURL: config.branding.statusURL, }); return });
data = data.map((item) => {
const d = item;
d.url = atob(d.url);
d.groups = d.groups.replace(',', "<br />")
return d;
})
res.render('adminlinks', {
partials,
productName: config.branding.title,
logoPath: config.branding.logoPath,
copyrightOwner: config.branding.copyrightOwner,
statusURL: config.branding.statusURL,
orgHome: config.branding.orgHome,
data,
name,
email,
baseURL,
productName: config.branding.title,
isAdminUser: checkIfAdmin(req)
})
})
app.delete('/deleteLink', ensureAuthenticated, async function (req, res) {
const name = req.query.name;
removeURLfromDB(name).then(() => {
res.json({
name, deleted: true
})
return
}).catch(() => {
res.status(500).json({
message: "Could not delete the link. Please try again."
})
return
})
})
app.put('/updateLink', ensureAuthenticated, async function (req, res) {
const name = req.query.name;
const url = req.query.url;
if (url.indexOf(baseURL) > -1) {
res.json({
message: `The origin URL cannot be a path of ${baseURL}`
})
return
}
updateRecord(name, url).then((data) => {
res.json(data);
return;
}).catch(() => {
res.status(500).json({
message: "Could not update the link. Please try again."
})
return
})
})
app.get('/getRandomURL', ensureAuthenticated, async function (req, res) {
let exists = true;
let generatedURL = '';
let i = 0;
while (exists) {
try {
generatedURL = getRandomURL();
const url = await getRedirectURL(generatedURL);
exists = url[0] !== undefined;
if (i > 10) {
throw new Error("In a generation loop, must exit.")
}
} catch {
res.status(500).json({ success: false })
return
}
}
try {
if (generatedURL !== '') {
res.json({ success: true, generatedURL })
return
}
throw new Error("Did not actually generate a new URL.")
} catch {
res.status(500).json({ success: false })
return
}
})
app.get('/:id', async function (req, res) {
const name = req.params.id;
const ts = Date.now();
try {
const url = await getRedirectURL(name)
if (url[0] !== undefined) {
res.redirect(atob(url[0].url))
return
} else {
res.status(404).render('404', { partials, productName: config.branding.title, logoPath: config.branding.logoPath, copyrightOwner: config.branding.copyrightOwner, statusURL: config.branding.statusURL, })
return
}
} catch {
res.status(500).render('500', { partials, productName: config.branding.title, logoPath: config.branding.logoPath, copyrightOwner: config.branding.copyrightOwner, statusURL: config.branding.statusURL, })
return
}
})