Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: ✨ add AuthGuard #96

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion apps/gateway/src/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { IntrospectAndCompose } from '@apollo/gateway';
import { IntrospectAndCompose, RemoteGraphQLDataSource } from '@apollo/gateway';
import { gatewayConfig, userAppConfig } from '@shared/config';
import { ApolloGatewayDriver, ApolloGatewayDriverConfig } from '@nestjs/apollo';
import { Module } from '@nestjs/common';
Expand Down Expand Up @@ -31,6 +31,20 @@ import { AppService } from './app.service';
},
],
}),
buildService: ({ url = '' }) => {
return new RemoteGraphQLDataSource({
url,
willSendRequest({ request, context }) {
// rebuild header
if (Object.keys(context).length > 0 && request.http) {
request.http.headers.set(
'Authorization',
context['req']['headers']['authorization'],
);
}
},
});
},
},
};
},
Expand Down
3 changes: 3 additions & 0 deletions apps/users/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ import { AppService } from './app.service';
playground: process.env['NODE_ENV'] !== 'production',
sortSchema: true,
plugins: [ApolloServerPluginInlineTrace()],
context: ({ req }: { req: Request }) => {
return { headers: req?.headers };
},
}),
UsersModule,
AuthModule,
Expand Down
2 changes: 2 additions & 0 deletions libs/auth/interface-adapters/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export * from './lib/guard/auth.guard';

export * from './lib/auth.module';
44 changes: 44 additions & 0 deletions libs/auth/interface-adapters/src/lib/guard/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';

@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private jwtService: JwtService,
private configService: ConfigService,
) {}

async canActivate(context: ExecutionContext): Promise<boolean> {
const authConfig = this.configService.get('auth');
const request = context.switchToHttp().getRequest();
const token = this.extractTokenFromHeader(request);

if (!token) {
throw new UnauthorizedException();
}

try {
const payload = await this.jwtService.verifyAsync(token, {
secret: authConfig.secret,
});
// 💡 We're assigning the payload to the request object here
// so that we can access it in our route handlers
request['user'] = payload;
} catch {
throw new UnauthorizedException();
}
return true;
}

private extractTokenFromHeader(request: Request): string | undefined {
const [type, token] = request.headers.authorization?.split(' ') ?? [];
return type === 'Bearer' ? token : undefined;
}
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { AuthGuard } from '@auth/interface-adapters';
import { UseGuards } from '@nestjs/common';
import { Args, ID, Query, Resolver } from '@nestjs/graphql';
import { UsersService } from '@users/application';
import { User } from '@users/domain';
Expand All @@ -8,9 +10,12 @@ import { UserDto } from '../dto/user.dto';
export class UsersResolver {
constructor(private usersService: UsersService) {}

@UseGuards(AuthGuard)
@Query(() => UserDto, { nullable: true })
async getUser(@Args({ name: 'id', type: () => ID }) id: string): Promise<UserDto | null> {
const user: User| null = await this.usersService.findById(id);
async getUser(
@Args({ name: 'id', type: () => ID }) id: string,
): Promise<UserDto | null> {
const user: User | null = await this.usersService.findById(id);

if (!user) {
return null;
Expand Down
2 changes: 2 additions & 0 deletions libs/users/interface-adapters/src/lib/users.module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Module } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { DatabaseModule } from '@shared/infrastructure-mongoose';
import { UsersService, GetUserByIdUseCase, GetUserByEmailUseCase } from '@users/application';
import {
Expand All @@ -15,6 +16,7 @@ import { UsersResolver } from './resolver/users.resolver';
providers: [
UsersResolver,
UsersService,
JwtService,
GetUserByIdUseCase,
GetUserByEmailUseCase,
{
Expand Down
Loading