Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nest.js get request header in passport local strategy

How can I get the request headers inside passport local strategy? I need a separate database for each entity, using mongodb so I need a way to get the subdomain before authentication in order to determine the database that I should connect to

    @Injectable()
    export class LocalStrategy extends PassportStrategy(Strategy) {
        constructor(private authService: AuthService) {
            super({ usernameField: 'email' })
        }
    
        async validate(email: string, password: string, headers:Headers): Promise<IUser> {
            //** this is what I want to have
            //** const subdomain = headers.host.split(".")[0]
            const user = await this.authService.validateUser({ email, password ,//** subdomain})
            if (!user) {
                throw new UnauthorizedException()
            }
            return user
        }
    }

like image 240
Daniel Levy Avatar asked Sep 08 '25 04:09

Daniel Levy


1 Answers

You need to add passReqToCallback: true to the super call in the constructor. This will make req the first parameter of the validate so you can do something like

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({ usernameField: 'email', passReqToCallback: true })
  }

  async validate(req: Request, email: string, password: string, headers:Headers): Promise<IUser> {
    const subdomain = req.headers.host.split(".")[0];
    const user = await this.authService.validateUser({ email, password ,//** subdomain})
    if (!user) {
      throw new UnauthorizedException()
    }
    return user
  }
}
like image 156
Jay McDoniel Avatar answered Sep 10 '25 04:09

Jay McDoniel