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

Context and auth #1

Merged
merged 2 commits into from
Oct 18, 2023
Merged
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
2 changes: 1 addition & 1 deletion backend/dsp-service/src/clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export async function userByToken(token: string): Promise<User> {
}

export async function userById(id: string): Promise<User> {
const user = await clerkClient.users.getUser(id as string);
const user = await clerkClient.users.getUser(id);
return user;
}

Expand Down
24 changes: 7 additions & 17 deletions backend/dsp-service/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { User } from "@clerk/clerk-sdk-node";
import { PrismaClient } from "@prisma/client";
import { PubSub } from "graphql-subscriptions";
import { logger, Logger } from "./logger";
import { userByToken } from "./clerk";
import { userById } from "./clerk";
import { ExpressContextFunctionArgument } from "@apollo/server/dist/esm/express4";

export const prisma = new PrismaClient();
Expand All @@ -19,39 +19,29 @@ export interface DspContext {
};


export async function makeRequestContext({ req, res }: ExpressContextFunctionArgument): Promise<DspContext> {

export async function makeRequestContext({ req, res }: any): Promise<DspContext> {
let newContext: DspContext = {
prisma,
pubsub,
logger: logger,
};

try {

const headers = req.headers;

if (headers && headers.authorization) {

logger.info('[server.makeRequestContext] has authoriztion header');
logger.debug(`[server.makeRequestContext] req.headers.authorization ${JSON.stringify(headers.authorization, undefined, 2)}`);
const token = headers.authorization.split(' ')[1];
const userProfile: User = await userByToken(token);
logger.debug(`[server.makeRequestContext] userProfile ${JSON.stringify(userProfile, undefined, 2)}`);
if (req.auth && req.auth.userId) {
const auth = req.auth;
newContext = {
...newContext,
user: userProfile,
token: token,
user: await userById(auth.userId),
token: auth.getToken(),
};

}
} catch (error) {
logger.error(`[server.makeRequestContext] 💀 Error creating context ${JSON.stringify(error, undefined, 2)}`);
}
return newContext;
}

export async function makeWebSocketContext(args: ExpressContextFunctionArgument): Promise<DspContext> {
export function makeWebSocketContext(args: any): DspContext {

let newContext: DspContext = {
prisma,
Expand Down
11 changes: 4 additions & 7 deletions backend/dsp-service/src/resolvers/accountsResolvers.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import { GraphQLResolveInfo } from "graphql";
import { QueryAccountsArgs, QueryAccountArgs, MutationNewAccountArgs, MutationMapAccountRetailersArgs } from "../resolver-types";
import { withFilter } from "graphql-subscriptions";
import { DspContext, pubsub } from "../context";

// TODO: add logger to context for sunscription
import { logger } from "../logger";
import { DspContext } from "../context";

const ACCOUNT_CREATED = 'ACCOUNT_CREATED';

Expand Down Expand Up @@ -132,12 +129,12 @@ export const accountResolvers/*: Resolvers*/ = {
accountCreated: {
subscribe: withFilter(
(_: any, varibles: any, context: DspContext, info: any) => {
context.logger.info(`[accountsResolvers.accountCreated] subscribe ${varibles}`);
context.logger.debug(`[accountsResolvers.accountCreated] subscribe ${JSON.stringify(varibles, null, 2)}`);
return context.pubsub.asyncIterator(ACCOUNT_CREATED);
},
(payload, variables, context: DspContext, info: any) => {
context.logger.debug(`accountCreated variables ${variables}`);
context.logger.info(`accountCreated payload ${payload}`);
context.logger.debug(`accountCreated variables ${JSON.stringify(variables, null, 2)}`);
context.logger.debug(`accountCreated payload ${JSON.stringify(payload, null, 2)}`);
return payload;
}
)
Expand Down
19 changes: 12 additions & 7 deletions backend/dsp-service/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ApolloServer } from '@apollo/server';

import { ExpressContextFunctionArgument, expressMiddleware } from '@apollo/server/express4';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import { ApolloServerPluginLandingPageLocalDefault } from '@apollo/server/plugin/landingPage/default';
import { createServer } from 'http';
Expand All @@ -26,6 +26,7 @@ import { resolvers } from './resolvers';
import { DspContext, makeRequestContext, pubsub, prisma, makeWebSocketContext } from './context';

import { corsOptions } from './cors';
import { ClerkExpressWithAuth, LooseAuthProp, WithAuthProp } from '@clerk/clerk-sdk-node';

const PORT = (process.env.PORT) ? Number.parseInt(process.env.PORT) : 4000;

Expand Down Expand Up @@ -86,7 +87,7 @@ async function listen() {
// WebSocketServer start listening.
const serverCleanup = useServer({
schema: graphSchema,
context: async (args: ExpressContextFunctionArgument) => {
context: async (args: any) => {
return makeWebSocketContext(args);
},
onConnect: async (ctx: any) => {
Expand Down Expand Up @@ -166,11 +167,15 @@ async function listen() {
'/graphql',
cors(corsOptions),
json(),
expressMiddleware(server, {
context: async (args: ExpressContextFunctionArgument) => {
return makeRequestContext(args);
},
}),
ClerkExpressWithAuth(),
expressMiddleware(server,
{
context: async (args: any) => {
// console.log(`[server] expressMiddleware context ${JSON.stringify(args, undefined, 2)}`);
return await makeRequestContext(args);
},
}
),
);


Expand Down