Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add request.user property only to routes with fastify.authenticate hook applied in Typescript #323

Closed
2 tasks done
tjapa opened this issue Dec 27, 2023 · 1 comment
Closed
2 tasks done

Comments

@tjapa
Copy link

tjapa commented Dec 27, 2023

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Hello.

I'm using the fastify with typescript.

I created this plugin:

export interface AuthPluginOptions {
  jwtAuthSecret: string
}

export default fp<AuthPluginOptions>(
  async (fastify, opts) => {
    fastify.register(fastifyJwt, {
      secret: opts.jwtAuthSecret,
    })

    fastify.decorate(
      'authenticate',
      async function authenticate(
        request: FastifyRequest,
        reply: FastifyReply,
      ) {
        try {
          await request.jwtVerify()
          // console.log(request.user)
        } catch (err) {
          reply.send(err)
        }
      },
    )
  },
  { dependencies: ['application-config'] },
)

declare module 'fastify' {
  export interface FastifyInstance {
    authenticate(request: any, reply: any): void
  }
  interface FastifyInstance
    extends FastifyJwtNamespace<{ namespace: 'security' }> {}
  interface FastifyRequest
    extends FastifyJwtNamespace<{ namespace: 'security' }> {}
}

The problem is that now the request.user option appears for all routes, even those that do not use the authenticate plugin in the onRequest hook.
Is there a way to make the user property only appear for hooked routes?

@mcollina
Copy link
Member

Unfortunately no, we are planning to make it possible in v5.

fastify/fastify#5061

@mcollina mcollina closed this as not planned Won't fix, can't repro, duplicate, stale Dec 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants