Fastify Rate Limit From Custom Auth Handler
- Dominant language
- No language data
- Stars
- 68
- Forks
- 8
- Avg merge
- 11h 2m
- Merged PRs (30d)
- 2
Description
Hi, I'm looking at using https://github.com/fastify/fastify-rate-limit and trying to fit it (or my project) to accommodate.
I want to:
1. check and apply the rate limit against IP address IF authorization token is bad/not-supplied etc.
2. check and apply the rate limit against user id IF authorization token is good
I decorate my fastify instance with something like:
```ts
fastify.decorate('authenticate', async function (request, reply) {
const token = request.headers.authorization?.replace('Bearer ', '');
if (!token) {
// ###
// WANT TO CHECK RATE LIMIT HERE AGAINST IP
// ###
return reply
.code(401)
.send(createFailResponseApiModel('68b59dd8d73f85a46a49a18d', 'No token provided'));
}
const verifyAccessTokenResult = verifyAccessToken(token);
if (!verifyAccessTokenResult.success) {
// ###
// WANT TO CHECK RATE LIMIT HERE AGAINST IP
// ###
return reply
.code(401)
.send(createFailResponseApiModel('68b59e0b91a929648f0fb03b', 'Invalid token'));
}
const sessionResult = getSessionFromUserClaims(
verifyAccessTokenResult.data,
);
if (!sessionResult.success) {
// ###
// WANT TO CHECK RATE LIMIT HERE AGAINST IP
// ###
return reply
.code(401)
.send(createFailResponseApiModel('68b59dfdb827d5a7354aaf33', 'Invalid session'));
}
request.session = sessionResult.data;
// ###
// WANT TO CHECK RATE LIMIT HERE AGAINST USER ID
// ###
return undefined;
});
```
If I use the plugin as written I have the option for setting a `hook` to `preHandler` or `onRequest`.
Both don't seem to apply well here, `onRequest` will trigger before my auth thus only `IP` is available. Whilst `preHandler` triggers after my auth and by that point its too late.
Maybe I'm missing something, be happy to hear of solutions?
Contributor guide
Assessment
This issue has not been assessed yet.