-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
623 lines (524 loc) · 28.6 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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
const dotenv = require('dotenv')
const env = dotenv.config({ path: './config.env' })
const express = require('express')
const session = require('express-session')
const helmet = require('helmet')
const FileStore = require('session-file-store')(session)
const bodyParser = require('body-parser')
const passport = require('passport')
const ldapstrategy = require('passport-ldapauth')
const mysql = require('mysql')
const moment = require('moment')
const { DateTime } = require('luxon')
const uuid = require('uuid/v4')
let {google} = require('googleapis')
const google_key = require(process.env.GS_APIKEY)
const Sentry = require('@sentry/node');
// Sentry.init({ dsn: 'SENTRY_DSN' });
function addCal(summary, desc, start, end, user, calendarId) {
(() => {
"use strict";
// const google_key = require("./nt_gsuite_priv.json");
var event = {
'summary': summary,
'description': desc,
'start': {
'date': start,
'timeZone': 'Europe/Berlin'
},
'end': {
'date': end,
'timeZone': 'Europe/Berlin'
},
'attendees': [
{'email': user}
],
'reminders': {
'useDefault': true
}
};
const jwtClient = new google.auth.JWT(
google_key.client_email,
null,
google_key.private_key,
["https://mail.google.com/", "https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/calendar.events"],
process.env.GS_USER
);
jwtClient.authorize((err, tokens) => (err
? console.log(err)
: (() => {
console.log("Google-API Authed!");
let calendar = google.calendar('v3');
calendar.events.insert({
auth: jwtClient,
calendarId: calendarId,
resource: event
}, function (err, response) {
console.log(err)
// console.log(response)
});
})()
))
})();
}
function sendMsg(userName, userMail, subject, body) {
(() => {
"use strict";
const company = process.env.COMPANY_NAME
const gsUser = process.env.GS_USER
subject = `[VACATION] ${subject}`
const utf8Subject = `=?utf-8?B?${Buffer.from(subject).toString('base64')}?=`;
const messageParts = [
`From: ${company} Vacations <${gsUser}>`,
`To: ${userName} <${userMail}>`,
// `Cc: ["${ccMail}"]`,
`Content-Type: text/html; charset=utf-8`,
`MIME-Version: 1.0`,
`Subject: ${utf8Subject}`,
'',
body,
''
];
const message = messageParts.join('\n');
// The body needs to be base64url encoded.
const encodedMessage = Buffer.from(message)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
const jwtClient = new google.auth.JWT(
google_key.client_email,
null,
google_key.private_key,
["https://mail.google.com/", "https://www.googleapis.com/auth/calendar"],
process.env.GS_USER
);
jwtClient.authorize((err, tokens) => (err
? console.log(err)
: (() => { //--------------------------------
console.log("Google-API Authed!");
const gmail = google.gmail({
version: "v1",
auth: jwtClient
});
gmail.users.messages.send({
userId: process.env.GS_USER,
resource: {
raw: encodedMessage
}
}, (err, messages) => {
//will print out an array of messages plus the next page token
console.log(err);
// console.dir(messages);
});
})()
));
})();
}
function memberOfAdmin(group) {
for(i = 0; i < group.length; i++) {
if(group[i].includes('AdminGroup') || group[i].includes('Administratoren') || group[i].includes('Management')) {
return true
}
}
return false
}
var connection = mysql.createConnection({
host : process.env.DB_HOST,
user : process.env.DB_USER,
password : process.env.DB_PW,
database : process.env.DB_DB,
port : process.env.DB_PORT
})
connection.connect((err) => {
if (err) throw err
console.log('You are now connected...')
})
const ldapUrl = `ldap://${process.env.LDAP_URL}`
var OPTS = {
server: {
url : ldapUrl,
bindDN : process.env.LDAP_BINDDN,
bindCredentials : process.env.LDAP_BINDPW,
searchBase : process.env.LDAP_SEARCHBASE,
searchFilter : process.env.LDAP_SEARCHFILTER
}
}
const app = express()
passport.use(new ldapstrategy(OPTS))
app.use(session({
secret: '87oY7tsTHbYuU6oeS36RudzZjrXopf0ltNUeQInlDbTPSeRSWglLcEWVDPy43twKmjOl8rRlE8cvFSpWEhaIS0e5mPli17bhyve2vVRBld6ZRpyw94tM5ms7YY932W1u',
resave: false,
saveUninitialized: true,
// cookie: { secure: true }
store: new FileStore()
}))
app.use(express.static('public'))
app.use(helmet())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
app.use(passport.initialize())
app.use(passport.session())
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
app.get('/', (req, res) => {
if(req.isAuthenticated()) {
res.redirect('/dashboard.html')
}
})
app.get('/login', (req, res) => {
res.status(403).redirect('/?failed=1')
})
app.post('/login', (req, res, next) => {
passport.authenticate('ldapauth', {session: false}, (err, user, info) => {
if (err) {
return next(err); // will generate a 500 error
}
if (! user) {
console.log('\nRequest Login failed!')
return res.status(403).redirect('/?failed=1')
}
req.login(user,(err) => {
if (err) return next(err)
var loginTime = moment().local().format('DD.MM.YYYY HH:mm:ss')
console.log(`[LOGIN] ${req.user.sAMAccountName} - ${loginTime}`)
let returnToUrl = ''
if(req.session.returnTo != ''){
returnToUrl = req.session.returnTo
delete req.session.returnTo
}
return res.redirect(returnToUrl || 'dashboard')
})
})(req, res, next);
});
app.get('/logout', (req, res) => {
//req.session.destroy()
req.logout()
return res.redirect('/')
})
app.get('/dashboard', (req, res) => {
if(req.isAuthenticated()) {
res.sendFile(__dirname + '/public/dashboard.html')
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.get('/request', (req, res) => {
if(req.isAuthenticated()) {
res.sendFile(__dirname + '/public/request.html')
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.get('/overview', (req, res) => {
if(req.isAuthenticated()) {
res.sendFile(__dirname + '/public/overview.html')
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.get('/admin', (req, res) => {
if(req.isAuthenticated() && memberOfAdmin(req.user.memberOf)) {
res.sendFile(__dirname + '/public/admin.html')
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.get('/admin/response', (req, res) => {
if (req.isAuthenticated() && memberOfAdmin(req.user.memberOf)) {
const id = req.query.h
let action = req.query.a
if(action == 'a') {
// approve
action = '2'
} else if (action == 'd') {
// deny
action = '1'
} else {
// if gibberish - keep on '?' status
action = '0'
}
const datetimeNow = moment().format('YYYY-MM-DD HH:mm:ss')
// on request response, first update the DB with approval value
connection.query(`UPDATE vacations SET approval_datetime = "${datetimeNow}", approved = "${action}" WHERE approval_hash LIKE "${id}";`, (error, results1, fields) => {
if (error) throw error
connection.query(`SELECT name, email, submitted_datetime, toDate, fromDate, approved, approval_datetime, manager FROM vacations WHERE approval_hash LIKE "${id}";`, (error, results, fields) => {
if (error) throw error
reqUser = results[0]
let start = moment.utc(reqUser.fromDate).local().format('YYYY-MM-DD')
let end = moment.utc(reqUser.toDate).local().format('YYYY-MM-DD')
let mailStart = moment(start).format('DD.MM.YYYY')
let mailEnd = moment(end).format('DD.MM.YYYY')
let userMail = reqUser.email
let userName = reqUser.name
let manager = reqUser.manager
let approvalDateTime = moment(reqUser.approval_datetime).format('DD.MM.YYYY HH:mm')
if(action == '2') {
ntvacaCal = process.env.GS_CALID
const baseUrl = process.env.BASE_URL
let reqDateTime = moment.utc(reqUser.submitted_datetime).local().format('DD.MM.YYYY HH:mm')
let summary = userName
let desc = `From: ${mailStart}\nTo: ${mailEnd}\n\nSubmitted On: ${reqDateTime}\n\nManager: ${manager}\nApproved On: ${approvalDateTime}\n\n${baseUrl}`
// end + 1 day hack for google calendar
end = moment(end).local().add(1,'d').format('YYYY-MM-DD')
addCal(summary, desc, start, end, userMail, ntvacaCal)
let userSubject = 'Request Approved'
let userBody = `<html><head> <style>@font-face{font-family: "Lato"; font-style: normal; font-weight: 300; src: local("Lato Light"), local("Lato-Light"), url(https://fonts.gstatic.com/s/lato/v15/S6u9w4BMUTPHh7USSwiPGQ.woff2) format("woff2"); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;}@font-face{font-family: "Lato"; font-style: normal; font-weight: 400; src: local("Lato Regular"), local("Lato-Regular"), url(https://fonts.gstatic.com/s/lato/v15/S6uyw4BMUTPHjx4wXg.woff2) format("woff2"); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;}html{font-family: Lato, Arial;}img{display: block; margin: auto;}#wrapper{max-width: 600px; margin: 0 auto;}#header{height: 80px; margin: auto 0; background-color: #67B246; width: 100%; text-align: center; line-height: 80px;}#subheader{text-align: center;}h1{font-size: 34px; color: #ffffff; font-weight: 300;}h3{font-size: 18px; font-weight: 900;}hr{width: 90%; height: 3px; border: none; color: #67B246; background-color: #67B246;}#msgBody > p{padding: 15px;}.dateSpan{display: inline-block; width: 45%;}.dateBox{border: 4px solid #8c8c8c; border-radius: 10px; padding: 40px; margin-top: 20px; margin-bottom: 20px; height: 220px;}.dateBox:after{clear: both;}.dateHeader{color: #8c8c8c; display: inline-block; font-size: 28px; text-align: center; width: 100%; font-weight: 800; margin-bottom: 5px;}.fa-calendar-alt{margin-bottom: 5px;}.fa-calendar-alt, .dateText{color: #8c8c8c; display: inline-block; text-align: center; width: 100%;}.dateText{font-size: 22px; font-weight: 900;}.btnWrapper{}.button{margin-top: 10px; display: inline-block; font-size: 24px; font-weight: 900; width: 200px; height: 60px; text-align: center; line-height: 60px; text-decoration: none; color: #ffffff !important; border-radius: 5px;}.negative{margin-left: 70px; background-color: rgba(255, 0, 0, 0.5);}.negative:hover{box-shadow: 0 0 20px 1px rgba(255, 0, 0, 0.7);}.positive{margin-right: 70px; background-color: #67B246; float: right;}.positive:hover{box-shadow: 0 0 20px 1px #67B246;}.footerBar{background-color:#67B246;text-align:center;color:#fff;font-size:16px;font-weight:300;line-height:60px;height:60px;width:100%;margin-top: 40px;}</style></head><body> <div id="wrapper"> <div id="header"> <h1>Vacation Request</h1> </div><div id="subheader"> <h3>Vacation Request Approved</h3> <hr> </div><div id="msgBody"> <p style="margin-bottom:0 !important;font-size: 16px;">Hello ${userName}, <br><br>We would like to inform you that your vacation request has been approved</p><div class="dateBox"> <div style="float: left;" class="dateSpan"> <div class="dateHeader">From</div><img src="https://home.newtelco.de/calendar_icon.png"/> <h2 class="dateText">${mailStart}</h2> </div><div style="float: right;" class="dateSpan"> <div class="dateHeader">To</div><img src="https://home.newtelco.de/calendar_icon.png"/> <h2 class="dateText">${mailEnd}</h2> </div></div></div><div class="footerBar"><3 ndom91 <b>|</b> NewTelco GmbH</div></div></body></html>`
sendMsg(userName, userMail, userSubject, userBody)
} else if (action == '1') {
let userSubject = 'Request Denied'
let userBody = `<html><head> <style>@font-face{font-family: "Lato"; font-style: normal; font-weight: 300; src: local("Lato Light"), local("Lato-Light"), url(https://fonts.gstatic.com/s/lato/v15/S6u9w4BMUTPHh7USSwiPGQ.woff2) format("woff2"); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;}@font-face{font-family: "Lato"; font-style: normal; font-weight: 400; src: local("Lato Regular"), local("Lato-Regular"), url(https://fonts.gstatic.com/s/lato/v15/S6uyw4BMUTPHjx4wXg.woff2) format("woff2"); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;}html{font-family: Lato, Arial;}img{display: block; margin: auto;}#wrapper{max-width: 600px; margin: 0 auto;}#header{height: 80px; margin: auto 0; background-color: #67B246; width: 100%; text-align: center; line-height: 80px;}#subheader{text-align: center;}h1{font-size: 34px; color: #ffffff; font-weight: 300;}h3{font-size: 18px; font-weight: 900;}hr{width: 90%; height: 3px; border: none; color: #67B246; background-color: #67B246;}#msgBody > p{padding: 15px;}.dateSpan{display: inline-block; width: 45%;}.dateBox{border: 4px solid #8c8c8c; border-radius: 10px; padding: 40px; margin-top: 20px; margin-bottom: 20px; height: 220px;}.dateBox:after{clear: both;}.dateHeader{color: #8c8c8c; display: inline-block; font-size: 28px; text-align: center; width: 100%; font-weight: 800; margin-bottom: 5px;}.fa-calendar-alt{margin-bottom: 5px;}.fa-calendar-alt, .dateText{color: #8c8c8c; display: inline-block; text-align: center; width: 100%;}.dateText{font-size: 22px; font-weight: 900;}.btnWrapper{}.button{margin-top: 10px; display: inline-block; font-size: 24px; font-weight: 900; width: 200px; height: 60px; text-align: center; line-height: 60px; text-decoration: none; color: #ffffff !important; border-radius: 5px;}.negative{margin-left: 70px; background-color: rgba(255, 0, 0, 0.5);}.negative:hover{box-shadow: 0 0 20px 1px rgba(255, 0, 0, 0.7);}.positive{margin-right: 70px; background-color: #67B246; float: right;}.positive:hover{box-shadow: 0 0 20px 1px #67B246;}.footerBar{background-color:#67B246;text-align:center;color:#fff;font-size:16px;font-weight:300;line-height:60px;height:60px;width:100%;margin-top: 40px;}</style></head><body> <div id="wrapper"> <div id="header"> <h1>Vacation Request</h1> </div><div id="subheader"> <h3>Vacation Request Denied</h3> <hr> </div><div id="msgBody"> <p style="margin-bottom:0 !important;font-size: 16px;">Hello ${userName}, <br><br>We regret to inform you, that your vacation request has been denied.</p><div class="dateBox"> <div style="float: left;" class="dateSpan"> <div class="dateHeader">From</div><img src="https://home.newtelco.de/calendar_icon.png"/> <h2 class="dateText">${mailStart}</h2> </div><div style="float: right;" class="dateSpan"> <div class="dateHeader">To</div><img src="https://home.newtelco.de/calendar_icon.png"/> <h2 class="dateText">${mailEnd}</h2> </div></div></div><div class="footerBar"><3 ndom91 <b>|</b> NewTelco GmbH</div></div></body></html>`
sendMsg(userName, userMail, userSubject, userBody)
}
if(results1.affectedRows > 0) {
res.sendFile(__dirname + "/public/responseSuccess.html")
} else {
res.sendFile(__dirname + "/public/responseError.html")
}
})
// TO DO: save req URL and pass it into login path to redirect
// after successful login incase manager isnt pre-logged in
// when approving vacation request
})
} else {
console.error('not Authenticated!')
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/?response=2')
}
})
app.post('/admin/users', (req, res) => {
if (req.isAuthenticated() && memberOfAdmin(req.user.memberOf)) {
connection.query('SELECT DISTINCT name, email FROM vacations ORDER BY name', (error, results, fields) => {
if (error) throw error
// res.end(JSON.stringify(results))
return res.status(202).send(results)
})
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.post('/admin/managers', (req, res) => {
if (req.isAuthenticated() && memberOfAdmin(req.user.memberOf)) {
connection.query('SELECT * FROM managers', (error, results, fields) => {
if (error) throw error
// res.end(JSON.stringify(results))
return res.status(202).send(results)
})
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.post('/admin/managers/update', (req, res) => {
if (req.isAuthenticated() && memberOfAdmin(req.user.memberOf)) {
body = req.body
const id = body.id
const name = body.name
const email = body.email
connection.query(`UPDATE managers SET name = "${name}", email = "${email}" WHERE id LIKE "${id}";`, (error, results, fields) => {
if (error) throw error
// res.end(JSON.stringify(results))
return res.status(202).send(results)
})
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.post('/admin/managers/add', (req, res) => {
if (req.isAuthenticated() && memberOfAdmin(req.user.memberOf)) {
body = req.body
const id = body.id
const name = body.name
const email = body.email
connection.query(`INSERT INTO managers SET name = "${name}", email = "${email}";`, (error, results, fields) => {
if (error) throw error
return res.status(202).send(results)
})
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.post('/report/myVacations', (req, res) => {
if (req.isAuthenticated()) {
body = req.body
const userMail = body.userMail
connection.query(`SELECT MONTHNAME(fromDate) MONTH, YEAR(fromDate) YEAR, COUNT(*) COUNT FROM vacations WHERE fromDate > CURRENT_DATE() - INTERVAL 7 MONTH AND fromdate <= CURRENT_DATE + INTERVAL 1 MONTH AND email LIKE '${userMail}' GROUP BY MONTH(fromDate), YEAR(fromDate) ORDER BY YEAR(fromDate), MONTH(fromDate)`, (error, results, fields) => {
if (error) throw error
return res.status(202).send(results)
})
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.post('/report/allVacations', (req, res) => {
if (req.isAuthenticated()) {
connection.query(`SELECT MONTHNAME(fromDate) MONTH, YEAR(fromDate) YEAR, COUNT(*) COUNT FROM vacations WHERE fromDate > CURRENT_DATE() - INTERVAL 7 MONTH AND fromdate < CURRENT_DATE GROUP BY MONTH(fromDate), YEAR(fromDate) ORDER BY YEAR(fromDate), MONTH(fromDate)`, (error, results, fields) => {
if (error) throw error
return res.status(202).send(results)
})
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.post('/report/year', (req, res) => {
if (req.isAuthenticated()) {
body = req.body
const year = body.year
connection.query(`SELECT * FROM vacations WHERE YEAR(fromDate) = "${year}" OR YEAR(toDate) = "${year}";`, (error, results, fields) => {
if (error) throw error
return res.status(202).send(results)
})
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.post('/report/month', (req, res) => {
if (req.isAuthenticated() && memberOfAdmin(req.user.memberOf)) {
body = req.body
const month = body.month
const year = body.year
connection.query(`SELECT * FROM vacations WHERE (MONTH(toDate) = "${month}" AND YEAR(toDate) = "${year}") OR (MONTH(fromDate) = "${month}" AND YEAR(fromDate) = "${year}");`, (error, results, fields) => {
if (error) throw error
return res.status(202).send(results)
})
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.post('/admin/vacations/delete', (req, res) => {
if (req.isAuthenticated() && memberOfAdmin(req.user.memberOf)) {
body = req.body
connection.query(`DELETE FROM vacations WHERE id IN (${body});`, (error, results, fields) => {
if (error) throw error
return res.status(202).send(results)
})
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.post('/admin/managers/delete', (req, res) => {
if (req.isAuthenticated() && memberOfAdmin(req.user.memberOf)) {
body = req.body
const id = body.id
connection.query(`DELETE FROM managers WHERE id = "${id}";`, (error, results, fields) => {
if (error) throw error
return res.status(202).send(results)
})
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.post('/admin/listall', (req, res) => {
if (req.isAuthenticated() && memberOfAdmin(req.user.memberOf)) {
connection.query('SELECT id, name, resturlaubVorjahr, jahresurlaubInsgesamt, restjahresurlaubInsgesamt, beantragt, resturlaubJAHR, fromDate, toDate, manager, note, submitted_datetime, approval_hash, approved, approval_datetime FROM vacations;', (error, results, fields) => {
if (error) throw error
return res.status(202).send(results)
})
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.post('/vacation/user', (req, res) => {
if (req.isAuthenticated() == true) {
user = req.user
return res.status(202).send(user)
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.post('/vacation/list', (req, res) => {
if (req.isAuthenticated() == true) {
if(req.body.username){
user = req.body.username
} else {
user = req.user.sAMAccountName
}
connection.query(`SELECT resturlaubVorjahr, jahresurlaubInsgesamt, restjahresurlaubInsgesamt, beantragt, resturlaubJAHR, fromDate, toDate, manager, note, submitted_datetime, approved FROM vacations WHERE submitted_by LIKE "${user}";`, (error, results, fields) => {
if (error) throw error
return res.status(202).send(results)
})
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.post('/request/managers', (req, res) => {
if (req.isAuthenticated() == true) {
connection.query('SELECT * FROM managers', (error, results, fields) => {
if (error) throw error
return res.status(202).send(results)
})
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
app.post('/request/submit', (req, res) => {
if (req.isAuthenticated() == true) {
user = req.user
let newVaca = req.body
let approval_hash = uuid()
approval_hash = approval_hash.replace(/-/g, '')
const submitted_datetime = DateTime.local().toFormat('kkkk-MM-dd HH:mm:ss')
const toDATE = moment(newVaca.toDate).format('YYYY-MM-DD HH:mm:ss')
const fromDATE = moment(newVaca.fromDate).format('YYYY-MM-DD HH:mm:ss')
newVaca['toDate'] = toDATE
newVaca['fromDate'] = fromDATE
newVaca['submitted_by'] = user.sAMAccountName
newVaca['submitted_datetime'] = submitted_datetime
newVaca['approval_hash'] = approval_hash
connection.query('INSERT INTO vacations SET ?', newVaca, (error, results, fields) => {
if (error) throw error
return res.status(202).send(results)
})
// MANAGER APPROVE / DENY REQUEST
const reqUser = newVaca['name']
const reqfromDate = moment(newVaca['fromDate']).format('ddd MMM Do, YYYY')
const reqtoDate = moment(newVaca['toDate']).format('ddd MMM Do, YYYY')
const dateToday = moment().format('DD.MM.YYYY')
let msgSubject = `Request by ${newVaca['name']} [${newVaca['fromDate']} to ${newVaca['toDate']}]`
let mgrMail = newVaca['manager']
let optNote = ''
if(newVaca['note'] != '') {
const fName = reqUser.substr(0,reqUser.indexOf(' '));
optNote = `<p style="margin-top: 0 !important; font-size: 16px;"><b>Note from ${fName}:<br></b>${newVaca['note']}</p>`
} else {
optNote = ''
}
let msgBody = `<html><head> <style>@font-face{font-family: "Lato"; font-style: normal; font-weight: 300; src: local("Lato Light"), local("Lato-Light"), url(https://fonts.gstatic.com/s/lato/v15/S6u9w4BMUTPHh7USSwiPGQ.woff2) format("woff2"); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;}@font-face{font-family: "Lato"; font-style: normal; font-weight: 400; src: local("Lato Regular"), local("Lato-Regular"), url(https://fonts.gstatic.com/s/lato/v15/S6uyw4BMUTPHjx4wXg.woff2) format("woff2"); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;}html{font-family: Lato, Arial;}img{display: block; margin: auto;}#wrapper{max-width: 600px; margin: 0 auto;}#header{height: 80px; margin: auto 0; background-color: #67B246; width: 100%; text-align: center; line-height: 80px;}#subheader{text-align: center;}h1{font-size: 34px; color: #ffffff; font-weight: 300;}h3{font-size: 18px; font-weight: 900;}hr{width: 90%; height: 3px; border: none; color: #67B246; background-color: #67B246;}#msgBody > p{padding: 15px;}.dateSpan{display: inline-block; width: 45%;}.dateBox{border: 4px solid #8c8c8c; border-radius: 10px; padding: 40px; margin-top: 20px; margin-bottom: 20px; height: 220px;}.dateBox:after{clear: both;}.dateHeader{color: #8c8c8c; display: inline-block; font-size: 28px; text-align: center; width: 100%; font-weight: 800; margin-bottom: 5px;}.fa-calendar-alt{margin-bottom: 5px;}.fa-calendar-alt, .dateText{color: #8c8c8c; display: inline-block; text-align: center; width: 100%;}.dateText{font-size: 22px; font-weight: 900;}.btnWrapper{}.button{margin-top: 10px; display: inline-block; font-size: 24px; font-weight: 900; width: 200px; height: 60px; text-align: center; line-height: 60px; text-decoration: none; color: #ffffff !important; border-radius: 5px;}.negative{margin-left: 70px; background-color: rgba(255, 0, 0, 0.5);}.negative:hover{box-shadow: 0 0 20px 1px rgba(255, 0, 0, 0.7);}.positive{margin-right: 70px; background-color: #67B246; float: right;}.positive:hover{box-shadow: 0 0 20px 1px #67B246;}.footerBar{background-color:#67B246;text-align:center;color:#fff;font-size:16px;font-weight:300;line-height:60px;height:60px;width:100%;margin-top: 40px;}</style></head><body> <div id="wrapper"> <div id="header"> <h1>Vacation Request</h1> </div><div id="subheader"> <h3>New Vacation Request from ${reqUser}</h3> <hr> </div><div id="msgBody"> <p style="margin-bottom:0 !important;font-size: 16px;"> There has been a new vacation request from ${reqUser} <br><br>Please approve or deny this request below. This user will be notified via email of your decision. </p>${optNote}<div class="dateBox"> <div style="float: left;" class="dateSpan"> <div class="dateHeader">From</div><img src="https://home.newtelco.de/calendar_icon.png"/> <h2 class="dateText">${reqfromDate}</h2> </div><div style="float: right;" class="dateSpan"> <div class="dateHeader">To</div><img src="https://home.newtelco.de/calendar_icon.png"/> <h2 class="dateText">${reqtoDate}</h2> </div></div><div class="btnWrapper"> <a href="${process.env.BASE_URL}/admin/response?h=${approval_hash}&a=d" class="button negative">Deny</a> <a href="${process.env.BASE_URL}/admin/response?h=${approval_hash}&a=a" class="button positive">Approve</a> </div></div><div class="footerBar">${dateToday} <b>|</b> <3 ndom91 <b>|</b> NewTelco GmbH</div></div></body></html>`
mgrName = mgrMail.substring(0, mgrMail.lastIndexOf("@"));
// const ccMail = "[email protected]"
// if(mgrName = 'nhartmann') {
// sendMsg(mgrName, mgrMail, msgSubject, msgBody)
// } else {
// sendMsg(mgrName, mgrMail, msgSubject, msgBody, ccMail)
// }
sendMsg(mgrName, mgrMail, msgSubject, msgBody)
} else {
req.session.returnTo = req.originalUrl
return res.status(403).redirect('/')
}
})
port = process.env.WEB_PORT || 7555
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`)
})