forked from Bostonhacks/BU-SSO-Example
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
368 lines (324 loc) · 10.9 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
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
const fs = require("fs");
const path = require("path");
const cron = require("node-cron");
const fetch = require("node-fetch");
const cors = require('cors');
const admin = require("firebase-admin");
const { v4: uuidv4 } = require("uuid");
const express = require("express");
const favicon = require("serve-favicon");
const session = require("express-session");
const FirestoreStore = require("firestore-store")(session);
const dotenv = require("dotenv");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const passport = require("passport");
const SamlStrategy = require("passport-saml").Strategy;
dotenv.config();
admin.initializeApp({
credential: admin.credential.cert({
projectId: process.env.FIREBASE_PROJECT_ID,
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
privateKey: JSON.parse(`"${process.env.FIREBASE_PRIVATE_KEY}"`)
}),
databaseURL: process.env.FIREBASE_DATABASE_URL
});
const firestore = admin.firestore();
const removeUndefined = obj => JSON.parse(JSON.stringify(obj));
passport.serializeUser((user, done) => done(null, user));
passport.deserializeUser((user, done) => done(null, user));
const SamlOptions = {
// URL that goes from the Identity Provider -> Service Provider
callbackUrl: process.env.CALLBACK_URL,
// URL that goes from the Service Provider -> Identity Provider
entryPoint: process.env.ENTRY_POINT,
// Usually specified as `/shibboleth` from site root
issuer: process.env.ISSUER,
identifierFormat: null,
validateInResponseTo: false,
disableRequestedAuthnContext: true
};
// Service Provider private key
if (process.env.SHIBBOLETH_KEY) {
SamlOptions.decryptionPvk = JSON.parse(`"${process.env.SHIBBOLETH_KEY}"`);
SamlOptions.privateCert = JSON.parse(`"${process.env.SHIBBOLETH_KEY}"`);
} else {
SamlOptions.decryptionPvk = fs.readFileSync(
__dirname + "/cert/key.pem",
"utf8"
);
SamlOptions.privateCert = fs.readFileSync(
__dirname + "/cert/key.pem",
"utf8"
);
}
// Identity Provider's public key
if (process.env.SHIBBOLETH_IDP_CERT) {
SamlOptions.cert = JSON.parse(`"${process.env.SHIBBOLETH_IDP_CERT}"`);
} else {
SamlOptions.cert = fs.readFileSync(__dirname + "/cert/cert_idp.pem", "utf8");
}
const samlStrategy = new SamlStrategy(SamlOptions, (profile, done) =>
done(null, profile)
);
passport.use(samlStrategy);
const app = express();
// custom parser for session store
// adds dateModified field so we can prune old ones
const parser = {
read: doc => JSON.parse(doc.session),
save: doc => {
return {
session: JSON.stringify(doc),
dateModified: new Date()
};
}
};
app.enable("trust proxy"); // required when running on Heroku as SSL terminates before reaching express
app.use(favicon(path.join(__dirname, "favicon.ico")));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
session({
store: new FirestoreStore({
parser,
database: firestore,
collection: "authSessions"
}),
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
proxy: true, // required when running on Heroku as SSL terminates before reaching express
cookie: {
secure: true,
maxAge: 25 * 60 * 1000
}
})
);
app.use(passport.initialize());
app.use(passport.session());
// saves request referrer to session storage before initiating login
const saveReferrer = (req, res, next) => {
const { redirectUrl } = req.query;
req.session.referrer = redirectUrl ;
console.log(`saving referrer as ${redirectUrl }`);
return next();
};
// makes sure user is authenticated before forwarding to route
const ensureAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) return next();
else return res.redirect("/login");
};
const ensureAdmin = (req, res, next) => {
let authToken = null;
if (
req.headers.authorization &&
req.headers.authorization.split(" ")[0] === "Bearer"
)
authToken = req.headers.authorization.split(" ")[1];
else
res
.status(403)
.json({ error: "No Bearer token found in Authorization header!" });
if (authToken) {
admin
.auth()
.verifyIdToken(authToken)
.then(claims => {
if (claims.admin || claims.eboard) next();
else
res
.status(403)
.json({ error: "You don't have permission for this route!" });
})
.catch(error => {
console.error(error);
res.status(403).json({ error: "Failed to verify token!" });
});
}
};
// checks firestore for uid, if not it creates one for the future
const fetchUID = email => {
const doc = firestore.doc(`uids/${email}`);
return doc.get().then(async snapshot => {
const data = snapshot.data();
let uid = null;
if (data) uid = data.value;
if (uid === null) {
uid = uuidv4();
await doc.set({ value: uid });
}
return uid;
});
};
// generates a firebase token, tied to the uid that matches the sso email
const generateToken = async user => {
const { email } = user;
const uid = await fetchUID(email);
const { emailVerified } = await admin
.auth()
.getUser(uid)
.catch(error => {
if (error.code === "auth/user-not-found") {
return admin
.auth()
.createUser({ uid })
.catch(console.error);
} else console.error(error);
});
// if user is new, set displayName and email
if (!emailVerified) {
await admin
.auth()
.updateUser(
uid,
removeUndefined({
displayName: `${user.firstName} ${user.lastName}`,
email,
emailVerified: true
})
)
.catch(console.error);
}
const doc = await firestore.doc(`users/${uid}`).get();
let dbUser = {};
const now = new Date();
const onemonth = 1000 /*ms*/ * 60 /*s*/ * 60 /*min*/ * 24 /*h*/ * 30; /*days*/
if (!doc.exists) {
// if user not in db, populate with kerberos fields
dbUser.name = `${user.firstName} ${user.lastName}`;
dbUser.email = user.email;
dbUser.organization = user.organization;
dbUser.roles = {nonmember: true};
user.affiliations.forEach(
affiliation => (dbUser.roles[affiliation] = "kerberos")
);
dbUser.lastMergedAffiliations = new Date();
await firestore.doc(`users/${uid}`).set(removeUndefined(dbUser));
} else {
dbUser = doc.data();
// merge kerberos with db every month to catch changes
const delta = now - dbUser.lastMergedAffiliations;
if (delta > onemonth || Number.isNaN(delta)) {
dbUser.organization = user.organization; // update organization
// delete old affiliations that no longer apply
for (const [key, value] of Object.entries(dbUser.roles)) {
if (value === "kerberos" && !user.affiliations.includes(key))
delete dbUser.roles[key];
}
// add new affiliations
user.affiliations.forEach(
affiliation => (dbUser.roles[affiliation] = "kerberos")
);
// update date and push changes
dbUser.lastMergedAffiliations = new Date();
await firestore.doc(`users/${uid}`).update(removeUndefined(dbUser));
}
}
const additionalClaims = { ...dbUser.roles }; // include roles as claims so security rules can access them
return admin
.auth()
.createCustomToken(uid, additionalClaims)
.then(customToken => customToken)
.catch(error => console.error("Error creating custom token:", error));
};
// maps kerberos field names to human readable ones
const mapKerberosFields = kerberosData => {
return {
firstName: kerberosData["urn:oid:2.5.4.42"],
lastName: kerberosData["urn:oid:2.5.4.4"],
email: kerberosData.email,
affiliations: kerberosData["urn:oid:1.3.6.1.4.1.5923.1.1.1.1"],
primaryAffiliation: kerberosData["urn:oid:1.3.6.1.4.1.5923.1.1.1.5"],
organization: kerberosData["urn:oid:2.5.4.10"]
};
};
// generates a token and redirects user with token as query param
const redirectWithToken = async (req, res) => {
const token = await generateToken(mapKerberosFields(req.user));
console.log(`sending user to ${req.session.referrer}`);
res.redirect(`${req.session.referrer}?token=${token}`);
};
// general error handler
app.use((err, req, res, next) => {
console.error("Fatal error: " + JSON.stringify(err));
next(err);
});
// if redirectWithToken is hit here, it means user has been authenticated this session
app.get("/", saveReferrer, ensureAuthenticated, redirectWithToken);
app.get(
"/login",
passport.authenticate("saml", { failureRedirect: "/login/fail" }),
(req, res) => res.redirect("/")
);
// redirectWithToken here rather than redirecting to root as that will change the saved referrer
app.post(
"/login/callback",
passport.authenticate("saml", { failureRedirect: "/login/fail" }),
redirectWithToken
);
app.get("/login/fail", (req, res) => res.status(401).send("Login failed"));
const validEmail = email => {
// eslint-disable-next-line
const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((bu\.edu)|(([a-zA-Z\-0-9]+\.)bu\.edu))$/;
return re.test(String(email).toLowerCase());
};
app.options('/generateUIDs', cors());
app.post("/generateUIDs", cors(), ensureAdmin, (req, res) => {
const { emails } = req.body;
// validate request
if (emails === undefined)
return res
.status(400)
.json({ error: '"emails" field is missing from request body!' });
else if (!Array.isArray(emails))
return res.status(400).json({ error: '"emails" field must be an array!' });
else if (!emails.every(validEmail))
return res
.status(400)
.json({ error: '"emails" must contain valid emails!' });
const fetchUIDs = emails.map(email => fetchUID(email));
Promise.all(fetchUIDs).then(uids => {
const mapped = uids.map((uid, i) => {
return {
email: emails[i],
uid
};
});
res.json(mapped);
});
});
app.get("/shibboleth/metadata", (req, res) => {
res.type("application/xml");
let cert = null;
if (process.env.SHIBBOLETH_CERT) {
cert = JSON.parse(`"${process.env.SHIBBOLETH_CERT}"`);
} else {
cert = fs.readFileSync(__dirname + "/cert/cert.pem", "utf8");
}
res
.status(200)
.send(samlStrategy.generateServiceProviderMetadata(cert, cert));
});
app.get("/keepalive", (req, res) => res.send("Alive"));
const serverPort = process.env.PORT || 3030;
app.listen(serverPort, () => console.log(`Listening on port ${serverPort}`));
console.log(`Starting keepalive for ${process.env.KEEPALIVE_URL}`);
cron.schedule("0 */25 * * * *", () => {
fetch(process.env.KEEPALIVE_URL)
.then(res =>
console.log(`Keepalive: response-ok: ${res.ok}, status: ${res.status}`)
)
.catch(console.error);
console.log("Pruning authSessions...");
const now = new Date();
const pruneTime = new Date(now.getTime() - 25 * 60000);
firestore
.collection("authSessions")
.where("dateModified", "<", pruneTime)
.get()
.then(querySnapshot =>
querySnapshot.forEach(snapshot => snapshot.ref.delete())
);
});