Skip to content

Commit

Permalink
fix(lint): apply prettier rules (#971)
Browse files Browse the repository at this point in the history
  • Loading branch information
garrappachc authored Apr 9, 2021
1 parent 9b41b8a commit b7b3e89
Show file tree
Hide file tree
Showing 220 changed files with 11,069 additions and 6,559 deletions.
7 changes: 4 additions & 3 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:jest/recommended"
"plugin:jest/recommended",
"plugin:prettier/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
Expand All @@ -17,7 +18,7 @@
"createDefaultProgram": true
},
"plugins": [
"@typescript-eslint",
"@typescript-eslint/eslint-plugin",
"jest"
],
"rules": {
Expand All @@ -29,7 +30,7 @@
},
"overrides": [
{
"files": ["*.spec.ts"],
"files": ["*.spec.ts", "**/__mocks__/**"],
"env": {
"jest/globals": true
},
Expand Down
9,368 changes: 5,571 additions & 3,797 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,9 @@
"@typescript-eslint/parser": "4.21.0",
"copyfiles": "2.4.1",
"eslint": "7.23.0",
"eslint-config-prettier": "8.1.0",
"eslint-plugin-jest": "24.3.4",
"eslint-plugin-prettier": "3.3.1",
"jest": "26.6.3",
"mongodb-memory-server": "6.9.6",
"prettier": "2.2.1",
Expand Down
4 changes: 1 addition & 3 deletions src/app.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@ describe('AppController', () => {
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [
{ provide: Environment, useClass: EnvironmentStub },
],
providers: [{ provide: Environment, useClass: EnvironmentStub }],
}).compile();

appController = app.get<AppController>(AppController);
Expand Down
5 changes: 1 addition & 4 deletions src/app.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ import { Environment } from './environment/environment';

@Controller()
export class AppController {

constructor(
private environment: Environment,
) { }
constructor(private environment: Environment) {}

@Get()
index() {
Expand Down
14 changes: 5 additions & 9 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ import { createMongoDbUri } from './utils/create-mongo-db-uri';
},
}),
TypegooseModule.forRootAsync({
imports: [ EnvironmentModule ],
inject: [ Environment ],
imports: [EnvironmentModule],
inject: [Environment],
useFactory: async (environment: Environment) => ({
uri: createMongoDbUri({
host: environment.mongoDbHost,
Expand Down Expand Up @@ -74,11 +74,7 @@ import { createMongoDbUri } from './utils/create-mongo-db-uri';
PluginsModule.configure(),
LogReceiverModule,
],
controllers: [
AppController,
],
providers: [
AppService,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule { }
export class AppModule {}
60 changes: 36 additions & 24 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,57 +25,69 @@ const passportModule = PassportModule.register({
@Module({
imports: [
passportModule,
TypegooseModule.forFeature([ RefreshToken, Key ]),
TypegooseModule.forFeature([RefreshToken, Key]),

PlayersModule,
],
providers: [
{
// keys used to sign & validate auth JWT
provide: 'AUTH_TOKEN_KEY',
inject: [ getModelToken(Key.name), Environment ],
useFactory: async (keyModel: ReturnModelType<typeof Key>, environment: Environment) =>
await importOrGenerateKeys(keyModel, KeyName.auth, environment.keyStorePassphare),
inject: [getModelToken(Key.name), Environment],
useFactory: async (
keyModel: ReturnModelType<typeof Key>,
environment: Environment,
) =>
await importOrGenerateKeys(
keyModel,
KeyName.auth,
environment.keyStorePassphare,
),
},
{
// keys used to sign & validate refresh JWT
provide: 'REFRESH_TOKEN_KEY',
inject: [ getModelToken(Key.name), Environment ],
useFactory: async (keyModel: ReturnModelType<typeof Key>, environment: Environment) =>
await importOrGenerateKeys(keyModel, KeyName.refresh, environment.keyStorePassphare),
inject: [getModelToken(Key.name), Environment],
useFactory: async (
keyModel: ReturnModelType<typeof Key>,
environment: Environment,
) =>
await importOrGenerateKeys(
keyModel,
KeyName.refresh,
environment.keyStorePassphare,
),
},
{
provide: 'WEBSOCKET_SECRET',
useFactory: () => generate({ length: 32, numbers: true, uppercase: true }),
useFactory: () =>
generate({ length: 32, numbers: true, uppercase: true }),
},
{
provide: 'CONTEXT_TOKEN_KEY',
inject: [ getModelToken(Key.name), Environment ],
useFactory: async (keyModel: ReturnModelType<typeof Key>, environment: Environment) =>
await importOrGenerateKeys(keyModel, KeyName.context, environment.keyStorePassphare),
inject: [getModelToken(Key.name), Environment],
useFactory: async (
keyModel: ReturnModelType<typeof Key>,
environment: Environment,
) =>
await importOrGenerateKeys(
keyModel,
KeyName.context,
environment.keyStorePassphare,
),
},
AuthService,
SteamStrategy,
JwtStrategy,
AuthGateway,
],
controllers: [
AuthController,
],
exports: [
passportModule,
AuthService,
],
controllers: [AuthController],
exports: [passportModule, AuthService],
})
export class AuthModule implements NestModule {

configure(consumer: MiddlewareConsumer) {
consumer
.apply(
setRedirectUrlCookie,
authenticate('steam', { session: false }),
)
.apply(setRedirectUrlCookie, authenticate('steam', { session: false }))
.forRoutes('/auth/steam');
}

}
35 changes: 26 additions & 9 deletions src/auth/controllers/auth.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,13 @@ class HttpAdapterHostStub {
}

class AuthServiceStub {
authToken = 'eyJhbGciOiJFUzUxMiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkNDQ4ODc1Yjk2M2ZmN2UwMGM2YjZiMyIsImlhdCI6MTU3Njc5NzQxNCwiZXhwIjoxNTc2Nzk4MzE0fQ.AXeWhEMSRS_kB7ISiRUt5vk9T71_mXUWevl_wT_tnyiS9vHQScMIY4qVzQnrx21FUwfyAmUVOdRdFNPpndGFPW4kARaPbeVkOSgF4vPt4MHJqvlXrA-B97Z7u9ahRqMFcdNyCIWbbR-bQ4592TJLdoGdx1Mqbc0brSYDlLaaG2aGPYN';
refreshToken = 'eyJhbGciOiJFUzUxMiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkNDQ4ODc1Yjk2M2ZmN2UwMGM2YjZiMyIsImlhdCI6MTU3Njc5NzQxNCwiZXhwIjoxNTc3NDAyMjE0fQ.AAOwakFw8lKXRwmeLqPWksQTKjXqYVAb-Gc_sXhXolU36fPr69Flxgf5c2YZ6qCghZlloZ3TR5PaJ1PT3b2s1je5AfQw01fcZ56E10LGUyfLvV02Mgy5ler9PzbLi7sZzRs1QgDUeq3Ml9WYRIZirP_r9VxVS_4eDluP3NNlpFVqymDs';
generateJwtToken(name: string, userId: string) { return ''; }
authToken =
'eyJhbGciOiJFUzUxMiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkNDQ4ODc1Yjk2M2ZmN2UwMGM2YjZiMyIsImlhdCI6MTU3Njc5NzQxNCwiZXhwIjoxNTc2Nzk4MzE0fQ.AXeWhEMSRS_kB7ISiRUt5vk9T71_mXUWevl_wT_tnyiS9vHQScMIY4qVzQnrx21FUwfyAmUVOdRdFNPpndGFPW4kARaPbeVkOSgF4vPt4MHJqvlXrA-B97Z7u9ahRqMFcdNyCIWbbR-bQ4592TJLdoGdx1Mqbc0brSYDlLaaG2aGPYN';
refreshToken =
'eyJhbGciOiJFUzUxMiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkNDQ4ODc1Yjk2M2ZmN2UwMGM2YjZiMyIsImlhdCI6MTU3Njc5NzQxNCwiZXhwIjoxNTc3NDAyMjE0fQ.AAOwakFw8lKXRwmeLqPWksQTKjXqYVAb-Gc_sXhXolU36fPr69Flxgf5c2YZ6qCghZlloZ3TR5PaJ1PT3b2s1je5AfQw01fcZ56E10LGUyfLvV02Mgy5ler9PzbLi7sZzRs1QgDUeq3Ml9WYRIZirP_r9VxVS_4eDluP3NNlpFVqymDs';
generateJwtToken(name: string, userId: string) {
return '';
}
refreshTokens(oldToken: string) {
return {
authToken: this.authToken,
Expand Down Expand Up @@ -63,20 +67,33 @@ describe('Auth Controller', () => {
});

it('should reject if the old refresh token is not present', async () => {
await expect(controller.refreshToken(undefined)).rejects.toThrow(BadRequestException);
await expect(controller.refreshToken(undefined)).rejects.toThrow(
BadRequestException,
);
});

it('should be rejected if the token is invalid', async () => {
jest.spyOn(authService, 'refreshTokens').mockRejectedValue('invalid token' as never);
await expect(controller.refreshToken('OLD_REFRESH_TOKEN')).rejects.toThrow(BadRequestException)
jest
.spyOn(authService, 'refreshTokens')
.mockRejectedValue('invalid token' as never);
await expect(
controller.refreshToken('OLD_REFRESH_TOKEN'),
).rejects.toThrow(BadRequestException);
});
});

describe('#refreshWsToken()', () => {
it('should generate ws token', async () => {
const spy = jest.spyOn(authService, 'generateJwtToken').mockImplementation(() => 'FAKE_WS_TOKEN');
const result = await controller.refreshWsToken({ id: 'FAKE_USER_ID' } as Player);
expect(spy).toHaveBeenCalledWith(JwtTokenPurpose.websocket, 'FAKE_USER_ID');
const spy = jest
.spyOn(authService, 'generateJwtToken')
.mockImplementation(() => 'FAKE_WS_TOKEN');
const result = await controller.refreshWsToken({
id: 'FAKE_USER_ID',
} as Player);
expect(spy).toHaveBeenCalledWith(
JwtTokenPurpose.websocket,
'FAKE_USER_ID',
);
expect(result).toEqual({ wsToken: 'FAKE_WS_TOKEN' });
});
});
Expand Down
63 changes: 43 additions & 20 deletions src/auth/controllers/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { Controller, Get, Post, Query, BadRequestException, Logger } from '@nestjs/common';
import {
Controller,
Get,
Post,
Query,
BadRequestException,
Logger,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import { authenticate } from 'passport';
import { Environment } from '@/environment/environment';
Expand All @@ -11,7 +18,6 @@ import { JwtTokenPurpose } from '../jwt-token-purpose';

@Controller('auth')
export class AuthController {

private logger = new Logger(AuthController.name);

constructor(
Expand All @@ -22,31 +28,46 @@ export class AuthController {
// The steam return route has to be defined like that. Any nestjs route decorators
// would screw up some request params, resulting in OpenID throwing an error.
// https://github.com/liamcurry/passport-steam/issues/57
this.adapterHost.httpAdapter?.get('/auth/steam/return', (req, res, next) => {
return authenticate('steam', async (error, player: Player) => {
const url = req.cookies?.[redirectUrlCookieName] || this.environment.clientUrl;
this.adapterHost.httpAdapter?.get(
'/auth/steam/return',
(req, res, next) => {
return authenticate('steam', async (error, player: Player) => {
const url =
req.cookies?.[redirectUrlCookieName] || this.environment.clientUrl;

if (error) {
this.logger.warn(`Login error: ${error}`);
return res.redirect(`${url}/auth-error?error=${error.message}`);
}
if (error) {
this.logger.warn(`Login error: ${error}`);
return res.redirect(`${url}/auth-error?error=${error.message}`);
}

if (!player) {
return res.sendStatus(401);
}
if (!player) {
return res.sendStatus(401);
}

const refreshToken = await this.authService.generateJwtToken(JwtTokenPurpose.refresh, player.id);
const authToken = await this.authService.generateJwtToken(JwtTokenPurpose.auth, player.id);
return res.redirect(`${url}?refresh_token=${refreshToken}&auth_token=${authToken}`);
})(req, res, next);
});
const refreshToken = await this.authService.generateJwtToken(
JwtTokenPurpose.refresh,
player.id,
);
const authToken = await this.authService.generateJwtToken(
JwtTokenPurpose.auth,
player.id,
);
return res.redirect(
`${url}?refresh_token=${refreshToken}&auth_token=${authToken}`,
);
})(req, res, next);
},
);
}

@Post()
async refreshToken(@Query('refresh_token') oldRefreshToken: string) {
if (oldRefreshToken !== undefined) {
try {
const { refreshToken, authToken } = await this.authService.refreshTokens(oldRefreshToken);
const {
refreshToken,
authToken,
} = await this.authService.refreshTokens(oldRefreshToken);
return { refreshToken, authToken };
} catch (error) {
throw new BadRequestException(error.message);
Expand All @@ -59,8 +80,10 @@ export class AuthController {
@Get('wstoken')
@Auth()
async refreshWsToken(@User() user: Player) {
const wsToken = await this.authService.generateJwtToken(JwtTokenPurpose.websocket, user.id);
const wsToken = await this.authService.generateJwtToken(
JwtTokenPurpose.websocket,
user.id,
);
return { wsToken };
}

}
5 changes: 4 additions & 1 deletion src/auth/decorators/user.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';

// tslint:disable-next-line: variable-name
export const User = createParamDecorator((data: unknown, ctx: ExecutionContext) => ctx.switchToHttp().getRequest().user);
export const User = createParamDecorator(
(data: unknown, ctx: ExecutionContext) =>
ctx.switchToHttp().getRequest().user,
);
4 changes: 1 addition & 3 deletions src/auth/decorators/ws-authorized.decorator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,5 @@ import { applyDecorators, UseGuards } from '@nestjs/common';
import { WsAuthorizedGuard } from '../guards/ws-authorized.guard';

export function WsAuthorized() {
return applyDecorators(
UseGuards(WsAuthorizedGuard),
);
return applyDecorators(UseGuards(WsAuthorizedGuard));
}
2 changes: 0 additions & 2 deletions src/auth/errors/invalid-token.error.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
export class InvalidTokenError extends Error {

constructor() {
super('invalid token');
}

}
8 changes: 4 additions & 4 deletions src/auth/gateways/auth.gateway.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import { Test, TestingModule } from '@nestjs/testing';
import { AuthGateway } from './auth.gateway';
import { PlayersService } from '@/players/services/players.service';

class PlayersServiceStub {

}
class PlayersServiceStub {}

describe('AuthGateway', () => {
let gateway: AuthGateway;
Expand All @@ -26,7 +24,9 @@ describe('AuthGateway', () => {
});

describe('#onModuleInit()', () => {
beforeEach(() => gateway.server = { use: jest.fn().mockReturnValue(null) } as any);
beforeEach(
() => (gateway.server = { use: jest.fn().mockReturnValue(null) } as any),
);

it('should register middleware', () => {
gateway.onModuleInit();
Expand Down
Loading

0 comments on commit b7b3e89

Please sign in to comment.