This repository provides an example implementation of multiple authentication from two separate table (user & staff) using Jwt Passport in a NestJS application. It demonstrates how to protect routes and retrieve the authenticated user and staff from the database.
Before getting started, ensure that you have the following prerequisites:
- Node.js (version 14 or above)
- npm or yarn package manager
- NestJS (installed globally or as a project dependency)
- A database (e.g., PostgreSQL, MySQL, MongoDB) supported by your NestJS application
- Prisma client set up and connected to your database
- Clone this repository to your local machine:
git clone https://github.com/SujoySust/Multi-Auth-with-Jwt-Passport-in-NestJS.git
- Navigate to the project directory:
cd nestjs-simple-auth-restapi
- Install the dependencies:
npm install or yarn install
-
Configure your database connection by updating the configuration file: prisma/schema.prisma
-
Run the database migrations to create the necessary tables:
npm prisma db push or yarn prisma db push
To use the authentication setup provided by JwtAuthGuard, follow these steps:
For User Gaurd: Include the JwtAuthGuard() in your route or controller using the @UseGuards() decorator:
import { Controller, Get, UseGuards } from '@nestjs/common';
import { User } from '../../models/db/user.model';
import { UserEntity } from '../../../libs/decorators/user.decorator';
import { JwtAuthGuard } from '../../../libs/auth/auth.gaurd';
@UseGuards(JwtAuthGuard())
@Controller()
export class UserController {
@Get('/profile')
async profile(@UserEntity() user: User): Promise<User> {
return user;
}
}
For Staff Gaurd: Include the JwtAuthGuard('staff') in your route or controller using the @UseGuards() decorator:
@UseGuards(JwtAuthGuard('staff'))
@Controller('staff')
export class StaffController {
@Get('/profile')
async profile(@UserEntity() staff: Staff): Promise<Staff> {
return staff;
}
}
To configure the authentication setup, you may need to modify the following files:
config/jwt.config.ts: Adjust the JWT secret, expiration time, and other configurations to suit your needs.
Make sure to review and modify the configurations according to your specific application requirements.