-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add custom auth strategies (#24)
* feat: add custom auth strategies * feat: add addAuthStrategy method * docs: add docs for custom strategies
- Loading branch information
1 parent
f775e57
commit efaba64
Showing
7 changed files
with
362 additions
and
171 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,191 @@ | ||
'use strict' | ||
|
||
const fastify = require('fastify') | ||
const { test } = require('tap') | ||
const { Agent, setGlobalDispatcher } = require('undici') | ||
const fastifyUser = require('..') | ||
|
||
const { buildAuthorizer } = require('./helper') | ||
|
||
const agent = new Agent({ | ||
keepAliveTimeout: 10, | ||
keepAliveMaxTimeout: 10 | ||
}) | ||
setGlobalDispatcher(agent) | ||
|
||
test('custom auth strategy', async ({ teardown, strictSame, equal }) => { | ||
const app = fastify({ | ||
forceCloseConnections: true | ||
}) | ||
|
||
app.register(fastifyUser, { | ||
authStrategies: [{ | ||
name: 'myStrategy', | ||
createSession: async function (req) { | ||
req.user = { id: 42, role: 'user' } | ||
} | ||
}] | ||
}) | ||
|
||
app.addHook('preHandler', async (request, reply) => { | ||
await request.extractUser() | ||
}) | ||
|
||
app.get('/', async function (request, reply) { | ||
return request.user | ||
}) | ||
|
||
teardown(app.close.bind(app)) | ||
|
||
await app.ready() | ||
|
||
{ | ||
const res = await app.inject({ method: 'GET', url: '/' }) | ||
equal(res.statusCode, 200) | ||
strictSame(res.json(), { id: 42, role: 'user' }) | ||
} | ||
}) | ||
|
||
test('multiple custom strategies', async ({ teardown, strictSame, equal }) => { | ||
const app = fastify({ | ||
forceCloseConnections: true | ||
}) | ||
|
||
app.register(fastifyUser, { | ||
authStrategies: [ | ||
{ | ||
name: 'myStrategy1', | ||
createSession: function () { | ||
throw new Error('myStrategy1 failed') | ||
} | ||
}, | ||
{ | ||
name: 'myStrategy2', | ||
createSession: async function (req) { | ||
req.user = { id: 43, role: 'user' } | ||
} | ||
} | ||
] | ||
}) | ||
|
||
app.addHook('preHandler', async (request, reply) => { | ||
await request.extractUser() | ||
}) | ||
|
||
app.get('/', async function (request, reply) { | ||
return request.user | ||
}) | ||
|
||
teardown(app.close.bind(app)) | ||
|
||
await app.ready() | ||
|
||
{ | ||
const res = await app.inject({ method: 'GET', url: '/' }) | ||
equal(res.statusCode, 200) | ||
strictSame(res.json(), { id: 43, role: 'user' }) | ||
} | ||
}) | ||
|
||
test('webhook + custom strategy', async ({ teardown, strictSame, equal }) => { | ||
const authorizer = await buildAuthorizer() | ||
teardown(() => authorizer.close()) | ||
|
||
const app = fastify({ | ||
forceCloseConnections: true | ||
}) | ||
|
||
app.register(fastifyUser, { | ||
webhook: { | ||
url: `http://localhost:${authorizer.server.address().port}/authorize` | ||
}, | ||
authStrategies: [ | ||
{ | ||
name: 'myStrategy1', | ||
createSession: function (req) { | ||
if (req.headers['x-custom-auth'] !== undefined) { | ||
req.user = { id: 42, role: 'user' } | ||
} else { | ||
throw new Error('myStrategy1 failed') | ||
} | ||
} | ||
} | ||
] | ||
}) | ||
|
||
app.addHook('preHandler', async (request, reply) => { | ||
await request.extractUser() | ||
}) | ||
|
||
app.get('/', async function (request, reply) { | ||
return request.user | ||
}) | ||
|
||
teardown(app.close.bind(app)) | ||
teardown(() => authorizer.close()) | ||
|
||
await app.ready() | ||
|
||
{ | ||
const cookie = await authorizer.getCookie({ | ||
'USER-ID-FROM-WEBHOOK': 42 | ||
}) | ||
|
||
const res = await app.inject({ | ||
method: 'GET', | ||
url: '/', | ||
headers: { | ||
cookie | ||
} | ||
}) | ||
equal(res.statusCode, 200) | ||
strictSame(res.json(), { | ||
'USER-ID-FROM-WEBHOOK': 42 | ||
}) | ||
} | ||
|
||
{ | ||
const res = await app.inject({ | ||
method: 'GET', | ||
url: '/', | ||
headers: { | ||
'x-custom-auth': 'true' | ||
} | ||
}) | ||
equal(res.statusCode, 200) | ||
strictSame(res.json(), { id: 42, role: 'user' }) | ||
} | ||
}) | ||
|
||
test('add custom strategy via addCustomStrategy hook', async ({ teardown, strictSame, equal }) => { | ||
const app = fastify({ | ||
forceCloseConnections: true | ||
}) | ||
|
||
await app.register(fastifyUser) | ||
|
||
app.addAuthStrategy({ | ||
name: 'myStrategy', | ||
createSession: async function (req) { | ||
req.user = { id: 42, role: 'user' } | ||
} | ||
}) | ||
|
||
app.addHook('preHandler', async (request, reply) => { | ||
await request.extractUser() | ||
}) | ||
|
||
app.get('/', async function (request, reply) { | ||
return request.user | ||
}) | ||
|
||
teardown(app.close.bind(app)) | ||
|
||
await app.ready() | ||
|
||
{ | ||
const res = await app.inject({ method: 'GET', url: '/' }) | ||
equal(res.statusCode, 200) | ||
strictSame(res.json(), { id: 42, role: 'user' }) | ||
} | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
'use strict' | ||
|
||
const { createPublicKey, generateKeyPairSync } = require('crypto') | ||
const { request } = require('undici') | ||
const fastify = require('fastify') | ||
|
||
async function buildJwksEndpoint (jwks, fail = false) { | ||
const app = fastify() | ||
app.get('/.well-known/jwks.json', async () => { | ||
if (fail) { | ||
throw Error('JWKS ENDPOINT ERROR') | ||
} | ||
return jwks | ||
}) | ||
await app.listen({ port: 0 }) | ||
return app | ||
} | ||
|
||
function generateKeyPair () { | ||
// creates a RSA key pair for the test | ||
const { publicKey, privateKey } = generateKeyPairSync('rsa', { | ||
modulusLength: 2048, | ||
publicKeyEncoding: { type: 'pkcs1', format: 'pem' }, | ||
privateKeyEncoding: { type: 'pkcs1', format: 'pem' } | ||
}) | ||
const publicJwk = createPublicKey(publicKey).export({ format: 'jwk' }) | ||
return { publicKey, publicJwk, privateKey } | ||
} | ||
|
||
async function buildAuthorizer (opts = {}) { | ||
const app = fastify() | ||
app.register(require('@fastify/cookie')) | ||
app.register(require('@fastify/session'), { | ||
cookieName: 'sessionId', | ||
secret: 'a secret with minimum length of 32 characters', | ||
cookie: { secure: false } | ||
}) | ||
|
||
app.post('/login', async (request, reply) => { | ||
request.session.user = request.body | ||
return { | ||
status: 'ok' | ||
} | ||
}) | ||
|
||
app.post('/authorize', async (request, reply) => { | ||
if (typeof opts.onAuthorize === 'function') { | ||
await opts.onAuthorize(request) | ||
} | ||
|
||
const user = request.session.user | ||
if (!user) { | ||
return reply.code(401).send({ error: 'Unauthorized' }) | ||
} | ||
return user | ||
}) | ||
|
||
app.decorate('getCookie', async (cookie) => { | ||
const res = await request(`http://localhost:${app.server.address().port}/login`, { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json' | ||
}, | ||
body: JSON.stringify(cookie) | ||
}) | ||
|
||
res.body.resume() | ||
|
||
return res.headers['set-cookie'].split(';')[0] | ||
}) | ||
|
||
await app.listen({ port: 0 }) | ||
|
||
return app | ||
} | ||
|
||
module.exports = { | ||
generateKeyPair, | ||
buildJwksEndpoint, | ||
buildAuthorizer | ||
} |
Oops, something went wrong.