Skip to content

Commit

Permalink
feat: adding strategy for jwt validation (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
nathan2slime authored Jul 11, 2024
1 parent 52a340c commit 9c4f629
Show file tree
Hide file tree
Showing 17 changed files with 710 additions and 19 deletions.
6 changes: 5 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
PORT=
DATABASE_URL=
DATABASE_URL="mongodb://user:password@mongo:27017/morgoth?directConnection=true&serverSelectionTimeoutMS=2000&authSource=admin&appName=mongosh+2.2.6"

MONGO_INITDB_ROOT_USERNAME="user"
MONGO_INITDB_ROOT_PASSWORD="password"
MONGO_INITDB_ROOT_DATABASE="morgoth"
1 change: 1 addition & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"@typescript-eslint/interface-name-prefix": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/no-explicit-any": "off"
}
}
13 changes: 13 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
services:
mongo:
image: mongo
restart: unless-stopped
env_file:
- .env.production.local
ports:
- '27017:27017'
healthcheck:
test: [ 'CMD', 'mongo', 'admin', '--port', '27017', '--eval', "db.adminCommand('ping').ok" ]
interval: 5s
timeout: 2s
retries: 20
11 changes: 11 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,26 +26,37 @@
"@commitlint/config-conventional": "^19.2.2",
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/jwt": "^10.2.0",
"@nestjs/mongoose": "^10.0.10",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/terminus": "^10.2.3",
"@typescript-eslint/eslint-plugin": "^7.16.0",
"@typescript-eslint/parser": "^7.16.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"commitizen": "^4.3.0",
"dotenv": "^16.4.5",
"husky": "^9.0.11",
"lint-staged": "^15.2.7",
"mongoose": "^8.5.0",
"mongoose-paginate": "^5.0.3",
"passport-jwt": "^4.0.1",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1",
"winston": "^3.13.1",
"znv": "^0.4.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
"@nestjs/schematics": "^10.0.0",
"@nestjs/swagger": "^7.4.0",
"@nestjs/testing": "^10.0.0",
"@types/express": "^4.17.17",
"@types/jest": "^29.5.2",
"@types/node": "^20.3.1",
"@types/passport-jwt": "^4.0.1",
"@types/supertest": "^6.0.0",
"cz-conventional-changelog": "^3.3.0",
"eslint": "^8.42.0",
Expand Down
592 changes: 577 additions & 15 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

12 changes: 11 additions & 1 deletion src/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';

import { AppController } from './app.controller';
import { AppService } from './app.service';
import { env } from '~/env';

@Module({
imports: [],
imports: [
MongooseModule.forRoot(env.DATABASE_URL, {
connectionFactory: connection => {
connection.plugin(require('mongoose-paginate'));

return connection;
},
}),
],
controllers: [AppController],
providers: [AppService],
})
Expand Down
Empty file added src/auth/auth.controller.ts
Empty file.
3 changes: 3 additions & 0 deletions src/auth/auth.decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { Reflector } from '@nestjs/core';

export const Roles = Reflector.createDecorator<string[]>();
19 changes: 19 additions & 0 deletions src/auth/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import {
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
return super.canActivate(context);
}

handleRequest(err: Error, user: any) {
if (err || !user) throw err || new UnauthorizedException();

return user;
}
}
Empty file added src/auth/auth.module.ts
Empty file.
Empty file added src/auth/auth.service.ts
Empty file.
29 changes: 29 additions & 0 deletions src/auth/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';

import { env } from '~/env';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: env.SECRET_KEY,
});
}

async validate(payload: Record<string, string>) {
// const user = await this.prisma.user.findUnique({
// where: { id: payload.user },
// select: {
// id: true,
// },
// });

// if (user) return user;

throw new UnauthorizedException();
}
}
Empty file added src/auth/refresh.strategy.ts
Empty file.
Empty file.
1 change: 1 addition & 0 deletions src/env/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ config();

export const env = parseEnv(process.env, {
DATABASE_URL: z.string().url(),
SECRET_KEY: z.string().min(4),
PORT: z.string().min(1),
});
14 changes: 14 additions & 0 deletions src/logger/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { createLogger, format, transports } from 'winston';
import { join } from 'node:path';

export const logger = createLogger({
format: format.json(),
transports: [
new transports.Console(),
new transports.File({
level: 'error',
filename: join(__dirname, 'logs', 'error.log'),
}),
new transports.File({ filename: join(__dirname, 'logs', 'debug.log') }),
],
});
28 changes: 26 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,34 @@
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';

import { env } from '~/env';

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

import 'reflect-metadata';
import { logger } from '~/logger';

(async () => {
const app = await NestFactory.create(AppModule);
await app.listen(env.PORT);
const app = await NestFactory.create(AppModule, { });
app.useGlobalPipes(
new ValidationPipe({
transform: true,
}),
);

const config = new DocumentBuilder()
.setTitle('Morgoth')
.setDescription('Docs')
.setVersion('1.0')
.build();

app.setGlobalPrefix('api');

const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api/docs', app, document);

await app.listen(env.PORT, () =>
logger.error('app running in http://localhost:'.concat(env.PORT)),
);
})();

0 comments on commit 9c4f629

Please sign in to comment.