├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── README.md ├── nest-cli.json ├── package-lock.json ├── package.json ├── src ├── app.controller.spec.ts ├── app.controller.ts ├── app.module.ts ├── app.service.ts ├── auth │ ├── auth.controller.ts │ ├── auth.module.ts │ ├── auth.service.ts │ ├── dto │ │ ├── authenticate.dto.ts │ │ └── profile.dto.ts │ ├── interfaces │ │ └── user.interface.ts │ ├── jwt-auth.guard.ts │ ├── jwt.strategy.ts │ ├── role.guard.ts │ └── roles.decorator.ts └── main.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | tsconfigRootDir : __dirname, 6 | sourceType: 'module', 7 | }, 8 | plugins: ['@typescript-eslint/eslint-plugin'], 9 | extends: [ 10 | 'plugin:@typescript-eslint/recommended', 11 | 'plugin:prettier/recommended', 12 | ], 13 | root: true, 14 | env: { 15 | node: true, 16 | jest: true, 17 | }, 18 | ignorePatterns: ['.eslintrc.js'], 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/explicit-module-boundary-types': 'off', 23 | '@typescript-eslint/no-explicit-any': 'off', 24 | }, 25 | }; 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | pnpm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # OS 15 | .DS_Store 16 | 17 | # Tests 18 | /coverage 19 | /.nyc_output 20 | 21 | # IDEs and editors 22 | /.idea 23 | .project 24 | .classpath 25 | .c9/ 26 | *.launch 27 | .settings/ 28 | *.sublime-workspace 29 | 30 | # IDE - VSCode 31 | .vscode/* 32 | !.vscode/settings.json 33 | !.vscode/tasks.json 34 | !.vscode/launch.json 35 | !.vscode/extensions.json -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | Nest Logo 3 |

4 | 5 | [circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456 6 | [circleci-url]: https://circleci.com/gh/nestjs/nest 7 | 8 |

A progressive Node.js framework for building efficient and scalable server-side applications.

9 |

10 | NPM Version 11 | Package License 12 | NPM Downloads 13 | CircleCI 14 | Coverage 15 | Discord 16 | Backers on Open Collective 17 | Sponsors on Open Collective 18 | 19 | Support us 20 | 21 |

22 | 24 | 25 | ## Description 26 | 27 | [Nest](https://github.com/nestjs/nest) framework TypeScript starter repository. 28 | 29 | ## Installation 30 | 31 | ```bash 32 | $ npm install 33 | ``` 34 | 35 | ## Running the app 36 | 37 | ```bash 38 | # development 39 | $ npm run start 40 | 41 | # watch mode 42 | $ npm run start:dev 43 | 44 | # production mode 45 | $ npm run start:prod 46 | ``` 47 | 48 | ## Test 49 | 50 | ```bash 51 | # unit tests 52 | $ npm run test 53 | 54 | # e2e tests 55 | $ npm run test:e2e 56 | 57 | # test coverage 58 | $ npm run test:cov 59 | ``` 60 | 61 | ## Support 62 | 63 | Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support). 64 | 65 | ## Stay in touch 66 | 67 | - Author - [Kamil Myśliwiec](https://kamilmysliwiec.com) 68 | - Website - [https://nestjs.com](https://nestjs.com/) 69 | - Twitter - [@nestframework](https://twitter.com/nestframework) 70 | 71 | ## License 72 | 73 | Nest is [MIT licensed](LICENSE). 74 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/nest-cli", 3 | "collection": "@nestjs/schematics", 4 | "sourceRoot": "src" 5 | } 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "auth-app", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "prebuild": "rimraf dist", 10 | "build": "nest build", 11 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 12 | "start": "nest start", 13 | "start:dev": "nest start --watch", 14 | "start:debug": "nest start --debug --watch", 15 | "start:prod": "node dist/main", 16 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 17 | "test": "jest", 18 | "test:watch": "jest --watch", 19 | "test:cov": "jest --coverage", 20 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 21 | "test:e2e": "jest --config ./test/jest-e2e.json" 22 | }, 23 | "dependencies": { 24 | "@nestjs/common": "^9.0.0", 25 | "@nestjs/core": "^9.0.0", 26 | "@nestjs/jwt": "^9.0.0", 27 | "@nestjs/passport": "^9.0.0", 28 | "@nestjs/platform-express": "^9.0.0", 29 | "class-validator": "^0.13.2", 30 | "jsonwebtoken": "^8.5.1", 31 | "passport": "^0.6.0", 32 | "passport-jwt": "^4.0.0", 33 | "reflect-metadata": "^0.1.13", 34 | "rimraf": "^3.0.2", 35 | "rxjs": "^7.2.0" 36 | }, 37 | "devDependencies": { 38 | "@faker-js/faker": "^7.3.0", 39 | "@nestjs/cli": "^9.0.0", 40 | "@nestjs/schematics": "^9.0.0", 41 | "@nestjs/testing": "^9.0.0", 42 | "@types/express": "^4.17.13", 43 | "@types/jest": "28.1.4", 44 | "@types/jsonwebtoken": "^8.5.8", 45 | "@types/node": "^16.0.0", 46 | "@types/passport-jwt": "^3.0.6", 47 | "@types/supertest": "^2.0.11", 48 | "@typescript-eslint/eslint-plugin": "^5.0.0", 49 | "@typescript-eslint/parser": "^5.0.0", 50 | "eslint": "^8.0.1", 51 | "eslint-config-prettier": "^8.3.0", 52 | "eslint-plugin-prettier": "^4.0.0", 53 | "jest": "28.1.2", 54 | "prettier": "^2.3.2", 55 | "source-map-support": "^0.5.20", 56 | "supertest": "^6.1.3", 57 | "ts-jest": "28.0.5", 58 | "ts-loader": "^9.2.3", 59 | "ts-node": "^10.0.0", 60 | "tsconfig-paths": "4.0.0", 61 | "typescript": "^4.3.5" 62 | }, 63 | "jest": { 64 | "moduleFileExtensions": [ 65 | "js", 66 | "json", 67 | "ts" 68 | ], 69 | "rootDir": "src", 70 | "testRegex": ".*\\.spec\\.ts$", 71 | "transform": { 72 | "^.+\\.(t|j)s$": "ts-jest" 73 | }, 74 | "collectCoverageFrom": [ 75 | "**/*.(t|j)s" 76 | ], 77 | "coverageDirectory": "../coverage", 78 | "testEnvironment": "node" 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/app.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | 5 | describe('AppController', () => { 6 | let appController: AppController; 7 | 8 | beforeEach(async () => { 9 | const app: TestingModule = await Test.createTestingModule({ 10 | controllers: [AppController], 11 | providers: [AppService], 12 | }).compile(); 13 | 14 | appController = app.get(AppController); 15 | }); 16 | 17 | describe('root', () => { 18 | it('should return "Hello World!"', () => { 19 | expect(appController.getHello()).toBe('Hello World!'); 20 | }); 21 | }); 22 | }); 23 | -------------------------------------------------------------------------------- /src/app.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get } from '@nestjs/common'; 2 | import { AppService } from './app.service'; 3 | 4 | @Controller() 5 | export class AppController { 6 | constructor(private readonly appService: AppService) {} 7 | 8 | @Get() 9 | getHello(): string { 10 | return this.appService.getHello(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | import { AuthController } from './auth/auth.controller'; 5 | import { AuthService } from './auth/auth.service'; 6 | import { AuthModule } from './auth/auth.module'; 7 | import { PassportModule } from '@nestjs/passport'; 8 | import { JwtModule } from '@nestjs/jwt'; 9 | import { JwtStrategy } from './auth/jwt.strategy'; 10 | 11 | @Module({ 12 | imports: [ 13 | AuthModule, 14 | PassportModule, 15 | JwtModule.register({ secret: 'secrete', signOptions: { expiresIn: '1h' } }), 16 | ], 17 | controllers: [AppController, AuthController], 18 | providers: [AppService, AuthService, JwtStrategy], 19 | }) 20 | export class AppModule {} 21 | -------------------------------------------------------------------------------- /src/app.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | 3 | @Injectable() 4 | export class AppService { 5 | getHello(): string { 6 | return 'Hello World!'; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/auth/auth.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Body, 3 | Controller, 4 | Get, 5 | HttpStatus, 6 | Post, 7 | Req, 8 | Res, 9 | UseGuards, 10 | } from '@nestjs/common'; 11 | import { AuthService } from './auth.service'; 12 | import { AuthenticateDto } from './dto/authenticate.dto'; 13 | import { JwtAuthGuard } from './jwt-auth.guard'; 14 | import { RoleGuard } from './role.guard'; 15 | import { Roles } from './roles.decorator'; 16 | 17 | @Controller('auth') 18 | export class AuthController { 19 | constructor(private readonly authService: AuthService) {} 20 | 21 | @Post() 22 | login(@Res() res, @Body() authenticateDto: AuthenticateDto) { 23 | try { 24 | const response = this.authService.authenticate(authenticateDto); 25 | return res.status(HttpStatus.OK).json({ response }); 26 | } catch (error) { 27 | return res.status(error.status).json(error.response); 28 | } 29 | } 30 | 31 | @Roles('customer') 32 | @UseGuards(JwtAuthGuard, RoleGuard) 33 | @Get() 34 | profile(@Req() req, @Res() res) { 35 | return res.status(HttpStatus.OK).json(req.user); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AuthService } from './auth.service'; 3 | import { AuthController } from './auth.controller'; 4 | 5 | @Module({ 6 | providers: [AuthService], 7 | controllers: [AuthController], 8 | }) 9 | export class AuthModule {} 10 | -------------------------------------------------------------------------------- /src/auth/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, NotFoundException } from '@nestjs/common'; 2 | import { faker } from '@faker-js/faker'; 3 | import { sign } from 'jsonwebtoken'; 4 | import { AuthenticateDto } from './dto/authenticate.dto'; 5 | import { IAuthenticate, Role } from './interfaces/user.interface'; 6 | 7 | @Injectable() 8 | export class AuthService { 9 | users = [ 10 | { 11 | id: faker.datatype.uuid(), 12 | userName: 'Terrence Ratke', 13 | password: 'terrence', 14 | role: Role.Admin, 15 | }, 16 | { 17 | id: faker.datatype.uuid(), 18 | userName: 'Samoa Jo', 19 | password: 'samoa', 20 | role: Role.Customer, 21 | }, 22 | ]; 23 | 24 | authenticate(authenticateDto: AuthenticateDto): IAuthenticate { 25 | const user = this.users.find( 26 | (u) => 27 | u.userName === authenticateDto.userName && 28 | u.password === authenticateDto.password, 29 | ); 30 | 31 | if (!user) throw new NotFoundException('Invalid credentials'); 32 | 33 | const token = sign({ ...user }, 'secrete'); 34 | 35 | return { token, user }; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/auth/dto/authenticate.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsNotEmpty, IsString } from 'class-validator'; 2 | 3 | export class AuthenticateDto { 4 | @IsNotEmpty() 5 | @IsString() 6 | readonly userName: string; 7 | 8 | @IsNotEmpty() 9 | @IsString() 10 | readonly password: string; 11 | } 12 | -------------------------------------------------------------------------------- /src/auth/dto/profile.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsNotEmpty, IsString } from 'class-validator'; 2 | import { Role } from '../interfaces/user.interface'; 3 | 4 | export class ProfileDto { 5 | @IsNotEmpty() 6 | @IsString() 7 | readonly id: string; 8 | 9 | @IsNotEmpty() 10 | @IsString() 11 | readonly userName: string; 12 | 13 | @IsNotEmpty() 14 | @IsString() 15 | readonly password: string; 16 | 17 | @IsNotEmpty() 18 | @IsString() 19 | readonly role: Role; 20 | } 21 | -------------------------------------------------------------------------------- /src/auth/interfaces/user.interface.ts: -------------------------------------------------------------------------------- 1 | export enum Role { 2 | Admin = 'admin', 3 | Customer = 'customer', 4 | } 5 | 6 | type User = { 7 | id: string; 8 | userName: string; 9 | password: string; 10 | role: Role; 11 | }; 12 | 13 | export interface IAuthenticate { 14 | readonly user: User; 15 | readonly token: string; 16 | } 17 | -------------------------------------------------------------------------------- /src/auth/jwt-auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { AuthGuard } from '@nestjs/passport'; 3 | 4 | @Injectable() 5 | export class JwtAuthGuard extends AuthGuard('jwt') {} 6 | -------------------------------------------------------------------------------- /src/auth/jwt.strategy.ts: -------------------------------------------------------------------------------- 1 | import { ExtractJwt, Strategy } from 'passport-jwt'; 2 | import { PassportStrategy } from '@nestjs/passport'; 3 | import { Injectable } from '@nestjs/common'; 4 | 5 | @Injectable() 6 | export class JwtStrategy extends PassportStrategy(Strategy) { 7 | constructor() { 8 | super({ 9 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 10 | ignoreExpiration: false, 11 | secretOrKey: 'secrete', 12 | }); 13 | } 14 | 15 | async validate(payload) { 16 | return { 17 | userId: payload.id, 18 | userName: payload.userName, 19 | role: payload.role, 20 | }; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/auth/role.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; 2 | import { Reflector } from '@nestjs/core'; 3 | 4 | @Injectable() 5 | export class RoleGuard implements CanActivate { 6 | constructor(private reflector: Reflector) {} 7 | 8 | matchRoles(roles: string[], userRole: string) { 9 | return roles.some((role) => role === userRole); 10 | } 11 | 12 | canActivate(context: ExecutionContext): boolean { 13 | const roles = this.reflector.get('roles', context.getHandler()); 14 | if (!roles) { 15 | return true; 16 | } 17 | const request = context.switchToHttp().getRequest(); 18 | const user = request.user; 19 | return this.matchRoles(roles, user.role); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/auth/roles.decorator.ts: -------------------------------------------------------------------------------- 1 | import { SetMetadata } from '@nestjs/common'; 2 | 3 | export const Roles = (...args: string[]) => SetMetadata('roles', args); 4 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | 4 | async function bootstrap() { 5 | const app = await NestFactory.create(AppModule); 6 | await app.listen(3000); 7 | } 8 | bootstrap(); 9 | -------------------------------------------------------------------------------- /test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from './../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); 13 | 14 | app = moduleFixture.createNestApplication(); 15 | await app.init(); 16 | }); 17 | 18 | it('/ (GET)', () => { 19 | return request(app.getHttpServer()) 20 | .get('/') 21 | .expect(200) 22 | .expect('Hello World!'); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "es2017", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true, 14 | "skipLibCheck": true, 15 | "strictNullChecks": false, 16 | "noImplicitAny": false, 17 | "strictBindCallApply": false, 18 | "forceConsistentCasingInFileNames": false, 19 | "noFallthroughCasesInSwitch": false 20 | } 21 | } 22 | --------------------------------------------------------------------------------