diff --git a/middleware/__tests__/adminMiddleware.spec.ts b/middleware/__tests__/adminMiddleware.spec.ts new file mode 100644 index 00000000..8e92758b --- /dev/null +++ b/middleware/__tests__/adminMiddleware.spec.ts @@ -0,0 +1,46 @@ +import { Context } from '@nuxt/types'; +import adminMiddleware from '../adminMiddleware'; + +const mockRedirect = jest.fn(); + +const BASE_INPUT = ({ + $auth: { + user: { + Policy: { + IsAdministrator: false + } + } + }, + redirect: mockRedirect +} as unknown) as Context; + +const INPUT_NOT_ADMIN = { + ...BASE_INPUT +}; + +const INPUT_ADMIN = ({ + ...BASE_INPUT, + $auth: { + user: { + Policy: { + IsAdministrator: true + } + } + } +} as unknown) as Context; + +afterEach(() => mockRedirect.mockReset()); + +describe('adminMiddleware', () => { + it('redirects to "/" when user is not an administrator', (): void => { + adminMiddleware(INPUT_NOT_ADMIN); + + expect(mockRedirect.mock.calls[0][0]).toBe('/'); + }); + + it('does not redirect when user is not an administrator', (): void => { + adminMiddleware(INPUT_ADMIN); + + expect(mockRedirect.mock.calls).toHaveLength(0); + }); +}); diff --git a/middleware/adminMiddleware.ts b/middleware/adminMiddleware.ts index 699629ec..a817c3f3 100644 --- a/middleware/adminMiddleware.ts +++ b/middleware/adminMiddleware.ts @@ -8,7 +8,7 @@ import { Context } from '@nuxt/types'; * @returns {void} */ export default function (context: Context): void { - if (!context.$auth.user.Policy.IsAdministrator) { + if (!context.$auth.user?.Policy?.IsAdministrator) { return context.redirect('/'); } }