This repository has been archived by the owner on Jan 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
457 lines (435 loc) · 13.1 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
const hogan = require('hogan-express');
const express = require('express');
const session = require('express-session');
const SQLiteStore = require('connect-sqlite3')(session);
const baseURL = process.env.baseURL || 'go.epochml.org';
const favicon = require('serve-favicon');
const sqlite3 = require('sqlite3')
const dbVendor = process.env.DB_VENDOR;
const config = require('./config');
const passport = require('passport')
const fetch = require('node-fetch')
var OIDCStrategy = require('passport-azure-ad').OIDCStrategy;
var cookieParser = require('cookie-parser');
require('dotenv').config()
if (dbVendor === "postgresql") {
console.error("SQL support not yet implemented")
process.exit(2)
} else {
var db = new sqlite3.Database(process.env.DB_FILE, sqlite3.OPEN_READWRITE, (err) => {
if (err) {
console.error(err.message);
process.exit(1);
}
})
var store = new SQLiteStore({'dir': process.env.SESSION_DB_FILE_LOC, 'db': process.env.SESSION_DB_FILE_NAME});
}
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);
// Create a session-store to be used by both the express-session
// middleware and the keycloak middleware.
function makeSecret() {
const length = 64;
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]\;\',./<>?:"{}|';
const charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
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.NODE_ENV === "development" ? "secret" : makeSecret()
app.use(session({
secret: secret,
resave: false,
saveUninitialized: true,
store: process.env.NODE_ENV === "development" ? undefined : store
}));
//-----------------------------------------------------------------------------
// 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 => {
const groups = result.value;
const cleanGroups = groups.map(x => x["displayName"])
return cleanGroups
})
.catch(error => console.log('error', error));
}
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);
}
if (!user){
// "Auto-registration"
// grab user groups from Graph API - groups in claim not reliable
profile._json.groups = await getUserGroups(profile.oid, accessToken)
users.push(profile);
return done(null, profile);
}
return done(null, user);
});
});
}
));
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'))
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login');
};
async function addURLToDB(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 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',
useCookieInsteadOfSession: true,
domain_hint: 'epochml.org'
}
)(req, res, next);
},
function(req, res) {
res.redirect('/');
});
app.get('/error', (req, res) => {
res.status(500).send("An error occurred.")
}
);
// 'GET returnURL'
// `passport.authenticate` will try to authenticate the content returned in
// query (such as authorization code). If authentication fails, user will be
// redirected to '/' (home page); otherwise, it passes to the next middleware.
app.get('/auth/openid/return',
function(req, res, next) {
passport.authenticate('azuread-openidconnect',
{
response: res, // required
failureRedirect: '/'
}
)(req, res, next);
},
function(req, res) {
res.redirect('/');
});
// '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
failureRedirect: '/'
}
)(req, res, next);
},
function(req, res) {
res.redirect('/');
});
// 'logout' route, logout from passport, and destroy the session with AAD.
app.get('/logout', function(req, res){
req.session.destroy(function(err) {
req.logOut();
res.redirect(config.destroySessionUrl);
});
});
// begin business logic
app.get('/', ensureAuthenticated, async function (req, res) {
res.render('index.html', { 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}}) : {}})
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 (url.indexOf(baseURL) > -1 ) {
res.json({
message: `The origin URL cannot be a path of ${baseURL}`
})
return
}
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: `https://go.epochml.org/${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) {
console.log(req.user)
const email = req.user._json.preferred_username;
const name = req.user.displayName;
const userGroups = req.user._json.groups !== undefined ? req.user._json.groups : [];
const data = await getDataForEmail(email).catch(() => {res.status(500).render('500'); return});
const delegatedLinks = await getDelegatedLinks(userGroups).catch(() => {res.status(500).render('500'); return});
res.render('mylinks', {
data,
name,
email,
baseURL,
delegatedLinks
})
})
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(url[0].url)
return
} else {
res.status(404).render('404')
return
}
} catch {
res.status(500).render('500')
return
}
})