aboutsummaryrefslogtreecommitdiffstats
path: root/db/normalized/user_subscriptions.js
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2020-07-07 19:02:37 -0700
committerAdam Soltys <[email protected]>2020-07-07 19:03:10 -0700
commit3dd0d83f3900818344e534681cf13155c210bd22 (patch)
tree5d6c329bd88eaf70881d19b7359c302c92585f13 /db/normalized/user_subscriptions.js
parent096ea59db20e729098066435ab5a8c4cfa01457d (diff)
downloadcoinos-server-3dd0d83f3900818344e534681cf13155c210bd22.tar.gz
coinos-server-3dd0d83f3900818344e534681cf13155c210bd22.zip
handle login decode
Diffstat (limited to 'db/normalized/user_subscriptions.js')
0 files changed, 0 insertions, 0 deletions
;id=6273b8dbd54534f17019caf78ab9db1286f5b66b'>6273b8db ^
c0888fab ^
49065ec0 ^

59b39a34 ^

49065ec0 ^


49065ec0 ^
c0888fab ^
6273b8db ^
fae6e8b5 ^

c0888fab ^
c0888fab ^
fae6e8b5 ^



c0888fab ^
fae6e8b5 ^
c0888fab ^






6273b8db ^
c0888fab ^
fae6e8b5 ^
c0888fab ^



c2f8fde4 ^

6273b8db ^



c2f8fde4 ^



05fa4435 ^

52baac02 ^
05fa4435 ^




c0888fab ^
6273b8db ^
05fa4435 ^
7a3a07bc ^
c0888fab ^




05fa4435 ^



b45deffe ^


25e8391a ^
b45deffe ^


25e8391a ^
b45deffe ^


25e8391a ^
b45deffe ^



25e8391a ^
a1c51d93 ^

74b7d2a0 ^



bf838e00 ^
05fa4435 ^
7a3a07bc ^
05fa4435 ^


c0888fab ^





6273b8db ^
c0888fab ^

a0e36844 ^

49065ec0 ^



c0888fab ^


a0e36844 ^
c0888fab ^

c0888fab ^
fae6e8b5 ^





a1c51d93 ^

6273b8db ^
fae6e8b5 ^


aed612c5 ^
b45deffe ^

c891dc49 ^




c0888fab ^
fae6e8b5 ^

c0888fab ^
e6c41a3a ^
c0888fab ^









































c4605df2 ^
c0888fab ^




74b7d2a0 ^

c0888fab ^


6273b8db ^
c0888fab ^





816bfa54 ^
c0888fab ^
b45deffe ^
6273b8db ^
b45deffe ^
6273b8db ^
b45deffe ^
c0888fab ^

6273b8db ^
c0888fab ^


8d15c4e7 ^
c0888fab ^
ed261b9f ^
c0888fab ^
74b7d2a0 ^
c0888fab ^







c8c2b9df ^
c0888fab ^







7a3a07bc ^




c0888fab ^

c8c2b9df ^
c0888fab ^





a1c51d93 ^


7a3a07bc ^
a1c51d93 ^
c0888fab ^


49065ec0 ^




c0888fab ^
49065ec0 ^
c0888fab ^







a1b56680 ^
c0888fab ^



74b7d2a0 ^












efc94656 ^
b45deffe ^

efc94656 ^

25e8391a ^



efc94656 ^






a1b56680 ^





6273b8db ^
a1b56680 ^






a1c51d93 ^
7a3a07bc ^

a1c51d93 ^
a1b56680 ^

a1c51d93 ^
a1b56680 ^

e166ab2c ^



c03559bd ^

6273b8db ^
c03559bd ^
e166ab2c ^
c03559bd ^

7a3a07bc ^












a1c51d93 ^
c03559bd ^
7a3a07bc ^
a1c51d93 ^
c03559bd ^

a1c51d93 ^
e166ab2c ^

c0888fab ^
74b7d2a0 ^


















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


                                    
                                                      
                                             
                                           





                                                                     

                     


                                   
                   
          

                 

                                                  


                                                
  
 
                            

                                   
                   
                  



                          
                                             
                             






                                            
                     
       
 



                      

                                                 



                                      



                                              

                                                                            
                               




                                                         
                                           
                                         
                          
 




                                                                           



                                                        


                                                                
 


                                                        
 


                                                               
 



                                                                              
 

                                                                          



                                                               
                                                                 
                                                    
   


                       





                   
             

    

                                                                      



                                                                 


                                                               
                                                                       

                                                  
                                    





                                         

                    
                


                            
 

                                                                        




                                                                         
 

                               
                                     
                                        









































                                                                            
           




                 

                  


                                        
                         





                                                    
                                                 
                               
 
                                                           
 
                                                              
 

                                                 
                                                 


         
                               
                             
                                 
 
                         







                                                     
                                      







                                        




                                                                  

       
                                                





                                                                  


                                               
                         
        


                                   




                                                    
                                                  
     







                                                                              
                                      



                          












                                                                                    
                                                

                                                                             

                                 



                                                              






                                                                       





                                                             
                               






                                  
 

                                            
               

                                                                            
   

   



                                                     

                                              
                                        
       
 

                                 












                                           
 
                                      
              
               

                                                                          
   

   
                                        


















                                                                                
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 pick = (O, ...K) => K.reduce((o, k) => ((o[k] = O[k]), o), {});
let faucet = 1000;
const DAY = 24 * 60 * 60 * 1000;
require("../lib/whitelist");

const challenge = {};

const twofa = (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();
};

const gift = async user => {
  const account = user.accounts[0];

  if (faucet > 0) {
    faucet -= 100;

    account.balance = 100;
    await account.save();

    const payment = await db.Payment.create({
      account_id: account.id,
      user_id: user.id,
      hash: "Welcome Gift",
      amount: 100,
      currency: user.currency,
      rate: app.get("rates")[user.currency],
      received: true,
      confirmed: 1,
      network: "GIFT"
    });

    await user.save();
  }
};

app.get("/users/:username", async (req, res) => {
  const { username } = req.params;
  const user = await db.User.findOne({
    attributes: ["username"],
    where: { username }
  });
  if (user) res.send(user);
  else res.status(500).send("User not found");
});

app.get("/challenge", 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", async (req, res) => {
  let err = m => res.status(500).send(m);
  let { user } = req.body;

  if (!user.username) return err("Username required");

  let exists = await db.User.count({ where: { username: user.username } });
  if (exists) return err("Username taken");

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

  if (config.bitcoin) {
    if (config.bitcoin.walletpass)
      await bc.walletPassphrase(config.bitcoin.walletpass, 300);

    user.address = await bc.getNewAddress("", "bech32");
    addresses[user.address] = user.username;
  }

  if (config.liquid) {
    if (config.liquid.walletpass)
      await lq.walletPassphrase(config.liquid.walletpass, 300);

    user.confidential = await lq.getNewAddress();
    user.liquid = (await lq.getAddressInfo(user.confidential)).unconfidential;
    addresses[user.liquid] = user.username;
  }

  let ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress;

  if (
    !challenge[ip] ||
    user.response.toLowerCase() !== challenge[ip].toLowerCase()
  ) {
    l.info("failed challenge", ip, user.response, challenge[ip]);
    return res.status(500).send("Failed challenge");
  }

  delete challenge[ip];

  let countries = {
    CA: "CAD",
    US: "USD",
    JP: "JPY",
    CN: "CNY",
    AU: "AUD",
    GB: "GBP"
  };

  if (!config.ipstack || ip.startsWith("127") || ip.startsWith("192"))
    user.currency = "CAD";
  else {
    let info = await axios.get(
      `http://api.ipstack.com/${ip}?access_key=${config.ipstack}`
    );
    user.currency = countries[info.data.country_code] || "USD";
  }

  user.currencies = [...new Set([user.currency, "CAD", "USD", "JPY"])];
  user.otpsecret = authenticator.generateSecret();

  user = await db.User.create(user);

  let account = await db.Account.create({
    user_id: user.id,
    asset: config.liquid.btcasset,
    balance: 0,
    pending: 0,
    name: "Bitcoin",
    ticker: "BTC",
    precision: 8
  });

  user.accounts = [account];

  const d = ip.split(".");
  const numericIp = ((+d[0] * 256 + +d[1]) * 256 + +d[2]) * 256 + +d[3];
  if (Number.isInteger(numericIp)) {
    user.ip = numericIp;
    const ipExists = await db.User.findOne({ where: { ip: numericIp } });
    if (!ipExists) await gift(user);
  }

  user.account_id = account.id;
  await user.save();
  res.send(pick(user, ...whitelist));
  l.info("new user", user.username, ip);
});

app.post("/disable2fa", auth, twofa, 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, async (req, res) => {
  let { user } = req;
  emit(user.username, "otpsecret", user.otpsecret);
  res.end();
});

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

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

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

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

    let token;
    if (user.username !== username && exists) {
      return res.status(500).send("Username taken");
    } else {
      sockets[username] = sockets[user.username];
      user.username = username;

      if (user.address) addresses[user.address] = username;

      if (user.liquid) addresses[user.liquid] = user.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;

    if (password && password === passconfirm) {
      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);
  }
});

app.post("/login", async (req, res) => {
  let twofa = req.body.token;
  l.info(
    "login attempt",
    req.body.username,
    req.headers["x-forwarded-for"] || req.connection.remoteAddress
  );

  try {
    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,
        req.body.password
      );
      return res.status(401).end();
    }

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

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

    user = pick(user, ...whitelist);
    res.send({ user, token });
  } catch (e) {
    l.error("login error", e.message);
    res.status(401).end();
  }
});


app.post("/logout", auth, async (req, res) => {
  let { subscription } = req.body;
  l.info("logging out", req.user.username);
  if (!subscription) return res.end();
  let i = req.user.subscriptions.findIndex(s => JSON.stringify(s) === subscription);
  if (i > -1) {
    req.user.subscriptions.splice(i, 1);
  } 
  await req.user.save();
  res.end();
});

app.post("/address", auth, async (req, res) => {
  if (!config.bitcoin) return res.status(500).send("Bitcoin not configured");

  let { user } = req;
  delete addresses[user.address];

  if (config.bitcoin.walletpass)
    await bc.walletPassphrase(config.bitcoin.walletpass, 300);

  user.address = await bc.getNewAddress("", req.body.type || "bech32");
  await user.save();
  addresses[user.address] = user.username;
  emit(user.username, "user", user);
  res.send(user.address);
});

app.post("/account", auth, async (req, res) => {
  let { user } = req;
  let { asset, precision, name, ticker, user_id } = req.body;

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

    account.name = name;
    account.ticker = ticker;
    account.precision = precision;

    await account.save();

    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, async (req, res) => {
  let { user } = req;
  let { asset } = req.body;

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

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

    emit(user.username, "user", user);
    res.end();
  } catch (e) {
    l.error(e.message);
    return res.status(500).send("There was a problem switching accounts");
  }
});

setInterval(() => (faucet = 2000), DAY);

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