Skip to content

Fastify Rate Limit From Custom Auth Handler #1112

@cmcnicholas

Description

@cmcnicholas

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:

    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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions