From 62b121285cd86ef9e59e7bb9888955e3e46201f1 Mon Sep 17 00:00:00 2001 From: Christopher Kolstad Date: Wed, 20 Oct 2021 13:16:07 +0200 Subject: [PATCH] Create a apiuser for demo auth. (#1045) - If api token middleware is disabled, still allow calls to /api/client with a populated fake api user with client access. --- src/lib/app.ts | 15 +++++++++++++-- src/lib/middleware/demo-authentication.ts | 20 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/lib/app.ts b/src/lib/app.ts index 09e93d80b7..6afe923ea7 100644 --- a/src/lib/app.ts +++ b/src/lib/app.ts @@ -94,7 +94,12 @@ export default function getApp( } case IAuthType.DEMO: { app.use(baseUriPath, apiTokenMiddleware(config, services)); - demoAuthentication(app, config.server.baseUriPath, services); + demoAuthentication( + app, + config.server.baseUriPath, + services, + config, + ); break; } case IAuthType.CUSTOM: { @@ -107,7 +112,13 @@ export default function getApp( break; } default: { - demoAuthentication(app, config.server.baseUriPath, services); + app.use(baseUriPath, apiTokenMiddleware(config, services)); + demoAuthentication( + app, + config.server.baseUriPath, + services, + config, + ); break; } } diff --git a/src/lib/middleware/demo-authentication.ts b/src/lib/middleware/demo-authentication.ts index 2b1a8c964f..7f98efd06c 100644 --- a/src/lib/middleware/demo-authentication.ts +++ b/src/lib/middleware/demo-authentication.ts @@ -1,11 +1,15 @@ import { Application } from 'express'; import AuthenticationRequired from '../types/authentication-required'; import { IUnleashServices } from '../types/services'; +import { IUnleashConfig } from '../types/option'; +import ApiUser from '../types/api-user'; +import { ApiTokenType } from '../types/models/api-token'; function demoAuthentication( app: Application, basePath: string = '', { userService }: Pick, + { authentication }: Pick, ): void { app.post(`${basePath}/api/admin/login`, async (req, res) => { const { email } = req.body; @@ -39,6 +43,21 @@ function demoAuthentication( next(); }); + app.use(`${basePath}/api/client`, (req, res, next) => { + // @ts-ignore + if (!authentication.enableApiToken && !req.user) { + // @ts-ignore + req.user = new ApiUser({ + username: 'unauthed-default-client', + permissions: [], + environment: 'default', + type: ApiTokenType.CLIENT, + project: '*', + }); + } + next(); + }); + app.use(`${basePath}/api`, (req, res, next) => { // @ts-ignore if (req.user) { @@ -57,4 +76,5 @@ function demoAuthentication( .end(); }); } + export default demoAuthentication;