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) {
|
2021-03-07 23:53:54 +03:00
|
|
|
return res.status(401).send({ decorator: "SERVER_NOT_AUTHENTICATED", 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({
|
2021-03-07 23:53:54 +03:00
|
|
|
decorator: "SERVER_USER_NOT_FOUND",
|
2020-07-28 09:54:15 +03:00
|
|
|
error: true,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
if (user.error) {
|
2020-09-03 03:21:29 +03:00
|
|
|
return res.status(500).send({
|
2021-03-07 23:53:54 +03:00
|
|
|
decorator: "SERVER_USER_NOT_FOUND",
|
2020-07-28 09:54:15 +03:00
|
|
|
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,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-03-07 23:53:54 +03:00
|
|
|
const key = await Data.createAPIKey({
|
2020-07-28 09:54:15 +03:00
|
|
|
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,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-03-07 23:53:54 +03:00
|
|
|
// keys = await Data.getAPIKeysByUserId({ userId: user.id });
|
|
|
|
// ViewerManager.hydratePartialKeys(keys, user.id);
|
|
|
|
|
|
|
|
ViewerManager.hydratePartial(id, { keys: true });
|
2020-10-31 02:12:20 +03:00
|
|
|
|
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
|
|
|
};
|