-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
208 lines (171 loc) · 5.69 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
// Copyright 2017, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
const path = require('path');
const express = require('express');
const config = require('./config');
const app = express();
// Added for auth0 routing
// var authRouter = require('./routes/auth');
// CORS middleware to allow the frontend to access /email
const cors = require ('cors');
// jwt middleware for auth0 authorization
const jwt = require('express-jwt');
const jwksRsa = require('jwks-rsa');
const bodyParser = require('body-parser');
const jwtAuthz = require('express-jwt-authz');
const checkScopes = jwtAuthz(['post:email']);
// // Added for auth0 login
// var session = require('express-session');
var dotenv = require('dotenv'); // Load environment variables from .env, may eventually change all the env variables to be in config later
dotenv.config();
// scheduler (for unbooking all desks at a regular time every day)
var schedule = require('node-schedule');
// Load Passport
// var passport = require('passport');
// var Auth0Strategy = require('passport-auth0');
// SG mail
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
// enable the use of request body parsing middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
// Middleware for checking JWT for auth0 authentication
const checkJwt = jwt({
// Dynamically provide a signing key based on the kid in the header and the singing keys provided by the JWKS endpoint.
secret: jwksRsa.expressJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: 'https://angular-authentication.eu.auth0.com/.well-known/jwks.json'
}),
// Validate the audience and the issuer
audience: process.env.AUTH0_AUDIENCE,
issuer: 'https://angular-authentication.eu.auth0.com/',
algorithms: ['RS256']
});
function getModel () {
return require(`./desks/model-${require('./config').get('DATA_BACKEND')}`);
}
// Email endpoint and api
app.post('/email', checkJwt, checkScopes, function(req,res){
console.log(req.body.emails)
console.log(req.params['email'])
let emails = req.body.emails;
let thisDesk = req.body.desk;
let thisDeskID = req.body.desk.id;
// remove the desk id so datastore doesn't make a new field
// called 'id'
delete thisDesk['id'];
thisDesk.booked = true;
thisDesk.sign_in_time = new Date();
thisDesk.sign_out_time = null;
thisDesk.user_email = emails['email1'];
getModel().update(thisDeskID, thisDesk, null, (err, savedData) => {
if (err) {
console.log('update error: ', err)
return;
}
console.log('updated desk: ', savedData)
const msg = {
to: [emails['email1'], emails['email2']],
from: '[email protected]',
subject: 'IoT Desk Sign in Notice',
text: `
Hello, you have successfully booked ${thisDesk.name}. Thanks!
`,
html: `
<strong>Hello!</strong>
</br>
</br>
You have successfully booked me.
</br>
</br>
I'm all booked up until 5:30pm today.
</br>
</br>
You have a great day.
</br>
</br>
All the best,
</br>
</br>
<strong>${thisDesk.name}</strong>
`,
};
sgMail.send(msg);
console.log('email sent!')
res.status(200).send('email sent!');
});
});
// unbook all desks at 5:30PM every day
// https://www.npmjs.com/package/node-schedule
var j = schedule.scheduleJob('30 17 * * *', function() {
console.log("It's 5:30PM, unbooking all desks!")
getModel().list(30, null, (err, entities, cursor) => {
if (err) {
next(err);
return;
}
// set 'booked' in all desks to 'true'
const updated = entities.map( desk => {
if (desk.hotdesk) {
desk.booked = false;
desk.user_email = '';
}
const unbookedDesk = desk;
return unbookedDesk
});
getModel().update(null, null, updated, (err, savedData) => {
if (err) {
console.log("Something went horribly wrong with the bulk unbooking VIA CRON...");
next(err);
return;
}
console.log("All desks unbooked VIA CRON!");
});
});
});
app.disable('etag');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.set('trust proxy', true);
// Desks
app.use('/desks', require('./desks/crud'));
app.use('/api/desks', require('./desks/api'));
app.get('/', (req, res) => {
res.redirect('/desks');
});
// Basic 404 handler
app.use((req, res) => {
res.status(404).send('Not Found');
});
// Basic error handler
app.use((err, req, res, next) => {
/* jshint unused:false */
console.error(err);
// If our routes specified a specific response, then send that. Otherwise,
// send a generic message so as not to leak anything.
res.status(500).send(err.response || 'Something went horribly wrong!');
});
if (module === require.main) {
// Start the server
const server = app.listen(config.get('PORT'), () => {
const port = server.address().port;
console.log(`App listening on port ${port}`);
});
}
module.exports = app;