slate/pages/api/users/create.js

103 lines
2.8 KiB
JavaScript
Raw Normal View History

import * as Environment from "~/node_common/environment";
import * as Data from "~/node_common/data";
import * as Utilities from "~/node_common/utilities";
import * as LibraryManager from "~/node_common/managers/library";
import * as Social from "~/node_common/social";
import * as Validations from "~/common/validations";
import BCrypt from "bcrypt";
import { PrivateKey } from "@textile/hub";
export default async (req, res) => {
const existing = await Data.getUserByUsername({
username: req.body.data.username,
});
if (existing) {
return res
.status(403)
.send({ decorator: "SERVER_EXISTING_USER_ALREADY", error: true });
}
if (!Validations.username(req.body.data.username)) {
return res
.status(500)
.send({ decorator: "SERVER_INVALID_USERNAME", error: true });
}
if (!Validations.password(req.body.data.password)) {
return res
.status(500)
.send({ decorator: "SERVER_INVALID_PASSWORD", error: true });
}
2020-08-11 08:15:39 +03:00
const rounds = Number(Environment.LOCAL_PASSWORD_ROUNDS);
const salt = await BCrypt.genSalt(rounds);
const hash = await Utilities.encryptPassword(req.body.data.password, salt);
2020-08-24 09:50:52 +03:00
// const pg = await Powergate.createNewToken();
2020-08-11 08:15:39 +03:00
// TODO(jim):
// Single Key Textile Auth.
const identity = await PrivateKey.fromRandom();
const api = identity.toString();
// TODO(jim):
// Don't do this once you refactor.
const newUsername = req.body.data.username.toLowerCase();
const {
buckets,
bucketKey,
bucketName,
2020-09-23 12:46:59 +03:00
} = await Utilities.getBucketAPIFromUserToken({
user: {
username: newUsername,
data: { tokens: { api } },
},
});
if (!buckets) {
return res
.status(500)
.send({ decorator: "SERVER_BUCKET_INIT_FAILURE", error: true });
}
const user = await Data.createUser({
2020-08-11 08:15:39 +03:00
password: hash,
salt,
username: newUsername,
data: {
2020-09-08 10:01:21 +03:00
photo:
"https://slate.textile.io/ipfs/bafkreiexygfz4e5resu66xfviokddariztq4onuai5wii5mdd7syshftca",
2020-08-22 08:45:50 +03:00
body: "A user of Slate.",
settings_deals_auto_approve: false,
allow_automatic_data_storage: true,
allow_encrypted_data_storage: true,
2020-08-24 09:50:52 +03:00
tokens: { api },
library: LibraryManager.init({ bucketName, readableName: "Data" }),
},
});
if (!user) {
return res
.status(404)
.send({ decorator: "SERVER_USER_CREATE_USER_NOT_FOUND", error: true });
}
if (user.error) {
return res
.status(500)
.send({ decorator: "SERVER_USER_CREATE_USER_NOT_FOUND", error: true });
}
const userProfileURL = `https://slate.host/${user.username}`;
const userURL = `<${userProfileURL}|${user.username}>`;
Social.sendSlackMessage(`*${userURL}* joined the movement.`);
return res.status(200).send({
decorator: "SERVER_USER_CREATE",
user: { username: user.username, id: user.id },
});
};