├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── README.md ├── nest-cli.json ├── package-lock.json ├── package.json ├── src ├── app.module.ts ├── guards │ └── AuthGuard.ts ├── main.ts └── user │ ├── user.controller.ts │ ├── user.entity.ts │ ├── user.interface.ts │ ├── user.module.ts │ └── user.service.ts ├── tsconfig.build.json └── tsconfig.json /.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 | -------------------------------------------------------------------------------- /.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 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 3 | User microservice for post [TODO]() 4 | 5 | ## Installation 6 | 7 | ```bash 8 | $ npm install 9 | ``` 10 | 11 | ## Running the app 12 | 13 | ```bash 14 | # development 15 | $ npm run start 16 | 17 | # watch mode 18 | $ npm run start:dev 19 | ``` 20 | ## Stay in touch 21 | 22 | - Author - [Ale Sánchez](https://alesanchez.es) 23 | - Website - [https://alesanchez.es](https://alesanchez.es/) 24 | 25 | ## License 26 | 27 | This project is [MIT licensed](LICENSE). 28 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "user", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "license": "MIT", 7 | "scripts": { 8 | "prebuild": "rimraf dist", 9 | "build": "nest build", 10 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 11 | "start": "nest start", 12 | "start:dev": "nest start --watch", 13 | "start:debug": "nest start --debug --watch", 14 | "start:prod": "node dist/main", 15 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 16 | "test": "jest", 17 | "test:watch": "jest --watch", 18 | "test:cov": "jest --coverage", 19 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 20 | "test:e2e": "jest --config ./test/jest-e2e.json" 21 | }, 22 | "dependencies": { 23 | "@nestjs/common": "^7.0.7", 24 | "@nestjs/core": "^7.0.7", 25 | "@nestjs/microservices": "^7.0.7", 26 | "@nestjs/platform-express": "^7.0.7", 27 | "@nestjs/typeorm": "^7.0.0", 28 | "bcrypt": "^4.0.1", 29 | "class-validator": "^0.11.1", 30 | "pg": "^8.0.2", 31 | "reflect-metadata": "^0.1.13", 32 | "rimraf": "^3.0.0", 33 | "rxjs": "^6.5.4", 34 | "typeorm": "^0.2.24" 35 | }, 36 | "devDependencies": { 37 | "@nestjs/cli": "^7.1.2", 38 | "@nestjs/schematics": "^7.0.0", 39 | "@nestjs/testing": "^7.0.7", 40 | "@types/bcrypt": "^3.0.0", 41 | "@types/express": "^4.17.2", 42 | "@types/jest": "^25.2.1", 43 | "@types/node": "^13.1.6", 44 | "@types/supertest": "^2.0.8", 45 | "@typescript-eslint/eslint-plugin": "^2.12.0", 46 | "@typescript-eslint/parser": "^2.12.0", 47 | "eslint": "^6.7.2", 48 | "eslint-config-prettier": "^6.7.0", 49 | "eslint-plugin-import": "^2.19.1", 50 | "jest": "^25.3.0", 51 | "npm-check": "^5.9.2", 52 | "prettier": "^2.0.4", 53 | "supertest": "^4.0.2", 54 | "ts-jest": "^25.3.1", 55 | "ts-loader": "^6.2.1", 56 | "ts-node": "^8.6.0", 57 | "tsconfig-paths": "^3.9.0", 58 | "typescript": "^3.7.4" 59 | }, 60 | "jest": { 61 | "moduleFileExtensions": [ 62 | "js", 63 | "json", 64 | "ts" 65 | ], 66 | "rootDir": "src", 67 | "testRegex": ".spec.ts$", 68 | "transform": { 69 | "^.+\\.(t|j)s$": "ts-jest" 70 | }, 71 | "coverageDirectory": "../coverage", 72 | "testEnvironment": "node" 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | import { User } from './user/user.entity'; 4 | import { UserModule } from './user/user.module'; 5 | 6 | @Module({ 7 | imports: [TypeOrmModule.forRoot({ 8 | type: 'postgres', 9 | host: 'localhost', 10 | port: 5432, 11 | username: 'ms-user', 12 | password: 'ms-user-pass', 13 | database: 'ms-user', 14 | synchronize: true, 15 | entities: [User] 16 | }), UserModule], 17 | }) 18 | export class AppModule { } 19 | -------------------------------------------------------------------------------- /src/guards/AuthGuard.ts: -------------------------------------------------------------------------------- 1 | import { CanActivate, ExecutionContext, Inject, Logger } from '@nestjs/common'; 2 | import { ClientProxy } from '@nestjs/microservices'; 3 | import { timeout } from 'rxjs/operators'; 4 | 5 | export class AuthGuard implements CanActivate { 6 | constructor( 7 | @Inject('AUTH_CLIENT') 8 | private readonly client: ClientProxy 9 | ) {} 10 | 11 | async canActivate( 12 | context: ExecutionContext, 13 | ): Promise { 14 | Logger.log('Auth Guard'); 15 | const req = context.switchToHttp().getRequest(); 16 | 17 | try{ 18 | const res = await this.client.send( 19 | { role: 'auth', cmd: 'check' }, 20 | { jwt: req.headers['authorization']?.split(' ')[1]}) 21 | .pipe(timeout(5000)) 22 | .toPromise(); 23 | 24 | return res; 25 | } catch(err) { 26 | Logger.error(err); 27 | return false; 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | import { Transport } from '@nestjs/microservices'; 4 | import { Logger } from '@nestjs/common'; 5 | 6 | async function bootstrap() { 7 | const app = await NestFactory.create(AppModule); 8 | 9 | app.connectMicroservice({ 10 | transport: Transport.TCP, 11 | options: { 12 | host: 'localhost', 13 | port: 4010 14 | } 15 | }); 16 | 17 | await app.startAllMicroservicesAsync(); 18 | await app.listen(3010); 19 | Logger.log('User microservice running'); 20 | } 21 | bootstrap(); 22 | -------------------------------------------------------------------------------- /src/user/user.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, UseGuards, Get } from '@nestjs/common'; 2 | import { UserService } from './user.service'; 3 | import { MessagePattern } from '@nestjs/microservices'; 4 | import { User } from './user.entity'; 5 | import { AuthGuard } from '../guards/AuthGuard'; 6 | 7 | @Controller() 8 | export class UserController { 9 | constructor( 10 | private readonly userService: UserService 11 | ) { } 12 | 13 | @MessagePattern({ role: 'user', cmd: 'get' }) 14 | getUser(data: any): Promise { 15 | return this.userService.findOne({ username: data.username }); 16 | } 17 | 18 | @UseGuards(AuthGuard) 19 | @Get('greet') 20 | async greet(): Promise { 21 | return 'Greetings authenticated user'; 22 | } 23 | } -------------------------------------------------------------------------------- /src/user/user.entity.ts: -------------------------------------------------------------------------------- 1 | import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, BeforeInsert, Unique } from 'typeorm'; 2 | import { hash } from 'bcrypt'; 3 | import { IsEmail, Min } from 'class-validator'; 4 | import { UserInterface } from './user.interface'; 5 | 6 | @Entity() 7 | @Unique(['username']) 8 | @Unique(['email']) 9 | export class User implements UserInterface { 10 | @PrimaryGeneratedColumn() 11 | id: number; 12 | 13 | @Column() 14 | username: string; 15 | 16 | @Column() 17 | @Min(8) 18 | password: string; 19 | 20 | @Column() 21 | name: string; 22 | 23 | @Column() 24 | @IsEmail() 25 | email: string; 26 | 27 | @CreateDateColumn() 28 | createdAt: Date; 29 | 30 | @BeforeInsert() 31 | async hashPassword() { 32 | this.password = await hash(this.password, 10); 33 | } 34 | } -------------------------------------------------------------------------------- /src/user/user.interface.ts: -------------------------------------------------------------------------------- 1 | export interface UserInterface { 2 | id: number 3 | username: string 4 | password: string 5 | name: string 6 | email: string 7 | } 8 | -------------------------------------------------------------------------------- /src/user/user.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | import { User } from './user.entity'; 4 | import { UserService } from './user.service'; 5 | import { UserController } from './user.controller'; 6 | import { ClientsModule, Transport } from '@nestjs/microservices'; 7 | 8 | @Module({ 9 | imports: [ 10 | TypeOrmModule.forFeature([User]), 11 | ClientsModule.register([{ 12 | name: 'AUTH_CLIENT', 13 | transport: Transport.TCP, 14 | options: { 15 | host: 'localhost', 16 | port: 4000 17 | } 18 | }]) 19 | ], 20 | providers: [UserService], 21 | controllers: [UserController], 22 | }) 23 | export class UserModule {} -------------------------------------------------------------------------------- /src/user/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, Logger } from '@nestjs/common'; 2 | import { InjectRepository } from '@nestjs/typeorm'; 3 | import { Repository, InsertResult, FindConditions } from 'typeorm'; 4 | import { User } from './user.entity'; 5 | 6 | 7 | @Injectable() 8 | export class UserService { 9 | constructor( 10 | @InjectRepository(User) 11 | private readonly userRepository: Repository 12 | ) {} 13 | 14 | findOne(query: FindConditions): Promise { 15 | return this.userRepository.findOne(query); 16 | } 17 | 18 | async createUser(user: any): Promise { 19 | try { 20 | /** 21 | * Perform all needed checks 22 | */ 23 | 24 | const userEntity = this.userRepository.create(user); 25 | 26 | const res = await this.userRepository.insert(userEntity); 27 | 28 | Logger.log('createUser - Created user'); 29 | 30 | return res; 31 | } catch(e) { 32 | Logger.log(e); 33 | throw e; 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /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 | "target": "es2017", 9 | "sourceMap": true, 10 | "outDir": "./dist", 11 | "baseUrl": "./", 12 | "incremental": true 13 | }, 14 | "exclude": ["node_modules", "dist"] 15 | } 16 | --------------------------------------------------------------------------------