Преглед изворни кода

fix(core): Fix cookie auth for custom controller routes

Fixes #362
Michael Bromley пре 5 година
родитељ
комит
e36b9dbc25
2 измењених фајлова са 16 додато и 19 уклоњено
  1. 0 11
      packages/core/src/app.module.ts
  2. 16 8
      packages/core/src/bootstrap.ts

+ 0 - 11
packages/core/src/app.module.ts

@@ -4,10 +4,8 @@ import {
     NestModule,
     OnApplicationBootstrap,
     OnApplicationShutdown,
-    OnModuleInit,
 } from '@nestjs/common';
 import { ModuleRef } from '@nestjs/core';
-import cookieSession = require('cookie-session');
 import { RequestHandler } from 'express';
 
 import { ApiModule } from './api/api.module';
@@ -52,15 +50,6 @@ export class AppModule implements NestModule, OnApplicationBootstrap, OnApplicat
             { handler: i18nextHandler, route: adminApiPath },
             { handler: i18nextHandler, route: shopApiPath },
         ];
-        if (this.configService.authOptions.tokenMethod === 'cookie') {
-            const cookieHandler = cookieSession({
-                name: 'session',
-                secret: this.configService.authOptions.sessionSecret,
-                httpOnly: true,
-            });
-            defaultMiddleware.push({ handler: cookieHandler, route: adminApiPath });
-            defaultMiddleware.push({ handler: cookieHandler, route: shopApiPath });
-        }
         const allMiddleware = defaultMiddleware.concat(middleware);
         const middlewareByRoute = this.groupMiddlewareByRoute(allMiddleware);
         for (const [route, handlers] of Object.entries(middlewareByRoute)) {

+ 16 - 8
packages/core/src/bootstrap.ts

@@ -2,10 +2,10 @@ import { INestApplication, INestMicroservice } from '@nestjs/common';
 import { NestFactory } from '@nestjs/core';
 import { TcpClientOptions, Transport } from '@nestjs/microservices';
 import { Type } from '@vendure/common/lib/shared-types';
+import cookieSession = require('cookie-session');
 import { ConnectionOptions, EntitySubscriberInterface } from 'typeorm';
 
 import { InternalServerError } from './common/error/errors';
-import { ReadOnlyRequired } from './common/types/common-types';
 import { getConfig, setConfig } from './config/config-helpers';
 import { DefaultLogger } from './config/logger/default-logger';
 import { Logger } from './config/logger/vendure-logger';
@@ -53,6 +53,14 @@ export async function bootstrap(userConfig: Partial<VendureConfig>): Promise<INe
     DefaultLogger.restoreOriginalLogLevel();
     app.useLogger(new Logger());
     await runBeforeBootstrapHooks(config, app);
+    if (config.authOptions.tokenMethod === 'cookie') {
+        const cookieHandler = cookieSession({
+            name: 'session',
+            secret: config.authOptions.sessionSecret,
+            httpOnly: true,
+        });
+        app.use(cookieHandler);
+    }
     await app.listen(port, hostname || '');
     app.enableShutdownHooks();
     if (config.workerOptions.runInMainProcess) {
@@ -198,7 +206,7 @@ export async function getAllEntities(userConfig: Partial<VendureConfig>): Promis
     // Check to ensure that no plugins are defining entities with names
     // which conflict with existing entities.
     for (const pluginEntity of pluginEntities) {
-        if (allEntities.find((e) => e.name === pluginEntity.name)) {
+        if (allEntities.find(e => e.name === pluginEntity.name)) {
             throw new InternalServerError(`error.entity-name-conflict`, { entityName: pluginEntity.name });
         } else {
             allEntities.push(pluginEntity);
@@ -223,7 +231,7 @@ function setExposedHeaders(config: Readonly<RuntimeVendureConfig>) {
             } else if (typeof exposedHeaders === 'string') {
                 exposedHeadersWithAuthKey = exposedHeaders
                     .split(',')
-                    .map((x) => x.trim())
+                    .map(x => x.trim())
                     .concat(authTokenHeaderKey);
             } else {
                 exposedHeadersWithAuthKey = exposedHeaders.concat(authTokenHeaderKey);
@@ -303,18 +311,18 @@ function logWelcomeMessage(config: RuntimeVendureConfig) {
     apiCliGreetings.push(...getProxyMiddlewareCliGreetings(config));
     const columnarGreetings = arrangeCliGreetingsInColumns(apiCliGreetings);
     const title = `Vendure server (v${version}) now running on port ${port}`;
-    const maxLineLength = Math.max(title.length, ...columnarGreetings.map((l) => l.length));
+    const maxLineLength = Math.max(title.length, ...columnarGreetings.map(l => l.length));
     const titlePadLength = title.length < maxLineLength ? Math.floor((maxLineLength - title.length) / 2) : 0;
     Logger.info(`=`.repeat(maxLineLength));
     Logger.info(title.padStart(title.length + titlePadLength));
     Logger.info('-'.repeat(maxLineLength).padStart(titlePadLength));
-    columnarGreetings.forEach((line) => Logger.info(line));
+    columnarGreetings.forEach(line => Logger.info(line));
     Logger.info(`=`.repeat(maxLineLength));
 }
 
 function arrangeCliGreetingsInColumns(lines: Array<[string, string]>): string[] {
-    const columnWidth = Math.max(...lines.map((l) => l[0].length)) + 2;
-    return lines.map((l) => `${(l[0] + ':').padEnd(columnWidth)}${l[1]}`);
+    const columnWidth = Math.max(...lines.map(l => l[0].length)) + 2;
+    return lines.map(l => `${(l[0] + ':').padEnd(columnWidth)}${l[1]}`);
 }
 
 /**
@@ -341,7 +349,7 @@ function checkForDeprecatedOptions(config: Partial<VendureConfig>) {
         'middleware',
         'apolloServerPlugins',
     ];
-    const deprecatedOptionsUsed = deprecatedApiOptions.filter((option) => config.hasOwnProperty(option));
+    const deprecatedOptionsUsed = deprecatedApiOptions.filter(option => config.hasOwnProperty(option));
     if (deprecatedOptionsUsed.length) {
         throw new Error(
             `The following VendureConfig options are deprecated: ${deprecatedOptionsUsed.join(', ')}\n` +