Architecture Context:
I have a microservices architecture using NestJS, consisting of:
An API Gateway that routes requests.
An Auth Microservice is responsible for handling authentication (using Passport.js).
A User Microservice for user-related data and operations.
The workflow involves the API Gateway receiving login requests from clients and forwarding them to the Auth Microservice, which validates the user credentials (email and password).
Auth Guard:
import { Injectable, ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {
constructor() {
super();
}
async canActivate(context: ExecutionContext): Promise<boolean> {
const activate = await super.canActivate(context);
if (!activate) {
return false;
}
return true;
}
}
Passport Strategy
import { Injectable } from '@nestjs/common';
import { RpcException } from '@nestjs/microservices';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';
import { AuthService } from '../auth.service';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({ usernameField: 'email' });
}
async validate(email: string, password: string) {
const user = await this.authService.validateUser(email, password);
if (!user) {
console.log('++++++++++++++++++++++++++++++++++++++++++++++++');
throw new RpcException('Invalid credentials');
}
return user;
}
}