-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathuser.ts
545 lines (510 loc) · 15.3 KB
/
user.ts
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
import * as fs from "fs";
import * as R from "ramda";
import * as errs from "restify-errors";
import * as request from "request";
import * as rp from "request-promise-native";
import * as restify from "restify";
import * as jwt from "jsonwebtoken";
import * as Scrypt from "scrypt-kdf";
import * as db from "./db";
import * as publish from "./table/publish"; // avoid or refactor
import logger from "./logger";
import { Preferences, User, UserId, Network } from "./types";
import { Request } from "restify";
import * as dataUrlStream from "data-url-stream";
import { savePicture, downloadPicture, CropData } from "./helpers";
const GOOGLE_OAUTH_SECRET = process.env.GOOGLE_OAUTH_SECRET;
const GITHUB_OAUTH_SECRET = process.env.GITHUB_OAUTH_SECRET;
const REDDIT_OAUTH_SECRET = process.env.REDDIT_OAUTH_SECRET;
const STEAM_WEB_API_KEY = process.env.STEAM_WEB_API_KEY;
const STEAM_APPID = process.env.STEAM_APPID;
export const defaultPreferences = (): Preferences => ({});
export const login = async (req, res, next) => {
try {
const network: Network | undefined = req.params.network;
if (!network) {
return next(new errs.InternalError("unknown network"));
}
if (network === "steam") {
return steamAuth(
req.body.steamId,
req.body.playerName,
req.body.ticket,
res,
next
);
}
if (network === "password") {
try {
if ((req.body.email ?? "") === "" || (req.body.password ?? "") === "") {
return res.send(400, "missing parameters");
}
const id = await db.getUserId(req.body.email);
const oldPassword = await db.getPassword(id);
const buffer = Buffer.from(oldPassword, "base64");
const ok = await Scrypt.verify(buffer, req.body.password);
if (!ok) {
return res.send(403, "bad user/password");
}
const profile = await db.getUser(id);
const token = jwt.sign(
JSON.stringify(profile),
process.env.JWT_SECRET!
);
res.sendRaw(200, token);
next();
} catch (e) {
return res.send(403, "bad user/password");
} finally {
return;
}
}
const profile = await getProfile(
network,
req.body,
req.headers.origin + "/"
);
logger.debug("login", profile.id);
let user = await db.getUserFromAuthorization(network, profile.id);
if (!user) {
return next(new errs.InternalError("registration is currently disabled"));
}
if (!user) {
let name = profile.name;
if (network === db.NETWORK_GITHUB && profile.login) {
name = profile.login;
} else if (network === db.NETWORK_STEAM && profile.personaname) {
name = profile.personaname;
}
logger.debug("profile", profile);
user = await db.createUser(
network,
profile.id, // network-id, not user-id
name,
profile.email,
"",
profile
);
// TODO move this into db.createUser somehow
let picture: string | null = null;
const pictureURL = profile.picture ?? profile.avatar_url ?? null;
if (pictureURL) {
try {
picture = await downloadPicture(user.id, pictureURL);
} catch (e) {
logger.error(e);
}
}
if (picture) {
user = await db.updateUser(user.id, {
name: null,
email: null,
picture,
password: null,
});
}
}
const token = jwt.sign(JSON.stringify(user), process.env.JWT_SECRET!);
res.sendRaw(200, token);
next();
} catch (e) {
logger.error(`login error: ${e.toString()}`, e);
next(new errs.InternalError("could not log in"));
}
};
export const addLogin = (req, res, next) => {
const network = req.params.network;
getProfile(network, req.body, req.headers.origin + "/")
.then(profile => {
logger.debug("addlogin", profile);
return db
.getUserFromAuthorization(network, profile.id)
.then(user => {
if (user) {
throw new Error("already registered");
}
// db.getUser(req.user.id);
return db.addNetwork(
req.user.id,
network,
profile.id,
{} // GDPR friendly: don't save everything
);
})
.then(user => {
const token = jwt.sign(JSON.stringify(user), process.env.JWT_SECRET!);
res.sendRaw(200, token);
next();
});
})
.catch(e => {
console.error("login error", e.toString());
res.send(
403,
"Already registered for another user. Logout and login again."
);
next();
});
};
const getProfile = (
network: Network,
code: string,
referer: string
): Promise<any> => {
if (network === db.NETWORK_STEAM) {
return getSteamProfile(code);
}
return new Promise((resolve, reject) => {
const options = {
[db.NETWORK_GOOGLE]: {
url: "https://www.googleapis.com/oauth2/v4/token",
form: {
code: code,
client_id:
"1000163928607-54qf4s6gf7ukjoevlkfpdetepm59176n.apps.googleusercontent.com",
client_secret: GOOGLE_OAUTH_SECRET,
scope: ["email", "profile"],
grant_type: "authorization_code",
redirect_uri: referer,
},
},
[db.NETWORK_GITHUB]: {
url: "https://github.com/login/oauth/access_token",
form: {
code: code,
client_id: "acbcad9ce3615b6fb44d",
client_secret: GITHUB_OAUTH_SECRET,
redirect_uri: referer,
},
headers: {
Accept: "application/json",
},
},
[db.NETWORK_REDDIT]: {
url: "https://www.reddit.com/api/v1/access_token",
form: {
code: code,
scope: ["identity"],
grant_type: "authorization_code",
redirect_uri: referer,
},
auth: {
username: "FjcCKkabynWNug",
password: REDDIT_OAUTH_SECRET,
},
},
}[network];
const req = { method: "POST", ...options };
request(req, function(err, response, body) {
if (err) {
logger.debug(
"login token request error",
network,
R.omit(["client_secret", "auth"], options)
);
return reject(err);
} else if (response.statusCode !== 200) {
logger.error(
"could not get access_token",
code,
referer,
body.toString(),
req
);
return reject(new Error(`token request status ${response.statusCode}`));
}
var json = JSON.parse(body);
request(
{
url: {
[db.NETWORK_GOOGLE]: "https://www.googleapis.com/userinfo/v2/me",
[db.NETWORK_REDDIT]: "https://oauth.reddit.com/api/v1/me",
[db.NETWORK_GITHUB]: "https://api.github.com/user",
}[network],
method: "GET",
headers: {
"User-Agent": "webapp:qdice.wtf:v1.0",
Authorization: json.token_type + " " + json.access_token,
Accept: "application/json",
},
},
function(err, response, body) {
if (err) {
return reject(err);
} else if (response.statusCode !== 200) {
console.error(body);
return reject(new Error(`profile ${response.statusCode}`));
}
const profile = JSON.parse(body);
resolve(profile);
}
);
});
});
};
export const me = async function(
req: restify.Request & { user: { id: string } },
res,
next
) {
if (typeof req.user === undefined) {
return next(new errs.GoneError("could not decode JWT"));
}
try {
const profile = await db.getUser(req.user.id, req.header("X-Real-IP"));
const token = jwt.sign(JSON.stringify(profile), process.env.JWT_SECRET!);
const preferences = await db.getPreferences(req.user.id);
res.send(200, [R.omit(["ip"], profile), token, preferences]);
next();
} catch (e) {
logger.error("/me", req.user);
logger.error(e);
next(
new errs.BadRequestError("could not get profile, JWT, or preferences")
);
}
};
export const profile = async function(req, res, next) {
try {
let password: string | null = null;
if (req.body.password) {
if ((req.body.passwordCheck ?? "").length === 0) {
return res.send(400, "missing current password");
}
const oldPassword = await db.getPassword(req.user.id);
const buffer = Buffer.from(oldPassword, "base64");
const ok = await Scrypt.verify(buffer, req.body.passwordCheck);
if (!ok) {
return res.send(403, "bad password");
}
password = await hashPassword(req.body.password);
logger.debug("changing password", ok);
}
const picture = req.body.picture
? await saveAvatar(req.user.id, req.body.picture)
: null;
logger.debug("saved", picture);
const profile = await db.updateUser(req.user.id, {
name: req.body.name,
email: req.body.email,
password,
picture,
});
const token = jwt.sign(JSON.stringify(profile), process.env.JWT_SECRET!);
res.sendRaw(200, token);
next();
} catch (e) {
logger.error(e);
if (e.message === "user update needs some fields") {
res.sendRaw(400, "Profile was not updated because nothing has changed.");
} else {
res.sendRaw(500, "Something went wrong.");
}
}
};
export const password = async function(req, res, next) {
if (!(await db.isAvailable(req.body.email))) {
res.sendRaw(400, "Email already exists");
return next();
}
logger.debug("email did not exist");
try {
const password = await hashPassword(req.body.password);
const profile = await db.updateUser(req.user.id, {
email: req.body.email,
name: null,
picture: null,
password: password,
});
const token = jwt.sign(JSON.stringify(profile), process.env.JWT_SECRET!);
res.sendRaw(200, token);
next();
} catch (e) {
logger.error(e);
next(e);
}
};
export const hashPassword = async function(password: string) {
const buffer = await Scrypt.kdf(password, {
logN: 15,
r: 8,
p: 1,
});
return buffer.toString("base64");
};
export const register = function(req: restify.Request, res, next) {
return next(new errs.BadRequestError("registration is currently disabled"));
const profile =
req.header("Origin").indexOf(".ssl.hwcdn.net") !== -1
? { itchio: true }
: null;
logger.debug(profile);
db.createUser(db.NETWORK_PASSWORD, null, req.body.name, null, null, profile)
.then(profile => {
const token = jwt.sign(JSON.stringify(profile), process.env.JWT_SECRET!);
res.sendRaw(200, token);
next();
})
.catch(e => next(e));
};
export const del = function(req, res, next) {
db.deleteUser(req.user.id)
.then(_ => {
res.send(200);
next();
})
.catch(e => next(e));
};
export const addPushSubscription = (add: boolean) => async (req, res, next) => {
const subscription = req.body;
const user: User = (req as any).user;
try {
await db.addPushSubscription(user.id, subscription, add);
const profile = await db.addPushEvent(user.id, "turn", add);
const token = jwt.sign(JSON.stringify(profile), process.env.JWT_SECRET!);
const preferences = await db.getPreferences(user.id);
res.send(200, [R.omit(["ip"], profile), token, preferences]);
} catch (e) {
console.error(e);
next(e);
}
};
export const addPushEvent = (add: boolean) => async (req, res, next) => {
const event = req.body;
const user: User = (req as any).user;
logger.debug("register push event", event, user.id);
db.addPushEvent(user.id, event, add)
.then(async profile => {
const token = jwt.sign(JSON.stringify(profile), process.env.JWT_SECRET!);
const preferences = await db.getPreferences(user.id);
res.send(200, [R.omit(["ip"], profile), token, preferences]);
})
.catch(e => {
console.error(e);
return Promise.reject(e);
})
.catch(e => next(e));
};
export const registerVote = (source: "topwebgames") => async (
req: Request,
res,
next
) => {
try {
const { ID, uid, votecounted, client_id } = req.query;
logger.debug("register vote", source, ID, uid, votecounted, client_id);
const user = await db.getUser(uid);
if (user.voted.indexOf(source) !== -1) {
return next(new Error(`user ${user.id} already voted "${source}"`));
}
await db.registerVote(user, source);
const profile = await db.addScore(user.id, 1000);
if (client_id) {
const preferences = await db.getPreferences(profile.id);
publish.userUpdate(client_id)(profile, preferences);
publish.userMessage(client_id, "You received 1000✪!");
}
logger.debug("voted", profile, user);
res.sendRaw(200, "ok");
} catch (e) {
console.error(e);
next(e);
}
};
const saveAvatar = (
id: UserId,
crop: CropData & { url: string }
): Promise<string> => {
const suffix = `${Math.floor(Math.random() * 10000)}`;
const filename = `user_${id}_${suffix}.png`;
const stream: fs.ReadStream = dataUrlStream(crop.url);
return savePicture(filename, stream, R.omit(["url"], crop));
};
const steamAuth = async (
steamId: string,
playerName: string,
ticket: string,
res,
next
) => {
if (!steamId || !ticket) {
return res.send(400, "Missing steamId/ticket");
}
try {
const body = await rp({
method: "GET",
url:
"https://api.steampowered.com/ISteamUserAuth/AuthenticateUserTicket/v1/",
qs: {
key: STEAM_WEB_API_KEY,
appid: STEAM_APPID,
ticket: ticket,
},
});
console.log("steamapi reply:", body);
const params = JSON.parse(body).response.params;
if (params.result !== "OK") {
return res.send(500, 'steam response not "OK"');
}
if (params.steamid !== steamId) {
return res.send(500, "mismatching steamids");
}
let user = await db.getUserFromAuthorization(db.NETWORK_STEAM, steamId);
if (!user) {
const profile = await getSteamProfile(steamId);
user = await db.createUser(
db.NETWORK_STEAM,
steamId, // network-id, not user-id
profile.personaname,
null,
"",
profile
);
// TODO move this into db.createUser somehow
let picture: string | null = null;
const pictureURL = profile.avatarfull ?? null;
if (pictureURL) {
try {
picture = await downloadPicture(user.id, pictureURL);
} catch (e) {
logger.error(e);
}
}
if (picture) {
user = await db.updateUser(user.id, {
name: null,
email: null,
picture,
password: null,
});
}
}
const token = jwt.sign(JSON.stringify(user), process.env.JWT_SECRET!);
res.sendRaw(200, token);
next();
} catch (e) {
return res.send(500, "error: " + e);
}
};
const getSteamProfile = async (
steamId: string
): Promise<{
personaname: string;
avatarfull: string;
steamid: string;
}> => {
const body = await rp({
method: "GET",
url: "https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v2/",
qs: {
key: STEAM_WEB_API_KEY,
steamids: steamId,
},
});
const profile = JSON.parse(body).response.players[0];
if (profile.steamid !== steamId) {
throw new Error("mismatching steamids (profile)");
}
profile.id = profile.steamid;
return profile;
};