feat: remove cookie on sign out

Signed-off-by: Camila Belo <camilaibs@gmail.com>
This commit is contained in:
Camila Belo
2024-03-20 13:43:32 +01:00
committed by Patrik Oldsberg
parent 641a068514
commit a1950ad5e6
15 changed files with 169 additions and 6 deletions
@@ -0,0 +1,48 @@
/*
* Copyright 2024 The Backstage Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import express from 'express';
import request from 'supertest';
import { mockCredentials, mockServices } from '@backstage/backend-test-utils';
import { createCookieAuthRefreshMiddleware } from './createCookieAuthRefreshMiddleware';
describe('createCookieAuthRefreshMiddleware', () => {
let app: express.Express;
beforeAll(async () => {
const httpAuth = mockServices.httpAuth();
const router = createCookieAuthRefreshMiddleware({ httpAuth });
app = express().use(router);
});
beforeEach(() => {
jest.resetAllMocks();
});
it('should issue the user cookie', async () => {
const response = await request(app).get('/.backstage/v1-cookie');
expect(response.status).toBe(200);
expect(response.header['set-cookie'][0]).toMatch(
`backstage-auth=${mockCredentials.limitedUser.token()}`,
);
});
it('should remove the user cookie', async () => {
const response = await request(app).delete('/.backstage/v1-cookie');
expect(response.status).toBe(200);
expect(response.header['set-cookie'][0]).toMatch('backstage-auth=');
});
});
@@ -17,6 +17,8 @@
import { HttpAuthService } from '@backstage/backend-plugin-api';
import { Router } from 'express';
const WELL_KNOWN_COOKIE_PATH_V1 = '/.backstage/v1-cookie';
/**
* @public
* Creates a middleware that can be used to refresh the cookie for the user.
@@ -28,10 +30,16 @@ export function createCookieAuthRefreshMiddleware(options: {
const router = Router();
// Endpoint that sets the cookie for the user
router.get('/.backstage/v1-cookie', async (_, res) => {
router.get(WELL_KNOWN_COOKIE_PATH_V1, async (_, res) => {
const { expiresAt } = await httpAuth.issueUserCookie(res);
res.json({ expiresAt: expiresAt.toISOString() });
});
// Endpoint that removes the cookie for the user
router.delete(WELL_KNOWN_COOKIE_PATH_V1, async (_, res) => {
httpAuth.removeUserCookie(res);
res.send(200);
});
return router;
}