aboutsummaryrefslogtreecommitdiffstats
path: root/routes/users.coffee
blob: 718a649a5e0327c6e2dc75e469d154aecc221da6 (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
db = require("../redis")
bcrypt = require('bcrypt')

module.exports = (sessions) ->
  exists: (req, res) ->
      
    db.hgetall("user:"+req.params.user, (err, obj) ->
      if obj? then res.write('true') else res.write('false')
      res.end()
    )
  
  json: (req, res) ->
    db.hgetall("user:"+req.params.user, (err, obj) ->
      delete obj['password']
      res.write(JSON.stringify(obj))
      res.end()
    )

  show: (req, res) ->
    res.render('calculator/show', 
      user: req.params.user, 
      js: (-> global.js), 
      css: (-> global.css) 
    )

  new: (req, res) ->
    db.smembers('mts', (err, keys) ->
       mts = []
       for mt in keys
          db.hgetall(mt, (err, it) ->
            mts.push(it)
            if keys.length==mts.length
               res.render('users/new', 
                  js: (-> global.js), 
                  css: (-> global.css),
                  mtypes: mts
               )     
          )
    )
  create: (req, res) ->
    userkey = "user:"+req.body.username
    db.hgetall(userkey, (err, obj) ->
      if obj
        res.redirect(req.body.username)
      else
        bcrypt.hash(req.body.password, 12, (err, hash) ->
           db.sadd("users",userkey)
           db.hmset(userkey,
             username: req.body.username,
             password: hash,
             email: req.body.email,
             firstname: req.body.firstname,
             lastname: req.body.lastname,
             company: req.body.company,
             email: req.body.email,
             phone: req.body.phone,
             companytype: req.body.companytype,
             address1: req.body.address1,
             address2: req.body.address2,
             city: req.body.city,
             postcode: req.body.postcode,
             state: req.body.state,
             country: req.body.country,
             web: req.body.web
            , ->
              req.headers['referer'] = "/#{req.body.username}/edit"
              sessions.create(req, res)
           )
        )
    )

  edit: (req, res) ->
    res.render('calculator/setup', 
      user: req.params.user, 
      js: (-> global.js), 
      css: (-> global.css) 
    )

  update: (req, res) ->
    return unless req.params.user is req.user.username or 
    req.user.username is 'admin'
    db.hmset("user:"+req.params.user, req.body, ->
      res.redirect("/#{req.params.user}")
    )
for (const username in store.sockets) { for (const id in store.sockets[username]) { const ws = store.sockets[username][id]; ws.send(JSON.stringify({ type, data })); sent.push(ws.id); } } Object.values(all).map(ws => { if (!sent.includes(ws.id)) ws.send(JSON.stringify({ type, data })); }); }; function subtractSeconds(numOfSeconds, date = new Date()) { date.setSeconds(date.getSeconds() - numOfSeconds); return date; } app.register(fastifyWs); app.register(async function(app) { app.get("/ws", { websocket: true }, ({ socket: ws }, req) => { const id = v4(); ws.id = id; ws.beats = 0; ws.send(JSON.stringify({ type: "connected", data: id })); all[id] = ws; ws.on("message", async message => { let type, data; try { ({ type, data } = JSON.parse(message)); } catch (e) { err("coudn't parse socket message"); } switch (type) { case "heartbeat": ws.beats = 0; if (ws.user) emit(ws.user.username, "id", ws.id); break; case "login": let token = data; if (lastSeen[token] > subtractSeconds(5)) return; lastSeen[token] = new Date(); try { if (!token || token === "null" || !jwt.decode(token)) return ws.close(code, `bad token ${token}`); const username = jwt.decode(token).username; if (!username) throw new Error("Invalid JWT token"); if (!store.sockets[username]) store.sockets[username] = {}; const existing = Object.keys(store.sockets[username]); if (existing.length > 4) { const p = existing.find(sid => sid !== id); store.sockets[username][p].send( JSON.stringify({ type: "logout" }) ); setTimeout(() => { if (store.sockets[username][p]) store.sockets[username][p].close(code, "too many sockets"); }, 5000); } store.sockets[username][id] = ws; names[id] = username; let user = await getUser(username); if (user.locked) throw new Error("Account is locked"); let payments = await 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" } ] }); let accounts = await user.getAccounts(); let keys = await user.getKeys(); user = user.get({ plain: true }); user.accounts = accounts; user.keys = keys; user.payments = payments; ws.user = user; ws.send(JSON.stringify({ type: "login", data: user })); ws.send( JSON.stringify({ type: "version", data: config.clientVersion }) ); } catch (e) { err("caught socket error", e.message); if (e.message.includes("locked")) { ws.send(JSON.stringify({ type: "locked" })); ws.send(JSON.stringify({ type: "logout" })); } if (e.message.includes("not found")) ws.send(JSON.stringify({ type: "logout" })); setTimeout( () => ws && ws.close(code, `closing due to error ${e.message}`), 1000 ); } break; case "token": if (!ws.user) return; ws.token = data; break; case "lnurl": store.sessions[data] = ws; break; case "updateMemo": const payment = await db.Payment.findOne({ where: { user_id: ws.user.id, id: data.id }, include: { model: db.Account, as: "account" } }); if (payment) { payment.memo = data.memo; await payment.save(); emit(ws.user.username, "payment", payment); } break; case "subscribe": subscriptions.push({ invoice: data, ws }); break; default: warn("received socket message of unknown type", type, data); } }); ws.on("close", function(code, reason) { // if (reason) console.log("closing socket", reason.toString(), id); try { const username = names[id]; if (store.sockets[username] && store.sockets[username][id]) { delete store.sockets[username][id]; } if (all[id]) delete all[id]; } catch (e) { err("problem closing socket", e.message); } }); }); }); const names = {}; setInterval(() => { for (const username in store.sockets) { for (const id in store.sockets[username]) { let ws = store.sockets[username][id]; ws.beats++; if (ws.beats > 10) ws.close(code, `${username} ${id} lost heartbeat`); } } }, 2000);