nestjs firebase authentication

2.2k views Asked by At

I have nestjs application which uses typeorm and mysql. Now I would like to add firebase for authentication handling, i.e for signup, signin, email verification, forgot password etc.

Plans is create user first in firebase, then same user details will be added into mysql user table for further operaiton. So for this I am using customized middleware

@Injectable()
export class FirebaseAuthMiddleware implements NestMiddleware {
  async use(req: Request, _: Response, next: Function) {
    const { authorization } = req.headers
    // Bearer ezawagawg.....
    if(authorization){
      const token = authorization.slice(7)

      const user = await firebase
        .auth()
        .verifyIdToken(token)
        .catch(err => {
          throw new HttpException({ message: 'Input data validation failed', err }, HttpStatus.UNAUTHORIZED)
        })

      req.firebaseUser = user
      next()
    }
    
  }
}

Full code is available in Github

Problem with above code is that, it always looks for auth token, const { authorization } = req.headers const token = authorization.slice(7)

However, when user first time access application, authorization header always be null. example if user access signup page we cannot pass auth header.

please let me know how can I modify above code when user access signup page, it allows user create user firebase, then same details can be stored in database.

2

There are 2 answers

0
Uthaya Seelan On

We can exclude the routes for which you don't want this middleware.

consumer .apply(LoggerMiddleware) .exclude( { path: 'cats', method: RequestMethod.GET }, { path: 'cats', method: RequestMethod.POST }, 'cats/(.*)', )

.forRoutes(CatsController);

0
Borris Wiria On

You can just next() to skip this middleware if there is no authorization. so it s okay to access sign up api when no authorization