-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
179 lines (159 loc) · 5.31 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
'use strict';
var request = require('request');
var yargs = require('yargs');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const rp = require('request-promise');
const session = require('express-session');
const { ExpressOIDC } = require('@okta/oidc-middleware');
const fs = require('fs');
var model_options = {'null': 'null'};
fs.readFile('model_options.json', (err, data) => {
if (err) throw err;
model_options = JSON.parse(data);
});
var args = yargs
.default('port', 8090)
.default('model', 'http://localhost:5000')
.argv;
app.use(bodyParser.json({
type: function(req) {
return req.get('content-type').indexOf('multipart/form-data') !== 0;
},
}));
app.use(express.static('static'));
app.set('views', 'static/');
app.engine('.ejs', require('ejs').__express);
app.set('view engine', 'ejs');
// session support is required to use ExpressOIDC
app.use(session({
secret: 'this should be secure',
resave: true,
saveUninitialized: false
}));
const oidc = new ExpressOIDC({
issuer: 'https://dev-175192.okta.com/oauth2/default',
client_id: '0oaktrsrxTJ188Kw04x6',
client_secret: '2Z70yC_Z6ccpNgfeskwvyjEUEYRlN4h96EHbfb6a',
appBaseUrl: 'http://ncrs.d2.comp.nus.edu.sg:8090',
redirect_uri: 'http://ncrs.d2.comp.nus.edu.sg:8090/authorization-code/callback',
scope: 'openid profile',
});
// ExpressOIDC will attach handlers for the /login and /authorization-code/callback routes
app.use(oidc.router);
function getOktaApiParams(req, requestType, quota=-1) {
const userID = req.userContext.userinfo.sub;
const userURI = ('https://dev-175192.okta.com/api/v1/users/' + userID);
const std_headers = {'Accept':'application/json',
'Content-Type': 'application/json',
'Authorization': 'SSWS 00RweVBDUZLYiW36LwewLuJhqo31DBM6JWv5XH4D4d'
};
var params = {
method: 'GET',
uri: userURI,
json: true,
headers: std_headers
};
if (requestType == 'GetCurrentUser'){
} else if (requestType == 'GetCurrentUserGroups'){
params.uri = (userURI + '/groups');
} else if (requestType == 'DeductUserQuotaBy1') {
params.method = 'POST';
params.body = {"profile": {"quota": (quota-1)}};
}
return params;
}
function getUserModelAccess(userGroupsInfo = null){
var userGroups = [];
var models = [];
if(userGroupsInfo){
for (var i = 0; i < userGroupsInfo.length; i++) {
userGroups.push((userGroupsInfo[i].profile.name).toLowerCase());
}
}
for (let model_name of Object.keys(model_options)){
for (let model_group of model_options[model_name]["groups"].split(";")){
if(model_group.trim()=='' || userGroups.includes(model_group.toLowerCase().trim())){
models.push(model_name);
break;
}
}
}
return models;
}
app.get('/', (req, res) => {
if (req.userContext) {
async function oktaGetCurrentUser_response() {
const userInfo = await rp(getOktaApiParams(req,'GetCurrentUser'));
const userGroupsInfo = await rp(getOktaApiParams(req,'GetCurrentUserGroups'));
res.render("index.ejs", {userContext: req.userContext,
userInfo: userInfo,
modelOptions: getUserModelAccess(userGroupsInfo),
});
}
oktaGetCurrentUser_response();
} else {
res.render("index.ejs", {userContext: null,
userInfo: null,
modelOptions: getUserModelAccess(),
});
}
});
app.all('/model/predict', oidc.ensureAuthenticated(), function(req, res) {
var model_endpoint = model_options[req.query.chosen_model]["endpoint"];
return rp(getOktaApiParams(req,'GetCurrentUser')).then(body => {
var quota = body.profile.quota;
if(quota === undefined){
quota = 500
}
return rp(getOktaApiParams(req,'DeductUserQuotaBy1',quota));
}).then(body => {
req.pipe(request(model_endpoint + req.path))
.on('error', function(err) {
console.error(err);
res.status(500).send('Error connecting to the model microservice');
})
.pipe(res);
}).catch(err => {
res.status(400).send(err);
});
});
app.get('/admin', oidc.ensureAuthenticated(), function(req, res) {
fs.readFile('model_options.json', (err, data) => {
if (err) throw err;
model_options = JSON.parse(data);
});
async function oktaGetCurrentUserGroups_response() {
var groups = [];
const userGroupsInfo = await rp(getOktaApiParams(req,'GetCurrentUserGroups'));
for (var i = 0; i < userGroupsInfo.length; i++) {
groups.push(userGroupsInfo[i].profile.name);
}
if(groups.includes('Admin')) {
res.render("admin.ejs", {userContext: req.userContext,
modelOptionsKeys: Object.keys(model_options),
modelOptions: model_options,
});
} else {
res.status(401).send('Error! Unauthorized.');
}
}
oktaGetCurrentUserGroups_response();
});
app.post('/saveModelJSON', oidc.ensureAuthenticated(), function(req, res) {
fs.writeFile('model_options.json', JSON.stringify(req.body), (err) => {
if (err) throw err;
});
model_options = req.body;
res.send('Success')
});
oidc.on('ready', () => {
app.listen(args.port, () => console.log('Started!'));
});
oidc.on('error', err => {
console.log('Unable to configure ExpressOIDC', err);
});
console.log('Web App Started on Port ' + args.port);
console.log('Using Model Endpoint: ' + args.model);
console.log('Press Ctrl-C to stop...');