├── .prettierrc ├── src ├── auth │ ├── constants.ts │ ├── local-auth.guard.ts │ ├── jwt.strategy.ts │ ├── local.strategy.ts │ ├── auth.module.ts │ ├── auth.controller.ts │ └── auth.service.ts ├── app.module.ts └── main.ts ├── nest-cli.json ├── tsconfig.build.json ├── tsconfig.json ├── README.md ├── .gitignore ├── .eslintrc.js └── package.json /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /src/auth/constants.ts: -------------------------------------------------------------------------------- 1 | export default { 2 | jwtSecret: 'mysupersecret' 3 | } -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /src/auth/local-auth.guard.ts: -------------------------------------------------------------------------------- 1 | import { AuthGuard } from '@nestjs/passport'; 2 | import { Injectable } from '@nestjs/common'; 3 | 4 | @Injectable() 5 | export class LocalAuthGuard extends AuthGuard('local') {} -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { AuthModule } from './auth/auth.module'; 3 | 4 | @Module({ 5 | imports: [AuthModule], 6 | controllers: [], 7 | providers: [], 8 | }) 9 | export class AppModule {} 10 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 3 | Authentication 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 | -------------------------------------------------------------------------------- /.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 -------------------------------------------------------------------------------- /src/auth/jwt.strategy.ts: -------------------------------------------------------------------------------- 1 | import { PassportStrategy } from '@nestjs/passport'; 2 | import { Strategy, ExtractJwt } from 'passport-jwt'; 3 | import constants from './constants'; 4 | 5 | export class JwtStrategy extends PassportStrategy(Strategy) { 6 | constructor() { 7 | super({ 8 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 9 | ignoreExpiration: false, 10 | secretOrKey: constants.jwtSecret, 11 | }); 12 | } 13 | 14 | async validate(payload) { 15 | return { id: payload.sub, user: payload.user}; 16 | } 17 | } -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { Transport } from '@nestjs/microservices'; 3 | import { AppModule } from './app.module'; 4 | import { Logger } from '@nestjs/common'; 5 | 6 | async function bootstrap() { 7 | const app = await NestFactory.create(AppModule); 8 | app.connectMicroservice({ 9 | transport: Transport.TCP, 10 | options: { 11 | host: 'localhost', 12 | port: 4000 13 | } 14 | }) 15 | 16 | await app.startAllMicroservicesAsync(); 17 | await app.listen(3000); 18 | Logger.log('Auth microservice running'); 19 | } 20 | bootstrap(); 21 | -------------------------------------------------------------------------------- /src/auth/local.strategy.ts: -------------------------------------------------------------------------------- 1 | import { Strategy } from 'passport-local'; 2 | import { PassportStrategy } from '@nestjs/passport'; 3 | import { Injectable, UnauthorizedException } from '@nestjs/common'; 4 | import { AuthService } from './auth.service'; 5 | 6 | @Injectable() 7 | export class LocalStrategy extends PassportStrategy(Strategy) { 8 | constructor(private readonly authService: AuthService) { 9 | super(); 10 | } 11 | 12 | async validate(username: string, password: string): Promise { 13 | const user = await this.authService.validateUser(username, password); 14 | 15 | if(!user) { 16 | throw new UnauthorizedException(); 17 | } 18 | 19 | return user; 20 | } 21 | } -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /src/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from "@nestjs/common"; 2 | import { ClientsModule, Transport } from "@nestjs/microservices"; 3 | import { JwtModule } from '@nestjs/jwt'; 4 | import { AuthService } from "./auth.service"; 5 | import { LocalStrategy } from "./local.strategy"; 6 | import { AuthController } from "./auth.controller"; 7 | import constants from "./constants"; 8 | 9 | @Module({ 10 | imports: [ClientsModule.register([{ 11 | name: 'USER_CLIENT', 12 | transport: Transport.TCP, 13 | options: { 14 | host: 'localhost', 15 | port: 4010, 16 | } 17 | }]), JwtModule.register({ 18 | secret: constants.jwtSecret, 19 | signOptions: { expiresIn: '60s' } 20 | })], 21 | controllers: [AuthController], 22 | providers: [AuthService, LocalStrategy] 23 | }) 24 | export class AuthModule {} -------------------------------------------------------------------------------- /src/auth/auth.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Post, UseGuards, Request, Logger } from '@nestjs/common'; 2 | import { LocalAuthGuard } from './local-auth.guard'; 3 | import { AuthService } from './auth.service'; 4 | import { MessagePattern } from '@nestjs/microservices'; 5 | 6 | @Controller() 7 | export class AuthController { 8 | constructor( 9 | private readonly authService: AuthService) {} 10 | 11 | @UseGuards(LocalAuthGuard) 12 | @Post('auth') 13 | async login(@Request() req) { 14 | return this.authService.login(req.user); 15 | } 16 | 17 | @MessagePattern({ role: 'auth', cmd: 'check'}) 18 | async loggedIn(data) { 19 | try { 20 | const res = this.authService.validateToken(data.jwt); 21 | 22 | return res; 23 | } catch(e) { 24 | Logger.log(e); 25 | return false; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/auth/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, Inject, Logger, RequestTimeoutException } from '@nestjs/common'; 2 | import { compareSync } from 'bcrypt'; 3 | import { ClientProxy } from '@nestjs/microservices'; 4 | import { timeout, catchError } from 'rxjs/operators'; 5 | import { TimeoutError, throwError } from 'rxjs'; 6 | import { JwtService } from '@nestjs/jwt'; 7 | 8 | @Injectable() 9 | export class AuthService { 10 | constructor( 11 | @Inject('USER_CLIENT') 12 | private readonly client: ClientProxy, 13 | private readonly jwtService: JwtService) {} 14 | 15 | async validateUser(username: string, password: string): Promise { 16 | try { 17 | const user = await this.client.send({ role: 'user', cmd: 'get' }, { username }) 18 | .pipe( 19 | timeout(5000), 20 | catchError(err => { 21 | if (err instanceof TimeoutError) { 22 | return throwError(new RequestTimeoutException()); 23 | } 24 | return throwError(err); 25 | }),) 26 | .toPromise(); 27 | 28 | if(compareSync(password, user?.password)) { 29 | return user; 30 | } 31 | 32 | return null; 33 | } catch(e) { 34 | Logger.log(e); 35 | throw e; 36 | } 37 | } 38 | 39 | async login(user) { 40 | const payload = { user, sub: user.id}; 41 | 42 | return { 43 | userId: user.id, 44 | accessToken: this.jwtService.sign(payload) 45 | }; 46 | } 47 | 48 | validateToken(jwt: string) { 49 | return this.jwtService.verify(jwt); 50 | } 51 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "auth", 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/jwt": "^7.0.0", 26 | "@nestjs/microservices": "^7.0.7", 27 | "@nestjs/passport": "^7.0.0", 28 | "@nestjs/platform-express": "^7.0.7", 29 | "bcrypt": "^4.0.1", 30 | "nats": "^1.4.8", 31 | "passport": "^0.4.1", 32 | "passport-jwt": "^4.0.0", 33 | "passport-local": "^1.0.0", 34 | "reflect-metadata": "^0.1.13", 35 | "rimraf": "^3.0.0", 36 | "rxjs": "^6.5.4" 37 | }, 38 | "devDependencies": { 39 | "@nestjs/cli": "^7.1.2", 40 | "@nestjs/schematics": "^7.0.0", 41 | "@nestjs/testing": "^7.0.7", 42 | "@types/bcrypt": "^3.0.0", 43 | "@types/express": "^4.17.2", 44 | "@types/jest": "^25.2.1", 45 | "@types/node": "^13.1.6", 46 | "@types/passport-local": "^1.0.33", 47 | "@types/supertest": "^2.0.8", 48 | "@typescript-eslint/eslint-plugin": "^2.12.0", 49 | "@typescript-eslint/parser": "^2.12.0", 50 | "eslint": "^6.7.2", 51 | "eslint-config-prettier": "^6.7.0", 52 | "eslint-plugin-import": "^2.19.1", 53 | "jest": "^25.3.0", 54 | "npm-check": "^5.9.2", 55 | "prettier": "^2.0.4", 56 | "supertest": "^4.0.2", 57 | "ts-jest": "^25.3.1", 58 | "ts-loader": "^6.2.1", 59 | "ts-node": "^8.6.0", 60 | "tsconfig-paths": "^3.9.0", 61 | "typescript": "^3.7.4" 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 | "coverageDirectory": "../coverage", 75 | "testEnvironment": "node" 76 | } 77 | } 78 | --------------------------------------------------------------------------------