npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@hannesroth88/nestjs-firebase-auth

v2.0.3

Published

NestJS Passport Strategy for Firebase Auth using Firebase Admin SDK, forked from tfarras/nestjs-firebase-auth

Downloads

11

Readme

Installation

Fork

This is a fork from tfarras/nestjs-firebase-auth. All credits to him. I just updated dependencies and a bit of documentation.

Install peer dependencies

npm install passport passport-jwt
npm install --save-dev @types/passport-jwt

Install @nestjs/passport for authentication

npm install @nestjs/passport

Install strategy

npm install @hannesroth88/nestjs-firebase-auth

Important

To work with Firebase Auth you need to configure and initialize your firebase app. For this purpose you can use my module for firebase-admin.

Create strategy

import { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt } from 'passport-jwt';
import { FirebaseAuthStrategy } from '@tfarras/nestjs-firebase-auth';

@Injectable()
export class FirebaseStrategy extends PassportStrategy(FirebaseAuthStrategy, 'firebase') {
  public constructor() {
    super({
      extractor: ExtractJwt.fromAuthHeaderAsBearerToken(),
    });
  }
}

Note: You should provide an extractor. More information about passport-jwt extractors you can find here: http://www.passportjs.org/packages/passport-jwt/#included-extractors

Create AuthModule and provide created strategy

import { Module } from "@nestjs/common";
import { PassportModule } from "@nestjs/passport";
import { FirebaseStrategy } from "./firebase.strategy";

@Module({
  imports: [PassportModule],
  providers: [FirebaseStrategy],
  exports: [FirebaseStrategy],
  controllers: [],
})
export class AuthModule { }

Import AuthModule into AppModule

import { FirebaseAdminCoreModule } from '@tfarras/nestjs-firebase-admin';
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from 'nestjs-config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
import * as path from 'path';

@Module({
  imports: [
    ConfigModule.load(path.resolve(__dirname, 'config', '**', '!(*.d).{ts,js}')),
    FirebaseAdminCoreModule.forRootAsync({
      useFactory: (config: ConfigService) => config.get('firebase'),
      inject: [ConfigService],
    }),
    AuthModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }

Protect your routes

import { Controller, Get, Inject, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { FirebaseAdminSDK, FIREBASE_ADMIN_INJECT } from '@tfarras/nestjs-firebase-admin';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(
    private readonly appService: AppService,
    @Inject(FIREBASE_ADMIN_INJECT) private readonly fireSDK: FirebaseAdminSDK,
  ) { }

  @Get()
  @UseGuards(AuthGuard('firebase'))
  getHello() {
    return this.fireSDK.auth().listUsers();
  }
}

Custom second validation

In cases when you want to validate also if user exists in your database, or anything else after successfull Firebase validation you can define custom validate method in your strategy.

Example

import { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { FirebaseAuthStrategy, FirebaseUser } from '@tfarras/nestjs-firebase-auth';
import { ExtractJwt } from 'passport-jwt';

@Injectable()
export class FirebaseStrategy extends PassportStrategy(FirebaseAuthStrategy, 'firebase') {
  public constructor() {
    super({
      extractor: ExtractJwt.fromAuthHeaderAsBearerToken(),
    });
  }

  async validate(payload: FirebaseUser): Promise<FirebaseUser> {
    // Do here whatever you want and return your user
    return payload;
  }
}

Add Role requirement

In cases when you want to implement a Role Based Authorization you can do sth like this:

Controller

import {
  Controller,
  Get,
  Param,
  Put,
  Query,
  UseGuards,
} from '@nestjs/common';
import { UserService } from './user.service';
import { UserRecord } from 'firebase-admin/lib/auth/user-record';
import { Role } from 'src/auth/roles/roles.model';
import { RolesOneOf } from 'src/auth/roles/roles.decorator';
import { FirebaseAuthGuard } from 'src/auth/jwt.guard';
import { UserRolesDto } from './dto/user-role-update.dto';
import { ListUsersResult } from 'firebase-admin/lib/auth/base-auth';

@UseGuards(FirebaseAuthGuard)
@RolesOneOf(Role.ADMIN)
@Controller('users')
export class UserController {
  constructor(private userService: UserService) {}

  @Get()
  async listUsers(): Promise<ListUsersResult> {
    return this.userService.listUsers();
  }

  @Get(':id')
  async getUser(@Param('id') userId: string): Promise<UserRecord> {
    return await this.userService.getUser(userId);
  }

  @Put(':id/roles')
  async updateUserRoles(
    @Param('id') userId: string,
    @Query() query: UserRolesDto,
  ): Promise<void> {
    await this.userService.updateUserRoles(userId, query.rolesToUpdate);
  }
}

AuthGuard

import { ExecutionContext, Injectable, Logger } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';
import { FirebaseJwtPayload } from './firebase/firebase.types';
import { Role } from './roles/roles.model';

@Injectable()
export class FirebaseAuthGuard extends AuthGuard('firebase') {
  private readonly logger = new Logger(FirebaseAuthGuard.name);
  constructor(
    private reflector: Reflector,
  ) {
    super();
  }
  async canActivate(context: ExecutionContext): Promise<boolean> {
    // call AuthGuard in order to ensure user is injected in request
    const baseGuardResult = await super.canActivate(context);
    if (!baseGuardResult) {
      // unsuccessful authentication return false
      this.logger.error('baseGuardResult is null');
      return false;
    }

    // successfull authentication, user is injected
    const { user } = context.switchToHttp().getRequest();
    const jwt = user as FirebaseJwtPayload;

    const requireRolesOneOf = this.reflector.getAllAndOverride<Role[]>('rolesOneOf', [context.getHandler(), context.getClass()]);
    if (requireRolesOneOf) {
      const hasRole = requireRolesOneOf.some((role) => jwt.roles.includes(role));
      if (!hasRole) {
        this.logger.error(`User ${jwt.user_id} does not have any of the required roles: ${requireRolesOneOf.join(', ')}`);
      }
      return hasRole;
    } else {
      return true;
    }
  }
}

Role Decorator

import { SetMetadata } from '@nestjs/common';

export const RolesOneOf = (...roles: string[]) => SetMetadata('rolesOneOf', roles);

export enum Role {
    ADMIN = 'ADMIN',
    GUEST = 'GUEST',
  }

User Service

import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { ListUsersResult } from 'firebase-admin/lib/auth/base-auth';
import * as admin from 'firebase-admin';
import { UserRecord } from 'firebase-admin/lib/auth/user-record';

@Injectable()
export class UserService {
  constructor() {}

  async getUser(userId: string): Promise<UserRecord> {
    try {
      return await admin.auth().getUser(userId);
    } catch (error) {
      console.error('Error getting user:', error);
      throw new InternalServerErrorException('Error getting user');
    }
  }

  async listUsers(): Promise<ListUsersResult> {
    try {
      return await admin.auth().listUsers();
    } catch (error) {
      console.error('Error getting users:', error);
      throw new InternalServerErrorException('Error getting users');
    }
  }

  async updateUserRoles(uid: string, roles: string[]): Promise<void> {
    try {
      await admin.auth().setCustomUserClaims(uid, { roles });
    } catch (error) {
      console.error('Error updating user roles:', error);
      throw new InternalServerErrorException('Error updating user roles');
    }
  }
}