From ab1f8437ea9391f792e9b90f3190acc51538df4a Mon Sep 17 00:00:00 2001 From: ankitsridhar16 Date: Wed, 7 Dec 2022 20:30:02 +0530 Subject: [PATCH] chore: added existing auth guard and user model --- .../src/guards/gql-auth.guard.ts | 42 +++++++++++++++++++ .../hoppscotch-backend/src/user/user.model.ts | 27 ++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 packages/hoppscotch-backend/src/guards/gql-auth.guard.ts create mode 100644 packages/hoppscotch-backend/src/user/user.model.ts diff --git a/packages/hoppscotch-backend/src/guards/gql-auth.guard.ts b/packages/hoppscotch-backend/src/guards/gql-auth.guard.ts new file mode 100644 index 000000000..aabc77b10 --- /dev/null +++ b/packages/hoppscotch-backend/src/guards/gql-auth.guard.ts @@ -0,0 +1,42 @@ +import { CanActivate, Injectable, ExecutionContext } from '@nestjs/common'; +import { GqlExecutionContext } from '@nestjs/graphql'; +import { User } from '../user/user.model'; +import { IncomingHttpHeaders } from 'http2'; +import { AUTH_FAIL } from 'src/errors'; + +@Injectable() +export class GqlAuthGuard implements CanActivate { + // eslint-disable-next-line @typescript-eslint/no-empty-function + constructor() {} + + async canActivate(context: ExecutionContext): Promise { + try { + const ctx = GqlExecutionContext.create(context).getContext<{ + reqHeaders: IncomingHttpHeaders; + user: User | null; + }>(); + + if ( + ctx.reqHeaders.authorization && + ctx.reqHeaders.authorization.startsWith('Bearer ') + ) { + const idToken = ctx.reqHeaders.authorization.split(' ')[1]; + + const authUser: User = { + uid: 'aabb22ccdd', + displayName: 'exampleUser', + photoURL: 'http://example.com/avatar', + email: 'me@example.com', + }; + + ctx.user = authUser; + + return true; + } else { + return false; + } + } catch (e) { + throw new Error(AUTH_FAIL); + } + } +} diff --git a/packages/hoppscotch-backend/src/user/user.model.ts b/packages/hoppscotch-backend/src/user/user.model.ts new file mode 100644 index 000000000..779dbc4db --- /dev/null +++ b/packages/hoppscotch-backend/src/user/user.model.ts @@ -0,0 +1,27 @@ +import { ObjectType, ID, Field } from '@nestjs/graphql'; + +@ObjectType() +export class User { + @Field(() => ID, { + description: 'Firebase UID of the user', + }) + uid: string; + + @Field({ + nullable: true, + description: 'Displayed name of the user (if given)', + }) + displayName?: string; + + @Field({ + nullable: true, + description: 'Email of the user (if given)', + }) + email?: string; + + @Field({ + nullable: true, + description: 'URL to the profile photo of the user (if given)', + }) + photoURL?: string; +}