This repository has been archived by the owner on Aug 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
256 lines (210 loc) · 6.84 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
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const https = require('https');
const helmet = require('helmet');
const expressSession = require('express-session');
const ejs = require('ejs');
const { __ } = require('./src/logger.js');
const security = require('./src/security.js');
const { twitterConfig } = require('./config.js');
const globalEvents = require('./src/events/globalEvents.js');
const schemas = require('./src/database/mongoose.js');
const Session = require('./endpoints/session.js');
const Database = require('./src/database.js');
const database = new Database('cryptodidacte');
database.connect();
// HTTPS Server config
const app = express();
app.set('port', 8443);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(helmet());
app.use(expressSession({
secret: process.env.SALT,
resave: false,
saveUninitialized: true,
cookie: { secure: true, expires: null },
}));
/**
* Receives Account Activity events
* */
app.post('/webhook/twitter', (req, res) => {
const { for_user_id: forUserId } = req.body;
switch (forUserId) {
case twitterConfig.user_id_bot:
globalEvents.emit('bot', req.body);
break;
case twitterConfig.user_id_cryptodidacte:
globalEvents.emit('cryptodidacte', req.body);
break;
default:
__('Unknow request target');
break;
}
res.status(200).end();
});
/**
* Security Twitter endpoint
*/
app.get('/webhook/twitter', (req, res) => {
const { crc_token: crcToken } = req.query;
__(`Verification CRC...\n${crcToken}`, 2);
if (crcToken) {
const hash = security.get_challenge_response(crcToken, twitterConfig.consumer_secret);
res.status(200).send({ response_token: `sha256=${hash}` });
} else {
res.status(400).send('Error: crc_token missing from request.');
}
});
const isSessionValid = (session) => {
if (typeof session === 'undefined' || !session.timestamp) return false;
const now = (new Date()).getTime();
const time = (new Date(session.timestamp)).getTime();
const delta = now - time;
//* ** TEST ***//
if (delta > 1000 * 60 * 30 || !session.isValid) { // 30mins
// eslint-disable-next-line no-param-reassign
session.isValid = false;
return false;
}
return true;
};
app.get('/connect', (req, res) => {
const continueTo = req.query.continueTo || '';
const nextParams = req.query.nextParams || '';
if (typeof req.session !== 'undefined' && isSessionValid(req.session)) {
return res.redirect('/index');
}
ejs.renderFile(`${__dirname}/public/connect.ejs`, { continueTo, nextParams }, (err, str) => {
if (err) __(err, 9);
res.status(200).send(str);
});
});
app.get('/index', (req, res) => {
if (!isSessionValid(req.session)) { // 30mins
req.session.destroy((err) => {
if (err) return __(err, 9);
res.redirect('/connect');
});
} else {
ejs.renderFile(`${__dirname}/public/index.ejs`, { view: '', viewParams: '' }, (err, str) => {
if (err) __(err, 9);
res.status(200).send(str);
});
}
});
app.get('/view/:viewName/:viewParams*?', (req, res) => {
const viewName = req.params.viewName || null;
let viewParams = req.params.viewParams || '';
if (isSessionValid(req.session) === false) {
req.session.destroy((err) => {
if (err) return __(err, 9);
res.redirect(`/connect${viewName ? `?continueTo=${viewName}` : ''}${viewParams ? `&nextParams=${viewParams}` : ''}`);
});
} else {
viewParams = Buffer.from(viewParams, 'base64').toString();
ejs.renderFile(`${__dirname}/public/index.ejs`, { view: viewName, viewParams }, (err, str) => {
res.status(200).send(str);
});
}
});
app.post('/login', async (req, res) => {
const username = req.body.username || '';
const password = req.body.password || '';
const session = new Session({ username, password });
const status = await session.create();
if (status === -1) {
return res.status(403).send('-1');
}
req.session.timestamp = session.timestamp;
req.session.token = session.id;
req.session.isValid = true;
return res.status(200).send('0');
});
/*
* API
* */
const getSchemaFromName = (name) => {
const schemasMap = {
rewards: schemas.LNQuizReward,
// TODO: add other schemas
};
return (schemasMap[name] || null);
};
app.post('/api/db/:schema/get', async (req, res) => {
if (!isSessionValid(req.session) && req.body.isTest !== true) {
return res.status(403).send('-1');
}
const { schema } = req.params;
const SchemaObj = getSchemaFromName(schema);
if (!SchemaObj) return res.status(400).send('-1');
const filter = req.body.filter || {};
const schemaDescription = SchemaObj.loadUIDescription();
const queryResponse = await SchemaObj.find(filter);
const toSend = {
schemaDescription,
queryResponse,
};
res.status(200).send(toSend);
});
app.post('/api/db/:schema/insert', async (req, res) => {
if (!isSessionValid(req.session) && req.body.isTest === false) {
return res.status(403).send('-1');
}
const { schema } = req.params;
const entry = req.body.entry || null;
__(entry, 2);
const SchemaObj = getSchemaFromName(schema);
if (!SchemaObj || !entry) return res.status(400).send('-1');
const entries = [];
for (const element of entry) {
const Entry = new SchemaObj(element);
// eslint-disable-next-line no-await-in-loop
const saved = await Entry.save();
entries.push(saved);
}
res.status(200).send(entries);
});
app.post('/api/db/:schema/update', async (req, res) => {
if (!isSessionValid(req.session) && req.body.isTest === false) {
return res.status(403).send('-1');
}
const { schema } = req.params;
const query = req.body.query || null;
const filter = req.body.filter || {};
const SchemaObj = getSchemaFromName(schema);
if (!SchemaObj || !query) return res.status(400).send('-1');
const queryResponse = await SchemaObj.updateOne(filter, query);
res.status(200).send(queryResponse.nModified.toString()); // SHOULD SEND ONE
});
// TODO
app.post('/api/db/:schema/remove/idList', async (req, res) => {
if (!isSessionValid(req.session) && req.body.isTest === false) {
return res.status(403).send('-1');
}
const { schema } = req.params;
const idList = req.body.idList || null;
const SchemaObj = getSchemaFromName(schema);
if (!idList || !SchemaObj) return res.status(400).send('-1');
const resp = await SchemaObj.deleteMany({ _id: { $in: idList } });
res.status(200).send(resp);
});
/**
* Serve static files from directory public
*/
app.use(express.static('public'));
/**
* Returns logs
*/
app.get('/logs', (req, res) => {
res.sendFile(`${__dirname}/logs/main.log`);
});
// Starts server
https.createServer({
key: fs.readFileSync('./certs/privkey.pem'),
cert: fs.readFileSync('./certs/fullchain.pem'),
}, app)
.listen(app.get('port'), () => {
__(`Node app is running on port ${app.get('port')}`);
});