mirror of
https://github.com/directus/directus.git
synced 2026-01-15 04:17:57 -05:00
* Add "authenticate" filter hook that allows custom auth check * Start on test * Update Jest, restructure API tests, start implementing authenticate test * Move access token verify to util function * Ensure jest can show inline warnings on correct lines * Update is-directus-jwt to use jsonwebtoken decode + add tests * Remove unused package * Tweak and finish + test authenticate * Tweak test * Add authenticate filter to docs * Don't scan tests for codeql * No seriously, ignore tests
38 lines
1.5 KiB
TypeScript
38 lines
1.5 KiB
TypeScript
import { verifyAccessJWT } from '../../src/utils/jwt';
|
|
import jwt from 'jsonwebtoken';
|
|
import { InvalidTokenException, ServiceUnavailableException } from '../../src/exceptions';
|
|
import { DirectusTokenPayload } from '../../src/types';
|
|
|
|
const payload: DirectusTokenPayload = { role: null, app_access: false, admin_access: false };
|
|
const secret = 'test-secret';
|
|
const options = { issuer: 'directus' };
|
|
|
|
test('Returns the payload of a correctly signed token', () => {
|
|
const token = jwt.sign(payload, secret, options);
|
|
const result = verifyAccessJWT(token, secret);
|
|
expect(result).toEqual(payload);
|
|
});
|
|
|
|
const InvalidTokenCases = {
|
|
'wrong issuer': jwt.sign(payload, secret, { issuer: 'wrong' }),
|
|
'wrong secret': jwt.sign(payload, 'wrong-secret', options),
|
|
expired: jwt.sign({ ...payload, exp: new Date().getTime() / 1000 - 500 }, secret, options),
|
|
'string payload': jwt.sign('illegal payload', secret),
|
|
'missing properties in token payload': jwt.sign({ role: null }, secret, options),
|
|
};
|
|
|
|
Object.entries(InvalidTokenCases).forEach(([title, token]) =>
|
|
test(`Throws InvalidTokenError - ${title}`, () => {
|
|
expect(() => verifyAccessJWT(token, secret)).toThrow(InvalidTokenException);
|
|
})
|
|
);
|
|
|
|
test(`Throws ServiceUnavailableException for unexpected error from jsonwebtoken`, () => {
|
|
jest.spyOn(jwt, 'verify').mockImplementation(() => {
|
|
throw new Error();
|
|
});
|
|
|
|
const token = jwt.sign(payload, secret, options);
|
|
expect(() => verifyAccessJWT(token, secret)).toThrow(ServiceUnavailableException);
|
|
});
|