2020-07-28 09:54:15 +03:00
|
|
|
import * as Environment from "~/node_common/environment";
|
|
|
|
import * as Data from "~/node_common/data";
|
|
|
|
import * as Utilities from "~/node_common/utilities";
|
2020-10-31 02:12:20 +03:00
|
|
|
import * as ViewerManager from "~/node_common/managers/viewer";
|
2020-07-28 09:54:15 +03:00
|
|
|
|
|
|
|
import { v4 as uuid } from "uuid";
|
|
|
|
|
|
|
|
export default async (req, res) => {
|
|
|
|
const id = Utilities.getIdFromCookie(req);
|
|
|
|
if (!id) {
|
2020-10-31 02:12:20 +03:00
|
|
|
return res.status(500).send({ decorator: "SERVER_GENERATE_API_KEY_AUTH", error: true });
|
2020-07-28 09:54:15 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
const user = await Data.getUserById({
|
|
|
|
id,
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!user) {
|
2020-09-03 03:21:29 +03:00
|
|
|
return res.status(404).send({
|
2020-07-28 09:54:15 +03:00
|
|
|
decorator: "SERVER_GENERATE_API_KEY_USER_NOT_FOUND",
|
|
|
|
error: true,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (user.error) {
|
2020-09-03 03:21:29 +03:00
|
|
|
return res.status(500).send({
|
2020-07-28 09:54:15 +03:00
|
|
|
decorator: "SERVER_GENERATE_API_KEY_USER_NOT_FOUND",
|
|
|
|
error: true,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-10-31 02:12:20 +03:00
|
|
|
let keys = await Data.getAPIKeysByUserId({ userId: user.id });
|
2020-07-28 09:54:15 +03:00
|
|
|
|
|
|
|
if (keys.length > 9) {
|
2020-09-03 03:21:29 +03:00
|
|
|
return res.status(404).send({
|
2020-07-28 09:54:15 +03:00
|
|
|
decorator: "SERVER_GENERATE_API_KEY_TOO_MANY_KEYS",
|
|
|
|
error: true,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
const key = await Data.createAPIKeyForUserId({
|
|
|
|
userId: user.id,
|
|
|
|
key: `SLA${uuid()}TE`,
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!key) {
|
2020-09-03 03:21:29 +03:00
|
|
|
return res.status(404).send({
|
2020-07-28 09:54:15 +03:00
|
|
|
decorator: "SERVER_GENERATE_API_KEY_ERROR",
|
|
|
|
error: true,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (key.error) {
|
2020-09-03 03:21:29 +03:00
|
|
|
return res.status(500).send({
|
2020-07-28 09:54:15 +03:00
|
|
|
decorator: "SERVER_GENERATE_API_KEY_ERROR",
|
|
|
|
error: true,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-10-31 02:12:20 +03:00
|
|
|
keys = await Data.getAPIKeysByUserId({ userId: user.id });
|
|
|
|
ViewerManager.hydratePartialKeys(keys, user.id);
|
|
|
|
|
2020-09-03 03:21:29 +03:00
|
|
|
return res.status(200).send({ decorator: "SERVER_GENERATE_API_KEY", key });
|
2020-07-28 09:54:15 +03:00
|
|
|
};
|