-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
365 lines (343 loc) · 9.24 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
const express = require("express")
var bodyParser = require("body-parser")
var cookieParser = require('cookie-parser');
const app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(cookieParser());
const port = process.env.PORT || 1337;
const request = require('request-promise').defaults({ jar: true })
var sqlite3 = require('sqlite3')
var db = new sqlite3.Database("storage.db")
const uuidv4 = require('uuid/v4');
var fixSession = (req, res, next) => {
let token;
if (!req.cookies.token) {
const genToken = uuidv4()
res.cookie("token", genToken)
db.run("INSERT INTO sessions (token, userId) VALUES (?, -1)", [genToken])
token = genToken
} else {
token = req.cookies.token
}
req.token = token;
next()
}
var getUserId = (req, callback) => {
db.all("SELECT userId FROM sessions WHERE token = ?", req.token, (err, result) => {
if (err) {
callback(null, err)
return
}
if (!result[0]) {
db.run("INSERT INTO sessions (token, userId) VALUES (?, -1)", req.token)
callback(-1, null)
}
result ? callback(result[0].userId, null) : callback(-1, null)
})
}
var checkLogin = (req, res, next) => {
getUserId(req, (result, err) => {
console.log(result)
if (result != -1) {
next()
} else {
res.status(401).json({
status: "error",
error: "unauthorized"
})
}
})
}
app.use(fixSession)
app.get("/setup", (req, res) => {
db.run("SELECT COUNT(*) FROM users", async (result, err) => {
if (result && result.code == "SQLITE_ERROR") {
res.redirect('/public/setup.html')
} else {
res.send("Already setup.")
}
})
})
app.post("/setup", async (req, res) => {
db.run("SELECT COUNT(*) FROM users", async (result, err) => {
if (result && result.code == "SQLITE_ERROR") {
if (!req.body.username || !req.body.password || !req.body.grade) {
res.status(400).json({
status: "error",
error: "missing parameters"
})
return
} else {
let loginReq = await request({
url: "https://dalton.myschoolapp.com/api/SignIn",
method: "POST",
json: {
"From": "",
"InterfaceSource": "WebApp",
"Password": req.body.password,
"Username": req.body.username,
}
})
if (!loginReq.LoginSuccessful) {
res.json({ status: "error", error: "invalid login" })
return
}
peopleStr = await request(`https://dalton.myschoolapp.com/api/directory/directoryresultsget?directoryId=725&searchVal=&facets=1657_${req.body.grade}&searchAll=false`)
db.exec("CREATE TABLE sessions (id INTEGER PRIMARY KEY AUTOINCREMENT, token TEXT, userId INTEGER)");
db.exec("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT, nickname TEXT, email TEXT, killedBy INTEGER, userLevel INTEGER, kills INTEGER)");
let stmt = db.prepare("INSERT INTO users (firstname, lastname, nickname, email, killedBy, userLevel, kills) VALUES (?, ?, ?, ?, -1, 0, 0)");
let people = JSON.parse(peopleStr)
for (id in people) {
const p = people[id]
stmt.run(p.FirstName, p.LastName, p.Nickname, p.Email)
}
res.json({ status: "ok" })
}
} else {
res.json({ status: "error", error: "server already setup" })
}
})
})
app.get("/api/stats", (req, res) => {
db.all("SELECT users.id AS id, users.firstname AS firstname, users.lastname AS lastname, users.nickname AS nickname, users.kills AS kills, killers.id AS killer_id, killers.firstname AS killer_firstname, killers.nickname AS killer_nickname, killers.lastname AS killer_lastname, killers.kills AS killer_kills, killers.killedBy AS killer_killedBy FROM users LEFT JOIN users killers ON users.killedBy = killers.id ORDER BY users.killedby, users.kills DESC;", (err, rows) => {
if (err) {
console.log(err)
res.status(500).json({
status: "error",
error: "internal server error",
})
return
}
let resp = []
for (i in rows) {
let r = rows[i]
let user = {
firstname: r.firstname,
lastname: r.lastname,
nickname: r.nickname,
kills: r.kills,
id: r.id,
dead: !(r.killer_id == null),
killer: {
firstname: r.killer_firstname,
lastname: r.killer_lastname,
nickname: r.killer_nickname,
id: r.killer_id,
kills: r.killer_kills,
dead: !(r.killer_killedBy == -1)
}
}
resp.push(user)
}
res.json(resp)
})
})
app.post("/api/findSomeoneToKill", (req, res) => {
let query = req.body.query
if (!query) {
res.status(400).json({
status: "error",
error: "missing parameters"
})
return
}
if (query == "") {
res.json([])
return
}
let sqlQuery = `%${query}%`
db.all("SELECT id, firstname, nickname, lastname FROM users WHERE killedBy = -1 AND (firstname LIKE ? OR lastname LIKE ? OR nickname LIKE ?)", [sqlQuery, sqlQuery, sqlQuery], (err, rows) => {
if (err) {
console.log(err)
res.status(500).json({
status: "error",
error: "internal server error",
})
return
}
res.json(rows)
})
})
app.use('/api/kill', checkLogin)
app.post("/api/kill", (req, res) => {
getUserId(req, (id, err) => {
let player = req.body.player
if (!req.body.player) {
res.status(400).json({
status: "error",
error: "missing parameters"
})
return
}
db.all("SELECT killedBy FROM users WHERE id = ?", player, (err, killedBy) => {
if (err) {
console.log(err)
res.status(500).json({
status: "error",
error: "internal server error",
})
return
}
if (killedBy.length == 0) {
res.status(400).json({
status: "error",
error: "player not found"
})
return
} else if (killedBy[0].killedBy != -1) {
res.status(410).json({
status: "error",
error: "player already dead"
})
return
}
db.run("UPDATE users SET killedBy = ? WHERE id = ?", [id, player], (result, err) => {
if (err) {
console.log(err)
res.status(500).json({
status: "error",
error: "internal server error",
})
return
}
db.run("UPDATE users SET kills = kills + 1 WHERE id = ?", id, (result, err) => {
if (err) {
console.log(err)
res.json({
status: "ok",
warning: "kill count not updated"
})
return
}
res.json({
status: "ok"
})
})
})
})
})
})
app.get("/api/auth/me", (req, res) => {
getUserId(req, (id, err) => {
if (err) {
console.log(err)
res.status(500).json({
status: "error",
error: "internal server error",
})
return
}
if (id == -1) {
res.status(401).json({
status: "error",
error: "signed out",
})
} else {
db.all("SELECT users.id AS id, users.firstname AS firstname, users.lastname AS lastname, users.nickname AS nickname, users.kills AS kills, killers.id AS killer_id, killers.firstname AS killer_firstname, killers.lastname AS killer_lastname, killers.kills AS killer_kills, killers.killedBy AS killer_killedBy FROM users LEFT JOIN users killers ON users.killedBy = killers.id WHERE users.id = ?", id, (err, rows) => {
if (err) {
console.log(err)
res.status(500).json({
status: "error",
error: "internal server error",
})
return
}
let r = rows[0]
res.json({
firstname: r.firstname,
lastname: r.lastname,
nickname: r.nickname,
kills: r.kills,
id: r.id,
dead: !(r.killer_id == null),
killer: {
fistname: r.killer_firstname,
lastname: r.killer_lastname,
nickname: r.killer_nickname,
id: r.killer_id,
kills: r.killer_kills,
dead: !(r.killer_killedBy == -1)
}
})
})
}
})
})
app.post("/api/auth/logout", (req, res) => {
db.run("UPDATE sessions SET userId = -1 WHERE token = ?", req.token, (result, err) => {
if (err) {
console.log(err)
res.status(500).json({
status: "error",
error: "internal server error",
})
return
}
res.json({ status: "ok" })
})
})
app.post("/api/auth/login", async (req, res) => {
if (!req.body.username || !req.body.password) {
res.status(400).json({
status: "error",
error: "missing parameters"
})
}
let jar = request.jar()
let login = await request({
url: "https://dalton.myschoolapp.com/api/SignIn",
method: "POST",
jar: jar,
json: {
"From": "",
"InterfaceSource": "WebApp",
"Username": req.body.username,
"Password": req.body.password,
}
})
if (!login.LoginSuccessful) {
res.status(401).json({
status: "error",
error: "login was unsuccessful"
})
return
}
let emailReq = await request({
url: `https://dalton.myschoolapp.com/api/user/${login.CurrentUserForExpired}/?propertylist=Email`,
method: "GET",
jar: jar,
})
db.all("SELECT id FROM users WHERE email = ?", JSON.parse(emailReq).Email, (err, rows) => {
if (err) {
console.log(error)
res.status(500).json({
status: "error",
error: "internal server error",
})
return
} else if (rows == []) {
res.status(401).json({
status: "error",
error: "account does not exit",
})
return
}
db.run("UPDATE sessions SET userId = ? WHERE token = ?", [rows[0].id, req.token], (result, err) => {
if (err) {
console.log(err)
res.status(500).json({
status: "error",
error: "internal server error",
})
return
}
res.json({
status: "ok"
})
})
})
})
app.use('/', express.static('site'))
app.use('/public', express.static('public'))
app.listen(port, () => console.log(`Fork game listening on port ${port}!`))