diff --git a/src/auth.ts b/src/auth.ts index 0d3035c..67f990f 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -32,6 +32,14 @@ function getBearerToken(req: FastifyRequest): string { return token; } +function optionalBearerToken(req: FastifyRequest): string | null { + const auth = req.headers.authorization || ""; + if (!auth.startsWith("Bearer ")) return null; + const token = auth.slice(7); + if (!token || token === "undefined") return null; + return token; +} + function scopesFromPayload(payload: JWTPayload): string[] { const scope = payload.scope; if (!scope) return []; @@ -98,7 +106,8 @@ export async function teamContext(req: FastifyRequest): Promise { export async function managerContext( req: FastifyRequest, ): Promise { - const token = getBearerToken(req); + const token = optionalBearerToken(req); + if (token === null) return { scopes: [] }; const { payload } = await jwtVerify(token, jwks, { issuer: LOGTO_ISSUER, audience: LOGTO_ORDERS_AUDIENCE, diff --git a/src/index.ts b/src/index.ts index 3bef980..71f0627 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,12 +28,6 @@ if (SENTRY_DSN) { const app = Fastify(); await app.register(cors, { origin: ["https://optovia.ru"], credentials: true }); -type GraphqlBody = { - query?: string; - variables?: Record; - operationName?: string; -}; - async function registerGraphqlEndpoint( server: FastifyInstance, path: string, @@ -46,19 +40,9 @@ async function registerGraphqlEndpoint( await route.register(mercurius, { schema, resolvers: resolvers as never, - routes: false, - }); - route.post("/", async (request, reply) => { - const body = request.body as GraphqlBody; - if (typeof body.query !== "string") { - throw new Error("GraphQL query is required"); - } - return reply.graphql( - body.query, - (await context(request)) as Record, - body.variables, - body.operationName, - ); + path: "/", + context: async (request) => + (await context(request as FastifyRequest)) as Record, }); }, { prefix: path },