Skip to content

Commit

Permalink
fix(core): Fix cookie auth for custom controller routes
Browse files Browse the repository at this point in the history
Fixes #362
  • Loading branch information
michaelbromley committed Jun 4, 2020
1 parent 699c796 commit e36b9db
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 19 deletions.
11 changes: 0 additions & 11 deletions packages/core/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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)) {
Expand Down
24 changes: 16 additions & 8 deletions packages/core/src/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
Expand All @@ -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);
Expand Down Expand Up @@ -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]}`);
}

/**
Expand All @@ -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` +
Expand Down

0 comments on commit e36b9db

Please sign in to comment.