This repository has been archived by the owner on Jul 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
437 lines (390 loc) · 14.2 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
let crypto = require('crypto');
let express = require('express');
let session = require('express-session');
let SequelizeStore = require('connect-session-sequelize')(session.Store);
const Sequelize = require('sequelize');
const path = require('path');
const { body, check, validationResult } = require('express-validator');
const { Pool } = require('pg');
const axios = require('axios');
// Load environment variables
require('dotenv').config();
// Initialized express
let app = express();
// External and custom hash/encrypt methods
const uuidv4 = require('uuid/v4');
let base64 = exports = {
encode: function (unencoded) {
return Buffer.from(unencoded).toString('base64');
},
decode: function (encoded) {
return Buffer.from(encoded, 'base64').toString('utf8');
}
};
// Database credentials
const connectionData = {
user: process.env.POSTGRES_USER,
host: process.env.POSTGRES_HOST,
database: process.env.POSTGRES_DB,
password: process.env.POSTGRES_PASSWORD,
port: 5432,
};
// Initialized postgres database pooling
let db = new Pool(connectionData);
// API Key generator method
key_generator = () => {
return base64.encode(uuidv4());
}
// Express configuration
app.use(express.urlencoded({ extended: false }))
app.use(express.static('public'))
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Setup and Initialize Sequelize database
let sequelize = new Sequelize(
process.env.POSTGRES_DB,
process.env.POSTGRES_USER,
process.env.POSTGRES_PASSWORD,
{
"host": process.env.POSTGRES_HOST,
"dialect": "postgres",
"logging": false
}
);
// Setup and Initialize Sequelize Store
let sequelizeStore = new SequelizeStore({
db: sequelize
})
// Express Session initializer with sequelize store
app.use(session({
secret: process.env.SESSION_SECRET,
store: sequelizeStore,
cookie: { maxAge: 60 * 60 * 1000 },
resave: false,
saveUninitialized: true,
}))
// Sync session database
sequelizeStore.sync()
// Responses base
let responses = function (req, res, next) {
res.out = (statusCode, json, msg) => {
res.writeHead(statusCode, {'Content-Type': 'application/json', 'X-Powered-By': 'Datar API Service'});
res.end(JSON.stringify({status: res.statusMessage, data: json, message: msg}));
};
next();
};
app.use(responses);
// Time convertion for frontend visualizer
function timeSince(createdAt) {
let now = new Date();
let timeStamp = new Date(Number(createdAt));
let secondsPast = (now.getTime() - timeStamp.getTime()) / 1000;
if(secondsPast < 60){
return parseInt(secondsPast) + 's ago';
}
if(secondsPast < 3600){
return parseInt(secondsPast/60) + 'm ago';
}
if(secondsPast <= 86400){
return parseInt(secondsPast/3600) + 'h ago';
}
if(secondsPast > 86400){
day = timeStamp.getDate();
month = timeStamp.toDateString().match(/ [a-zA-Z]*/)[0].replace(" ","");
year = timeStamp.getFullYear();
return day + " " + month + " " + year;
}
}
// Key status
// 0 = created
// 1 = disable
// 2 = enable
// 3 = delete
// 4 = name changed
// Render signup page
app.get('/signup', (req, res, next) => {
res.render('signup');
});
// Signup post endpoint
app.post('/signup', [
// email attribute must be an email
check('email').isEmail(),
// password must be at least 5 chars long
check('password').isLength({min: 5}),
// confirmation field must be the same as password
body('confirmation').custom((value, { req }) => {
if (value !== req.body.password) {
throw new Error('Password confirmation does not match password');
}
return true;
})
], (req, res) => {
// Validation results
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.render('signup', {errors: errors.errors[0].msg});
}
// Some easy variables and password hash
let email = req.body.email;
let password = crypto.createHash('sha256').update(req.body.password).digest('base64');
// Create account
db.query('insert into users (email, password) values(\'' + email + '\', \'' + password + '\');')
.then(response => {
return res.render('login', {success: "The account successfully created."});
})
.catch(err => {
if (err.code === "23505") {
return res.render('signup', {errors: "Another account is registered with this email"});
} else {
return res.render('signup', {errors: "Something wrong with the server"});
}
});
});
// Render login page
app.get('/login', (req, res, next) => {
if (req.session.user) {
return res.redirect('/keys');
}
return res.render('login');
});
// Render keys page
app.post('/login', [
// email attribute must be an email
check('email').isEmail(),
// password must be at least 5 chars long
check('password').exists()
], (req, res, next) => {
// Validation results
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.render('login', {errors: "Your email or password are incorrect."});
}
// Some easy variables and password hash
let email = req.body.email;
let password = crypto.createHash('sha256').update(req.body.password).digest('base64');
// Look up account
db.query('select id, password from users where email = \'' + email + '\'')
.then(response => {
// if user exists check password and create session.
if (response.rowCount > 0) {
if (password === response.rows[0].password) {
req.session.regenerate(function(){
req.session.user = response.rows[0].id;
return res.redirect('/keys');
});
} else {
return res.render('login', {errors: "Your email or password are incorrect."});
}
} else {
return res.render('login', {errors: "Your email or password are incorrect."});
}
})
.catch(err => {
return res.render('login', {errors: "Your email or password are incorrect."});
});
});
// Logout endpoint
app.get('/logout', function(req, res){
// Destroy the user session to log them out
req.session.destroy(function(){
res.redirect('/');
});
});
// Render keys page
app.get('/keys', (req, res, next) => {
// if user is loggedin, then
if (req.session.user) {
// get system status and remove it from session
let error = req.session.error;
let success = req.session.success;
let middle = req.session.middle;
delete req.session.error;
delete req.session.success;
delete req.session.middle;
// initialized and get pagination page if exists
let page = 1;
let queryPage = parseInt(req.query.page);
if (queryPage && queryPage > 0)
page = queryPage
// Look up for keys from "user"
db.query('select count(*) OVER() AS "count", "createdAt", key, title, origins, enabled from auth_keys where "user" = \'' + req.session.user + '\' order by "createdAt" desc LIMIT 5 OFFSET ' + ((page - 1) * 5))
.then(response => {
// workaround fix when no data exists
let count = 0;
if (response.rows.length > 0)
count = response.rows[0].count
// create and initialized pagination widget with requested data
const paginate = require('paginate')();
let pagination = paginate.page(count, 5, page);
const html = pagination.render({ baseUrl: '/keys' });
return res.render('keys', {title: 'API Keys Management', errors: error, success: success, middle: middle, timeSince: timeSince, keys: response.rows, pagination_html: html });
})
.catch(err => {
return res.render('login', {errors: "Something wrong with the server"});
});
} else {
return res.redirect('/login');
}
});
// History endpoint callback for single and all histories
let history_method = (req, res, next) => {
// if user is loggedin, then
if (req.session.user) {
// if is the histories from a single, we added the filter
let auth_key = '';
if (req.params.auth_key)
auth_key = 'and key = \'' + req.params.auth_key + '\'';
// initialized and get pagination page if exists
let page = 1;
let queryPage = parseInt(req.query.page);
if (queryPage && queryPage > 0)
page = queryPage
// Look up for keys from "user" with or without key filtering
db.query('select count(*) OVER() AS "count", "createdAt", key, status, "user", "from" from history where "user" = \'' + req.session.user + '\' ' + auth_key + ' order by "createdAt" desc LIMIT 8 OFFSET ' + ((page - 1) * 8))
.then(response => {
// workaround fix when no data exists
let count = 0;
if (response.rows.length > 0)
count = response.rows[0].count
// create and initialized pagination widget with requested data
const paginate = require('paginate')();
let pagination = paginate.page(count, 8, page);
const html = pagination.render({ baseUrl: '/history' });
return res.render('history', {title: 'Histories', histories: response.rows, pagination_html: html});
})
.catch(err => {
// set system status in session
req.session.error = "Something wrong with the server";
return res.redirect('/keys');
});
} else {
return res.redirect('/login');
}
}
// History post endpoints
app.get('/history/:auth_key', history_method);
app.get('/history', history_method)
// Key create request endpoint
app.post('/key/create', (req, res, next) => {
// if user is loggedin, then
if (req.session.user) {
// generate key with the generator
let key = key_generator();
// insert generated key for current user into database
db.query('insert into auth_keys ("user", key, title) values(\'' + req.session.user + '\', \'' + key + '\', \'New App\')')
.then(async response => {
// insert success status for current user into database
await db.query('insert into history ("user", key, status) values(\'' + req.session.user + '\', \'' + key + '\', 0)');
// set system status in session
req.session.success = "Successfully key created";
return res.redirect('/keys');
})
.catch(err => {
// set system status in session
req.session.error = "Something wrong with the server";
return res.redirect('/keys');
});
} else {
return res.redirect('/login');
}
})
// Key delete request endpoint
app.post('/key/delete', [
// key must exist
check('key').exists(),
], (req, res, next) => {
// if user is loggedin, then
if (req.session.user) {
// Validation results
const errors = validationResult(req);
if (!errors.isEmpty()) {
// set system status in session
req.session.error = "Something wrong with the server";
return res.redirect('/keys');
}
// Some easy variables
let key = req.body.key;
// Delete requested key
db.query('DELETE FROM "auth_keys" WHERE ctid = (SELECT ctid FROM "auth_keys" WHERE "key" = \'' + key + '\' and "user" = ' + req.session.user + ' and enabled = false LIMIT 1)')
.then(async response => {
if (response.rowCount > 0) {
// insert success status for current user into database
await db.query('insert into history ("user", key, status) values(\'' + req.session.user + '\', \'' + key + '\', 3)');
// set system status in session
req.session.success = "Successfully key deleted";
return res.redirect('/keys');
} else {
// set system status in session
req.session.error = "Key doesn't exist, belong to your account or is disabled";
return res.redirect('/keys');
}
})
.catch(err => {
// set system status in session
req.session.error = "Something wrong with the server";
return res.redirect('/keys');
});
} else {
return res.redirect('/login');
}
})
// Key update request endpoint
app.post('/key/:auth_key/update', [
// key must exist
check('title').isLength({min: 1, max: 25})
], async (req, res, next) => {
// if user is loggedin and key exist in parameters, then
if (req.session.user && req.params.auth_key) {
// Validation results
const errors = validationResult(req);
if (!errors.isEmpty()) {
// set system status in session
req.session.error = "Please input a title (min: 1, max: 25)";
return res.redirect('/keys');
}
// Url checker with or without http:// or https://
// https://www.regextester.com/93652
let origins = req.body.origins.match(/(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,}(:[0-9]{1,5})?(\/.*)?/g);
if (!origins)
origins = ['*'];
// Some easy variables
let key = req.params.auth_key,
title = req.body.title,
enabled = req.body.enabled;
// Get old key data to update history
let auth_key_old_data = await db.query('select title, enabled from auth_keys where key = \'' + req.params.auth_key + '\'');
// Upate key
db.query('UPDATE auth_keys SET enabled = ' + (enabled == 'on' ? 'true' : 'false') + ', title = \'' + title + '\', origins = \'' + JSON.stringify(origins) + '\' WHERE "key" = \'' + key + '\' and "user" = ' + req.session.user)
.then(async response => {
if (response.rowCount > 0) {
if (auth_key_old_data.rows[0].title !== title)
// insert title changed status for current user into database
await db.query('insert into history ("user", key, status, "from") values(\'' + req.session.user + '\', \'' + key + '\', 4, \'\"' + auth_key_old_data.rows[0].title + '\"\')');
if ((enabled == 'on' ? true : false) !== auth_key_old_data.rows[0].enabled)
// insert enabled key status for current user into database
await db.query('insert into history ("user", key, status, "from") values(\'' + req.session.user + '\', \'' + key + '\', ' + (enabled == 'on' ? '2' : '1') + ', \'\"' + auth_key_old_data.rows[0].enabled + '\"\')');
// set system status in session
req.session.success = "Successfully updated the key";
return res.redirect('/keys');
} else {
// set system status in session
req.session.error = "Key doesn't exist or belong to your account";
return res.redirect('/keys');
}
})
.catch(err => {
// set system status in session
req.session.error = "Something wrong with the server";
return res.redirect('/keys');
});
} else {
return res.redirect('/login');
}
})
app.use(function(req, res) {
return res.redirect('/login');
});
let port = process.env.PORT || 3000
app.listen(port, function () {
console.log('DATAR API Management running at port', port, '!');
});