Skip to content

Commit

Permalink
Merge pull request #19 from gobeam/fix/winston
Browse files Browse the repository at this point in the history
Fix/winston
  • Loading branch information
gobeam committed Aug 1, 2022
2 parents 374ab98 + 7def76f commit cab6282
Show file tree
Hide file tree
Showing 8 changed files with 1,921 additions and 1,407 deletions.
26 changes: 22 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,21 @@ jobs:
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}

- name: Setup yarn
run: npm install -g yarn

- name: Setup Nodejs with yarn caching
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
cache: yarn

- name: Install dependencies
run: npm install
run: yarn

- name: Run unit test
run: npm run test:unit
run: yarn test:unit

e2e-test:
runs-on: ubuntu-latest
Expand All @@ -34,15 +44,23 @@ jobs:
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
- name: Setup yarn
run: npm install -g yarn

- name: Setup Nodejs with yarn caching
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
cache: yarn
- name: Set Environment Variables
uses: ./.github/actions/setvars
with:
varFilePath: ./.github/variables/myvars.env
- name: Start Docker-Compose
run: docker-compose -f docker-compose-test.yml up -d
- name: Install dependencies
run: npm install
run: yarn
- name: Run tests
run: npm run test:e2e
run: yarn test:e2e
- name: Stop Docker-Compose
run: docker-compose -f docker-compose-test.yml down
11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "truthy-api",
"version": "0.3.1",
"version": "0.3.3",
"description": "Truthy API",
"author": "gobeam <[email protected]>",
"license": "MIT",
Expand Down Expand Up @@ -34,14 +34,14 @@
"dependencies": {
"@aws-sdk/client-cloudwatch-logs": "^3.54.1",
"@faker-js/faker": "^6.0.0",
"@nestjs-modules/mailer": "^1.6.1",
"@nestjs-modules/mailer": "^1.8.1",
"@nestjs/bull": "^0.5.3",
"@nestjs/common": "^8.4.1",
"@nestjs/core": "^8.4.1",
"@nestjs/jwt": "^8.0.0",
"@nestjs/mapped-types": "^1.0.1",
"@nestjs/passport": "^8.2.1",
"@nestjs/platform-express": "^8.4.1",
"@nestjs/platform-express": "^9.0.5",
"@nestjs/serve-static": "^2.2.2",
"@nestjs/swagger": "^5.2.0",
"@nestjs/throttler": "^2.0.1",
Expand All @@ -55,13 +55,14 @@
"config": "^3.3.7",
"cookie-parser": "^1.4.6",
"coveralls": "^3.1.1",
"helmet": "^5.1.1",
"ioredis": "^4.28.5",
"nest-winston": "^1.6.2",
"nestjs-i18n": "^8.2.2",
"nestjs-throttler-storage-redis": "^0.1.18",
"nodemailer": "^6.7.2",
"otplib": "^12.0.1",
"passport": "^0.5.2",
"passport": "^0.6.0",
"passport-jwt": "^4.0.0",
"pg": "^8.7.3",
"pug": "^3.0.2",
Expand All @@ -80,7 +81,7 @@
"devDependencies": {
"@commitlint/cli": "^16.2.3",
"@commitlint/config-conventional": "^16.2.1",
"@nestjs/cli": "^8.2.3",
"@nestjs/cli": "^9.0.0",
"@nestjs/schematics": "^8.0.8",
"@nestjs/testing": "^8.4.1",
"@types/bull": "^3.15.8",
Expand Down
15 changes: 10 additions & 5 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,12 +212,17 @@ export class AuthController {
@Res()
response: Response
) {
const refreshCookie = req.cookies['Refresh'];
if (refreshCookie) {
await this.authService.revokeRefreshToken(req.cookies['Refresh']);
try {
const cookie = req.cookies['Refresh'];
response.setHeader('Set-Cookie', this.authService.getCookieForLogOut());
const refreshCookie = req.cookies['Refresh'];
if (refreshCookie) {
await this.authService.revokeRefreshToken(cookie);
}
return response.sendStatus(HttpStatus.NO_CONTENT);
} catch (e) {
return response.sendStatus(HttpStatus.NO_CONTENT);
}
response.setHeader('Set-Cookie', this.authService.getCookieForLogOut());
return response.sendStatus(HttpStatus.NO_CONTENT);
}

@UseGuards(JwtTwoFactorGuard)
Expand Down
16 changes: 14 additions & 2 deletions src/common/exception/exception-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,19 @@ import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException
HttpException,
Inject
} from '@nestjs/common';
import { Response } from 'express';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { Logger } from 'winston';

@Catch(HttpException)
export class CommonExceptionFilter implements ExceptionFilter {
constructor(private readonly i18n: I18nService) {}
constructor(
@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
private readonly i18n: I18nService
) {}

async catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
Expand All @@ -26,6 +32,12 @@ export class CommonExceptionFilter implements ExceptionFilter {
args: message.args
});

this.logger.error('Error: ', {
meta: {
error: message
}
});

response.status(statusCode).json({
statusCode,
message
Expand Down
21 changes: 13 additions & 8 deletions src/config/winston.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,27 @@ import { WinstonModuleOptions } from 'nest-winston';
import * as WinstonCloudWatch from 'winston-cloudwatch';
import * as config from 'config';

const isProduction = process.env.APP_ENV === 'production';
const isProduction = process.env.NODE_ENV === 'production';
const winstonConfig = config.get('winston');

export default {
format: winston.format.uncolorize(),
level: isProduction ? 'error' : 'info',
format: winston.format.colorize(),
exitOnError: false,
transports: isProduction
? new WinstonCloudWatch({
name: 'Truthy CMS',
awsOptions: {
credentials: {
accessKeyId:
process.env.AWS_ACCESS_KEY || winstonConfig.awsAccessKeyId,
secretAccessKey:
process.env.AWS_KEY_SECRET || winstonConfig.awsSecretAccessKey
}
},
logGroupName:
process.env.CLOUDWATCH_GROUP_NAME || winstonConfig.groupName,
logStreamName:
process.env.CLOUDWATCH_STREAM_NAME || winstonConfig.streamName,
awsAccessKeyId:
process.env.AWS_ACCESS_KEY || winstonConfig.awsAccessKeyId,
awsSecretKey:
process.env.AWS_KEY_SECRET || winstonConfig.awsSecretAccessKey,
awsRegion: process.env.CLOUDWATCH_AWS_REGION || winstonConfig.awsRegion,
messageFormatter: function (item) {
return (
Expand All @@ -33,7 +36,9 @@ export default {
format: winston.format.combine(
winston.format.timestamp(),
winston.format.ms(),
nestWinstonModuleUtilities.format.nestLike()
nestWinstonModuleUtilities.format.nestLike('Truthy Logger', {
prettyPrint: true
})
)
})
} as WinstonModuleOptions;
23 changes: 14 additions & 9 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
import { NestFactory } from '@nestjs/core';
import { Logger, ValidationPipe } from '@nestjs/common';
import { ValidationPipe } from '@nestjs/common';
import { useContainer } from 'class-validator';
import * as config from 'config';
import helmet from 'helmet';
import {
DocumentBuilder,
SwaggerCustomOptions,
SwaggerModule
} from '@nestjs/swagger';
import * as cookieParser from 'cookie-parser';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';

import { AppModule } from 'src/app.module';

async function bootstrap() {
const logger = new Logger('bootstrap');
const serverConfig = config.get('server');
const port = process.env.PORT || serverConfig.port;
const app = await NestFactory.create(AppModule);
app.use(helmet());
app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER));
const apiConfig = config.get('app');
if (process.env.NODE_ENV === 'development') {
app.enableCors({
Expand All @@ -38,15 +41,17 @@ async function bootstrap() {
const document = SwaggerModule.createDocument(app, swaggerConfig);
SwaggerModule.setup('api-docs', app, document, customOptions);
} else {
const whitelist = [apiConfig.get<string>('frontendUrl')];
app.enableCors({
origin: process.env.ORIGIN || serverConfig.origin,
origin: function (origin, callback) {
if (!origin || whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true
});
logger.log(
`Accepting request only from: ${
process.env.ORIGIN || serverConfig.origin
}`
);
}
useContainer(app.select(AppModule), {
fallbackOnErrors: true
Expand All @@ -61,7 +66,7 @@ async function bootstrap() {

app.use(cookieParser());
await app.listen(port);
logger.log(`Application listening in port: ${port}`);
console.log(`Application listening in port: ${port}`);
}

bootstrap();
8 changes: 6 additions & 2 deletions src/refresh-token/refresh-token.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,16 @@ export class RefreshTokenService {
const token = await this.repository.createRefreshToken(user, refreshToken);
const opts: SignOptions = {
...BASE_OPTIONS,
expiresIn: tokenConfig.refreshExpiresIn,
subject: String(user.id),
jwtid: String(token.id)
};

return this.jwt.signAsync({ ...opts });
return this.jwt.signAsync(
{ ...opts },
{
expiresIn: tokenConfig.refreshExpiresIn
}
);
}

/**
Expand Down
Loading

0 comments on commit cab6282

Please sign in to comment.