Add endpoints to UM to create/delete an API Key

This commit is contained in:
ricardo 2022-04-14 14:58:22 -04:00
parent 215fe9aad3
commit a3a0f57835
2 changed files with 31 additions and 2 deletions

View file

@ -570,7 +570,7 @@ class App {
this.app.post('/token', async (req: express.Request, res: express.Response) => {
const ramdonToken = randomBytes(20).toString('hex');
// @ts-ignore
await Db.collections.User!.update({ globalRole: 1 }, { apiKey: ramdonToken });
await Db.collections.User!.update({ globalRole: 1 }, { apiKey: `n8n_api_${ramdonToken}` });
return ResponseHelper.sendSuccessResponse(res, { token: ramdonToken }, true, 200);
});

View file

@ -8,7 +8,7 @@ import { LoggerProxy as Logger } from 'n8n-workflow';
import { Db, InternalHooksManager, ITelemetryUserDeletionData, ResponseHelper } from '../..';
import { N8nApp, PublicUser } from '../Interfaces';
import { UserRequest } from '../../requests';
import { AuthenticatedRequest, UserRequest } from '../../requests';
import {
getInstanceBaseUrl,
hashPassword,
@ -23,6 +23,7 @@ import * as UserManagementMailer from '../email/UserManagementMailer';
import * as config from '../../../config';
import { issueCookie } from '../auth/jwt';
import { randomBytes } from 'crypto';
export function usersNamespace(this: N8nApp): void {
/**
@ -564,4 +565,32 @@ export function usersNamespace(this: N8nApp): void {
return { success: true };
}),
);
/**
* Creates an API Key
*/
this.app.post(
`/${this.restEndpoint}/users/me/api-key`,
ResponseHelper.send(async (req: AuthenticatedRequest) => {
const ramdonToken = randomBytes(20).toString('hex');
const apiKey = `n8n_api_${ramdonToken}`;
await Db.collections.User!.update(req.user.id, {
apiKey,
});
return { apiKey, success: true };
}),
);
/**
* Deletes an API Key
*/
this.app.delete(
`/${this.restEndpoint}/users/me/api-key`,
ResponseHelper.send(async (req: AuthenticatedRequest) => {
await Db.collections.User!.update(req.user.id, {
apiKey: null,
});
return { success: true };
}),
);
}