-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
289 lines (262 loc) · 9.15 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
const hogan = require('hogan-express');
const express = require('express');
const session = require('cookie-session');
const favicon = require('serve-favicon');
const passport = require('passport')
const Joi = require('joi');
const fetch = require('node-fetch')
var OIDCStrategy = require('passport-azure-ad').OIDCStrategy;
var cookieParser = require('cookie-parser');
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 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,
}));
//-----------------------------------------------------------------------------
// 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);
if (!intserect) {
return res.status(401).redirect("/unauthorized");
}
next();
};
const stripe = require('stripe')(config.STRIPE_KEY)
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 />") });
});
// '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.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 });
})
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 } }) : {},
})
})
app.post('/paylink', ensureAuthenticated, async function (req, res) {
const schema = Joi.object().keys({
amnt: Joi.number().greater(0.5).required(),
invoice: Joi.string().required(),
contactName: Joi.string().required(),
contactEmail: Joi.string().email().required()
})
const { body } = req;
const {error} = schema.validate(body);
if (error) {
return res.status(422).json({
success: false,
message: error.details[0].message
})
}
try {
const email = req.user._json.preferred_username;
const { amnt, invoice, contactName, contactEmail } = req.body
const description = `Payment for Invoice ID ${invoice} \nContact Name: ${contactName}\nContact Email: ${contactEmail}\nCreated By: ${email}`
const product = await stripe.products.create({
name: `Payment for Invoice: ${invoice}`,
description
});
const price = await stripe.prices.create({
currency: 'usd',
unit_amount: amnt * 100,
product: product.id
})
const paymentLink = await stripe.paymentLinks.create({
line_items: [
{
price: price.id,
quantity: 1,
},
],
});
console.log(paymentLink.url)
return res.json({
success: true,
message: paymentLink.url
})
} catch {
return res.status(500).json({
success: false,
message: "Could not create link."
})
}
});