Skip to content

Commit

Permalink
breaking(nestjs8): Upgrading library to nestjs8. (#31)
Browse files Browse the repository at this point in the history
  • Loading branch information
benMain authored Nov 29, 2021
1 parent 4a28f7b commit 3594ad4
Show file tree
Hide file tree
Showing 11 changed files with 3,525 additions and 4,572 deletions.
24 changes: 24 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import { Module } from '@nestjs/common';
],
serviceTokens: ['random-string-generated-by-you'], // option - used to allow service-to-service communication, ala AWS x-api-key
enableDebugLogs: true, // optional - false by default
tokenHeader: 'authorization' // The Header in which the jwt appears defaults to 'authtoken' by default.
}),
],
controllers: [AppController],
Expand Down
7,930 changes: 3,435 additions & 4,495 deletions package-lock.json

Large diffs are not rendered by default.

59 changes: 29 additions & 30 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,54 +31,53 @@
"scripts": {
"build": "tsc -p tsconfig.build.json",
"format": "prettier --write \"src/**/*.ts\"",
"lint": "tslint -p tsconfig.json -c tslint.json",
"lint:fix": "node --max_old_space_size=8000 ./node_modules/tslint/bin/tslint -p tsconfig.json -c tslint.json --fix --force",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:cov": "jest --coverage",
"release": "semantic-release",
"release-local": "node -r dotenv/config node_modules/semantic-release/bin/semantic-release --no-ci --dry-run"
},
"dependencies": {
"@nestjs/common": "^7.0.8",
"jsonwebtoken": "^8.5.1"
},
"peerDependencies": {
"@nestjs/core": "^7.0.8",
"@nestjs/common": "^8.2.3",
"@nestjs/core": "^8.2.3",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.5.5"
"rxjs": "^7.2.0"
},
"devDependencies": {
"@nestjs/common": "^7.0.8",
"@nestjs/core": "^7.0.8",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.5.5",
"@nestjs/testing": "^7.0.8",
"@nestjs/common": "^8.2.3",
"@nestjs/core": "^8.2.3",
"@semantic-release/changelog": "^5.0.1",
"@semantic-release/git": "^9.0.0",
"@types/express": "^4.17.6",
"@types/jest": "^25.2.1",
"@types/jsonwebtoken": "^8.3.9",
"@types/node": "^12.7.5",
"@types/supertest": "^2.0.8",
"concurrently": "^5.1.0",
"husky": "^4.2.5",
"@nestjs/testing": "^8.0.0",
"@types/express": "^4.17.13",
"@types/jest": "27.0.2",
"@types/node": "^16.0.0",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"husky": "^7.0.4",
"import-sort-style-eslint": "^6.0.0",
"jest": "^25.3.0",
"jest": "^27.2.5",
"lint-staged": "^10.1.3",
"nodemon": "^2.0.3",
"prettier": "^2.0.4",
"prettier": "^2.3.2",
"prettier-plugin-import-sort": "0.0.4",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0",
"semantic-release": "^17.0.4",
"supertest": "^4.0.2",
"ts-jest": "25.3.1",
"ts-node": "8.8.2",
"tsconfig-paths": "3.9.0",
"tslint": "6.1.1",
"tslint-config-prettier": "^1.18.0",
"typescript": "3.8.3",
"wait-on": "^4.0.2"
"supertest": "^6.1.3",
"ts-jest": "^27.0.3",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "^3.10.1",
"typescript": "^4.3.5"
},
"release": {
"branch": "master",
Expand Down Expand Up @@ -153,7 +152,7 @@
},
"lint-staged": {
"*.js": [
"tslint -p tsconfig.json -c tslint.json",
"eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"jest --findRelatedTests"
],
"./**/*.{js,json,css,md}": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ describe('AzureTokenValidationService', () => {
AzureTokenValidationService,
);
httpService = module.get<HttpService>(HttpService);
servicePrivate = (service as any) as AzureTokenValidationServicePrivate;
servicePrivate = service as any as AzureTokenValidationServicePrivate;
verifyMock = jest.spyOn(servicePrivate, 'verifyToken');
getTokensMock = jest.spyOn(httpService, 'get');
getTokensMock.mockReturnValue(
Expand Down Expand Up @@ -116,6 +116,7 @@ describe('AzureTokenValidationService', () => {
const response = await service.isTokenValid(testToken);
const response2 = await service.isTokenValid(testToken2);
expect(response[0]).toBeTruthy();
expect(response2[0]).toBeFalsy();
expect(getTokensMock).toHaveBeenCalledTimes(2);
expect(verifyMock).toHaveBeenCalledTimes(1);
});
Expand All @@ -132,6 +133,8 @@ describe('AzureTokenValidationService', () => {
testToken,
);
expect(response).toBeFalsy();
expect(user).toBeFalsy();
expect(isServiceToken).toBeTruthy();
expect(getTokensMock).toHaveBeenCalledTimes(1);
expect(verifyMock).toHaveBeenCalledTimes(1);
});
Expand All @@ -141,6 +144,8 @@ describe('AzureTokenValidationService', () => {
'fdae',
);
expect(response).toBeFalsy();
expect(user).toBeFalsy();
expect(isServiceToken).toBeTruthy();
expect(getTokensMock).toHaveBeenCalledTimes(1);
expect(verifyMock).toHaveBeenCalledTimes(0);
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { AzureAdUser, JwtKey, JwtPayload, TokenHeader } from '../models';
import { HttpService, Inject, Injectable, Logger } from '@nestjs/common';
import { HttpService, Injectable, Logger } from '@nestjs/common';

import { EOL } from 'os';
import { NestAzureAdJwtValidatorModuleOptions } from '../module-config';
Expand Down
17 changes: 3 additions & 14 deletions src/guards/azure-active-directory.guard.spec.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
import { AxiosRequestConfig, AxiosResponse } from 'axios';
import { AzureAdUser, JwtKey, JwtPayload } from '../models';
import {
Controller,
ExecutionContext,
Get,
HttpService,
Injectable,
Module,
SetMetadata,
} from '@nestjs/common';
import { ExecutionContext, HttpService, SetMetadata } from '@nestjs/common';
import { Observable, Observer } from 'rxjs';
import { Test, TestingModule } from '@nestjs/testing';

import { AxiosResponse } from 'axios';
import { AzureActiveDirectoryGuard } from './azure-active-directory.guard';
import { AzureTokenValidationService } from '../azure-token-validation';
import { NestAzureAdJwtValidatorModuleOptions } from '../module-config';
Expand All @@ -20,10 +12,6 @@ import { readFileSync } from 'fs';

export const Roles = (...roles: string[]) => SetMetadata('roles', roles);

interface AzureTokenValidationServicePrivate {
verifyToken: () => JwtPayload;
}

describe('AzureActiveDirectoryGuard', () => {
let guard: AzureActiveDirectoryGuard;
let service: AzureTokenValidationService;
Expand Down Expand Up @@ -147,6 +135,7 @@ describe('AzureActiveDirectoryGuard', () => {
expect(canActivate).toEqual(true);
expect(tokenValidateMock).toHaveBeenCalledTimes(1);
expect(tokenValidateMock).toHaveBeenCalledWith('12345A');
expect(getAzureUserFromTokenMock).not.toHaveBeenCalled();
});
it('should activate for valid token with roles', async () => {
tokenValidateMock.mockResolvedValue([true, mockUser as any, false]);
Expand Down
16 changes: 5 additions & 11 deletions src/guards/azure-active-directory.guard.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {
CanActivate,
ExecutionContext,
Inject,
Injectable,
Logger,
} from '@nestjs/common';
Expand All @@ -22,11 +21,8 @@ export class AzureActiveDirectoryGuard implements CanActivate {

async canActivate(context: ExecutionContext): Promise<boolean> {
const accessToken = this.parseTokenFromContext(context);
const [
isTokenValid,
user,
isServiceToken,
] = await this.tokenValidationService.isTokenValid(accessToken);
const [isTokenValid, user, isServiceToken] =
await this.tokenValidationService.isTokenValid(accessToken);

// token is not valid exit
if (!isTokenValid) {
Expand All @@ -50,11 +46,9 @@ export class AzureActiveDirectoryGuard implements CanActivate {

private parseTokenFromContext(context: ExecutionContext): string {
const request = context.switchToHttp().getRequest<IncomingMessage>();
const tokenHeader = request.headers.authtoken;
return (!!tokenHeader ? tokenHeader.toString() : '')
.trim()
.split(' ')
.pop();
const header = this.options.tokenHeader ?? 'authtoken';
const token = request.headers[header];
return (!!token ? token.toString() : '').trim().split(' ').pop();
}

private matchRoles(roles: string[], usersRoles: string[]) {
Expand Down
17 changes: 17 additions & 0 deletions src/module-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,31 @@ export type AsyncProvider<T> =
| ImportableFactoryProvider<T>
| Omit<ValueProvider<T>, 'provide'>;

/**
* An interface representing the shape of the tenant and app you are wanting to authenticate against.
*/
export interface TenantApplication {
tenantId: string;
audienceId: string;
}

export class NestAzureAdJwtValidatorModuleOptions {
/**
* The apps in question
*/
apps: TenantApplication[];
/**
* Service Tokens allow you to shortcut jwt authentication for clients that are unsophisticated
*/
serviceTokens?: string[];
/**
* Enable Debug Logging
*/
enableDebugLogs?: boolean;
/**
* Which header does the jwt appear in? If unspecified... defaults to authtoken header.
*/
tokenHeader?: string;

constructor(partial: Partial<NestAzureAdJwtValidatorModuleOptions>) {
Object.assign(this, partial);
Expand All @@ -33,5 +49,6 @@ export class NestAzureAdJwtValidatorModuleOptions {
this.serviceTokens = this.serviceTokens.filter((x) => !!x);

this.enableDebugLogs = !!this.enableDebugLogs;
this.tokenHeader = partial.tokenHeader;
}
}
6 changes: 4 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,7 @@
"baseUrl": "./",
"incremental": true
},
"exclude": ["node_modules"]
}
"exclude": [
"node_modules"
]
}
18 changes: 0 additions & 18 deletions tslint.json

This file was deleted.

0 comments on commit 3594ad4

Please sign in to comment.