aboutsummaryrefslogtreecommitdiffstats
path: root/lib/register.js
blob: b43a0ce73b11ee166186fea5f6f959a437f09632 (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
34pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888 } /* Comment */
.highlight .err { color: #A61717; background-color: #E3D2D2 } /* Error */
.highlight .k { color: #080; font-weight: bold } /* Keyword */
.highlight .ch { color: #888 } /* Comment.Hashbang */
.highlight .cm {
import bcrypt from "bcrypt";
import { got } from "got";
import { authenticator } from "otplib";
import { v4 } from "uuid";

import config from "$config";
import countries from "$lib/countries";
import { s, g, archive } from "$lib/db";
import { l, warn } from "$lib/logging";
import { fail, getUser } from "$lib/utils";

export default async (user, ip, requireChallenge) => {
  let { profile, password, pubkey, username } = user;
  l("registering", username);

  if (!username) fail("Username required");

  username = username.replace(/ /g, "").toLowerCase();
  let id = v4();
  user.id = id;

  let exists = await getUser(username);
  if (exists) fail(`Username ${username} taken`);

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

  user.currency = "USD";
  if (config.ipregistry) {
    try {
      let {
        location: { country: { code } },
      } = await got(
        `https://api.ipregistry.co/${ip}?key=${config.ipregistry}&fields=location.country.code`,
      ).json();

      user.currency = countries[code];
    } catch (e) {
      warn("unable to detect country from IP", username);
    }
  }

  user.currencies = [...new Set([user.currency, "CAD", "USD"])];
  user.fiat = false;
  user.otpsecret = authenticator.generateSecret();
  user.migrated = true;
  user.locktime = 300;

  await s(`user:${id}`, user);
  await s(`user:${username}`, id);
  await s(`user:${pubkey}`, id);
  await s(`balance:${id}`, 0);

  l("new user", username);
  return user;
};