Skip to content

Instantly share code, notes, and snippets.

@mguay22
Created September 29, 2024 12:08
Show Gist options
  • Save mguay22/12752475f41547d627ebdf098144f4b6 to your computer and use it in GitHub Desktop.
Save mguay22/12752475f41547d627ebdf098144f4b6 to your computer and use it in GitHub Desktop.
import { UnauthorizedException } from '@nestjs/common';
import { app } from './app';
import { ClientProxy } from '@nestjs/microservices';
import { AUTH_SERVICE } from '@app/common';
import { lastValueFrom } from 'rxjs';
const publicRoutes = ['/public-route', '/another-public-route'];
export const authContext = async ({ req }) => {
// Check if the request path is in the list of public routes
if (publicRoutes.includes(req.path)) {
return { user: null }; // Allow access without authentication
}
try {
const authClient = app.get<ClientProxy>(AUTH_SERVICE);
const user = await lastValueFrom(
authClient.send('authenticate', {
Authentication: req.headers?.authentication,
}),
);
return { user };
} catch (err) {
throw new UnauthorizedException(err);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment