From b2271fc09478ff02fabb227a71cc2b6b700ef322 Mon Sep 17 00:00:00 2001 From: Richard William Date: Tue, 22 Aug 2023 19:43:33 +0700 Subject: [PATCH 1/6] changed structure --- package-lock.json | 342 ++++++++++++++++-- package.json | 4 +- src/auth/auth.controller.ts | 19 +- src/auth/auth.service.ts | 38 +- src/auth/interface/authenticate.interface.ts | 14 - .../authenticate.request.ts} | 6 +- src/auth/requests/register.request.ts | 24 ++ src/auth/test/auth.service.spec.ts | 2 +- src/main.ts | 1 + .../user-create.request.ts} | 2 +- src/users/user.controller.ts | 4 +- src/users/user.repository.ts | 7 +- vercel.json | 24 -- 13 files changed, 404 insertions(+), 83 deletions(-) delete mode 100644 src/auth/interface/authenticate.interface.ts rename src/auth/{dto/authenticate.dto.ts => requests/authenticate.request.ts} (62%) create mode 100644 src/auth/requests/register.request.ts rename src/users/{dto/user-create.dto.ts => requests/user-create.request.ts} (93%) delete mode 100644 vercel.json diff --git a/package-lock.json b/package-lock.json index 428f795..e0f5162 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,6 +19,7 @@ "@nestjs/swagger": "^6.3.0", "@prisma/client": "^5.0.0", "ajv": "^6.12.6", + "bcrypt": "^5.1.1", "class-validator": "^0.14.0", "passport": "^0.6.0", "passport-google-oauth20": "^2.0.0", @@ -32,6 +33,7 @@ "@nestjs/cli": "^9.0.0", "@nestjs/schematics": "^9.0.0", "@nestjs/testing": "^9.4.3", + "@types/bcrypt": "^5.0.0", "@types/express": "^4.17.13", "@types/jest": "29.5.1", "@types/node": "18.16.12", @@ -1337,6 +1339,39 @@ "node": ">=8" } }, + "node_modules/@mapbox/node-pre-gyp": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz", + "integrity": "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==", + "dependencies": { + "detect-libc": "^2.0.0", + "https-proxy-agent": "^5.0.0", + "make-dir": "^3.1.0", + "node-fetch": "^2.6.7", + "nopt": "^5.0.0", + "npmlog": "^5.0.1", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "tar": "^6.1.11" + }, + "bin": { + "node-pre-gyp": "bin/node-pre-gyp" + } + }, + "node_modules/@mapbox/node-pre-gyp/node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/@nestjs/cli": { "version": "9.5.0", "resolved": "https://registry.npmjs.org/@nestjs/cli/-/cli-9.5.0.tgz", @@ -1843,6 +1878,15 @@ "@babel/types": "^7.20.7" } }, + "node_modules/@types/bcrypt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/@types/bcrypt/-/bcrypt-5.0.0.tgz", + "integrity": "sha512-agtcFKaruL8TmcvqbndlqHPSJgsolhf/qPWchFlgnW1gECTN/nKbFcoFnvKAQRFfKbh+BO6A3SWdJu9t+xF3Lw==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/body-parser": { "version": "1.19.2", "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.2.tgz", @@ -2485,6 +2529,11 @@ "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==" }, + "node_modules/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" + }, "node_modules/accepts": { "version": "1.3.8", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", @@ -2534,6 +2583,17 @@ "node": ">=0.4.0" } }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, "node_modules/ajv": { "version": "6.12.6", "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", @@ -2636,7 +2696,6 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, "engines": { "node": ">=8" } @@ -2673,6 +2732,36 @@ "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==" }, + "node_modules/aproba": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", + "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==" + }, + "node_modules/are-we-there-yet": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz", + "integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==", + "dependencies": { + "delegates": "^1.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/are-we-there-yet/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/arg": { "version": "4.1.3", "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", @@ -2804,8 +2893,7 @@ "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" }, "node_modules/base64-js": { "version": "1.5.1", @@ -2835,6 +2923,19 @@ "node": ">=6.0.0" } }, + "node_modules/bcrypt": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-5.1.1.tgz", + "integrity": "sha512-AGBHOG5hPYZ5Xl9KXzU5iKq9516yEmvCKDg3ecP5kX2aB6UqTeXZxk2ELnDgDm6BQSMlLt9rDB4LoSMx0rYwww==", + "hasInstallScript": true, + "dependencies": { + "@mapbox/node-pre-gyp": "^1.0.11", + "node-addon-api": "^5.0.0" + }, + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/binary-extensions": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", @@ -2909,7 +3010,6 @@ "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -3138,6 +3238,14 @@ "fsevents": "~2.3.2" } }, + "node_modules/chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "engines": { + "node": ">=10" + } + }, "node_modules/chrome-trace-event": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz", @@ -3280,6 +3388,14 @@ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" }, + "node_modules/color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "bin": { + "color-support": "bin.js" + } + }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -3310,8 +3426,7 @@ "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" }, "node_modules/concat-stream": { "version": "1.6.2", @@ -3332,6 +3447,11 @@ "resolved": "https://registry.npmjs.org/consola/-/consola-2.15.3.tgz", "integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw==" }, + "node_modules/console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==" + }, "node_modules/content-disposition": { "version": "0.5.4", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", @@ -3433,7 +3553,6 @@ "version": "4.3.4", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "dev": true, "dependencies": { "ms": "2.1.2" }, @@ -3488,6 +3607,11 @@ "node": ">=0.4.0" } }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==" + }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -3505,6 +3629,14 @@ "npm": "1.2.8000 || >= 1.4.16" } }, + "node_modules/detect-libc": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.2.tgz", + "integrity": "sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==", + "engines": { + "node": ">=8" + } + }, "node_modules/detect-newline": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", @@ -3607,8 +3739,7 @@ "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" }, "node_modules/encodeurl": { "version": "1.0.2", @@ -4366,6 +4497,33 @@ "node": ">=12" } }, + "node_modules/fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/fs-minipass/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fs-minipass/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, "node_modules/fs-monkey": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/fs-monkey/-/fs-monkey-1.0.4.tgz", @@ -4375,8 +4533,7 @@ "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==" }, "node_modules/fsevents": { "version": "2.3.2", @@ -4397,6 +4554,25 @@ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" }, + "node_modules/gauge": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz", + "integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==", + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.2", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.1", + "object-assign": "^4.1.1", + "signal-exit": "^3.0.0", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.2" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/gensync": { "version": "1.0.0-beta.2", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", @@ -4454,7 +4630,6 @@ "version": "7.2.3", "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "dev": true, "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -4574,6 +4749,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==" + }, "node_modules/hexoid": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/hexoid/-/hexoid-1.0.0.tgz", @@ -4604,6 +4784,18 @@ "node": ">= 0.8" } }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/human-signals": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", @@ -4701,7 +4893,6 @@ "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "dev": true, "dependencies": { "once": "^1.3.0", "wrappy": "1" @@ -4798,7 +4989,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, "engines": { "node": ">=8" } @@ -5797,7 +5987,6 @@ "version": "3.1.0", "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", - "dev": true, "dependencies": { "semver": "^6.0.0" }, @@ -5812,7 +6001,6 @@ "version": "6.3.1", "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, "bin": { "semver": "bin/semver.js" } @@ -5935,7 +6123,6 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -5960,6 +6147,34 @@ "node": ">=8" } }, + "node_modules/minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minizlib/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minizlib/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, "node_modules/mkdirp": { "version": "0.5.6", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", @@ -6030,6 +6245,11 @@ "integrity": "sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==", "dev": true }, + "node_modules/node-addon-api": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-5.1.0.tgz", + "integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA==" + }, "node_modules/node-emoji": { "version": "1.11.0", "resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-1.11.0.tgz", @@ -6069,6 +6289,20 @@ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.13.tgz", "integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==" }, + "node_modules/nopt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", + "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -6090,6 +6324,17 @@ "node": ">=8" } }, + "node_modules/npmlog": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz", + "integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==", + "dependencies": { + "are-we-there-yet": "^2.0.0", + "console-control-strings": "^1.1.0", + "gauge": "^3.0.0", + "set-blocking": "^2.0.0" + } + }, "node_modules/oauth": { "version": "0.9.15", "resolved": "https://registry.npmjs.org/oauth/-/oauth-0.9.15.tgz", @@ -6126,7 +6371,6 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, "dependencies": { "wrappy": "1" } @@ -6376,7 +6620,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, "engines": { "node": ">=0.10.0" } @@ -7139,6 +7382,11 @@ "node": ">= 0.8.0" } }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==" + }, "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", @@ -7198,8 +7446,7 @@ "node_modules/signal-exit": { "version": "3.0.7", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" }, "node_modules/sisteransi": { "version": "1.0.5", @@ -7315,7 +7562,6 @@ "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -7329,7 +7575,6 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, "dependencies": { "ansi-regex": "^5.0.1" }, @@ -7458,6 +7703,46 @@ "node": ">=6" } }, + "node_modules/tar": { + "version": "6.1.15", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.1.15.tgz", + "integrity": "sha512-/zKt9UyngnxIT/EAGYuxaMYgOIJiP81ab9ZfkILq4oNLPFX50qyYmu7jRj9qeXoxmJHjGlbH0+cm2uy1WCs10A==", + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^5.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/tar/node_modules/minipass": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", + "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/tar/node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/tar/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, "node_modules/terser": { "version": "5.18.2", "resolved": "https://registry.npmjs.org/terser/-/terser-5.18.2.tgz", @@ -8113,6 +8398,14 @@ "node": ">= 8" } }, + "node_modules/wide-align": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", + "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", + "dependencies": { + "string-width": "^1.0.2 || 2 || 3 || 4" + } + }, "node_modules/windows-release": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/windows-release/-/windows-release-4.0.0.tgz", @@ -8195,8 +8488,7 @@ "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" }, "node_modules/write-file-atomic": { "version": "4.0.2", diff --git a/package.json b/package.json index 9393033..7607e5b 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "build": "nest build", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "start": "node dist/main", - "dev": "SET NODE_ENV=dev && nest start", + "dev": "nest start", "start:dev": "nest start --watch", "start:debug": "nest start --debug --watch", "start:prod": "node dist/main", @@ -31,6 +31,7 @@ "@nestjs/swagger": "^6.3.0", "@prisma/client": "^5.0.0", "ajv": "^6.12.6", + "bcrypt": "^5.1.1", "class-validator": "^0.14.0", "passport": "^0.6.0", "passport-google-oauth20": "^2.0.0", @@ -44,6 +45,7 @@ "@nestjs/cli": "^9.0.0", "@nestjs/schematics": "^9.0.0", "@nestjs/testing": "^9.4.3", + "@types/bcrypt": "^5.0.0", "@types/express": "^4.17.13", "@types/jest": "29.5.1", "@types/node": "18.16.12", diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts index 6b4db05..9be97f4 100644 --- a/src/auth/auth.controller.ts +++ b/src/auth/auth.controller.ts @@ -9,13 +9,14 @@ import { UseGuards, } from '@nestjs/common'; import { AuthService } from './auth.service'; -import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'; +import { ApiBearerAuth, ApiCookieAuth, ApiTags } from '@nestjs/swagger'; import { Roles } from './roles/role.decorator'; import { Role } from './roles/role.enum'; -import { AuthenticateDto } from './dto/authenticate.dto'; +import { AuthenticateRequest } from './requests/authenticate.request'; import { JwtAuthGuard } from './jwt/jwt-auth.guard'; import { RoleGuard } from './roles/role.guard'; import { GoogleGuard } from './google/google.guard'; +import { RegisterRequest } from './requests/register.request'; @ApiTags('Auth') @Controller('auth') @@ -23,7 +24,7 @@ export class AuthController { constructor(private authService: AuthService) {} @Post('login') - async signIn(@Res() res, @Body() authenticateDto: AuthenticateDto) { + async signIn(@Res() res, @Body() authenticateDto: AuthenticateRequest) { try { const response = await this.authService.login(authenticateDto, res); return res.status(HttpStatus.OK).json({ ...response }); @@ -32,8 +33,19 @@ export class AuthController { } } + @Post('register') + async signUp(@Res() res, @Body() request: RegisterRequest) { + try { + const response = await this.authService.register(request); + return res.status(HttpStatus.OK).json({ ...response }); + } catch (error) { + return res.status(error.status).json({ error: error.message }); + } + } + @Get('google') @UseGuards(GoogleGuard) + // this end point is needed for google authentication // eslint-disable-next-line @typescript-eslint/no-empty-function async googleAuth() {} @@ -49,6 +61,7 @@ export class AuthController { } @ApiBearerAuth() + @ApiCookieAuth() @Roles(Role.USER) @UseGuards(JwtAuthGuard, RoleGuard) @Get('info') diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index 2eb279e..eb5a168 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -1,10 +1,12 @@ import { Injectable, UnauthorizedException } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { UsersService } from '../users/users.service'; -import { AuthenticateDto } from './dto/authenticate.dto'; -import { IAuthenticate, IGoogleUser } from './interface/authenticate.interface'; +import { AuthenticateRequest } from './requests/authenticate.request'; +import { IAuthenticate, IGoogleUser } from './interface/auth.interface'; import { IUser } from '../users/interface/user.interface'; import { Role } from './roles/role.enum'; +import * as bcyrpt from 'bcrypt'; +import { RegisterRequest } from './requests/register.request'; @Injectable() export class AuthService { @@ -13,8 +15,10 @@ export class AuthService { private jwtService: JwtService, ) {} - async validateUser(authenticateDto: AuthenticateDto): Promise { - const user = await this.usersService.findOne(authenticateDto); + async validateUser( + authenticateRequest: AuthenticateRequest, + ): Promise { + const user = await this.usersService.findOne(authenticateRequest); if (!user) { throw new UnauthorizedException('INVALID_CREDENTIALS'); } @@ -25,13 +29,29 @@ export class AuthService { return data; } - async login(authenitcateDto: AuthenticateDto, res): Promise { - const user = await this.validateUser(authenitcateDto); + async login( + authenticateRequest: AuthenticateRequest, + res, + ): Promise { + const user = await this.validateUser(authenticateRequest); user.token = this.jwtService.sign(user); res.cookie('EToken', user.token); return user; } + async register(registerRequest: RegisterRequest): Promise { + const { repeatPassword, ...userCreate } = registerRequest; + + if (userCreate.password !== repeatPassword) { + throw new UnauthorizedException('PASSWORD_NOT_MATCH'); + } + + const user = await this.usersService.create({ + ...userCreate, + }); + return user; + } + async googleLogin(req, res): Promise { const user: IGoogleUser = req.user; @@ -57,4 +77,10 @@ export class AuthService { return userData; } + + private hashPassword(password: string): string { + const salt = bcyrpt.genSaltSync(10); + const hashedPassword = bcyrpt.hashSync(password, salt); + return hashedPassword; + } } diff --git a/src/auth/interface/authenticate.interface.ts b/src/auth/interface/authenticate.interface.ts deleted file mode 100644 index 8473f9e..0000000 --- a/src/auth/interface/authenticate.interface.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { IUser } from '../../users/interface/user.interface'; - -export interface IAuthenticate { - user: IUser; - token?: string; -} - -export interface IGoogleUser { - email: string; - firstName: string; - lastName: string; - picture: string; - _accessToken: string; -} diff --git a/src/auth/dto/authenticate.dto.ts b/src/auth/requests/authenticate.request.ts similarity index 62% rename from src/auth/dto/authenticate.dto.ts rename to src/auth/requests/authenticate.request.ts index 92192da..61e2ba2 100644 --- a/src/auth/dto/authenticate.dto.ts +++ b/src/auth/requests/authenticate.request.ts @@ -1,10 +1,10 @@ import { ApiProperty } from '@nestjs/swagger'; -import { IsNotEmpty, IsString } from 'class-validator'; +import { IsEmail, IsNotEmpty, IsString } from 'class-validator'; -export class AuthenticateDto { +export class AuthenticateRequest { @ApiProperty() @IsNotEmpty() - @IsString() + @IsEmail() readonly email: string; @ApiProperty() diff --git a/src/auth/requests/register.request.ts b/src/auth/requests/register.request.ts new file mode 100644 index 0000000..588bb03 --- /dev/null +++ b/src/auth/requests/register.request.ts @@ -0,0 +1,24 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { IsEmail, IsNotEmpty, IsString } from 'class-validator'; + +export class RegisterRequest { + @ApiProperty() + @IsNotEmpty() + @IsEmail() + readonly email: string; + + @ApiProperty() + @IsNotEmpty() + @IsString() + readonly password: string; + + @ApiProperty() + @IsNotEmpty() + @IsString() + readonly repeatPassword: string; + + @ApiProperty() + @IsNotEmpty() + @IsString() + readonly username: string; +} diff --git a/src/auth/test/auth.service.spec.ts b/src/auth/test/auth.service.spec.ts index 1dc75dd..e0f9f1f 100644 --- a/src/auth/test/auth.service.spec.ts +++ b/src/auth/test/auth.service.spec.ts @@ -5,7 +5,7 @@ import { AuthService } from '../auth.service'; import { UsersService } from '../../users/users.service'; import { UnauthorizedException } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; -import { IGoogleUser } from '../interface/authenticate.interface'; +import { IGoogleUser } from '../interface/auth.interface'; import { mock } from 'node:test'; import { Role } from '../roles/role.enum'; diff --git a/src/main.ts b/src/main.ts index c5a4d31..db187e4 100644 --- a/src/main.ts +++ b/src/main.ts @@ -14,6 +14,7 @@ async function bootstrap() { .setDescription('This is auth service for 8Tech app') .setVersion(version) .addBearerAuth() + .addCookieAuth('EToken') .build(); const document = SwaggerModule.createDocument(app, config); diff --git a/src/users/dto/user-create.dto.ts b/src/users/requests/user-create.request.ts similarity index 93% rename from src/users/dto/user-create.dto.ts rename to src/users/requests/user-create.request.ts index a1d483b..fa12f83 100644 --- a/src/users/dto/user-create.dto.ts +++ b/src/users/requests/user-create.request.ts @@ -2,7 +2,7 @@ import { ApiProperty } from '@nestjs/swagger'; import { IsArray, IsEmail, IsNotEmpty, IsString } from 'class-validator'; import { Role } from '../../auth/roles/role.enum'; -export class UserCreateDto { +export class UserCreateRequest { @ApiProperty() @IsNotEmpty() @IsEmail() diff --git a/src/users/user.controller.ts b/src/users/user.controller.ts index 67c8044..73e8306 100644 --- a/src/users/user.controller.ts +++ b/src/users/user.controller.ts @@ -8,11 +8,11 @@ import { } from '@nestjs/common'; import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'; import { UsersService } from './users.service'; -import { UserCreateDto } from './dto/user-create.dto'; import { Roles } from '../auth/roles/role.decorator'; import { JwtAuthGuard } from '../auth/jwt/jwt-auth.guard'; import { RoleGuard } from '../auth/roles/role.guard'; import { Role } from '../auth/roles/role.enum'; +import { UserCreateRequest } from './requests/user-create.request'; @ApiTags('User') @Controller('user') @@ -35,7 +35,7 @@ export class UserController { @Roles(Role.ADMIN) @UseGuards(JwtAuthGuard, RoleGuard) @Post('create') - async createAdmin(@Res() res, @Body() user: UserCreateDto) { + async createAdmin(@Res() res, @Body() user: UserCreateRequest) { try { const response = await this.userService.create(user); return res.status(HttpStatus.OK).json({ response }); diff --git a/src/users/user.repository.ts b/src/users/user.repository.ts index 4e0f1f4..215baa4 100644 --- a/src/users/user.repository.ts +++ b/src/users/user.repository.ts @@ -1,5 +1,6 @@ import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; +import { IUser } from './interface/user.interface'; @Injectable() export class UserRepository { @@ -12,7 +13,7 @@ export class UserRepository { async findOnebyEmailPassword( email: string, password: string, - ): Promise { + ): Promise { return this.prisma.user.findUnique({ where: { email, @@ -21,7 +22,7 @@ export class UserRepository { }); } - async findOneByEmail(email: string): Promise { + async findOneByEmail(email: string): Promise { return this.prisma.user.findUnique({ where: { email, @@ -29,7 +30,7 @@ export class UserRepository { }); } - async create(user: any): Promise { + async create(user: any): Promise { return this.prisma.user.create({ data: user, }); diff --git a/vercel.json b/vercel.json deleted file mode 100644 index 84f9bdb..0000000 --- a/vercel.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "version": 2, - "builds": [ - { - "src": "src/main.ts", - "use": "@vercel/node" - } - ], - "routes": [ - { - "src": "/(.*)", - "dest": "src/main.ts", - "methods": [ - "GET", - "POST", - "PUT", - "PATCH", - "DELETE", - "HEAD", - "OPTIONS" - ] - } - ] -} \ No newline at end of file From 208e3f40e6824b91a449aba4ae0b2ff9da34d65a Mon Sep 17 00:00:00 2001 From: richard483 Date: Wed, 23 Aug 2023 19:57:03 +0700 Subject: [PATCH 2/6] re-added removed interface --- src/auth/interface/auth.interface.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/auth/interface/auth.interface.ts diff --git a/src/auth/interface/auth.interface.ts b/src/auth/interface/auth.interface.ts new file mode 100644 index 0000000..8473f9e --- /dev/null +++ b/src/auth/interface/auth.interface.ts @@ -0,0 +1,14 @@ +import { IUser } from '../../users/interface/user.interface'; + +export interface IAuthenticate { + user: IUser; + token?: string; +} + +export interface IGoogleUser { + email: string; + firstName: string; + lastName: string; + picture: string; + _accessToken: string; +} From 035707f53339755f3500988136c4cf427e34bff5 Mon Sep 17 00:00:00 2001 From: richard483 Date: Thu, 24 Aug 2023 01:40:46 +0700 Subject: [PATCH 3/6] feat: add password hashing functional --- package-lock.json | 16 ++++++++++++++-- package.json | 2 +- src/app.module.ts | 8 +------- src/auth/auth.controller.ts | 6 +++++- src/auth/auth.module.ts | 5 ++--- src/auth/auth.service.ts | 18 ++++++++++++++---- src/auth/jwt/jwt.strategy.ts | 3 +-- src/auth/requests/register.request.ts | 2 +- src/auth/test/auth.service.spec.ts | 1 - src/main.ts | 3 ++- src/users/user.controller.ts | 2 ++ src/users/users.service.ts | 7 ++----- 12 files changed, 45 insertions(+), 28 deletions(-) diff --git a/package-lock.json b/package-lock.json index e0f5162..80fd0d3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "8T-Auth", - "version": "0.0.1", + "version": "1.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "8T-Auth", - "version": "0.0.1", + "version": "1.0.1", "license": "UNLICENSED", "dependencies": { "@golevelup/ts-jest": "^0.3.7", @@ -21,6 +21,7 @@ "ajv": "^6.12.6", "bcrypt": "^5.1.1", "class-validator": "^0.14.0", + "dotenv": "^16.3.1", "passport": "^0.6.0", "passport-google-oauth20": "^2.0.0", "passport-jwt": "^4.0.1", @@ -3698,6 +3699,17 @@ "node": ">=6.0.0" } }, + "node_modules/dotenv": { + "version": "16.3.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz", + "integrity": "sha512-IPzF4w4/Rd94bA9imS68tZBaYyBWSCE47V1RGuMrB94iyTOIEwRmVL2x/4An+6mETpLrKJ5hQkB8W4kFAadeIQ==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/motdotla/dotenv?sponsor=1" + } + }, "node_modules/dotenv-expand": { "version": "10.0.0", "resolved": "https://registry.npmjs.org/dotenv-expand/-/dotenv-expand-10.0.0.tgz", diff --git a/package.json b/package.json index 7607e5b..a45c475 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "8T-Auth", - "version": "0.0.1", + "version": "1.0.1", "description": "", "author": "8tech", "private": true, diff --git a/src/app.module.ts b/src/app.module.ts index 8be14d7..311be61 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -6,13 +6,7 @@ import { UsersModule } from './users/users.module'; import { ConfigModule } from '@nestjs/config'; @Module({ - imports: [ - AuthModule, - UsersModule, - ConfigModule.forRoot({ - isGlobal: true, - }), - ], + imports: [ConfigModule.forRoot(), AuthModule, UsersModule], controllers: [AppController], providers: [AppService], }) diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts index 9be97f4..2e690f7 100644 --- a/src/auth/auth.controller.ts +++ b/src/auth/auth.controller.ts @@ -29,7 +29,8 @@ export class AuthController { const response = await this.authService.login(authenticateDto, res); return res.status(HttpStatus.OK).json({ ...response }); } catch (error) { - return res.status(error.status).json({ error: error.message }); + console.error('#AuthLogin error caused by: ', error); + return res.status(error.status).json({ error }); } } @@ -39,6 +40,7 @@ export class AuthController { const response = await this.authService.register(request); return res.status(HttpStatus.OK).json({ ...response }); } catch (error) { + console.error('#AuthRegister error caused by: ', error); return res.status(error.status).json({ error: error.message }); } } @@ -54,8 +56,10 @@ export class AuthController { async googleAuthRedirect(@Request() req, @Res() res) { try { const response = await this.authService.googleLogin(req, res); + // TODO : redirect to frontend return res.status(HttpStatus.OK).json({ ...response }); } catch (error) { + console.error('#AutGoogleAuthRedirect error caused by: ', error); return res.status(error.status).json({ error: error.message }); } } diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.ts index 0353150..dba1956 100644 --- a/src/auth/auth.module.ts +++ b/src/auth/auth.module.ts @@ -5,7 +5,6 @@ import { UsersModule } from '../users/users.module'; import { JwtModule } from '@nestjs/jwt'; import { PassportModule } from '@nestjs/passport'; import { JwtStrategy } from './jwt/jwt.strategy'; -import { env } from 'process'; import { GoogleStrategy } from './google/google.strategy'; @Module({ @@ -14,8 +13,8 @@ import { GoogleStrategy } from './google/google.strategy'; PassportModule, JwtModule.register({ global: true, - secret: env.JWT_SECRET, - signOptions: { expiresIn: '6000s' }, + secret: process.env.JWT_SECRET, + signOptions: { expiresIn: '600000s' }, }), PassportModule, ], diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index eb5a168..e76d2c3 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -5,7 +5,7 @@ import { AuthenticateRequest } from './requests/authenticate.request'; import { IAuthenticate, IGoogleUser } from './interface/auth.interface'; import { IUser } from '../users/interface/user.interface'; import { Role } from './roles/role.enum'; -import * as bcyrpt from 'bcrypt'; +import { compare, genSaltSync, hashSync } from 'bcrypt'; import { RegisterRequest } from './requests/register.request'; @Injectable() @@ -18,11 +18,20 @@ export class AuthService { async validateUser( authenticateRequest: AuthenticateRequest, ): Promise { - const user = await this.usersService.findOne(authenticateRequest); + const user = await this.usersService.findOne(authenticateRequest.email); if (!user) { throw new UnauthorizedException('INVALID_CREDENTIALS'); } + const isPasswordMatch = await compare( + authenticateRequest.password, + user.password, + ); + + if (!isPasswordMatch) { + throw new UnauthorizedException('INVALID_CREDENTIALS'); + } + // remove password from user object const { password, ...userData } = user; const data = { user: userData }; @@ -46,6 +55,7 @@ export class AuthService { throw new UnauthorizedException('PASSWORD_NOT_MATCH'); } + userCreate.password = this.hashPassword(userCreate.password); const user = await this.usersService.create({ ...userCreate, }); @@ -79,8 +89,8 @@ export class AuthService { } private hashPassword(password: string): string { - const salt = bcyrpt.genSaltSync(10); - const hashedPassword = bcyrpt.hashSync(password, salt); + const salt = genSaltSync(10); + const hashedPassword = hashSync(password, salt); return hashedPassword; } } diff --git a/src/auth/jwt/jwt.strategy.ts b/src/auth/jwt/jwt.strategy.ts index 1d310d5..de97c89 100644 --- a/src/auth/jwt/jwt.strategy.ts +++ b/src/auth/jwt/jwt.strategy.ts @@ -1,7 +1,6 @@ import { Injectable } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; -import { env } from 'process'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { @@ -12,7 +11,7 @@ export class JwtStrategy extends PassportStrategy(Strategy) { ExtractJwt.fromAuthHeaderAsBearerToken(), ]), ignoreExpiration: false, - secretOrKey: env.JWT_SECRET, + secretOrKey: process.env.JWT_SECRET, }); } diff --git a/src/auth/requests/register.request.ts b/src/auth/requests/register.request.ts index 588bb03..2c52f3b 100644 --- a/src/auth/requests/register.request.ts +++ b/src/auth/requests/register.request.ts @@ -20,5 +20,5 @@ export class RegisterRequest { @ApiProperty() @IsNotEmpty() @IsString() - readonly username: string; + readonly userName: string; } diff --git a/src/auth/test/auth.service.spec.ts b/src/auth/test/auth.service.spec.ts index e0f9f1f..c315f6a 100644 --- a/src/auth/test/auth.service.spec.ts +++ b/src/auth/test/auth.service.spec.ts @@ -6,7 +6,6 @@ import { UsersService } from '../../users/users.service'; import { UnauthorizedException } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { IGoogleUser } from '../interface/auth.interface'; -import { mock } from 'node:test'; import { Role } from '../roles/role.enum'; describe('AuthService', () => { diff --git a/src/main.ts b/src/main.ts index db187e4..1e9cd47 100644 --- a/src/main.ts +++ b/src/main.ts @@ -20,7 +20,8 @@ async function bootstrap() { const document = SwaggerModule.createDocument(app, config); SwaggerModule.setup('/api/swagger', app, document); - await app.listen(3000, process.env.HOSTNAME); + // await app.listen(3000, process.env.HOSTNAME); + await app.listen(3000); console.log( `8Tech-auth swagger is running on: ${await app.getUrl()}/api/swagger`, ); diff --git a/src/users/user.controller.ts b/src/users/user.controller.ts index 73e8306..3d99cdd 100644 --- a/src/users/user.controller.ts +++ b/src/users/user.controller.ts @@ -19,6 +19,8 @@ import { UserCreateRequest } from './requests/user-create.request'; export class UserController { constructor(private userService: UsersService) {} + // TODO: add log for each controller + // create user, for dev only // @Post('create') diff --git a/src/users/users.service.ts b/src/users/users.service.ts index 8fe9c2d..4da4992 100644 --- a/src/users/users.service.ts +++ b/src/users/users.service.ts @@ -6,11 +6,8 @@ import { IUser } from './interface/user.interface'; export class UsersService { constructor(private userRepository: UserRepository) {} - async findOne(user: any): Promise { - return this.userRepository.findOnebyEmailPassword( - user.email, - user.password, - ); + async findOne(email: any): Promise { + return this.userRepository.findOneByEmail(email); } async findOneByEmail(email: string): Promise { From 57fc9e3b8f472a29c81222dc517061143b5987bc Mon Sep 17 00:00:00 2001 From: richard483 Date: Sun, 27 Aug 2023 02:35:53 +0700 Subject: [PATCH 4/6] fixed error test, need to cover new cases --- src/auth/auth.controller.ts | 7 +++++-- src/auth/test/auth.controller.spec.ts | 11 +++++++++-- src/auth/test/auth.service.spec.ts | 3 +++ src/users/test/users.service.spec.ts | 25 +++++++++---------------- src/users/user.repository.ts | 2 +- src/users/users.service.ts | 6 +++--- 6 files changed, 30 insertions(+), 24 deletions(-) diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts index 2e690f7..a82c741 100644 --- a/src/auth/auth.controller.ts +++ b/src/auth/auth.controller.ts @@ -25,6 +25,7 @@ export class AuthController { @Post('login') async signIn(@Res() res, @Body() authenticateDto: AuthenticateRequest) { + console.info('#AuthLogin request incoming with: ', authenticateDto); try { const response = await this.authService.login(authenticateDto, res); return res.status(HttpStatus.OK).json({ ...response }); @@ -36,6 +37,7 @@ export class AuthController { @Post('register') async signUp(@Res() res, @Body() request: RegisterRequest) { + console.info('#AuthRegister request incoming with: ', request); try { const response = await this.authService.register(request); return res.status(HttpStatus.OK).json({ ...response }); @@ -54,6 +56,7 @@ export class AuthController { @Get('google/redirect') @UseGuards(GoogleGuard) async googleAuthRedirect(@Request() req, @Res() res) { + console.info('#AuthGoogleAuthRedirect google auth request incoming'); try { const response = await this.authService.googleLogin(req, res); // TODO : redirect to frontend @@ -69,7 +72,7 @@ export class AuthController { @Roles(Role.USER) @UseGuards(JwtAuthGuard, RoleGuard) @Get('info') - async getProfileInfo(@Request() req) { - return req.user; + async getProfileInfo(@Request() req, @Res() res) { + return res.status(HttpStatus.OK).json({ ...req.user }); } } diff --git a/src/auth/test/auth.controller.spec.ts b/src/auth/test/auth.controller.spec.ts index dfc69cb..2a9fdd5 100644 --- a/src/auth/test/auth.controller.spec.ts +++ b/src/auth/test/auth.controller.spec.ts @@ -98,7 +98,7 @@ describe('AuthController', () => { expect(response).toEqual(mockResponse); expect(statusSpy).toBeCalledWith(HttpStatus.BAD_REQUEST); expect(jsonSpy).toBeCalledWith({ - error: mockResponse.message, + error: mockResponse, }); expect(loginSpy).toBeCalledTimes(1); statusSpy.mockRestore(); @@ -118,10 +118,17 @@ describe('AuthController', () => { const mockReq = { user, }; + const jsonSpy = jest.fn().mockReturnValue(user); + const statusSpy = jest.fn().mockReturnValue({ json: jsonSpy }); + const mockRes = { + status: statusSpy, + }; - const response = await controller.getProfileInfo(mockReq); + const response = await controller.getProfileInfo(mockReq, mockRes); expect(response).toEqual(user); + expect(statusSpy).toBeCalledWith(HttpStatus.OK); + expect(jsonSpy).toBeCalledWith(user); }); it('googleRedirectLogin success', async () => { diff --git a/src/auth/test/auth.service.spec.ts b/src/auth/test/auth.service.spec.ts index c315f6a..f09b75a 100644 --- a/src/auth/test/auth.service.spec.ts +++ b/src/auth/test/auth.service.spec.ts @@ -7,6 +7,7 @@ import { UnauthorizedException } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { IGoogleUser } from '../interface/auth.interface'; import { Role } from '../roles/role.enum'; +import { compare } from 'bcrypt'; describe('AuthService', () => { let service: AuthService; @@ -59,6 +60,8 @@ describe('AuthService', () => { .spyOn(userService, 'findOne') .mockResolvedValue(mockAuthenticateDto.user); + (compare as jest.Mock) = jest.fn().mockResolvedValue(true); + const res = await service.validateUser({ email: 'test', password: 'password', diff --git a/src/users/test/users.service.spec.ts b/src/users/test/users.service.spec.ts index f610a66..8d12b98 100644 --- a/src/users/test/users.service.spec.ts +++ b/src/users/test/users.service.spec.ts @@ -34,40 +34,33 @@ describe('UsersService', () => { it('findOne success', async () => { const findOneSpy = jest - .spyOn(reposiotry, 'findOnebyEmailPassword') + .spyOn(reposiotry, 'findOnebyEmail') .mockResolvedValue(userMock); - const res = await service.findOne({ - email: 'email@email.com', - password: 'test', - }); + const res = await service.findOne('email@email.com'); expect(res).toEqual(userMock); - expect(findOneSpy).toBeCalledTimes(1); + expect(findOneSpy).toBeCalledWith('email@email.com'); findOneSpy.mockRestore(); }); it('findOne success null', async () => { const findOneSpy = jest - .spyOn(reposiotry, 'findOnebyEmailPassword') + .spyOn(reposiotry, 'findOnebyEmail') .mockResolvedValue(null); - const res = await service.findOne({ - email: 'email@email.com', - password: 'test', - }); + const res = await service.findOne('email@email.com'); expect(res).toEqual(null); - expect(findOneSpy).toBeCalledTimes(1); - expect(findOneSpy).toBeCalledWith('email@email.com', 'test'); + expect(findOneSpy).toBeCalledWith('email@email.com'); findOneSpy.mockRestore(); }); it('create success', async () => { const findOneSpy = jest - .spyOn(reposiotry, 'findOneByEmail') + .spyOn(reposiotry, 'findOnebyEmail') .mockResolvedValue(null); const createSpy = jest @@ -88,7 +81,7 @@ describe('UsersService', () => { it('create fail email already used', async () => { const findOneSpy = jest - .spyOn(reposiotry, 'findOneByEmail') + .spyOn(reposiotry, 'findOnebyEmail') .mockResolvedValue(userMock); const createSpy = jest.spyOn(reposiotry, 'create'); @@ -110,7 +103,7 @@ describe('UsersService', () => { it('findOnebyEmail success', async () => { const findOneSpy = jest - .spyOn(reposiotry, 'findOneByEmail') + .spyOn(reposiotry, 'findOnebyEmail') .mockResolvedValue(userMock); const res = await service.findOneByEmail('email@email.com'); diff --git a/src/users/user.repository.ts b/src/users/user.repository.ts index 215baa4..be0a987 100644 --- a/src/users/user.repository.ts +++ b/src/users/user.repository.ts @@ -22,7 +22,7 @@ export class UserRepository { }); } - async findOneByEmail(email: string): Promise { + async findOnebyEmail(email: string): Promise { return this.prisma.user.findUnique({ where: { email, diff --git a/src/users/users.service.ts b/src/users/users.service.ts index 4da4992..93fe04f 100644 --- a/src/users/users.service.ts +++ b/src/users/users.service.ts @@ -7,15 +7,15 @@ export class UsersService { constructor(private userRepository: UserRepository) {} async findOne(email: any): Promise { - return this.userRepository.findOneByEmail(email); + return this.userRepository.findOnebyEmail(email); } async findOneByEmail(email: string): Promise { - return this.userRepository.findOneByEmail(email); + return this.userRepository.findOnebyEmail(email); } async create(user: any): Promise { - const existingUser = await this.userRepository.findOneByEmail(user.email); + const existingUser = await this.userRepository.findOnebyEmail(user.email); if (existingUser !== null) { throw new HttpException('EMAIL_ALREADY_USED', HttpStatus.BAD_REQUEST); } From ff3b56b551b414540402129878f1fa1276f896c1 Mon Sep 17 00:00:00 2001 From: richard483 Date: Mon, 28 Aug 2023 01:35:09 +0700 Subject: [PATCH 5/6] added test for auth controller & service --- src/auth/auth.controller.ts | 2 +- src/auth/auth.service.ts | 8 +- src/auth/test/auth.controller.spec.ts | 162 +++++++++++++++----------- src/auth/test/auth.service.spec.ts | 96 ++++++++++++--- 4 files changed, 181 insertions(+), 87 deletions(-) diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts index a82c741..27525bf 100644 --- a/src/auth/auth.controller.ts +++ b/src/auth/auth.controller.ts @@ -31,7 +31,7 @@ export class AuthController { return res.status(HttpStatus.OK).json({ ...response }); } catch (error) { console.error('#AuthLogin error caused by: ', error); - return res.status(error.status).json({ error }); + return res.status(error.status).json({ error: error.message }); } } diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index e76d2c3..94bf59f 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -1,4 +1,8 @@ -import { Injectable, UnauthorizedException } from '@nestjs/common'; +import { + BadRequestException, + Injectable, + UnauthorizedException, +} from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { UsersService } from '../users/users.service'; import { AuthenticateRequest } from './requests/authenticate.request'; @@ -52,7 +56,7 @@ export class AuthService { const { repeatPassword, ...userCreate } = registerRequest; if (userCreate.password !== repeatPassword) { - throw new UnauthorizedException('PASSWORD_NOT_MATCH'); + throw new BadRequestException('PASSWORD_NOT_MATCH'); } userCreate.password = this.hashPassword(userCreate.password); diff --git a/src/auth/test/auth.controller.spec.ts b/src/auth/test/auth.controller.spec.ts index 2a9fdd5..a004f6b 100644 --- a/src/auth/test/auth.controller.spec.ts +++ b/src/auth/test/auth.controller.spec.ts @@ -7,6 +7,34 @@ import { RoleGuard } from '../roles/role.guard'; import { JwtAuthGuard } from '../jwt/jwt-auth.guard'; import { GoogleGuard } from '../google/google.guard'; +const mockIAuthSuccessResponse = { + user: { + id: '1', + userName: 'test', + email: 'email@email.com', + createdAt: new Date(), + updatedAt: new Date(), + roles: ['MEMBER'], + hasGoogleAccount: false, + }, + token: 'token', +}; + +const mockBadRequestResponse = { + status: HttpStatus.BAD_REQUEST, + message: 'ERROR_BAD_REQUEST', +}; + +const mockIUserResponse = { + id: '1', + userName: 'test', + email: 'email@email.com', + createdAt: new Date(), + updatedAt: new Date(), + roles: ['MEMBER'], + hasGoogleAccount: false, +}; + describe('AuthController', () => { let controller: AuthController; let authService: DeepMocked; @@ -39,21 +67,8 @@ describe('AuthController', () => { }); it('login success', async () => { - const mockResponse = { - user: { - id: '1', - userName: 'test', - email: 'email@email.com', - createdAt: new Date(), - updatedAt: new Date(), - roles: ['MEMBER'], - hasGoogleAccount: false, - }, - token: 'token', - }; - const statusSpy = jest.fn().mockReturnThis(); - const jsonSpy = jest.fn().mockReturnValue(mockResponse); + const jsonSpy = jest.fn().mockReturnValue(mockIAuthSuccessResponse); const mockRes = { status: statusSpy, @@ -62,13 +77,13 @@ describe('AuthController', () => { const loginSpy = jest .spyOn(authService, 'login') - .mockResolvedValue(mockResponse); + .mockResolvedValue(mockIAuthSuccessResponse); const response = await controller.signIn(mockRes, null); - expect(response).toEqual(mockResponse); + expect(response).toEqual(mockIAuthSuccessResponse); expect(statusSpy).toBeCalledWith(HttpStatus.OK); - expect(jsonSpy).toBeCalledWith(mockResponse); + expect(jsonSpy).toBeCalledWith(mockIAuthSuccessResponse); expect(loginSpy).toBeCalledTimes(1); statusSpy.mockRestore(); jsonSpy.mockRestore(); @@ -76,13 +91,8 @@ describe('AuthController', () => { }); it('login error', async () => { - const mockResponse = { - status: HttpStatus.BAD_REQUEST, - message: 'ERROR_BAD_REQUEST', - }; - const statusSpy = jest.fn().mockReturnThis(); - const jsonSpy = jest.fn().mockReturnValue(mockResponse); + const jsonSpy = jest.fn().mockReturnValue(mockBadRequestResponse); const mockRes = { status: statusSpy, @@ -91,34 +101,72 @@ describe('AuthController', () => { const loginSpy = jest .spyOn(authService, 'login') - .mockRejectedValue(mockResponse); + .mockRejectedValue(mockBadRequestResponse); const response = await controller.signIn(mockRes, null); - expect(response).toEqual(mockResponse); + expect(response).toEqual(mockBadRequestResponse); expect(statusSpy).toBeCalledWith(HttpStatus.BAD_REQUEST); - expect(jsonSpy).toBeCalledWith({ - error: mockResponse, - }); + expect(jsonSpy).toBeCalledWith({ error: mockBadRequestResponse.message }); expect(loginSpy).toBeCalledTimes(1); statusSpy.mockRestore(); jsonSpy.mockRestore(); loginSpy.mockRestore(); }); - it('getProfileInfo', async () => { - const user = { - id: '1', - userName: 'test', - email: 'email@email.com', - createdAt: new Date(), - updatedAt: new Date(), - roles: ['MEMBER'], + it('register success', async () => { + const statusSpy = jest.fn().mockReturnThis(); + const jsonSpy = jest.fn().mockReturnValue(mockIUserResponse); + + const mockRes = { + status: statusSpy, + json: jsonSpy, + }; + + const registerSpy = jest + .spyOn(authService, 'register') + .mockResolvedValue(mockIUserResponse); + + const response = await controller.signUp(mockRes, null); + + expect(response).toEqual(mockIUserResponse); + expect(statusSpy).toBeCalledWith(HttpStatus.OK); + expect(jsonSpy).toBeCalledWith(mockIUserResponse); + expect(registerSpy).toBeCalledTimes(1); + statusSpy.mockRestore(); + jsonSpy.mockRestore(); + registerSpy.mockRestore(); + }); + + it('register error', async () => { + const statusSpy = jest.fn().mockReturnThis(); + const jsonSpy = jest.fn().mockReturnValue(mockBadRequestResponse); + + const mockRes = { + status: statusSpy, + json: jsonSpy, }; + + const registerSpy = jest + .spyOn(authService, 'register') + .mockRejectedValue(mockBadRequestResponse); + + const response = await controller.signUp(mockRes, null); + + expect(response).toEqual(mockBadRequestResponse); + expect(statusSpy).toBeCalledWith(HttpStatus.BAD_REQUEST); + expect(jsonSpy).toBeCalledWith({ error: mockBadRequestResponse.message }); + expect(registerSpy).toBeCalledTimes(1); + statusSpy.mockRestore(); + jsonSpy.mockRestore(); + registerSpy.mockRestore(); + }); + + it('getProfileInfo', async () => { const mockReq = { - user, + user: mockIUserResponse, }; - const jsonSpy = jest.fn().mockReturnValue(user); + const jsonSpy = jest.fn().mockReturnValue(mockIUserResponse); const statusSpy = jest.fn().mockReturnValue({ json: jsonSpy }); const mockRes = { status: statusSpy, @@ -126,27 +174,14 @@ describe('AuthController', () => { const response = await controller.getProfileInfo(mockReq, mockRes); - expect(response).toEqual(user); + expect(response).toEqual(mockIUserResponse); expect(statusSpy).toBeCalledWith(HttpStatus.OK); - expect(jsonSpy).toBeCalledWith(user); + expect(jsonSpy).toBeCalledWith(mockIUserResponse); }); it('googleRedirectLogin success', async () => { - const mockResponse = { - user: { - id: '1', - userName: 'test', - email: 'email@email.com', - createdAt: new Date(), - updatedAt: new Date(), - roles: ['MEMBER'], - hasGoogleAccount: false, - }, - token: 'token', - }; - const statusSpy = jest.fn().mockReturnThis(); - const jsonSpy = jest.fn().mockReturnValue(mockResponse); + const jsonSpy = jest.fn().mockReturnValue(mockIAuthSuccessResponse); const mockRes = { status: statusSpy, @@ -155,13 +190,13 @@ describe('AuthController', () => { const googleLoginSpy = jest .spyOn(authService, 'googleLogin') - .mockResolvedValue(mockResponse); + .mockResolvedValue(mockIAuthSuccessResponse); const response = await controller.googleAuthRedirect(null, mockRes); - expect(response).toEqual(mockResponse); + expect(response).toEqual(mockIAuthSuccessResponse); expect(statusSpy).toBeCalledWith(HttpStatus.OK); - expect(jsonSpy).toBeCalledWith(mockResponse); + expect(jsonSpy).toBeCalledWith(mockIAuthSuccessResponse); expect(googleLoginSpy).toBeCalledTimes(1); statusSpy.mockRestore(); jsonSpy.mockRestore(); @@ -169,13 +204,8 @@ describe('AuthController', () => { }); it('googleRedirectLogin error', async () => { - const mockResponse = { - status: HttpStatus.BAD_REQUEST, - message: 'ERROR_BAD_REQUEST', - }; - const statusSpy = jest.fn().mockReturnThis(); - const jsonSpy = jest.fn().mockReturnValue(mockResponse); + const jsonSpy = jest.fn().mockReturnValue(mockBadRequestResponse); const mockRes = { status: statusSpy, @@ -184,14 +214,14 @@ describe('AuthController', () => { const loginSpy = jest .spyOn(authService, 'googleLogin') - .mockRejectedValue(mockResponse); + .mockRejectedValue(mockBadRequestResponse); const response = await controller.googleAuthRedirect(null, mockRes); - expect(response).toEqual(mockResponse); + expect(response).toEqual(mockBadRequestResponse); expect(statusSpy).toBeCalledWith(HttpStatus.BAD_REQUEST); expect(jsonSpy).toBeCalledWith({ - error: mockResponse.message, + error: mockBadRequestResponse.message, }); expect(loginSpy).toBeCalledTimes(1); statusSpy.mockRestore(); diff --git a/src/auth/test/auth.service.spec.ts b/src/auth/test/auth.service.spec.ts index f09b75a..125cbe4 100644 --- a/src/auth/test/auth.service.spec.ts +++ b/src/auth/test/auth.service.spec.ts @@ -3,11 +3,12 @@ import { Test, TestingModule } from '@nestjs/testing'; import { DeepMocked, createMock } from '@golevelup/ts-jest'; import { AuthService } from '../auth.service'; import { UsersService } from '../../users/users.service'; -import { UnauthorizedException } from '@nestjs/common'; +import { BadRequestException, UnauthorizedException } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { IGoogleUser } from '../interface/auth.interface'; import { Role } from '../roles/role.enum'; -import { compare } from 'bcrypt'; +import { compare, genSaltSync, hashSync } from 'bcrypt'; +import { RegisterRequest } from '../requests/register.request'; describe('AuthService', () => { let service: AuthService; @@ -15,7 +16,9 @@ describe('AuthService', () => { let jwtService: JwtService; let mockAuthenticateDto: any; + let mockUser: any; let googleUserData: IGoogleUser; + let mockRegisterRequest: any; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -28,17 +31,19 @@ describe('AuthService', () => { userService = module.get(UsersService); jwtService = module.get(JwtService); + mockUser = { + id: '1', + userName: 'test', + email: 'email@email.com', + createdAt: new Date(), + updatedAt: new Date(), + roles: ['USER'], + password: 'password', + hasGoogleAccount: false, + }; + mockAuthenticateDto = { - user: { - id: '1', - userName: 'test', - email: 'email@email.com', - createdAt: new Date(), - updatedAt: new Date(), - roles: ['USER'], - password: 'password', - hasGoogleAccount: false, - }, + user: mockUser, token: null, }; @@ -49,6 +54,13 @@ describe('AuthService', () => { picture: 'picture', _accessToken: 'accessToken', }; + + mockRegisterRequest = { + email: 'email@email.com', + password: 'password', + repeatPassword: 'password', + userName: 'userName', + }; }); it('should be defined', () => { @@ -58,7 +70,7 @@ describe('AuthService', () => { it('validateUser success', async () => { const findOneSpy = jest .spyOn(userService, 'findOne') - .mockResolvedValue(mockAuthenticateDto.user); + .mockResolvedValue(mockUser); (compare as jest.Mock) = jest.fn().mockResolvedValue(true); @@ -67,7 +79,7 @@ describe('AuthService', () => { password: 'password', }); - const { password, ...result } = mockAuthenticateDto.user; + const { password, ...result } = mockUser; expect(res).toEqual({ user: result }); expect(findOneSpy).toBeCalledTimes(1); @@ -94,6 +106,28 @@ describe('AuthService', () => { findOneSpy.mockRestore(); }); + it('validateUser fail wrong password', async () => { + const findOneSpy = jest + .spyOn(userService, 'findOne') + .mockResolvedValue(mockUser); + + (compare as jest.Mock) = jest.fn().mockResolvedValue(false); + + try { + await service.validateUser({ + email: 'test', + password: 'password', + }); + } catch (e) { + expect(e).toBeInstanceOf(UnauthorizedException); + expect(e.message).toBe('INVALID_CREDENTIALS'); + } + + expect(findOneSpy).toBeCalledTimes(1); + + findOneSpy.mockRestore(); + }); + it('login success', async () => { const authenticateDto = { email: 'test', @@ -130,6 +164,32 @@ describe('AuthService', () => { cookieSpy.mockRestore(); }); + it('register success', async () => { + (genSaltSync as jest.Mock) = jest.fn().mockReturnValue('salt'); + (hashSync as jest.Mock) = jest.fn().mockReturnValue('hashedPassword'); + const userCreateSpy = jest + .spyOn(userService, 'create') + .mockResolvedValue(mockUser); + + expect(await service.register(mockRegisterRequest)).toEqual(mockUser); + expect(userCreateSpy).toBeCalledTimes(1); + + userCreateSpy.mockRestore(); + }); + + it('register success', async () => { + mockRegisterRequest.repeatPassword = 'wrongPassword'; + (genSaltSync as jest.Mock) = jest.fn().mockReturnValue('salt'); + (hashSync as jest.Mock) = jest.fn().mockReturnValue('hashedPassword'); + + try { + await service.register(mockRegisterRequest); + } catch (e) { + expect(e).toBeInstanceOf(BadRequestException); + expect(e.message).toBe('PASSWORD_NOT_MATCH'); + } + }); + it('googleLogin success', async () => { const req = { user: { @@ -139,7 +199,7 @@ describe('AuthService', () => { const findOneByEmailSpy = jest .spyOn(userService, 'findOneByEmail') - .mockResolvedValue(mockAuthenticateDto.user); + .mockResolvedValue(mockUser); const signSpy = jest.spyOn(jwtService, 'sign').mockReturnValue('token'); const cookieSpy = jest.fn(); @@ -187,11 +247,11 @@ describe('AuthService', () => { const findOneByEmailSpy = jest .spyOn(userService, 'findOneByEmail') .mockResolvedValueOnce(null) - .mockResolvedValueOnce(mockAuthenticateDto.user); + .mockResolvedValueOnce(mockUser); const createUserSpy = jest .spyOn(userService, 'create') - .mockResolvedValueOnce(mockAuthenticateDto.user); + .mockResolvedValueOnce(mockUser); const signSpy = jest.spyOn(jwtService, 'sign').mockReturnValueOnce('token'); const cookieSpy = jest.fn(); @@ -207,7 +267,7 @@ describe('AuthService', () => { expect(cookieSpy).toBeCalledWith('EToken', 'token'); expect(signSpy).toBeCalledTimes(1); expect(createUserSpy).toBeCalledWith({ - email: mockAuthenticateDto.user.email, + email: mockUser.email, userName: googleUserData.firstName + ' ' + googleUserData.lastName, roles: [Role.USER], hasGoogleAccount: true, From 130bfaa62097fed09ab1ce5151949cb25257c7f3 Mon Sep 17 00:00:00 2001 From: richard483 Date: Mon, 28 Aug 2023 01:37:55 +0700 Subject: [PATCH 6/6] removed unused import --- src/auth/test/auth.service.spec.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/auth/test/auth.service.spec.ts b/src/auth/test/auth.service.spec.ts index 125cbe4..49da8e6 100644 --- a/src/auth/test/auth.service.spec.ts +++ b/src/auth/test/auth.service.spec.ts @@ -8,7 +8,6 @@ import { JwtService } from '@nestjs/jwt'; import { IGoogleUser } from '../interface/auth.interface'; import { Role } from '../roles/role.enum'; import { compare, genSaltSync, hashSync } from 'bcrypt'; -import { RegisterRequest } from '../requests/register.request'; describe('AuthService', () => { let service: AuthService;