-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
255 lines (222 loc) · 6.5 KB
/
server.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
//Imports and Requirements
const express = require('express');
const Sequelize = require('sequelize');
const shelljs = require('shelljs');
const crypto = require('crypto');
const cookie = require('cookie');
const jwt = require('jsonwebtoken');
//Database config
const env = "dev";
const config = require('./config.json')[env];
const password = config.password || null;
// JWT stuff
const secret = 'super-secret';
//middleware
const QuizMiddleware = require('./quizMiddleware');
const port = process.env.port || 8080;
//initiate database connection
const sequelize = new Sequelize(
config.database,
config.user,
config.password,
{
dialect: config.dialect,
port: config.port,
host: config.host,
logging: console.log,
define: {
timestamps: false
},
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
}
);
//Authenticate Database connection
sequelize
.authenticate()
.then(function (err) {
console.log('Connection has been established successfully.');
})
.catch(function (err) {
console.log('Unable to connect to the database:', err);
});
//Models
const Organizers = sequelize.define('organizers', {
id: {type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
username: {type: Sequelize.STRING(512),},
access_token: {type: Sequelize.STRING,}
});
const Quizzes = sequelize.define('quizzes', {
id: {type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
name: {type: Sequelize.STRING(512),},
questions: {type: Sequelize.STRING,},
organizer: {type: Sequelize.INTEGER},
url: {type: Sequelize.STRING(128)}, // url to their game server
code: {type: Sequelize.STRING(5), unique: true}
});
// Create Server
const server = express();
const bodyParser = require('body-parser');
const morgan = require('morgan');
const cors = require('cors');
whitelist = (process.env.ENV === 'PROD') ? ["https://dashboard.howlplay.com", 'https://howlplay.com'] : ['http://localhost:3000'];
// CORS settings
const corsSettings = {
"origin": whitelist, // note this cannot be a wildcard or true
"credentials" : true
};
// Initialize Body Parser
server.use(bodyParser.json());
server.use(cors(corsSettings));
server.use(morgan('tiny'));
const verifyUser = (req, res, next) => {
let parsedCookie = cookie.parse(req.headers.cookie);
console.log(parsedCookie);
let token = parsedCookie.token;
jwt.verify(token, secret, function(err, decoded) {
if (err) {console.log(err); return res.send(401, 'access denied') }
else {
req.id = decoded.id;
}
next();
});
};
// server.options('*', cors(corsSettings))
// Quiz End Points
// Create New Quiz
server.post('/quiz', [verifyUser, QuizMiddleware.setQuizValidator], function (req, res) {
if (!req.body.name || !req.body.questions || !req.body.url) {
res.status(400).send();
} else {
console.log(req.body.questions);
Quizzes.create({
name: req.params.name,
questions: JSON.stringify(req.params.questions),
organizer: req.id,
url: req.params.url,
code: Math.floor(Math.random()*90000) + 10000
}).then(quiz => {
res.send(quiz);
});
}
});
// PWA quiz login
server.post('/pwa/game', function(req, res) {
const code = req.body.code;
if (!code) {
res.status(400).send();
return;
}
Quizzes.findOne({
attributes: ['id', 'url'],
where: {'code' : code}
}).then(quiz => {
console.log(quiz.dataValues);
if (!quiz) {
res.status(500).send();
return;
}
res.send(quiz.dataValues);
})
});
server.post('/dashboard/signin', function (req, res, next) {
let accessToken = req.body.token;
if (!accessToken) {
return res.send(400, "Requires accessToken");
}
Organizers.findOne({where: {"access_token": accessToken}})
.then(quizzes => {
console.log(quizzes.dataValues.id);
let id = quizzes.dataValues.id;
let token = jwt.sign({id : id}, secret);
res.cookie('token', token, {
path : '/',
maxAge: 60 * 60 * 24 * 7, // 1 week in number of seconds
});
res.send({token: token});
})
});
server.get('/quizzes', verifyUser, async function (req, res) {
let {id} = req;
try {
let quizzes = await Quizzes.findAll({where: {"organizer": id}});
res.send(quizzes);
} catch (err) {
console.log(err);
res.status(400).send(err);
}
});
// Spin up a game server
server.post('/spinup', function(req, res){
let data = body;
let quiz_hash = crypto.createHash('md5').update(data.details).digest('base64');
let admin_key = data.key;
shelljs.exec('bash ./create-game-server.sh QUIZ_HASH:' + quiz_hash + ' ADMIN_KEY:' + admin_key);
res.send();
});
// Get Quiz
server.get('/quiz/:quizId', verifyUser, function (req, res) {
const quizId = req.params.quizId;
Quizzes.findOne({
attributes: ['id', 'name', 'questions', 'url', 'code'],
where: {
"id": quizId,
organizer: req.id
}
}).then(Quiz => {
if (Quiz == null) {
res.status(400).send();
}
else {
Quiz.questions = JSON.parse(Quiz.questions);
res.status(200).send(Quiz)
}
});
});
// Update Quiz
server.patch('/quiz/:id', [verifyUser, QuizMiddleware.updateQuizValidator], function (req, res) {
let json = {};
if (req.body.name != null) {
json.name = req.body.name;
}
Quizzes.update(json, {
where: {
id: req.params.id,
organizer: req.id
}
}
).catch(err => {
res.status(400).send(err);
});
Quizzes.findOne({
attributes: ['id', 'name', 'questions'],
where: {
id: req.params.id,
organizer: req.id
}
}).then(Quiz => {
Quiz.questions = JSON.parse(Quiz.questions);
res.status(200).send(Quiz);
});
});
server.post('/login', function (req, res) {
let { username, password } = req.body;
if (username !== "LeBron" || password !== "James") {
res.statu(401).send("Invalid Username or Password");
} else {
res.send({
access_token: "ABC123"
})
}
});
server.get('/', (req, res) => {
res.send('API is Running');
});
// Start Server
server.listen(port, function () {
console.log(`Server listening on ${port}`);
});