-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
369 lines (350 loc) · 11.3 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
369
const settings = require('./config/conf.json');
const bodyParser = require('body-parser');
const jwt = require('jwt-simple');
const moment = require('moment');
const LdapAuth = require('ldapauth-fork');
const Promise = require('promise');
const fs = require('fs');
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('database.sqlite3');
const nodemailer = require('nodemailer');
const hbs = require('handlebars');
app = require('express')();
app.use(bodyParser.json());
app.use(require('cors')());
const gmailTransport = nodemailer.createTransport('SMTP', settings.mailer);
ldapSetts = settings.ldap;
ldapSetts.tlsOptions = {
tlsOptions: {
ca: [fs.readFileSync('./cert.pem')],
},
};
let auth = new LdapAuth(ldapSetts);
app.set('jwtTokenSecret', settings.jwt.secret);
const authenticate = (username, password) => {
return new Promise((resolve, reject) => {
auth.authenticate(username, password, (err, user) => {
if (err) {
reject(err);
} else if (!user) {
reject(new Error('Not correct user'));
} else {
resolve(user);
}
});
});
};
app.get('/valid', (req, res) => {
if (req.headers.token) {
try {
const decoded = jwt.decode(req.headers.token, app.get('jwtTokenSecret'));
if (decoded.exp <= parseInt(moment().format('X'))) {
res.json({valid: 'no'});
return;
} else {
res.json({valid: 'yes'});
return;
}
} catch (err) {
res.json({valid: 'no'});
return;
}
} else {
res.json({valid: 'no'});
return;
}
});
app.post('/login', (req, res) => {
if (req.body.username && req.body.password) {
if (/^[a-zA-Z]/.test(req.body.username)) {
authenticate(req.body.username, req.body.password)
.then((user) => {
const expires = parseInt(moment().add(2, 'days').format('X'));
const token = jwt.encode({
exp: expires,
user_name: user.uid,
full_name: user.cn,
mail: user.mail,
}, app.get('jwtTokenSecret'));
db.get(
'SELECT count(user) as count FROM professors WHERE user ' +
'like "' + user.uid + '"',
(err, row) => {
if (row.count===0) {
res.status(401)
.send({error: 'Unauthorized, not proffesor.'});
} else {
res.json({token: token, full_name: user.cn});
return;
}
});
})
.catch((err) => {
if (err.name === 'InvalidCredentialsError'||
(typeof err === 'string' && err.match(/no such user/i))) {
res.status(401).send({error: 'Wrong user or password'});
} else {
res.status(500).send({error: 'Unexpected Error'});
auth = new LdapAuth(settings.ldap);
}
});
} else {
res.status(400).send({error: 'Bad username supplied'});
}
} else {
res.status(400).send({error: 'No username or password supplied'});
}
});
app.get('/sponsor', (req, res) => {
const token = req.headers.token;
if (token) {
try {
const decoded = jwt.decode(token, app.get('jwtTokenSecret'));
if (decoded.exp <= parseInt(moment().format('X'))) {
res.status(400).send({error: 'Access token has expired'});
} else {
db.all('SELECT * FROM sponsor INNER JOIN request on ' +
' request.request_id = sponsor.request_id where ' +
'sponsor.professor like ?',
[decoded.user_name],
(error, rows) => {
if (error) {
res.json({error: 'Could not get sponsors'});
return;
} else {
rows.map((row) => {
row.Fecha = row.Fecha.split('T')[0];
});
res.json({rows});
return;
}
});
}
} catch (err) {
res.status(500).send({error: 'Access token could not be decoded'});
}
} else {
res.status(400).send({error: 'Access token is missing'});
}
});
app.get('/recommend', (req, res) => {
const token = req.headers.token;
if (token) {
try {
const decoded = jwt.decode(token, app.get('jwtTokenSecret'));
if (decoded.exp <= parseInt(moment().format('X'))) {
res.status(400).send({error: 'Access token has expired'});
} else {
const query = 'SELECT * FROM recommend';
db.all(query, (error, rows) => {
if (error) {
res.json({error: 'The request doesnt exist'});
return;
}
res.json({rows});
});
}
} catch (err) {
res.status(500).send({error: 'Access token could not be decoded'});
}
} else {
res.status(400).send({error: 'Access token is missing'});
}
});
app.post('/recommend', (req, res) => {
const query = 'INSERT INTO recommend VALUES (?, ?, ?, ?)';
try {
db.run(query, [
req.body.name,
req.body.email,
req.body.type,
req.body.msg,
],
(err) => {
console.log(err);
});
} catch (err) {
res.status(500).send({status: 'Internal server error'});
}
res.status(200).send({status: 'Confirmed'});
});
app.post('/sponsor', (req, res) => {
const token = req.headers.token;
if (token) {
try {
const decoded = jwt.decode(token, app.get('jwtTokenSecret'));
if (decoded.exp <= parseInt(moment().format('X'))) {
res.status(400).send({error: 'Access token has expired'});
} else {
db.run('UPDATE request SET Apadrinado = 1 WHERE request_id like ?',
[req.body.request_id],
(error, rows) => {
if (error) {
res.json({error: 'Could not update request status'});
return;
}
});
db.get('SELECT * FROM request WHERE request_id = ?',
[req.body.request_id],
(err, row) => {
try {
db.run('INSERT INTO sponsor VALUES(?,?)',
[decoded.user_name, req.body.request_id],
(error, rows) => {
if (error) {
res.json({error: 'There is a problem updating the DB'});
return;
}
try {
const emailCompiled = hbs.compile(
fs.readFileSync('views/email/toProfessor.hbs')
.toString(),
)({
nombre: row.Nombre,
programa: row.Programa,
pbm: row.PBM,
procedencia: row.Procedencia,
apoyo: row.Apoyo,
correo: row.Correo,
celular: row.Celular,
direccion: row.Direccion,
});
const HelperOptions = {
from: 'Decanatura - Facultad de Ingenieria' +
'<[email protected]>',
to: decoded.mail,
subject: '[Apoya UN] Gracias!',
html: emailCompiled,
};
gmailTransport
.sendMail(HelperOptions, (error, info) => {
if (error) {
console.log(error);
res.json(error);
return;
}
res.json(info);
return;
});
} catch (err) {
console.log('the mail could not be sent');
res.json({error: 'The mail could not be sent'});
return;
}
});
} catch (err) {
res.status(400).send({error: 'invalid request id.'});
}
});
}
} catch (err) {
res.status(500).send({error: 'Access token could not be decoded'});
}
} else {
res.status(400).send({error: 'Access token is missing'});
}
});
/**
* Says if register has Bogotá procedence.
* @param {string} procedencia The string to be compared.
* @return {int} 1 if provedencia is like bogota, 0 otherwise.
*/
function includesBogot(procedencia) {
if (procedencia.toString()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase().includes('bogota')) {
return 0;
} else {
return 1;
}
}
/**
* Shows the priority level of register.
* @param {Register} row The register to be compared.
* @return {int} The value of the priority of the register.
*/
function getPrioriry(row) {
return 80 * ((100 - parseInt(row.PBM)) / 100.0) +
20 * includesBogot(row.Procedencia);
}
app.get('/prequest', (req, res) => {
const token = req.headers.token;
if (token) {
try {
const decoded = jwt.decode(token, app.get('jwtTokenSecret'));
if (decoded.exp <= parseInt(moment().format('X'))) {
res.status(400).send({error: 'Access token has expired'});
} else {
const query = 'SELECT request_id, Programa, Fecha, PBM, Procedencia, ' +
'Bogota, Apoyo, Descripcion FROM request ' +
'where Apadrinado = 0 AND Apoyo like "%canasta%"';
db.all(query, (error, r) => {
if (error) {
res.json({error: 'The request doesnt exist'});
return;
}
try {
const rows = Array.prototype.slice.call(r);
rows.map((row) => {
row.Fecha = row.Fecha.split('T')[0];
});
rows.sort((a, b) => {
return getPrioriry(b) - getPrioriry(a);
});
res.json({rows});
return;
} catch (err) {
res.status(500).send({
error: 'Error retriving values ' +
err.toString(),
});
}
});
}
} catch (err) {
res.status(500).send({error: 'Access token could not be decoded'});
}
} else {
res.status(400).send({error: 'Access token is missing'});
}
});
app.post('/request', (req, res) => {
const query = 'INSERT INTO request VALUES (?, ?, ?, ?, ?, ?, ?, ' +
'?, ?, ?, ?, ?, ?, ?, ?)';
try {
db.run(query, [
undefined,
req.body.Nombre,
req.body.Correo,
req.body.Fecha,
req.body.Programa,
req.body.Tipo_Documento,
req.body.Documento,
req.body.PBM,
req.body.Procedencia,
req.body.Bogota,
req.body.Celular,
req.body.Direccion,
req.body.Apoyo,
req.body.Descripcion,
0,
],
(err) => {
console.log(err);
});
} catch (err) {
res.status(500).send({status: 'Internal server error'});
Console.log('There is a problem posting the request into the database');
}
res.status(200).send({status: 'Confirmed'});
});
const port = (process.env.PORT || 3001);
app.listen(port, function() {
console.log('Listening on port: ' + port);
if (typeof settings.ldap.reconnect === 'undefined' ||
settings.ldap.reconnect === null || settings.ldap.reconnect === false) {
console.warn('WARN: This service may become unresponsive ' +
'when ldap reconnect is not configured.');
}
});