@@ -1,23 +1,24 @@
|
||||
import Router from "koa-router";
|
||||
import auth from "@server/middlewares/authentication";
|
||||
import { ApiKey, Event } from "@server/models";
|
||||
import policy from "@server/policies";
|
||||
import { authorize } from "@server/policies";
|
||||
import { presentApiKey } from "@server/presenters";
|
||||
import { assertUuid, assertPresent } from "@server/validation";
|
||||
import pagination from "./middlewares/pagination";
|
||||
|
||||
const { authorize } = policy;
|
||||
const router = new Router();
|
||||
|
||||
router.post("apiKeys.create", auth(), async (ctx) => {
|
||||
const { name } = ctx.body;
|
||||
assertPresent(name, "name is required");
|
||||
const user = ctx.state.user;
|
||||
const { user } = ctx.state;
|
||||
|
||||
authorize(user, "createApiKey", user.team);
|
||||
const key = await ApiKey.create({
|
||||
name,
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
await Event.create({
|
||||
name: "api_keys.create",
|
||||
modelId: key.id,
|
||||
@@ -28,13 +29,14 @@ router.post("apiKeys.create", auth(), async (ctx) => {
|
||||
},
|
||||
ip: ctx.request.ip,
|
||||
});
|
||||
|
||||
ctx.body = {
|
||||
data: presentApiKey(key),
|
||||
};
|
||||
});
|
||||
|
||||
router.post("apiKeys.list", auth(), pagination(), async (ctx) => {
|
||||
const user = ctx.state.user;
|
||||
const { user } = ctx.state;
|
||||
const keys = await ApiKey.findAll({
|
||||
where: {
|
||||
userId: user.id,
|
||||
@@ -43,6 +45,7 @@ router.post("apiKeys.list", auth(), pagination(), async (ctx) => {
|
||||
offset: ctx.state.pagination.offset,
|
||||
limit: ctx.state.pagination.limit,
|
||||
});
|
||||
|
||||
ctx.body = {
|
||||
pagination: ctx.state.pagination,
|
||||
data: keys.map(presentApiKey),
|
||||
@@ -52,9 +55,10 @@ router.post("apiKeys.list", auth(), pagination(), async (ctx) => {
|
||||
router.post("apiKeys.delete", auth(), async (ctx) => {
|
||||
const { id } = ctx.body;
|
||||
assertUuid(id, "id is required");
|
||||
const user = ctx.state.user;
|
||||
const { user } = ctx.state;
|
||||
const key = await ApiKey.findByPk(id);
|
||||
authorize(user, "delete", key);
|
||||
|
||||
await key.destroy();
|
||||
await Event.create({
|
||||
name: "api_keys.delete",
|
||||
@@ -66,6 +70,7 @@ router.post("apiKeys.delete", auth(), async (ctx) => {
|
||||
},
|
||||
ip: ctx.request.ip,
|
||||
});
|
||||
|
||||
ctx.body = {
|
||||
success: true,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user