From 5ff23abda5544d3764a7e90dfdca755dc217c2d8 Mon Sep 17 00:00:00 2001 From: Hasta Ragil Saputra Date: Wed, 8 Dec 2021 17:15:02 +0700 Subject: [PATCH] feat: generate jwt on login --- package.json | 2 ++ src/app.module.ts | 9 +++++---- src/auth/auth.controller.ts | 5 ++++- src/auth/auth.module.ts | 17 ++++++++++++++++- src/auth/auth.service.ts | 17 ++++++++++++++++- src/config/configuration.ts | 1 + yarn.lock | 33 ++++++++++++++++++++++++++++++++- 7 files changed, 76 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index 8782836..12187a9 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ "@nestjs/common": "^8.0.0", "@nestjs/config": "^1.0.1", "@nestjs/core": "^8.0.0", + "@nestjs/jwt": "^8.0.0", "@nestjs/mapped-types": "*", "@nestjs/passport": "^8.0.1", "@nestjs/platform-express": "^8.0.0", @@ -53,6 +54,7 @@ "@types/express": "^4.17.13", "@types/jest": "^27.0.1", "@types/node": "^16.0.0", + "@types/passport-jwt": "^3.0.6", "@types/passport-local": "^1.0.34", "@types/supertest": "^2.0.11", "@typescript-eslint/eslint-plugin": "^4.28.2", diff --git a/src/app.module.ts b/src/app.module.ts index 463420d..22dd095 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -21,10 +21,11 @@ import configuration from './config/configuration'; .valid('development', 'production', 'test', 'provision') .default('development'), PORT: Joi.number().default(3000), - DATABASE_CLIENT: Joi.valid('mysql', 'postgres'), - DATABASE_HOST: Joi.string(), - DATABASE_NAME: Joi.string(), - DATABASE_USERNAME: Joi.string(), + SECRET: Joi.string().required(), + DATABASE_CLIENT: Joi.valid('mysql', 'postgres').required(), + DATABASE_HOST: Joi.string().required(), + DATABASE_NAME: Joi.string().required(), + DATABASE_USERNAME: Joi.string().required(), DATABASE_PASSWORD: Joi.string().empty('').default(''), DATABASE_PORT: Joi.number().default(5432), }), diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts index ca340e3..34ab9da 100644 --- a/src/auth/auth.controller.ts +++ b/src/auth/auth.controller.ts @@ -1,14 +1,17 @@ import { Controller, Post, UseGuards, Request } from '@nestjs/common'; import { LocalAuthGuard } from './local-auth.guard'; +import { AuthService } from './auth.service'; @Controller({ path: 'auth', version: '1', }) export class AuthController { + constructor(private authService: AuthService) {} + @UseGuards(LocalAuthGuard) @Post('login') async login(@Request() req) { - return req.user; + return this.authService.login(req.user); } } diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.ts index 8d2d164..5df33e9 100644 --- a/src/auth/auth.module.ts +++ b/src/auth/auth.module.ts @@ -4,9 +4,24 @@ import { UsersModule } from '../users/users.module'; import { PassportModule } from '@nestjs/passport'; import { LocalStrategy } from './local.strategy'; import { AuthController } from './auth.controller'; +import { JwtModule } from '@nestjs/jwt'; +import { ConfigModule, ConfigService } from '@nestjs/config'; @Module({ - imports: [UsersModule, PassportModule], + imports: [ + UsersModule, + PassportModule, + JwtModule.registerAsync({ + imports: [ConfigModule], + inject: [ConfigService], + useFactory: (configService: ConfigService) => { + return { + secret: configService.get('secret'), + signOptions: { expiresIn: '1d' }, + }; + }, + }), + ], providers: [AuthService, LocalStrategy], controllers: [AuthController], }) diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index 0e1ffd9..5e6ab4b 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -1,10 +1,14 @@ import { Injectable } from '@nestjs/common'; import { UsersService } from '../users/users.service'; import { hashPassword } from '../helper/hash_password'; +import { JwtService } from '@nestjs/jwt'; @Injectable() export class AuthService { - constructor(private usersService: UsersService) {} + constructor( + private usersService: UsersService, + private jwtService: JwtService, + ) {} async validateUser(username: string, pass: string): Promise { const user = await this.usersService.findOneByUsername(username); @@ -17,4 +21,15 @@ export class AuthService { return null; } + + async login(user: any) { + const payload = { + username: user.username, + sub: user.userId, + }; + + return { + access_token: this.jwtService.sign(payload), + }; + } } diff --git a/src/config/configuration.ts b/src/config/configuration.ts index 17bbed2..1b088c3 100644 --- a/src/config/configuration.ts +++ b/src/config/configuration.ts @@ -1,6 +1,7 @@ export default () => { return { port: parseInt(process.env.PORT, 10) || 3000, + secret: process.env.SECRET, database: { client: process.env.DATABASE_CLIENT, host: process.env.DATABASE_HOST, diff --git a/yarn.lock b/yarn.lock index 4400fb7..64ac2a4 100644 --- a/yarn.lock +++ b/yarn.lock @@ -675,6 +675,14 @@ tslib "2.3.1" uuid "8.3.2" +"@nestjs/jwt@^8.0.0": + version "8.0.0" + resolved "https://registry.yarnpkg.com/@nestjs/jwt/-/jwt-8.0.0.tgz#6c811c17634252dd1dcd5dabf409dbd692b812da" + integrity sha512-fz2LQgYY2zmuD8S+8UE215anwKyXlnB/1FwJQLVR47clNfMeFMK8WCxmn6xdPhF5JKuV1crO6FVabb1qWzDxqQ== + dependencies: + "@types/jsonwebtoken" "8.5.4" + jsonwebtoken "8.5.1" + "@nestjs/mapped-types@*": version "1.0.0" resolved "https://registry.npmjs.org/@nestjs/mapped-types/-/mapped-types-1.0.0.tgz" @@ -963,6 +971,20 @@ resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee" integrity sha1-7ihweulOEdK4J7y+UnC86n8+ce4= +"@types/jsonwebtoken@*": + version "8.5.6" + resolved "https://registry.yarnpkg.com/@types/jsonwebtoken/-/jsonwebtoken-8.5.6.tgz#1913e5a61e70a192c5a444623da4901a7b1a9d42" + integrity sha512-+P3O/xC7nzVizIi5VbF34YtqSonFsdnbXBnWUCYRiKOi1f9gA4sEFvXkrGr/QVV23IbMYvcoerI7nnhDUiWXRQ== + dependencies: + "@types/node" "*" + +"@types/jsonwebtoken@8.5.4": + version "8.5.4" + resolved "https://registry.yarnpkg.com/@types/jsonwebtoken/-/jsonwebtoken-8.5.4.tgz#50ccaf0aa6f5d7b9956e70fe323b76e582991913" + integrity sha512-4L8msWK31oXwdtC81RmRBAULd0ShnAHjBuKT9MRQpjP0piNrZdXyTRcKY9/UIfhGeKIT4PvF5amOOUbbT/9Wpg== + dependencies: + "@types/node" "*" + "@types/mime@^1": version "1.3.2" resolved "https://registry.yarnpkg.com/@types/mime/-/mime-1.3.2.tgz#93e25bf9ee75fe0fd80b594bc4feb0e862111b5a" @@ -978,6 +1000,15 @@ resolved "https://registry.yarnpkg.com/@types/parse-json/-/parse-json-4.0.0.tgz#2f8bb441434d163b35fb8ffdccd7138927ffb8c0" integrity sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA== +"@types/passport-jwt@^3.0.6": + version "3.0.6" + resolved "https://registry.yarnpkg.com/@types/passport-jwt/-/passport-jwt-3.0.6.tgz#41cc8b5803d5f5f06eb33e19c453b42716def4f1" + integrity sha512-cmAAMIRTaEwpqxlrZyiEY9kdibk94gP5KTF8AT1Ra4rWNZYHNMreqhKUEeC5WJtuN5SJZjPQmV+XO2P5PlnvNQ== + dependencies: + "@types/express" "*" + "@types/jsonwebtoken" "*" + "@types/passport-strategy" "*" + "@types/passport-local@^1.0.34": version "1.0.34" resolved "https://registry.yarnpkg.com/@types/passport-local/-/passport-local-1.0.34.tgz#84d3b35b2fd4d36295039ded17fe5f3eaa62f4f6" @@ -3788,7 +3819,7 @@ jsonfile@^6.0.1: optionalDependencies: graceful-fs "^4.1.6" -jsonwebtoken@^8.2.0: +jsonwebtoken@8.5.1, jsonwebtoken@^8.2.0: version "8.5.1" resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz#00e71e0b8df54c2121a1f26137df2280673bcc0d" integrity sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==