aboutsummaryrefslogtreecommitdiffstats
path: root/routes/users.js
blob: 49aeebd7725756434cdb7a892dc289973455751e (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
import { g, s } from "$lib/db";
import config from "$config";
import store from "$lib/store";
import { nada, pick, uniq, wait } from "$lib/utils";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import { authenticator } from "otplib";
import whitelist from "$lib/whitelist";
import { l, err, warn } from "$lib/logging";
import { emit } from "$lib/sockets";
import register from "$lib/register";
import { requirePin } from "$lib/utils";
import got from "got";
import upload from "$lib/upload";

export default {
  upload,

  async me({ user }, res) {
    try {
      user.balance = await g(`balance:${user.id}`);
      res.send(pick(user, whitelist));
    } catch (e) {
      console.log("problem fetching user", e);
      res.code(500).send(e.message);
    }
  },

  async get({ params: { key } }, res) {
    try {
      if (key.startsWith("npub")) {
        key = Buffer.from(fromWords(decode(key).words)).toString("hex");
      }

      let user = await g(`user:${key}`);
      if (typeof user === "string") {
        user = await g(`user:${user}`);
      }

      if (!user && key.length === 64) {
        user = {
          username: key.substr(0, 6),
          pubkey: key,
          anon: true
        };
      }

      if (!user) return res.code(500).send("User not found");

      let whitelist = [
        "username",
        "banner",
        "profile",
        "address",
        "currency",
        "pubkey",
        "display",
        "prompt",
        "id"
      ];

      res.send(pick(user, whitelist));
    } catch (e) {
      console.log(e);
      res.code(500).send(e.message);
    }
  },

  async create(req, res) {
    try {
      const ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress;
      let { cipher, pubkey, password, username, salt } = req.body.user;

      let user = {
        cipher,
        pubkey,
        password,
        username,
        salt
      };

      user = await register(user, ip, false);
      l("registered new user", username);
      res.send(pick(user, whitelist));
    } catch (e) {
      res.code(500).send(e.message);
    }
  },

  async disable2fa({ user, body: { token } }, res) {
    let { id, twofa, username, otpsecret } = user;
    if (twofa && !authenticator.check(token, otpsecret)) {
      return res.code(401).send("2fa required");
    }

    user.twofa = false;
    await s(`user:${id}`, user);
    emit(username, "user", user);
    emit(username, "otpsecret", user.otpsecret);
    l("disabled 2fa", username);
    res.send({});
  },

  async enable2fa({ user, body: { token } }, res) {
    let { id, otpsecret, username } = user;
    const isValid = authenticator.check(token, otpsecret);
    if (isValid) {
      user.twofa = true;
      await s(`user:${id}`, user);
      emit(username, "user", user);
    } else {
      return res.code(500).send("Invalid token");
    }

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

  async update({ user, body }, res) {
    l("updating user", user.username);

    let { confirm, password, pin, newpin, username } = body;

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

    let exists;
    if (username) exists = await g(`user:${username}`);

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

    let attributes = [
      "address",
      "cipher",
      "currencies",
      "currency",
      "display",
      "email",
      "fiat",
      "locktime",
      "prompt",
      "pubkey",
      "salt",
      "seed",
      "tokens",
      "twofa"
    ];

    for (let a of attributes) {
      if (body[a]) user[a] = body[a];
    }

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

    user.haspin = !!user.pin;
    await s(`user:${user.id}`, user);

    emit(user.username, "user", user);
    res.send({ user, token });
  },

  async login(req, res) {
    try {
      const { params, sig, key, password, username, token: twofa } = req.body;
      l("logging in", username);

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

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

        return;
      }

      let id = await g(`user:${username}`);
      let user = await g(`user:${id}`);

      if (
        !user ||
        (user.password && !(await bcrypt.compare(password, user.password)))
      ) {
        warn("invalid username or password attempt", 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",
        username,
        req.headers["x-forwarded-for"] || req.socket.remoteAddress
      );

      let payload = { username, id: user.id };
      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) {
      console.log(e);
      err("login error", e.message, req.socket.remoteAddress);
      res.code(401).send({});
    }
  },

  async logout(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({});
  },

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

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

  async otpsecret(req, res) {
    try {
      await requirePin(req);
      let { otpsecret, username } = req.user;
      res.send({ secret: otpsecret, username });
    } catch (e) {
      res.code(500).send(e.message);
    }
  },

  async contacts({ user: { uuid } }, res) {
    let payments = (await g(`${uuid}:payments`)) || [];
    res.send(
      Promise.all(
        [...new Set(payments.map(p => p.with_id))].map(id => g(`user:${id}`))
      )
    );
  }
};