slate/pages/api/users/delete.js

75 lines
2.2 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";
2020-09-23 12:46:59 +03:00
import * as Social from "~/node_common/social";
2020-11-10 00:20:38 +03:00
import * as SearchManager from "~/node_common/managers/search";
import { Buckets, PrivateKey } from "@textile/hub";
import JWT from "jsonwebtoken";
const TEXTILE_KEY_INFO = {
key: Environment.TEXTILE_HUB_KEY,
secret: Environment.TEXTILE_HUB_SECRET,
};
export default async (req, res) => {
const id = Utilities.getIdFromCookie(req);
if (!id) {
2020-10-29 21:39:40 +03:00
return res.status(500).send({ decorator: "SERVER_USER_DELETE", error: true });
}
const user = await Data.getUserById({
id,
});
if (!user) {
2020-10-29 21:39:40 +03:00
return res.status(404).send({ decorator: "SERVER_USER_DELETE_USER_NOT_FOUND", error: true });
}
if (user.error) {
2020-10-29 21:39:40 +03:00
return res.status(500).send({ decorator: "SERVER_USER_DELETE_USER_NOT_FOUND", error: true });
}
2020-11-10 00:20:38 +03:00
let slates = await Data.getSlatesByUserId({ userId: user.id, publicOnly: true });
for (let slate of slates) {
SearchManager.updateSlate(slate, "REMOVE");
}
await Data.deleteAPIKeysForUserId({ userId: user.id });
await Data.deleteSlatesForUserId({ userId: user.id });
2020-11-10 00:20:38 +03:00
const i = await PrivateKey.fromString(user.data.tokens.api);
const b = await Buckets.withKeyInfo(TEXTILE_KEY_INFO);
2020-09-23 12:46:59 +03:00
const defaultData = await Utilities.getBucketAPIFromUserToken({ user });
2020-09-23 14:17:56 +03:00
// NOTE(jim): Just assume they all delete even if exception is thrown, it seems like they do.
try {
2020-09-23 12:46:59 +03:00
const roots = await defaultData.buckets.list();
2020-09-23 14:17:56 +03:00
2020-09-23 12:46:59 +03:00
for (let i = 0; i < roots.length; i++) {
await defaultData.buckets.remove(roots[i].key);
}
} catch (e) {
2020-09-23 12:46:59 +03:00
Social.sendTextileSlackMessage({
file: "/pages/api/users/delete.js",
user,
message: e.message,
code: e.code,
functionName: `b.remove`,
});
}
2020-11-10 00:20:38 +03:00
SearchManager.updateUser(user, "REMOVE");
const deleted = await Data.deleteUserByUsername({
username: user.username,
});
2020-11-10 00:20:38 +03:00
if (!deleted || deleted.error) {
2020-10-29 21:39:40 +03:00
return res.status(500).send({ decorator: "SERVER_USER_DELETE", error: true });
}
return res.status(200).send({ decorator: "SERVER_USER_DELETE", deleted });
};