slate/pages/api/users/create.js

73 lines
2.2 KiB
JavaScript
Raw Normal View History

import * as Environment from "~/node_common/environment";
import * as MW from "~/node_common/middleware";
import * as Data from "~/node_common/data";
import * as Utilities from "~/node_common/utilities";
import * as LibraryManager from "~/node_common/managers/library";
import * as Validations from "~/common/validations";
import BCrypt from "bcrypt";
import { PrivateKey } from "@textile/hub";
const initCORS = MW.init(MW.CORS);
export default async (req, res) => {
initCORS(req, res);
const existing = await Data.getUserByUsername({
username: req.body.data.username,
});
if (existing) {
2020-08-24 09:50:52 +03:00
return res.status(403).json({ decorator: "SERVER_EXISTING_USER_ALREADY", error: true });
}
if (!Validations.username(req.body.data.username)) {
2020-08-24 09:50:52 +03:00
return res.status(500).send({ decorator: "SERVER_INVALID_USERNAME", error: true });
}
if (!Validations.password(req.body.data.password)) {
2020-08-24 09:50:52 +03:00
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.
2020-08-24 09:50:52 +03:00
const { buckets, bucketKey, bucketName } = await Utilities.getBucketAPIFromUserToken(api);
const user = await Data.createUser({
2020-08-11 08:15:39 +03:00
password: hash,
salt,
2020-08-06 23:01:05 +03:00
username: req.body.data.username.toLowerCase(),
data: {
2020-07-22 14:02:32 +03:00
photo: "https://slate.host/static/a1.jpg",
2020-08-22 08:45:50 +03:00
body: "A user of Slate.",
settings_deals_auto_approve: false,
2020-08-24 09:50:52 +03:00
tokens: { api },
library: LibraryManager.init({ bucketName, readableName: "Data" }),
},
});
if (!user) {
2020-08-24 09:50:52 +03:00
return res.status(404).json({ decorator: "SERVER_USER_CREATE_USER_NOT_FOUND", error: true });
}
if (user.error) {
2020-08-24 09:50:52 +03:00
return res.status(500).json({ decorator: "SERVER_USER_CREATE_USER_NOT_FOUND", error: true });
}
return res.status(200).json({
decorator: "SERVER_USER_CREATE",
user: { username: user.username, id: user.id },
});
};