Skip to content

Commit

Permalink
fix: handle versioning in url properly
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianbrs committed Feb 4, 2022
1 parent 27d3fac commit 5c35623
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions lib/oidc.controller.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,32 @@
import {
All,
Controller,
Inject,
Req,
Res,
VersioningType,
VERSION_NEUTRAL,
} from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import { Request, Response } from 'express';
import { Provider } from 'oidc-provider';
import { OIDC_PATH } from './oidc.constants';
import { PATH_METADATA, VERSION_METADATA } from '@nestjs/common/constants';

@Controller()
export class OidcController {
private callback: (req: Request, res: Response) => void;

constructor(
readonly provider: Provider,
@Inject(OIDC_PATH) private readonly oidcPath: string,
private readonly moduleRef: ModuleRef,
) {
this.callback = provider.callback();
}

private getUrl(originalUrl: string) {
let resultUrl = originalUrl;
const appConfig = this.moduleRef['container']?.applicationConfig;
const globalPrefix = appConfig?.getGlobalPrefix();
const versioning = appConfig?.getVersioning();
const appConfig = this.moduleRef['container']!.applicationConfig;
const globalPrefix = appConfig!.getGlobalPrefix();
const versioning = appConfig!.getVersioning();

// Remove global prefix
if (globalPrefix) {
Expand All @@ -36,17 +35,21 @@ export class OidcController {

// Remove version
if (versioning?.type === VersioningType.URI) {
const prefix = versioning.prefix ?? 'v';
const versionRegex = new RegExp(`^\/*${prefix}[^\/]+`);
resultUrl = resultUrl.replace(versionRegex, '');
const version: string | symbol =
Reflect.getMetadata(VERSION_METADATA, OidcController) ??
versioning.defaultVersion;

if (version && version !== VERSION_NEUTRAL) {
resultUrl = resultUrl.replace(/^\/*[^\/]+/, '');
}
}

// Remove controller path
if (this.oidcPath && this.oidcPath !== '/') {
resultUrl = resultUrl.replace(this.oidcPath, '');
}
const controllerPath = Reflect.getMetadata(PATH_METADATA, OidcController);
resultUrl = resultUrl.replace(controllerPath, '');

return resultUrl.replace(/^\/+/, '/');
// Normalize
return `/${resultUrl}`.replace(/^\/+/, '/');
}

@All('/*')
Expand Down

0 comments on commit 5c35623

Please sign in to comment.