🚨 Latest Research:Tanstack npm Packages Compromised in Ongoing Mini Shai-Hulud Supply-Chain Attack.Learn More →
Socket
Book a DemoSign in
Socket

@devts/nestjs-auth

Package Overview
Dependencies
Maintainers
2
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@devts/nestjs-auth

Oauth2 Auth Module to NestJS

latest
npmnpm
Version
1.3.14
Version published
Maintainers
2
Created
Source

nestjs-auth

npm version Downloads type-coverage

  • A way to apply Oauth2 Auth module to nestjs
  more type-safe than passport
  install only once
Table of Contents

Installation

npm i @devts/nestjs-auth

Example

import { HttpException, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Google, StrategyException } from '@devts/nestjs-auth';

interface GoogleProfile {
  username: string;
  email: string;
}

@Injectable()
export class GoogleStrategy extends Google.AbstractStrategy<
  'user',
  "emails" | "profile"
  GoogleProfile
> {
  constructor(configService: ConfigService) {
    super({
      client_id: configService.get('CLIENT_ID'),
      client_secret: configService.get('CLIENT_SECRET'),
      redirect_uri: configService.get('OAUTH_CALLBACK'),
      access_type: "offline",
      prompt: "consent",
      scope: ['email', 'profile'],
      key: 'user',
    });
  }

  protected throw({
    statusCode = 401,
    message = ''
  }:StrategyException): never {
    throw new HttpException(statusCode, message);
  }

  validate(
    identity: Google.IdToken<'email' | 'profile'>,
    credentials: Google.Credentials,
  ): boolean {
    return true;
  }

  transform(
    identity: Google.IdToken<'email' | 'profile'>,
  ): GoogleProfile {
    const { name, email } = identity;
    return { username: name, emails };
  }
}

// in module
@Module({
  providers: [
    {
      provide: 'GoogleStrategy',
      useClass: GoogleStrategy,
    },
  ],
})
export class AppModule {}
import { AuthGuard } from '@devts/nestjs-auth';
import { Req } from '@nestjs/common';
import type { Request } from 'express';

@Controller('auth')
export class AuthController {
  // Inject decorator get "GoogleStrategy" token
  @Get('sign-in')
  @UseGuards(AuthGuard('GoogleStrategy'))
  signIn() {
    return;
  }

  @Get('YOUR REDIRECT PATH')
  @UseGuards(AuthGuard('GoogleStrategy'))
  callback(@Req() req: Request) {
    return (req as any).user; // you can get data from request[key]
  }
}

Keywords

nestjs-auth

FAQs

Package last updated on 18 Apr 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts