(name: string)
| 40 | })); |
| 41 | |
| 42 | export const createApiKey = async (name: string): Promise<{ key: string } | ServiceError> => sew(() => |
| 43 | withAuth(async ({ org, user, role, prisma }) => { |
| 44 | if ((env.DISABLE_API_KEY_CREATION_FOR_NON_OWNER_USERS === 'true' || env.DISABLE_API_KEY_USAGE_FOR_NON_OWNER_USERS === 'true') && role !== OrgRole.OWNER) { |
| 45 | logger.error(`API key creation is disabled for non-admin users. User ${user.id} is not an owner.`); |
| 46 | return { |
| 47 | statusCode: StatusCodes.FORBIDDEN, |
| 48 | errorCode: ErrorCode.INSUFFICIENT_PERMISSIONS, |
| 49 | message: "API key creation is disabled for non-admin users.", |
| 50 | } satisfies ServiceError; |
| 51 | } |
| 52 | |
| 53 | const existingApiKey = await prisma.apiKey.findFirst({ |
| 54 | where: { |
| 55 | createdById: user.id, |
| 56 | name, |
| 57 | }, |
| 58 | }); |
| 59 | |
| 60 | if (existingApiKey) { |
| 61 | await createAudit({ |
| 62 | action: "api_key.creation_failed", |
| 63 | actor: { |
| 64 | id: user.id, |
| 65 | type: "user" |
| 66 | }, |
| 67 | target: { |
| 68 | id: org.id.toString(), |
| 69 | type: "org" |
| 70 | }, |
| 71 | orgId: org.id, |
| 72 | metadata: { |
| 73 | message: `API key ${name} already exists`, |
| 74 | api_key: name |
| 75 | } |
| 76 | }); |
| 77 | return { |
| 78 | statusCode: StatusCodes.BAD_REQUEST, |
| 79 | errorCode: ErrorCode.API_KEY_ALREADY_EXISTS, |
| 80 | message: `API key ${name} already exists`, |
| 81 | } satisfies ServiceError; |
| 82 | } |
| 83 | |
| 84 | const { key, hash } = generateApiKey(); |
| 85 | const apiKey = await prisma.apiKey.create({ |
| 86 | data: { |
| 87 | name, |
| 88 | hash, |
| 89 | orgId: org.id, |
| 90 | createdById: user.id, |
| 91 | } |
| 92 | }); |
| 93 | |
| 94 | await createAudit({ |
| 95 | action: "api_key.created", |
| 96 | actor: { |
| 97 | id: user.id, |
| 98 | type: "user" |
| 99 | }, |
no test coverage detected