aboutsummaryrefslogtreecommitdiffstats
Commit message (Expand)AuthorAgeFilesLines
* Implement send transaction functionAdam Soltys2015-11-277-50/+1686
* Fix tolerance calculationAdam Soltys2015-11-271-1/+3
* Cache balances properlyAdam Soltys2015-11-271-12/+16
* Error handlingAdam Soltys2015-11-274-5/+11
* Re-arrange wallet formAdam Soltys2015-11-271-41/+42
* Set amount field range and formattingAdam Soltys2015-11-272-2/+15
* Use custom units in walletAdam Soltys2015-11-272-14/+29
* Max buttonAdam Soltys2015-11-272-1/+8
* Currency toggleAdam Soltys2015-11-272-6/+29
* Cache wallet addressesAdam Soltys2015-11-273-40/+84
* Merge pull request #1 from alexmillar/masterAdam Soltys2015-11-131-0/+4
|\
| * Added a contributors sectionAlex Millar2015-11-131-0/+4
| * Merge remote-tracking branch 'asoltys/master'Alex Millar2015-11-131-2/+2
| |\ | |/ |/|
* | Use bcryptjs instead of bcryptAdam Soltys2015-11-136-7/+7
| * Merge remote-tracking branch 'asoltys/master'Alex Millar2015-11-1320-210/+287
| |\
| | * Use bcryptjs instead of bcryptAdam Soltys2015-11-135-5/+5
| |/ |/|
* | Get wallet balanceAdam Soltys2015-11-134-156/+77
* | Update wallet creation wordingAdam Soltys2015-11-123-12/+12
* | Ignore logosAdam Soltys2015-11-114-1/+1
* | Dropdown for discountAdam Soltys2015-11-111-2/+15
* | Move address management to separate wallet pageAdam Soltys2015-11-1110-190/+266
* | Change how socket retries are performedAdam Soltys2015-11-111-10/+19
* | New payment received soundAdam Soltys2015-11-113-5/+2
* | Fetch remote image files and store locallyAdam Soltys2015-11-115-4/+29
* | Bitcoin tips pageAdam Soltys2015-11-063-2/+36
* | Make QR code smallerAdam Soltys2015-10-151-1/+1
* | Don't detect static asset changesAdam Soltys2015-10-152-2/+3
* | Set logo width to 100%Adam Soltys2015-10-151-1/+1
* | Floathouse logoAdam Soltys2015-10-161-0/+0
* | Ignore passenger files and tmp folderAdam Soltys2015-10-161-0/+2
* | Set max width of logo imageAdam Soltys2015-10-161-1/+1
| * Make QR code smallerAdam Soltys2015-10-151-1/+1
| * Don't detect static asset changesAdam Soltys2015-09-162-2/+3
| * Set logo width to 100%Adam Soltys2015-09-141-1/+1
|/
* Only send mail in productionAdam Soltys2015-01-032-55/+61
* Update install instructionsAdam Soltys2014-12-082-4/+9
* Use external chain 0 for key derivationAdam Soltys2014-12-082-45/+10
* Key depth should be 1Adam Soltys2014-11-301-1/+1
* Check for empty transactions arrayAdam Soltys2014-09-164-2/+10
* Fix transactions index bugAdam Soltys2014-09-164-13/+14
* Mail keyAdam Soltys2014-09-1510-46/+133
* Streamline key generationAdam Soltys2014-09-1150-356/+11514
* Accept extended pubkeys, multisig, or single addressesAdam Soltys2014-09-065-77/+63
* Generate key on registrationAdam Soltys2014-09-0612-141/+540
* Use query instead of session for verified messageAdam Soltys2014-09-032-6/+4
* Separate account profile settingsAdam Soltys2014-09-0311-170/+32
* Start work on profile pageAdam Soltys2014-09-026-0/+211
* Verify emailAdam Soltys2014-09-0211-25/+138
* Fix up transactions UIAdam Soltys2014-09-017-9/+12
* Confirm transaction deleteAdam Soltys2014-09-012-2/+25
title='Blame the previous revision' href='/coinos-server.git/blame/routes/users.js?h=tickets&id=a9a061656668965fbf627ae73165d361d8ca9183'>^
99d71f03 ^



b45deffe ^
b14c1b44 ^



e40e68f4 ^
b14c1b44 ^
2a960a24 ^
b14c1b44 ^


2a960a24 ^
99d71f03 ^














2c695d52 ^
99d71f03 ^
e40e68f4 ^
99d71f03 ^


e40e68f4 ^
c0888fab ^
c0888fab ^
99d71f03 ^

5cd96cc0 ^
99d71f03 ^


4d2379b8 ^
99d71f03 ^
c0888fab ^
99d71f03 ^

e40e68f4 ^
99d71f03 ^

c0888fab ^
99d71f03 ^


96dff083 ^
99d71f03 ^




d6af2106 ^
2c695d52 ^
99d71f03 ^

d6af2106 ^
99d71f03 ^


d6af2106 ^
99d71f03 ^











e40e68f4 ^
99d71f03 ^

2621fec1 ^
99d71f03 ^











e40e68f4 ^

99d71f03 ^





e40e68f4 ^




















e40e68f4 ^











b5607df4 ^
e40e68f4 ^





f89b0ffd ^


a90d6cc9 ^









f89b0ffd ^


f89b0ffd ^



7ab3036c ^

e40e68f4 ^
f89b0ffd ^
cd3977c1 ^
e40e68f4 ^
49883ffc ^

f89b0ffd ^

e40e68f4 ^

b5607df4 ^




e40e68f4 ^
f89b0ffd ^




7335775c ^
99d71f03 ^
245e6afb ^













99d71f03 ^
245e6afb ^

d6af2106 ^
245e6afb ^
d6af2106 ^
99d71f03 ^








20273701 ^
99d71f03 ^











245e6afb ^





99d71f03 ^


f89b0ffd ^
99d71f03 ^



2621fec1 ^
99d71f03 ^






2717860d ^
99d71f03 ^

99d71f03 ^
2717860d ^





e40e68f4 ^
2717860d ^





e40e68f4 ^
2717860d ^
99d71f03 ^
c0888fab ^
99d71f03 ^


c0888fab ^
2bcd5e9c ^
99d71f03 ^
99d71f03 ^
a90d6cc9 ^
445a3823 ^
ba07b04f ^
a90d6cc9 ^




f14ebcba ^
c0888fab ^
a90d6cc9 ^













































c0888fab ^
a90d6cc9 ^




ba07b04f ^
f6954098 ^
a90d6cc9 ^



ba07b04f ^
245e6afb ^



a90d6cc9 ^








2717860d ^
ba07b04f ^
445a3823 ^
99d71f03 ^






f89b0ffd ^
e40e68f4 ^







cd3977c1 ^
e40e68f4 ^
54a9a19b ^
49883ffc ^
e40e68f4 ^
74b7d2a0 ^
99d71f03 ^
d01159ce ^





eb860d78 ^
d01159ce ^
a90d6cc9 ^









d01159ce ^
b45deffe ^
d01159ce ^
10bfc37a ^
d01159ce ^








99d71f03 ^





efc94656 ^
99d71f03 ^




f89b0ffd ^
a1b56680 ^
99d71f03 ^

0904ac98 ^
99d71f03 ^
a1b56680 ^
99d71f03 ^

e40e68f4 ^
99d71f03 ^
e40e68f4 ^

99d71f03 ^




e40e68f4 ^

99d71f03 ^

49883ffc ^
a1b56680 ^
49883ffc ^
99d71f03 ^
10bfc37a ^
49883ffc ^
99d71f03 ^





a1c51d93 ^
e40e68f4 ^
99d71f03 ^
a1b56680 ^

99d71f03 ^


e40e68f4 ^
99d71f03 ^




e40e68f4 ^
99d71f03 ^












e40e68f4 ^
6be7b95a ^
99d71f03 ^

e166ab2c ^
99d71f03 ^
e166ab2c ^
99d71f03 ^
7a3a07bc ^
e40e68f4 ^
7a3a07bc ^
7a3a07bc ^

e40e68f4 ^

7a3a07bc ^
a1c51d93 ^
99d71f03 ^






7b0767e3 ^


e40e68f4 ^
7b0767e3 ^



99d71f03 ^




1f44dadf ^

7b0767e3 ^
99d71f03 ^
e40e68f4 ^
072dd8dc ^
99d71f03 ^









f82838d4 ^
99d71f03 ^





e40e68f4 ^
99d71f03 ^


e166ab2c ^
d01159ce ^

74b7d2a0 ^
99d71f03 ^








10bfc37a ^

54a9a19b ^










10bfc37a ^

e40e68f4 ^
10bfc37a ^






d01159ce ^

































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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750


                                    
                                                      
                                             
                                           
                                             
                                       
                                         
                                       


                                                        

                                                                     

                            
                                      

         
                   
          

                 

                                                  


                                                

   



                                    
 

                                        


                                                         
       
       
 







                                                
                                                                              











                                                                                
                                                            


                                         
     







                          
                       


















                                                     
 
















                                                                              
 



                                         
 



                                        
                                             
       
 


                       
 














                          
                
               
            


                                          
                           
         
 

                                                 
                                                                            


                                                      
                                                                                             
                                 
 

                                                   
                                                   

           
 


                                   
 




                           
 
                                             

                                                       
 


                                        
                 











                                                
         

                                        
                  











                               

             





                




















                                                











                                              
                                                                





                                         


                          









                 


                                           



                                    

             
                
             
              
           

             

       

                                            




                                      
 




                      
              
                          













                                                            
 

               
 
                                 
 








                                                                    
                           











                                                      





                                                                      


                                                                                
                                               



                                       
                                        






                            
               

                                    
                                        





                                               
                                               





                                            
                                                                   
        
     
 


              
 
        
             
                          
                                      
                                     
 




                            
                               
 













































                                                                                
 




                                                     
 
                                                     



                                      
 



                                             








                                 
     
 
                                               






                          
                         







                
              
           
           
           
                 
 
         





                                                 
 
                      









                    
          
 
                                                                          
 








                                                





                                                                              
 




                          
                          
 

                                                
                                       
         
 

                                   
                                               
                

                           




                                

                       

                               
                                                  
 
                                                   
                                        
 
                     





                                                                            
 
                                               
                                   

   


               
                               




                                           
                                                               












                                             
                               
                                                                 

                                              
 
                       
 
                                             
              
                                       
        

                          

                     
       
 






                                                                                


                                            
                      



             




                                                                                

                                    
     
 
                                               
                                                                              









                                                           
                                        





                                                
             


                       
 

                                                                           
 








                                                     

         










                                                                        

              
                               






                                                            

































                                                          
const axios = require("axios");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const authenticator = require("otplib").authenticator;
const textToImage = require("text-to-image");
const randomWord = require("random-words");
const getAccount = require("../lib/account");
const Sequelize = require("sequelize");
const bitcoin = require("bitcoinjs-lib");
const liquid = require("liquidjs-lib");
const { fromBase58, fromPrivateKey } = require("bip32");
const { Mutex } = require("async-mutex");
const bip32 = require("bip32");

const pick = (O, ...K) => K.reduce((o, k) => ((o[k] = O[k]), o), {});
require("../lib/whitelist");

const twofa = ah((req, res, next) => {
  let {
    user,
    body: { token }
  } = req;
  if (
    user.twofa &&
    (typeof token === "undefined" ||
      !authenticator.check(token, user.otpsecret))
  ) {
    return res.status(401).send("2fa required");
  } else next();
});

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

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

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

app.get(
  "/challenge",
  ah(async (req, res) => {
    const ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress;
    challenge[ip] = randomWord();
    l.info("setting up challenge", ip, challenge[ip]);
    const data = await textToImage.generate(challenge[ip]);
    res.send(data);
  })
);

app.post(
  "/register",
  ah(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.status(500).send(e.message);
    }
  })
);

app.post(
  "/disable2fa",
  auth,
  twofa,
  ah(async (req, res) => {
    let { user } = req;
    user.twofa = false;
    await user.save();
    emit(user.username, "user", user);
    emit(user.username, "otpsecret", user.otpsecret);
    l.info("disabled 2fa", user.username);
    res.end();
  })
);

app.get(
  "/otpsecret",
  auth,
  twofa,
  ah(async (req, res) => {
    let { user } = req;
    emit(user.username, "otpsecret", user.otpsecret);
    res.end();
  })
);

app.post(
  "/2fa",
  auth,
  ah(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.status(500).send("Invalid token");
      }
    } catch (e) {
      l.error("error setting up 2fa", e);
    }

    l.info("enabled 2fa", user.username);
    res.end();
  })
);

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

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

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

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

      let token;
      if (user.username !== username && exists) {
        l.error("username taken", username, user.username, exists.username);
        return res.status(500).send("Username taken");
      } else {
        sockets[username] = sockets[user.username];
        if (user.username !== username) l.info("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.tokens = tokens;
      user.twofa = twofa;
      user.pin = pin;
      user.seed = seed;
      user.fiat = fiat;

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

      await user.save();
      emit(user.username, "user", user);
      res.send({ user, token });
    } catch (e) {
      l.error("error updating user", e.message);
    }
  })
);

app.post(
  "/keys",
  auth,
  ah(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,
  ah(async (req, res) => {
    const { hex } = req.body;
    (
      await db.Key.findOne({
        where: {
          user_id: req.user.id,
          hex
        }
      })
    ).destroy();
  })
);

app.post(
  "/updateSeeds",
  auth,
  ah(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.end();
  })
);

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

app.post(
  "/accounts",
  auth,
  ah(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);
  })
);

app.post(
  "/taboggan",
  ah(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) {
          l.error("problem calling lnurl login", e.message);
          res.status(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)))
      ) {
        l.warn(
          "invalid username or password attempt",
          req.body.username
        );
        return res.status(401).end();
      }

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

      l.info(
        "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) {
      l.error("login error", e.message);
      res.status(401).end();
    }
  })
);

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

    const { username } = req.user;

    if (username) {
      l.info("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.end();
  })
);

app.get(
  "/address",
  ah(async (req, res) => {
    let { network, type } = req.query;
    let address, confidentialAddress;

    type = {
      bech32: "p2wpkh",
      "p2sh-segwit": "p2sh",
      legacy: "p2pkh"
    }[type];
    if (!type) type = "p2wpkh";

    let hd, i, p, n;
    const mutex = new Mutex();
    const release = await mutex.acquire();
    try {
      if (network === "bitcoin") {
        if (!config.bitcoin)
          return res.status(500).send("Bitcoin not configured");
        p = bitcoin.payments;
        n = prod ? bitcoin.networks["bitcoin"] : bitcoin.networks["regtest"];

        i = parseInt(app.get("bcAddressIndex"));
        hd = fromBase58(config.bitcoin.masterkey, n).derivePath(
          `m/0'/0'/${i}'`
        );
        app.set("bcAddressIndex", i + 1);
      } else if (network === "liquid") {
        p = liquid.payments;
        n =
          liquid.networks[
            config.liquid.network === "mainnet"
              ? "liquid"
              : config.liquid.network
          ];
        type = "p2sh";

        i = parseInt(app.get("lqAddressIndex"));
        hd = fromBase58(config.liquid.masterkey, n).derivePath(`m/0'/0'/${i}'`);
        app.set("lqAddressIndex", i + 1);
      } else {
        throw new Error("Unsupported network");
      }
    } finally {
      release();
    }

    if (type !== "p2sh") {
      ({ address } = p[type]({
        pubkey: hd.publicKey,
        network: n
      }));
    } else {
      if (network === "liquid") {
        const p2wpkh = p.p2wpkh({
          pubkey: hd.publicKey,
          network: n
        });

        const blindkey = fromPrivateKey(
          Buffer.from(config.liquid.blindkey, "hex"),
          hd.chainCode,
          n
        );

        ({ address, confidentialAddress } = p[type]({
          redeem: p2wpkh,
          network: n,
          blindkey: blindkey.publicKey
        }));

        lq.importBlindingKey(
          confidentialAddress,
          blindkey.privateKey.toString("hex")
        );
      } else {
        ({ address } = p[type]({
          redeem: p.p2wpkh({
            pubkey: hd.publicKey,
            network: n
          }),
          network: n
        }));
      }
    }

    res.send({ address, confidentialAddress });
  })
);

app.post(
  "/account",
  auth,
  ah(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.end();
      });
    } catch (e) {
      l.error(e.message);
      return res.status(500).send("There was a problem updating the account");
    }
  })
);

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

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

      user.account_id = account.id;
      await user.save();
      let payments = await db.Payment.findAll({
        where: {
          user_id: user.id,
          account_id: id
        },
        order: [["id", "DESC"]],
        limit: 12,
        include: {
          model: db.Account,
          as: "account"
        }
      });
      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) {
      l.error(e.message);
      return res.status(500).send("There was a problem switching accounts");
    }
  })
);

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

app.post(
  "/subscribe",
  auth,
  ah(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.info("subscribing", req.user.username);
    await req.user.save();
    res.sendStatus(201);
  })
);

app.post(
  "/redeem",
  optionalAuth,
  ah(async function(req, res) {
    return res.status(500).send("Vouchers temporarily disabled");
    const { redeemcode } = req.body;
    if (!redeemcode) fail("no code provided");

    let { user } = req;

    const source = await db.Payment.findOne({
      where: {
        redeemcode: req.body.redeemcode
      },
      include: {
        model: db.Account,
        as: "account"
      }
    });

    l.info("redeeming", redeemcode);

    if (!source) fail("Invalid code");
    if (source.redeemed) fail("Voucher has already been redeemed");

    if (!user) {
      const ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress;
      user = await register(
        {
          username: redeemcode.substr(0, 8),
          password: ""
        },
        ip,
        false
      );

      let payload = { username: user.username };
      let token = jwt.sign(payload, config.jwt);
      res.cookie("token", token, { expires: new Date(Date.now() + 432000000) });
      return res.send({ user });
    } else {
      l.info("user", user.username);
    }

    await db.transaction(async transaction => {
      let account = await getAccount(source.account.asset, user, transaction);
      let { hash, memo, confirmed, fee, network } = source;

      source.redeemed = true;
      await source.save();

      let payment = await db.Payment.create(
        {
          amount: -source.amount,
          account_id: account.id,
          user_id: user.id,
          hash: "Voucher " + redeemcode,
          memo,
          rate: app.get("rates")[user.currency],
          currency: user.currency,
          confirmed,
          network,
          received: true,
          fee
        },
        { transaction }
      );

      await account.decrement({ balance: source.amount }, { transaction });
      await account.reload({ transaction });

      payment = payment.get({ plain: true });
      payment.account = account.get({ plain: true });
      emit(user.username, "payment", payment);
      emit(user.username, "account", account);

      res.send({ payment });
    });
  })
);

app.post(
  "/checkRedeemCode",
  auth,
  ah(async function(req, res) {
    const { redeemcode } = req.body;

    const payment = await db.Payment.findOne({ where: { redeemcode } });
    res.send(payment);
  })
);

app.post(
  "/password",
  auth,
  ah(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,
  ah(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);
  })
);