fastify/fastify-passport

the user property remains occupied by the type when userProperty is changed

kravetsone opened this issue · 3 comments

Prerequisites

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

Fastify version

4.5.2

Plugin version

2.2.0

Node.js version

18.12.1

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

20.04

Description

The user property remains occupied by the type PassportUser when userProperty is changed

import { Authenticator } from "@fastify/passport";
const fastifyPassport = new Authenticator({
    userProperty: "authUser",
});
//...
const userGroup = await Group.findOne({
    where: {
          name: req.user?.group,
     },
});

image

image

Steps to Reproduce

import { Authenticator } from "@fastify/passport";
const fastifyPassport = new Authenticator({
    userProperty: "authUser",
});
//...
const userGroup = await Group.findOne({
    where: {
          name: req.user?.group,
     },
});

Expected Behavior

The property user should not have remained a busy type for further use

Sadly the way that TypeScript works makes this really hard for us to adjust dynamically when you use a different property. TypeScript would need Fastify to use a factory function or something similar to return a dynamic type for the server based on the options provided to the plugin, but fastify doesn't work like that (for good reason, its a bunch of extra syntax and noise). So, the types are just wrong when you use a different property, sorry :( I think you may need to use a custom type declaration that merges in your own types to fastify like this:

declare module "fastify" {
  interface FastifyRequest {
    user: <your desired type>,
    otherProp: User // from fastify-passport
  }
}

or use patch-package or similar to change the types this library adds to your project. Sorry about this -- totally awkward.

... or similar to change the types this library adds to your project.

I changed key in the file ./node_modules/@fastify/passport/dist/type-extensions.d.ts on line 16

{
    user?: PassportUser;
}

to

{
    authUser?: PassportUser;
}

and it worked for me. Thanks!

@airhorns
As user property is optional can I make it required without patch-package? Even after overriding FastifyRequest interface it still can be undefined.