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

@alpha018/nestjs-firebase-auth

v1.2.0

Published

NestJS Firebase library and Role based guard for authentication with some utils functions

Downloads

17

Readme

NestJS Firebase Auth

Table of Contents

Installation

$ npm i @alpha018/nestjs-firebase-auth firebase-admin

Usage

Import The Module

To use Firebase authentication in your application, import the module into your main module.

import { FirebaseAuthGuard } from '@alpha018/nestjs-firebase-auth';

@Module({
  imports: [
    ...
      FirebaseAdminModule.forRootAsync({
        imports: [ConfigModule],
        useFactory: (configService: ConfigService) => ({
          // SELECT ONLY ONE: BASE64 OR OPTIONS (Firebase Options)!
          base64: configService.get('FIREBASE_SERVICE_ACCOUNT_BASE64'), // Base64 encoded service account JSON string
          options: {}, // Use this if not using base64
          auth: {
            config: {
              extractor: ExtractJwt.fromAuthHeaderAsBearerToken(), // Choose your extractor from the Passport library
              checkRevoked: true, // Set to true if you want to check for revoked Firebase tokens
              validateRole: true, // Set to true if you want to validate user roles
            },
          },
        }),
        inject: [TicketServiceConfig],
      }),
    ...
  ],
})

Parameter Options

| Parameter | Type | Required | Description | |--------------------------------|--------------|----------|-----------------------------------------------------------------------------------------------------| | base64 | string | Yes* | Base64 encoded service account JSON string. Required if options is not provided. | | options | object | Yes* | Firebase Admin SDK configuration options. Required if base64 is not provided. | | auth.config.extractor | function | Optional | A custom extractor function from the Passport library to extract the token from the request. | | auth.config.checkRevoked | boolean | Optional | Set to true to check if the Firebase token has been revoked. Defaults to false. | | auth.config.validateRole | boolean | Optional | Set to true to validate user roles using Firebase custom claims. Defaults to false. |

Auth Guard Without Role Validation

To protect an endpoint without validating user roles, use the Auth Guard to ensure the Firebase user's token is valid.

import { FirebaseGuard, FirebaseProvider } from '@alpha018/nestjs-firebase-auth';

export class AppController {
  constructor(
    private readonly firebaseProvider: FirebaseProvider,
  ) {}

  @UseGuards(FirebaseGuard) // This line protects your endpoint. If `validateRole` is enabled, it also validates the user's role.
  @Get()
  mainFunction() {
    return 'Hello World';
  }
}

Auth Guard With Role Validation

To enforce role-based access control, you need to set custom claims in Firebase. Here's how you can set custom claims:

import { FirebaseProvider } from '@alpha018/nestjs-firebase-auth';

enum Roles {
  ADMIN,
  USER,
}

@Controller('')
export class AppController implements OnModuleInit {
  constructor(
    private readonly firebaseProvider: FirebaseProvider,
  ) {}

  @Get()
  async setClaims() {
    await this.firebaseProvider.setClaimsRoleBase<Roles>(
      'FirebaseUID',
      [Roles.ADMIN, ...]
    );
    return { status: 'ok' }
  }
}

Then, use the Auth Guard with role validation to check if a user has the necessary permissions to access an endpoint:

import { FirebaseGuard, FirebaseProvider, RolesGuard } from '@alpha018/nestjs-firebase-auth';
enum Roles {
  ADMIN,
  USER,
}

@Controller('')
export class AppController {
  constructor(
    private readonly firebaseProvider: FirebaseProvider,
  ) {}

  @RolesGuard(Roles.ADMIN, Roles.USER) // This line checks the custom claims of the Firebase user to protect the endpoint
  @UseGuards(FirebaseGuard) // This line protects your endpoint and, if `validateRole` is enabled, validates the user's role
  @Get()
  mainFunction() {
    return 'Hello World';
  }
}

Additional Information

To retrieve user claims, use the following example:

import { FirebaseProvider } from '@alpha018/nestjs-firebase-auth';

enum Roles {
  ADMIN,
  USER,
}

@Controller('')
export class AppController {
  constructor(
    private readonly firebaseProvider: FirebaseProvider,
  ) {}

  @Get()
  async mainFunction() {
    const claims = await this.firebaseProvider.getClaimsRoleBase<Roles>(
      'FirebaseUID',
    );
    return claims; // This returns an array of the user's claims
  }
}

To retrieve Decode ID Token and Claims, use the following example:

import {
  FirebaseGuard,
  FirebaseProvider, FirebaseUser, FirebaseUserClaims,
  RolesGuard,
} from '@alpha018/nestjs-firebase-auth';

import { auth } from 'firebase-admin';

enum Roles {
  ADMIN,
  USER,
}

@Controller('')
export class AppController {
  constructor(
    private readonly firebaseProvider: FirebaseProvider,
  ) {}

  @RolesGuard(Roles.ADMIN, Roles.USER)
  @UseGuards(FirebaseGuard)
  @Get()
  async mainFunction(
    @FirebaseUser() user: auth.DecodedIdToken,
    @FirebaseUserClaims() claims: Roles[],
  ) {
    return {
      user,
      claims
    };
  }
}

Resources

Check out a few resources that may come in handy when working with NestJS:

Stay in touch

License

Nest is MIT licensed.