aboutsummaryrefslogtreecommitdiffstats
path: root/routes/users.js
blob: c4b613eb9d349d95511967cdd4c8d59a45aa2900 (plain) (blame)
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
import app from "$app";
import config from "$config";
import store from "$lib/store";
import { auth, optionalAuth } from "$lib/passport";
import { getUser } from "$lib/utils";
import axios from "axios";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import { authenticator } from "otplib";
import Sequelize from "@sequelize/core";
import bitcoin from "bitcoinjs-lib";
import liquid from "liquidjs-lib";
import { fromBase58, fromPrivateKey } from "bip32";
import { Mutex } from "async-mutex";
import bip32 from "bip32";
import whitelist from "$lib/whitelist";
import { l, err, warn } from "$lib/logging";
import db from "$db";
import bc from "$lib/bitcoin";
import lq from "$lib/liquid";
import { emit } from "$lib/sockets";
import register from "$lib/register";
import { requirePin } from "$lib/utils";

const pick = (O, ...K) => K.reduce((o, k) => ((o[k] = O[k]), o), {});

app.get("/me", auth, async (req, res) => {
  try {
    let user = req.user.get({ plain: true });
    let payments = await req.user.getPayments({
      where: {
        account_id: user.account_id
      },
      order: [["id", "DESC"]],
      limit: 12,
      include: [
        {
          model: db.Account,
          as: "account"
        },
        {
          model: db.Payment,
          as: "fee_payment"
        }
      ]
    });
    user.accounts = await req.user.getAccounts();
    user.payments = payments;
    user.haspin = !!user.pin;
    res.send(pick(user, ...whitelist));
  } catch (e) {
    res.code(500).send(e.message);
  }
});

app.get("/users/:username", async (req, res) => {
  const { username } = req.params;

  const user = await db.User.findOne({
    attributes: ["username", "banner", "profile", "address", "currency"],
    where: Sequelize.where(
      Sequelize.fn("lower", Sequelize.col("username")),
      username.toLowerCase()
    )
  });

  if (user) res.send(user);
  else res.code(500).send("User not found");
});

app.post("/register", async (req, res) => {
  try {
    const ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress;
    const user = await register(req.body.user, ip, false);
    res.send(pick(user, ...whitelist));
  } catch (e) {
    res.code(500).send(e.message);
  }
});

app.post("/disable2fa", auth, async (req, res) => {
  try {
    let {
      user,
      body: { token }
    } = req;

    if (user.twofa && !authenticator.check(token, user.otpsecret)) {
      return res.code(401).send("2fa required");
    }

    user.twofa = false;
    await user.save();
    emit(user.username, "user", user);
    emit(user.username, "otpsecret", user.otpsecret);
    l("disabled 2fa", user.username);
    res.send({});
  } catch (e) {
    res.code(500).send("Problem disabling 2fa");
  }
});

app.post("/2fa", auth, async (req, res) => {
  let { user } = req;
  try {
    const isValid = authenticator.check(req.body.token, req.user.otpsecret);
    if (isValid) {
      user.twofa = true;
      user.save();
      emit(user.username, "user", req.user);
    } else {
      return res.code(500).send("Invalid token");
    }
  } catch (e) {
    err("error setting up 2fa", e);
  }

  l("enabled 2fa", user.username);
  res.send({});
});

app.get("/exists", async (req, res) => {
  let exists = await db.User.findOne({
    where: { username: req.query.username }
  });

  res.send(!!exists);
});

app.post("/user", auth, async (req, res) => {
  try {
    let { user } = req;
    let {
      address,
      confirm,
      currencies,
      currency,
      email,
      fiat,
      password,
      newpin,
      pin,
      seed,
      tokens,
      twofa,
      unit,
      username
    } = req.body;

    if (user.pin && !(pin === user.pin)) throw new Error("Pin required");

    let exists = await db.User.findOne({
      where: { username }
    });

    let token;
    if (user.username !== username && exists) {
      err("username taken", username, user.username, exists.username);
      throw new Error("Username taken");
    } else {
      store.sockets[username] = store.sockets[user.username];
      if (user.username !== username)
        l("changing username", user.username, username);
      user.username = username;

      token = jwt.sign({ username }, config.jwt);
      res.cookie("token", token, {
        expires: new Date(Date.now() + 432000000)
      });
    }

    if (unit) user.unit = unit;
    user.currency = currency;
    user.currencies = currencies;
    user.pin = newpin;
    user.tokens = tokens;
    user.twofa = twofa;
    user.seed = seed;
    user.fiat = fiat;
    user.email = email;
    user.address = address;

    if (password && password === confirm) {
      user.password = await bcrypt.hash(password, 1);
    }

    await user.save();

    user = user.get({ plain: true });
    user.haspin = !!user.pin;

    emit(user.username, "user", user);
    res.send({ user, token });
  } catch (e) {
    err("error updating user", e.message);
    res.code(500).send(e.message);
  }
});

app.post("/keys", auth, async (req, res) => {
  const { key: hex } = req.body;
  const key = await db.Key.create({
    user_id: req.user.id,
    hex
  });
  emit(req.user.username, "key", key);
  res.send(key);
});

app.post("/keys/delete", auth, async (req, res) => {
  const { hex } = req.body;
  (
    await db.Key.findOne({
      where: {
        user_id: req.user.id,
        hex
      }
    })
  ).destroy();
});

app.post("/updateSeeds", auth, async (req, res) => {
  let { user } = req;
  let { seeds } = req.body;
  let keys = Object.keys(seeds);

  for (let i = 0; i < keys.length; i++) {
    let id = keys[i];
    let seed = seeds[id];
    await db.Account.update(
      { seed },
      {
        where: { id, user_id: user.id }
      }
    );

    const account = await db.Account.findOne({
      where: { id }
    });

    emit(user.username, "account", account);
  }

  res.send({});
});

app.post("/accounts/delete", auth, async (req, res) => {
  const { id } = req.body;
  const account = await db.Account.findOne({ where: { id } });
  if (account) await account.destroy();
  res.send({});
});

app.post("/accounts", auth, async (req, res) => {
  const {
    name,
    seed,
    pubkey,
    ticker,
    precision,
    path,
    privkey,
    network
  } = req.body;
  const { user } = req;

  let account = await db.Account.create({
    user_id: user.id,
    asset: config.liquid.btcasset,
    balance: 0,
    pending: 0,
    name,
    ticker,
    precision,
    pubkey,
    privkey,
    seed,
    path,
    network
  });

  emit(user.username, "account", account);

  if (pubkey) user.index++;
  user.account_id = account.id;
  await user.save();
  user.account = account;
  emit(user.username, "user", user);

  res.send(account);
});

let login = async (req, res) => {
  try {
    const { params, sig, key } = req.body;

    if (sig) {
      const { callback } = params;

      try {
        const url = `${callback}&sig=${sig}&key=${key}`;
        const response = await axios.get(url);
        res.send(response.data);
      } catch (e) {
        err("problem calling lnurl login", e.message);
        res.code(500).send(e.message);
      }

      return;
    }

    let twofa = req.body.token;

    let user = await getUser(req.body.username);

    if (
      !user ||
      (user.password &&
        !(await bcrypt.compare(req.body.password, user.password)))
    ) {
      warn("invalid username or password attempt", req.body.username);
      return res.code(401).send({});
    }

    if (
      user.twofa &&
      (typeof twofa === "undefined" ||
        !authenticator.check(twofa, user.otpsecret))
    ) {
      return res.code(401).send("2fa required");
    }

    l(
      "login",
      req.body.username,
      req.headers["x-forwarded-for"] || req.connection.remoteAddress
    );

    let payload = { username: user.username };
    let token = jwt.sign(payload, config.jwt);
    res.cookie("token", token, { expires: new Date(Date.now() + 432000000) });
    user.accounts = await user.getAccounts();
    user.keys = await user.getKeys();
    user = pick(user, ...whitelist);
    res.send({ user, token });
  } catch (e) {
    err("login error", e.message, req.connection.remoteAddress);
    res.code(401).send({});
  }
};

app.post("/login", login);
app.post("/taboggan", login);
app.post("/doggin", login);

app.post("/logout", optionalAuth, async (req, res) => {
  let { subscription } = req.body;
  if (!subscription) return res.send({});

  const { username } = req.user;

  if (username) {
    l("logging out", username);
    let i = req.user.subscriptions.findIndex(
      s => JSON.stringify(s) === subscription
    );
    if (i > -1) {
      req.user.subscriptions.splice(i, 1);
    }
    await req.user.save();
    Object.keys(logins).map(
      k => logins[k]["username"] === username && delete logins[k]
    );
  }

  res.send({});
});

app.post("/account", auth, async (req, res) => {
  const { user } = req;
  const {
    id,
    name,
    ticker,
    precision,
    domain,
    seed,
    pubkey,
    privkey,
    path,
    hide,
    index
  } = req.body;

  try {
    await db.transaction(async transaction => {
      let account = await db.Account.findOne({
        where: { id, user_id: user.id },
        lock: transaction.LOCK.UPDATE,
        transaction
      });

      let params = {
        name,
        ticker,
        precision,
        domain,
        seed,
        pubkey,
        path,
        hide,
        index,
        privkey
      };

      if (!account || (account.pubkey && !pubkey)) delete params.pubkey;

      await db.Account.update(params, {
        where: { id, user_id: user.id },
        transaction
      });

      await account.reload({ transaction });
      emit(user.username, "account", account);
      res.send({});
    });
  } catch (e) {
    err("problem updating account", e.message);
    return res.code(500).send("There was a problem updating the account");
  }
});

app.post("/shiftAccount", auth, async (req, res) => {
  let { user } = req;
  let { id } = req.body;

  try {
    const account = await db.Account.findOne({
      where: { id }
    });

    if (account.user_id !== user.id)
      return res.code(500).send("Failed to open wallet");

    user.account_id = account.id;
    await user.save();
    let payments = await db.Payment.findAll({
      where: {
        account_id: id
      },
      order: [["id", "DESC"]],
      limit: 12,
      include: {
        model: db.Account,
        as: "account"
      }
    });

    user = user.get({ plain: true });
    user.payments = payments;
    user.account = account.get({ plain: true });

    emit(user.username, "account", user.account);
    emit(user.username, "user", user);

    res.send(user);
  } catch (e) {
    err("problem switching account", e.message);
    return res.code(500).send("There was a problem switching accounts");
  }
});

app.get("/vapidPublicKey", function(req, res) {
  res.send(config.vapid.publicKey);
});

app.post("/subscribe", auth, async function(req, res) {
  let { subscriptions } = req.user;
  let { subscription } = req.body;
  if (!subscriptions) subscriptions = [];
  if (
    !subscriptions.find(s => JSON.stringify(s) === JSON.stringify(subscription))
  )
    subscriptions.push(subscription);
  req.user.subscriptions = subscriptions;
  l("subscribing", req.user.username);
  await req.user.save();
  res.sendStatus(201);
});

app.post("/password", auth, async function(req, res) {
  const { user } = req;
  const { password } = req.body;

  if (!user.password) return res.send(true);
  res.send(await bcrypt.compare(password, user.password));
});

app.get("/isInternal", auth, async function(req, res) {
  let { user } = req;
  let { address } = req.query;
  if (!address) throw new Error("Address not provided");

  let invoice = await db.Invoice.findOne({
    where: { address },
    include: {
      attributes: ["username"],
      model: db.User,
      as: "user"
    }
  });

  if (invoice) {
    let info;
    try {
      info = await bc.getAddressInfo(address);
    } catch (e) {
      info = await lq.getAddressInfo(address);
    }
    if (info.ismine) {
      emit(user.username, "to", invoice.user);
      return res.send(true);
    }
  }

  res.send(false);
});

app.get("/invoices", auth, async function(req, res) {
  let invoices = await db.Invoice.findAll({
    where: { user_id: req.user.id }
  });
  res.send(invoices);
});

app.post("/signMessage", auth, async function(req, res) {
  let { address, message } = req.body;

  let invoices = await db.Invoice.findAll({
    where: { user_id: req.user.id }
  });

  if (invoices.find(i => i.address === address)) {
    if (config.bitcoin.walletpass)
      await bc.walletPassphrase(config.bitcoin.walletpass, 300);
    return res.send(await bc.signMessage(address, message));
  }

  res.code(500).send("Address not found for user");
});

app.post("/otpsecret", auth, async function(req, res) {
  try {
    await requirePin(req);
    let { otpsecret } = req.user;
    res.send({ secret: otpsecret });
  } catch (e) {
    res.code(500).send(e.message);
  }
});

app.get("/contacts", auth, async function(req, res) {
  try {
    let contacts = await db.Payment.findAll({
      where: {
        user_id: req.user.id,
        with_id: { [Sequelize.Op.ne]: null }
      },
      include: {
        attributes: ["username", "profile"],
        model: db.User,
        as: "with"
      },
      attributes: [
        [Sequelize.fn("max", Sequelize.col("payments_model.createdAt")), "last"]
      ],
      group: ["with_id"],
      order: [[{ model: db.User, as: "with" }, "username", "ASC"]]
    });

    res.send(
      contacts.map(c => {
        c = c.get({ plain: true });
        return { ...c.with, last: c.last };
      })
    );
  } catch (e) {
    console.log(e);
    res.code(500).send(e.message);
  }
});