From 97cd5abb357e6711e9837b81860abb47846a12ec Mon Sep 17 00:00:00 2001 From: Taylor McMonigle Date: Tue, 21 Mar 2023 10:21:10 -0500 Subject: [PATCH] feature: formatUser option (#269) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * formatUser * working test for formatting user * fix nearform action * revert nearform github action * improve types for formatUser * revert describe.only * fix tests * fix merge * chore: lint --------- Co-authored-by: RĂ´mulo Vitoi --- index.d.ts | 6 +++++- index.js | 3 ++- index.test-d.ts | 6 ++++++ test.js | 32 ++++++++++++++++++++++++++++++++ 4 files changed, 45 insertions(+), 2 deletions(-) diff --git a/index.d.ts b/index.d.ts index 42c81df..8b2a492 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,5 +1,5 @@ import { FastifyPluginCallback, FastifyReply, FastifyRequest } from 'fastify' -import '@fastify/jwt' +import { UserType, SignPayloadType } from '@fastify/jwt' import NodeCache from 'node-cache' @@ -51,6 +51,10 @@ export interface FastifyAuth0VerifyOptions { */ signed?: boolean } + /** + * You may customize the request.user object setting a custom sync function as parameter: + */ + readonly formatUser?: (payload: SignPayloadType) => UserType } export interface Auth0Verify extends Pick { diff --git a/index.js b/index.js index 9803ba4..4138fdf 100644 --- a/index.js +++ b/index.js @@ -178,7 +178,8 @@ function fastifyAuth0Verify(instance, options, done) { verify: auth0Options.verify, cookie: options.cookie, secret: getSecret, - jwtDecode: 'jwtDecode' + jwtDecode: 'jwtDecode', + formatUser: options.formatUser }) // Setup our decorators diff --git a/index.test-d.ts b/index.test-d.ts index 4b722e0..e359cc2 100644 --- a/index.test-d.ts +++ b/index.test-d.ts @@ -29,6 +29,12 @@ fastify.register(fastifyAuth0Verify, { signed: true } }) +fastify.register(fastifyAuth0Verify, { + domain: '', + issuer: '', + audience: '', + formatUser: () => ({ foo: 'bar' }), +}) fastify.register(function (instance, _options, done) { instance.get('/verify', { diff --git a/test.js b/test.js index 927a13f..9cce6d3 100644 --- a/test.js +++ b/test.js @@ -381,6 +381,38 @@ describe('JWT cookie token decoding', function () { }) }) +describe('format decoded token', function () { + let server + + beforeAll(async function () { + server = await buildServer({ + secret: 'secret', + token: 'token', + cookie: { cookieName: 'token' }, + formatUser: user => { + return { + sub: user.sub, + username: user.name, + admin: user.admin + } + } + }) + }) + + afterAll(() => server.close()) + + it('should format verified user', async function () { + const response = await server.inject({ + method: 'GET', + url: '/verify', + headers: { Authorization: `Bearer ${tokens.hs256Valid}` } + }) + + expect(response.statusCode).toEqual(200) + expect(response.json()).toEqual({ sub: '1234567890', username: 'John Doe', admin: true }) + }) +}) + describe('HS256 JWT token validation', function () { let server