├── .dockerignore ├── .eslintrc.js ├── .github └── FUNDING.yml ├── .gitignore ├── .prettierrc ├── Dockerfile ├── README.md ├── docker-compose.yml ├── nest-cli.json ├── package-lock.json ├── package.json ├── postman-collection └── NestJS-Auth-Jwt.postman_collection.json ├── src ├── app.controller.spec.ts ├── app.controller.ts ├── app.module.ts ├── app.service.ts ├── auth │ ├── auth.module.ts │ ├── guards │ │ └── jwt-auth.guard.ts │ ├── services │ │ └── auth │ │ │ ├── auth.service.spec.ts │ │ │ └── auth.service.ts │ └── strategies │ │ └── jwt.strategy.ts ├── main.ts └── user │ ├── controller │ ├── user.controller.spec.ts │ └── user.controller.ts │ ├── models │ ├── dto │ │ ├── CreateUser.dto.ts │ │ └── LoginUser.dto.ts │ ├── user.entity.ts │ └── user.interface.ts │ ├── service │ ├── user.service.spec.ts │ └── user.service.ts │ └── user.module.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | npm-debug.log -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | sourceType: 'module', 6 | }, 7 | plugins: ['@typescript-eslint/eslint-plugin'], 8 | extends: [ 9 | 'plugin:@typescript-eslint/eslint-recommended', 10 | 'plugin:@typescript-eslint/recommended', 11 | 'prettier', 12 | 'prettier/@typescript-eslint', 13 | ], 14 | root: true, 15 | env: { 16 | node: true, 17 | jest: true, 18 | }, 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/no-explicit-any': 'off', 23 | }, 24 | }; 25 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: ThomasOliver545 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | yarn-debug.log* 10 | yarn-error.log* 11 | lerna-debug.log* 12 | 13 | # OS 14 | .DS_Store 15 | 16 | # Tests 17 | /coverage 18 | /.nyc_output 19 | 20 | # IDEs and editors 21 | /.idea 22 | .project 23 | .classpath 24 | .c9/ 25 | *.launch 26 | .settings/ 27 | *.sublime-workspace 28 | 29 | # IDE - VSCode 30 | .vscode/* 31 | !.vscode/settings.json 32 | !.vscode/tasks.json 33 | !.vscode/launch.json 34 | !.vscode/extensions.json -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:14 2 | 3 | # Create app directory, this is in our container/in our image 4 | WORKDIR /thomas/src/app 5 | 6 | # Install app dependencies 7 | # A wildcard is used to ensure both package.json AND package-lock.json are copied 8 | # where available (npm@5+) 9 | COPY package*.json ./ 10 | 11 | RUN npm install 12 | # If you are building your code for production 13 | # RUN npm ci --only=production 14 | 15 | # Bundle app source 16 | COPY . . 17 | 18 | RUN npm run build 19 | 20 | EXPOSE 8080 21 | CMD [ "node", "dist/main" ] -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # General Information 2 | This Repository is about implementing Jwt Authorization with NestJs. 3 | The Youtube Playlist for this repository can be found here: https://www.youtube.com/playlist?list=PLVfq1luIZbSmjsLsM04De_eltKTX0lz7f 4 | 5 | This Repository is a clone of the Project "nestjs-dockerized" (see more under Concept of the series). 6 | 7 | In the folder 'postman-collection' you find a collection of postman requests that you can import into postman and execute against the api. 8 | 9 | ## Start Commands for docker-compose file and information 10 | Builds, (re)creates, starts, and attaches to containers for a service. 11 | `docker-compose up` 12 | Information: 13 | - Database can be accessed with PG-Admin via `localhost:5050` and then connect your database (see youtube playlist) 14 | - NestJS Api can be accessed on `localhost:8080/api` (see youtube playlist) 15 | 16 | # Concept of the series: 17 | 18 | With every series we clone/fork the last project, so that the code is always up to date with the according project. 19 | 20 | List in Order with all Youtube Playlists and Repository Links: 21 | 22 | 01. NestJS Dockerized 23 | Clone/Fork of: None 24 | Repo-Link: https://github.com/ThomasOliver545/nestjs-dockerized 25 | Youtube-Playlist: https://www.youtube.com/playlist?list=PLVfq1luIZbSlIzPhcm6bBV2h82nSYS6gK 26 | 27 | 02. NestJS Auth Jwt 28 | Clone/Fork of: 1. NestJS Dockerized 29 | Repo-Link: https://github.com/ThomasOliver545/nestjs-auth-jwt 30 | Youtube-Playlist: https://www.youtube.com/playlist?list=PLVfq1luIZbSmjsLsM04De_eltKTX0lz7f 31 | 32 | # You need the installed tools 33 | - NPM 34 | - Node.js 35 | - NestJS 36 | - Docker 37 | 38 | # Basic Commands for Docker 39 | Basic Docker Commands: 40 | List your docker images: `docker images` 41 | List your running containers: `docker ps` 42 | List also stopped containers: `docker ps -a` 43 | Kill a running container: `docker kill `, eg `docker kill fea` 44 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.8" 2 | services: 3 | api: 4 | # image: thomas-oliver/nestjs-dockerized 5 | build: 6 | dockerfile: Dockerfile 7 | context: . 8 | depends_on: 9 | - postgres 10 | environment: 11 | DATABASE_URL: postgres://user:password@postgres:5432/db 12 | NODE_ENV: development 13 | JWT_SECRET: 1hard_to_guess_secret7890a 14 | PORT: 3000 15 | ports: 16 | - "8080:3000" 17 | 18 | postgres: 19 | image: postgres:10.4 20 | environment: 21 | POSTGRES_USER: user 22 | POSTGRES_PASSWORD: password 23 | POSTGRES_DB: db 24 | ports: 25 | - "35000:5432" 26 | 27 | ### Postgres Adminer ### 28 | postgres_admin: 29 | image: dpage/pgadmin4:4.28 30 | depends_on: 31 | - postgres 32 | environment: 33 | PGADMIN_DEFAULT_EMAIL: admin@admin.de 34 | PGADMIN_DEFAULT_PASSWORD: password 35 | ports: 36 | - "5050:80" 37 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nestjs-dockerized", 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": "^8.2.4", 25 | "@nestjs/config": "^1.1.5", 26 | "@nestjs/core": "^8.2.4", 27 | "@nestjs/jwt": "^8.0.0", 28 | "@nestjs/passport": "^8.0.1", 29 | "@nestjs/platform-express": "^8.2.4", 30 | "@nestjs/typeorm": "^8.0.2", 31 | "bcrypt": "^5.0.1", 32 | "class-transformer": "^0.4.0", 33 | "class-validator": "^0.13.1", 34 | "passport": "^0.4.1", 35 | "passport-jwt": "^4.0.0", 36 | "pg": "^8.6.0", 37 | "reflect-metadata": "^0.1.13", 38 | "rimraf": "^3.0.2", 39 | "rxjs": "^7.2.0", 40 | "typeorm": "^0.2.41" 41 | }, 42 | "devDependencies": { 43 | "@nestjs/cli": "^8.1.6", 44 | "@nestjs/schematics": "^8.0.5", 45 | "@nestjs/testing": "^8.2.4", 46 | "@types/express": "^4.17.13", 47 | "@types/jest": "27.0.2", 48 | "@types/node": "^16.0.0", 49 | "@types/supertest": "^2.0.11", 50 | "@typescript-eslint/eslint-plugin": "^5.0.0", 51 | "@typescript-eslint/parser": "^5.0.0", 52 | "eslint": "^8.0.1", 53 | "eslint-config-prettier": "^8.3.0", 54 | "eslint-plugin-prettier": "^4.0.0", 55 | "jest": "^27.2.5", 56 | "prettier": "^2.3.2", 57 | "supertest": "^6.1.3", 58 | "ts-jest": "^27.0.3", 59 | "ts-loader": "^9.2.3", 60 | "ts-node": "^10.0.0", 61 | "tsconfig-paths": "^3.10.1", 62 | "typescript": "^4.3.5" 63 | }, 64 | "jest": { 65 | "moduleFileExtensions": [ 66 | "js", 67 | "json", 68 | "ts" 69 | ], 70 | "rootDir": "src", 71 | "testRegex": ".spec.ts$", 72 | "transform": { 73 | "^.+\\.(t|j)s$": "ts-jest" 74 | }, 75 | "coverageDirectory": "../coverage", 76 | "testEnvironment": "node" 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /postman-collection/NestJS-Auth-Jwt.postman_collection.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "_postman_id": "1ec55610-3493-4caa-8124-a7927055cd1f", 4 | "name": "NestJS-Auth-Jwt", 5 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" 6 | }, 7 | "item": [ 8 | { 9 | "name": "Register a user", 10 | "request": { 11 | "method": "POST", 12 | "header": [], 13 | "body": { 14 | "mode": "raw", 15 | "raw": "{\r\n \"name\": \"thomas\",\r\n \"email\": \"thomas@test.de\",\r\n \"password\": \"password\"\r\n}", 16 | "options": { 17 | "raw": { 18 | "language": "json" 19 | } 20 | } 21 | }, 22 | "url": { 23 | "raw": "http://localhost:8080/api/users/", 24 | "protocol": "http", 25 | "host": [ 26 | "localhost" 27 | ], 28 | "port": "8080", 29 | "path": [ 30 | "api", 31 | "users", 32 | "" 33 | ] 34 | }, 35 | "description": "Email needed\r\npassword needed" 36 | }, 37 | "response": [] 38 | }, 39 | { 40 | "name": "Get All Users (PROTECTED WITH AUTH)", 41 | "request": { 42 | "auth": { 43 | "type": "bearer", 44 | "bearer": [ 45 | { 46 | "key": "token", 47 | "value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjozLCJuYW1lIjoidGhvbWFzIiwiZW1haWwiOiJ0aG9tYXNAbWFpbC5kZSJ9LCJpYXQiOjE2MTA0ODE4MDAsImV4cCI6MTYxMDQ5MTgwMH0.pQPHajn-x_KI5zGCIvNrKMvCo14HNrQ4zIgFjB6h9jQ", 48 | "type": "string" 49 | } 50 | ] 51 | }, 52 | "method": "GET", 53 | "header": [], 54 | "url": { 55 | "raw": "http://localhost:8080/api/users/", 56 | "protocol": "http", 57 | "host": [ 58 | "localhost" 59 | ], 60 | "port": "8080", 61 | "path": [ 62 | "api", 63 | "users", 64 | "" 65 | ] 66 | }, 67 | "description": "To make this request you need a valid jwt. \r\nYou can get this with the login request" 68 | }, 69 | "response": [] 70 | }, 71 | { 72 | "name": "Login User", 73 | "request": { 74 | "method": "POST", 75 | "header": [], 76 | "body": { 77 | "mode": "raw", 78 | "raw": "{\r\n \"email\": \"thomas@mail.de\",\r\n \"password\": \"password\"\r\n}", 79 | "options": { 80 | "raw": { 81 | "language": "json" 82 | } 83 | } 84 | }, 85 | "url": { 86 | "raw": "http://localhost:8080/api/users/login", 87 | "protocol": "http", 88 | "host": [ 89 | "localhost" 90 | ], 91 | "port": "8080", 92 | "path": [ 93 | "api", 94 | "users", 95 | "login" 96 | ] 97 | }, 98 | "description": "Returns a JWT\r\n\r\nemail needed\r\npassword needed" 99 | }, 100 | "response": [] 101 | } 102 | ] 103 | } -------------------------------------------------------------------------------- /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 | // Rest Call: GET http://localhost:8080/api/ 9 | @Get() 10 | getHello(): string { 11 | return this.appService.getHello(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | import {TypeOrmModule} from '@nestjs/typeorm'; 5 | import { ConfigModule } from '@nestjs/config'; 6 | import { UserModule } from './user/user.module'; 7 | import { AuthModule } from './auth/auth.module'; 8 | 9 | @Module({ 10 | imports: [ 11 | ConfigModule.forRoot({isGlobal: true}), 12 | TypeOrmModule.forRoot({ 13 | type: 'postgres', 14 | url: process.env.DATABASE_URL, 15 | autoLoadEntities: true, 16 | synchronize: true 17 | }), 18 | UserModule, 19 | AuthModule 20 | ], 21 | controllers: [AppController], 22 | providers: [AppService], 23 | }) 24 | export class AppModule {} 25 | -------------------------------------------------------------------------------- /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.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { ConfigModule, ConfigService } from '@nestjs/config'; 3 | import { JwtModule } from '@nestjs/jwt'; 4 | import { JwtAuthGuard } from './guards/jwt-auth.guard'; 5 | import { AuthService } from './services/auth/auth.service'; 6 | import { JwtStrategy } from './strategies/jwt.strategy'; 7 | 8 | @Module({ 9 | imports: [ 10 | JwtModule.registerAsync({ 11 | imports: [ConfigModule], 12 | inject: [ConfigService], 13 | useFactory: async (configService: ConfigService) => ({ 14 | secret: configService.get('JWT_SECRET'), 15 | signOptions: {expiresIn: '10000s'} 16 | }) 17 | }) 18 | ], 19 | providers: [AuthService, JwtStrategy, JwtAuthGuard], 20 | exports: [AuthService] 21 | }) 22 | export class AuthModule {} 23 | -------------------------------------------------------------------------------- /src/auth/guards/jwt-auth.guard.ts: -------------------------------------------------------------------------------- 1 | 2 | import { Injectable } from '@nestjs/common'; 3 | import { AuthGuard } from '@nestjs/passport'; 4 | 5 | @Injectable() 6 | export class JwtAuthGuard extends AuthGuard('jwt') {} -------------------------------------------------------------------------------- /src/auth/services/auth/auth.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AuthService } from './auth.service'; 3 | 4 | describe('AuthService', () => { 5 | let service: AuthService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [AuthService], 10 | }).compile(); 11 | 12 | service = module.get(AuthService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/auth/services/auth/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { JwtService } from '@nestjs/jwt'; 3 | import { from, Observable } from 'rxjs'; 4 | import { UserI } from 'src/user/models/user.interface'; 5 | const bcrypt = require ('bcrypt'); 6 | 7 | @Injectable() 8 | export class AuthService { 9 | 10 | constructor(private readonly jwtService: JwtService) {} 11 | 12 | generateJwt(user: UserI): Observable { 13 | return from(this.jwtService.signAsync({user})); 14 | } 15 | 16 | hashPassword(password: string): Observable { 17 | return from(bcrypt.hash(password, 12)); 18 | } 19 | 20 | comparePasswords(password: string, storedPasswordHash: string): Observable { 21 | return from(bcrypt.compare(password, storedPasswordHash)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/auth/strategies/jwt.strategy.ts: -------------------------------------------------------------------------------- 1 | 2 | import { ExtractJwt, Strategy } from 'passport-jwt'; 3 | import { PassportStrategy } from '@nestjs/passport'; 4 | import { Injectable } from '@nestjs/common'; 5 | import { ConfigService } from '@nestjs/config'; 6 | 7 | @Injectable() 8 | export class JwtStrategy extends PassportStrategy(Strategy) { 9 | 10 | constructor(private configService: ConfigService) { 11 | super({ 12 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 13 | ignoreExpiration: false, 14 | secretOrKey: configService.get('JWT_SECRET') 15 | }); 16 | } 17 | 18 | async validate(payload: any) { 19 | return { ...payload.user }; 20 | } 21 | } -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { ValidationPipe } from '@nestjs/common'; 2 | import { NestFactory } from '@nestjs/core'; 3 | import { AppModule } from './app.module'; 4 | 5 | async function bootstrap() { 6 | const app = await NestFactory.create(AppModule); 7 | app.setGlobalPrefix('api'); 8 | app.useGlobalPipes(new ValidationPipe()); 9 | await app.listen(3000); 10 | } 11 | bootstrap(); 12 | -------------------------------------------------------------------------------- /src/user/controller/user.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { UserController } from './user.controller'; 3 | 4 | describe('UserController', () => { 5 | let controller: UserController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | controllers: [UserController], 10 | }).compile(); 11 | 12 | controller = module.get(UserController); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(controller).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/user/controller/user.controller.ts: -------------------------------------------------------------------------------- 1 | import { Body, Controller, Get, HttpCode, Post, Req, UseGuards } from '@nestjs/common'; 2 | import { Observable } from 'rxjs'; 3 | import { map } from 'rxjs/operators'; 4 | import { JwtAuthGuard } from 'src/auth/guards/jwt-auth.guard'; 5 | import { CreateUserDto } from '../models/dto/CreateUser.dto'; 6 | import { LoginUserDto } from '../models/dto/LoginUser.dto'; 7 | import { UserI } from '../models/user.interface'; 8 | import { UserService } from '../service/user.service'; 9 | 10 | @Controller('users') 11 | export class UserController { 12 | 13 | constructor(private userService: UserService) { } 14 | 15 | // Rest Call: POST http://localhost:8080/api/users/ 16 | @Post() 17 | create(@Body() createdUserDto: CreateUserDto): Observable { 18 | return this.userService.create(createdUserDto); 19 | } 20 | 21 | // Rest Call: POST http://localhost:8080/api/users/login 22 | @Post('login') 23 | @HttpCode(200) 24 | login(@Body() loginUserDto: LoginUserDto): Observable { 25 | return this.userService.login(loginUserDto).pipe( 26 | map((jwt: string) => { 27 | return { 28 | access_token: jwt, 29 | token_type: 'JWT', 30 | expires_in: 10000 31 | } 32 | }) 33 | ); 34 | } 35 | 36 | // Rest Call: GET http://localhost:8080/api/users/ 37 | // Requires Valid JWT from Login Request 38 | @UseGuards(JwtAuthGuard) 39 | @Get() 40 | findAll(@Req() request): Observable { 41 | return this.userService.findAll(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/user/models/dto/CreateUser.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsString } from "class-validator"; 2 | import { LoginUserDto } from "./LoginUser.dto"; 3 | 4 | 5 | export class CreateUserDto extends LoginUserDto { 6 | 7 | @IsString() 8 | name: string; 9 | 10 | } -------------------------------------------------------------------------------- /src/user/models/dto/LoginUser.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsEmail, IsNotEmpty } from "class-validator"; 2 | 3 | export class LoginUserDto { 4 | 5 | @IsEmail() 6 | email: string; 7 | 8 | @IsNotEmpty() 9 | password: string; 10 | } -------------------------------------------------------------------------------- /src/user/models/user.entity.ts: -------------------------------------------------------------------------------- 1 | import { BeforeInsert, BeforeUpdate, Column, Entity, PrimaryGeneratedColumn } from "typeorm"; 2 | 3 | @Entity() 4 | export class UserEntity { 5 | 6 | @PrimaryGeneratedColumn() 7 | id: number; 8 | 9 | @Column() 10 | name: string; 11 | 12 | @Column({ unique: true }) 13 | email: string; 14 | 15 | @Column({ select: false }) 16 | password: string; 17 | 18 | @BeforeInsert() 19 | @BeforeUpdate() 20 | emailToLowerCase() { 21 | this.email = this.email.toLowerCase(); 22 | } 23 | } -------------------------------------------------------------------------------- /src/user/models/user.interface.ts: -------------------------------------------------------------------------------- 1 | export interface UserI { 2 | id: number; 3 | name: string; 4 | email: string; 5 | password?: string; 6 | } -------------------------------------------------------------------------------- /src/user/service/user.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { UserService } from './user.service'; 3 | 4 | describe('UserService', () => { 5 | let service: UserService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ 9 | providers: [UserService], 10 | }).compile(); 11 | 12 | service = module.get(UserService); 13 | }); 14 | 15 | it('should be defined', () => { 16 | expect(service).toBeDefined(); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/user/service/user.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; 2 | import { InjectRepository } from '@nestjs/typeorm'; 3 | import { from, Observable } from 'rxjs'; 4 | import { map, switchMap } from 'rxjs/operators'; 5 | import { AuthService } from 'src/auth/services/auth/auth.service'; 6 | import { Repository } from 'typeorm'; 7 | import { CreateUserDto } from '../models/dto/CreateUser.dto'; 8 | import { LoginUserDto } from '../models/dto/LoginUser.dto'; 9 | import { UserEntity } from '../models/user.entity'; 10 | import { UserI } from '../models/user.interface'; 11 | 12 | @Injectable() 13 | export class UserService { 14 | 15 | constructor( 16 | @InjectRepository(UserEntity) 17 | private userRepository: Repository, 18 | private authService: AuthService 19 | ) { } 20 | 21 | create(createdUserDto: CreateUserDto): Observable { 22 | const userEntity = this.userRepository.create(createdUserDto); 23 | 24 | return this.mailExists(userEntity.email).pipe( 25 | switchMap((exists: boolean) => { 26 | if (!exists) { 27 | return this.authService.hashPassword(userEntity.password).pipe( 28 | switchMap((passwordHash: string) => { 29 | // Overwrite the user password with the hash, to store it in the db 30 | userEntity.password = passwordHash; 31 | return from(this.userRepository.save(userEntity)).pipe( 32 | map((savedUser: UserI) => { 33 | const { password, ...user } = savedUser; 34 | return user; 35 | }) 36 | ) 37 | }) 38 | ) 39 | } else { 40 | throw new HttpException('Email already in use', HttpStatus.CONFLICT); 41 | } 42 | }) 43 | ) 44 | } 45 | 46 | login(loginUserDto: LoginUserDto): Observable { 47 | return this.findUserByEmail(loginUserDto.email.toLowerCase()).pipe( 48 | switchMap((user: UserI) => { 49 | if (user) { 50 | return this.validatePassword(loginUserDto.password, user.password).pipe( 51 | switchMap((passwordsMatches: boolean) => { 52 | if (passwordsMatches) { 53 | return this.findOne(user.id).pipe( 54 | switchMap((user: UserI) => this.authService.generateJwt(user)) 55 | ) 56 | } else { 57 | throw new HttpException('Login was not Successfulll', HttpStatus.UNAUTHORIZED); 58 | } 59 | }) 60 | ) 61 | } else { 62 | throw new HttpException('User not found', HttpStatus.NOT_FOUND); 63 | } 64 | } 65 | ) 66 | ) 67 | } 68 | 69 | findAll(): Observable { 70 | return from(this.userRepository.find()); 71 | } 72 | 73 | findOne(id: number): Observable { 74 | return from(this.userRepository.findOne({ id })); 75 | } 76 | 77 | private findUserByEmail(email: string): Observable { 78 | return from(this.userRepository.findOne({ email }, { select: ['id', 'email', 'name', 'password'] })); 79 | } 80 | 81 | private validatePassword(password: string, storedPasswordHash: string): Observable { 82 | return this.authService.comparePasswords(password, storedPasswordHash); 83 | } 84 | 85 | private mailExists(email: string): Observable { 86 | email = email.toLowerCase(); 87 | return from(this.userRepository.findOne({ email })).pipe( 88 | map((user: UserI) => { 89 | if (user) { 90 | return true; 91 | } else { 92 | return false; 93 | } 94 | }) 95 | ) 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/user/user.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { UserService } from './service/user.service'; 3 | import { UserController } from './controller/user.controller'; 4 | import { TypeOrmModule } from '@nestjs/typeorm'; 5 | import { UserEntity } from './models/user.entity'; 6 | import { AuthModule } from 'src/auth/auth.module'; 7 | 8 | @Module({ 9 | imports: [ 10 | TypeOrmModule.forFeature([UserEntity]), 11 | AuthModule 12 | ], 13 | providers: [UserService], 14 | controllers: [UserController] 15 | }) 16 | export class UserModule {} 17 | -------------------------------------------------------------------------------- /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 | } 15 | } 16 | --------------------------------------------------------------------------------