This package has been deprecated

Author message:

please npm i @devts/authjs

@devts/nestjs-auth
TypeScript icon, indicating that this package has built-in type declarations

1.3.14 • Public • Published

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
  1. Installation
  2. example

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]
  }
}

Package Sidebar

Install

npm i @devts/nestjs-auth

Weekly Downloads

2

Version

1.3.14

License

MIT

Unpacked Size

95.6 kB

Total Files

96

Last publish

Collaborators

  • rojiwon123