├── .gitignore ├── LICENSE ├── README.md ├── package-lock.json ├── package.json └── src ├── controllers ├── AuthController.js └── FriendController.js ├── helpers └── jwt.helper.js ├── middleware └── AuthMiddleware.js ├── routes └── api.js └── server.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NodeJS authenticate user with JWT (JSON Web Tokens) ["accessToken" & "refreshToken"] 2 | 3 | ## Lưu ý quan trọng: Hướng dẫn ở repo này đã cũ vì mình làm từ 2019. Các bạn xem phần mình update mới nhất ở đây nhé: https://youtu.be/XwQ-wxfCeJs 4 | 5 | ## Requirements 6 | 7 | * Nodejs 8.10.x 8 | 9 | Clone project and run test. 10 | 11 | ``` 12 | $ git clone https://git_url_clone 13 | $ cd 14 | $ npm install 15 | $ node src/server.js 16 | ``` 17 | 18 | Guide for this repository is here: 19 | 20 | https://trungquandev.com/nodejs-xac-thuc-nguoi-dung-su-dung-jwt-token-refreshtoken/ 21 | 22 | Author: Trung Quân 23 | 24 | Blog: https://trungquandev.com/ 25 | 26 | CV: https://cv.trungquandev.com/ 27 | 28 | "A little bit of fragrance always clings to the hands that gives you roses!" 29 | 30 | Thanks for watching! 31 | -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-jwt-authenticate-user", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "accepts": { 8 | "version": "1.3.7", 9 | "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", 10 | "integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==", 11 | "requires": { 12 | "mime-types": "~2.1.24", 13 | "negotiator": "0.6.2" 14 | } 15 | }, 16 | "array-flatten": { 17 | "version": "1.1.1", 18 | "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", 19 | "integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=" 20 | }, 21 | "body-parser": { 22 | "version": "1.19.0", 23 | "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz", 24 | "integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==", 25 | "requires": { 26 | "bytes": "3.1.0", 27 | "content-type": "~1.0.4", 28 | "debug": "2.6.9", 29 | "depd": "~1.1.2", 30 | "http-errors": "1.7.2", 31 | "iconv-lite": "0.4.24", 32 | "on-finished": "~2.3.0", 33 | "qs": "6.7.0", 34 | "raw-body": "2.4.0", 35 | "type-is": "~1.6.17" 36 | } 37 | }, 38 | "buffer-equal-constant-time": { 39 | "version": "1.0.1", 40 | "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", 41 | "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" 42 | }, 43 | "bytes": { 44 | "version": "3.1.0", 45 | "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", 46 | "integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==" 47 | }, 48 | "content-disposition": { 49 | "version": "0.5.3", 50 | "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", 51 | "integrity": "sha512-ExO0774ikEObIAEV9kDo50o+79VCUdEB6n6lzKgGwupcVeRlhrj3qGAfwq8G6uBJjkqLrhT0qEYFcWng8z1z0g==", 52 | "requires": { 53 | "safe-buffer": "5.1.2" 54 | } 55 | }, 56 | "content-type": { 57 | "version": "1.0.4", 58 | "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", 59 | "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==" 60 | }, 61 | "cookie": { 62 | "version": "0.4.0", 63 | "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz", 64 | "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==" 65 | }, 66 | "cookie-signature": { 67 | "version": "1.0.6", 68 | "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", 69 | "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=" 70 | }, 71 | "debug": { 72 | "version": "2.6.9", 73 | "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", 74 | "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", 75 | "requires": { 76 | "ms": "2.0.0" 77 | } 78 | }, 79 | "depd": { 80 | "version": "1.1.2", 81 | "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", 82 | "integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=" 83 | }, 84 | "destroy": { 85 | "version": "1.0.4", 86 | "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", 87 | "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" 88 | }, 89 | "ecdsa-sig-formatter": { 90 | "version": "1.0.11", 91 | "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", 92 | "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", 93 | "requires": { 94 | "safe-buffer": "^5.0.1" 95 | } 96 | }, 97 | "ee-first": { 98 | "version": "1.1.1", 99 | "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", 100 | "integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=" 101 | }, 102 | "encodeurl": { 103 | "version": "1.0.2", 104 | "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", 105 | "integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=" 106 | }, 107 | "escape-html": { 108 | "version": "1.0.3", 109 | "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", 110 | "integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=" 111 | }, 112 | "etag": { 113 | "version": "1.8.1", 114 | "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", 115 | "integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=" 116 | }, 117 | "express": { 118 | "version": "4.17.1", 119 | "resolved": "https://registry.npmjs.org/express/-/express-4.17.1.tgz", 120 | "integrity": "sha512-mHJ9O79RqluphRrcw2X/GTh3k9tVv8YcoyY4Kkh4WDMUYKRZUq0h1o0w2rrrxBqM7VoeUVqgb27xlEMXTnYt4g==", 121 | "requires": { 122 | "accepts": "~1.3.7", 123 | "array-flatten": "1.1.1", 124 | "body-parser": "1.19.0", 125 | "content-disposition": "0.5.3", 126 | "content-type": "~1.0.4", 127 | "cookie": "0.4.0", 128 | "cookie-signature": "1.0.6", 129 | "debug": "2.6.9", 130 | "depd": "~1.1.2", 131 | "encodeurl": "~1.0.2", 132 | "escape-html": "~1.0.3", 133 | "etag": "~1.8.1", 134 | "finalhandler": "~1.1.2", 135 | "fresh": "0.5.2", 136 | "merge-descriptors": "1.0.1", 137 | "methods": "~1.1.2", 138 | "on-finished": "~2.3.0", 139 | "parseurl": "~1.3.3", 140 | "path-to-regexp": "0.1.7", 141 | "proxy-addr": "~2.0.5", 142 | "qs": "6.7.0", 143 | "range-parser": "~1.2.1", 144 | "safe-buffer": "5.1.2", 145 | "send": "0.17.1", 146 | "serve-static": "1.14.1", 147 | "setprototypeof": "1.1.1", 148 | "statuses": "~1.5.0", 149 | "type-is": "~1.6.18", 150 | "utils-merge": "1.0.1", 151 | "vary": "~1.1.2" 152 | } 153 | }, 154 | "finalhandler": { 155 | "version": "1.1.2", 156 | "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.1.2.tgz", 157 | "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", 158 | "requires": { 159 | "debug": "2.6.9", 160 | "encodeurl": "~1.0.2", 161 | "escape-html": "~1.0.3", 162 | "on-finished": "~2.3.0", 163 | "parseurl": "~1.3.3", 164 | "statuses": "~1.5.0", 165 | "unpipe": "~1.0.0" 166 | } 167 | }, 168 | "forwarded": { 169 | "version": "0.1.2", 170 | "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz", 171 | "integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=" 172 | }, 173 | "fresh": { 174 | "version": "0.5.2", 175 | "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", 176 | "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=" 177 | }, 178 | "http-errors": { 179 | "version": "1.7.2", 180 | "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.2.tgz", 181 | "integrity": "sha512-uUQBt3H/cSIVfch6i1EuPNy/YsRSOUBXTVfZ+yR7Zjez3qjBz6i9+i4zjNaoqcoFVI4lQJ5plg63TvGfRSDCRg==", 182 | "requires": { 183 | "depd": "~1.1.2", 184 | "inherits": "2.0.3", 185 | "setprototypeof": "1.1.1", 186 | "statuses": ">= 1.5.0 < 2", 187 | "toidentifier": "1.0.0" 188 | } 189 | }, 190 | "iconv-lite": { 191 | "version": "0.4.24", 192 | "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", 193 | "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", 194 | "requires": { 195 | "safer-buffer": ">= 2.1.2 < 3" 196 | } 197 | }, 198 | "inherits": { 199 | "version": "2.0.3", 200 | "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", 201 | "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=" 202 | }, 203 | "ipaddr.js": { 204 | "version": "1.9.0", 205 | "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.0.tgz", 206 | "integrity": "sha512-M4Sjn6N/+O6/IXSJseKqHoFc+5FdGJ22sXqnjTpdZweHK64MzEPAyQZyEU3R/KRv2GLoa7nNtg/C2Ev6m7z+eA==" 207 | }, 208 | "jsonwebtoken": { 209 | "version": "8.5.1", 210 | "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz", 211 | "integrity": "sha512-XjwVfRS6jTMsqYs0EsuJ4LGxXV14zQybNd4L2r0UvbVnSF9Af8x7p5MzbJ90Ioz/9TI41/hTCvznF/loiSzn8w==", 212 | "requires": { 213 | "jws": "^3.2.2", 214 | "lodash.includes": "^4.3.0", 215 | "lodash.isboolean": "^3.0.3", 216 | "lodash.isinteger": "^4.0.4", 217 | "lodash.isnumber": "^3.0.3", 218 | "lodash.isplainobject": "^4.0.6", 219 | "lodash.isstring": "^4.0.1", 220 | "lodash.once": "^4.0.0", 221 | "ms": "^2.1.1", 222 | "semver": "^5.6.0" 223 | }, 224 | "dependencies": { 225 | "ms": { 226 | "version": "2.1.2", 227 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", 228 | "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" 229 | } 230 | } 231 | }, 232 | "jwa": { 233 | "version": "1.4.1", 234 | "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", 235 | "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", 236 | "requires": { 237 | "buffer-equal-constant-time": "1.0.1", 238 | "ecdsa-sig-formatter": "1.0.11", 239 | "safe-buffer": "^5.0.1" 240 | } 241 | }, 242 | "jws": { 243 | "version": "3.2.2", 244 | "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", 245 | "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", 246 | "requires": { 247 | "jwa": "^1.4.1", 248 | "safe-buffer": "^5.0.1" 249 | } 250 | }, 251 | "lodash.includes": { 252 | "version": "4.3.0", 253 | "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", 254 | "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=" 255 | }, 256 | "lodash.isboolean": { 257 | "version": "3.0.3", 258 | "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", 259 | "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=" 260 | }, 261 | "lodash.isinteger": { 262 | "version": "4.0.4", 263 | "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", 264 | "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=" 265 | }, 266 | "lodash.isnumber": { 267 | "version": "3.0.3", 268 | "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", 269 | "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=" 270 | }, 271 | "lodash.isplainobject": { 272 | "version": "4.0.6", 273 | "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", 274 | "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" 275 | }, 276 | "lodash.isstring": { 277 | "version": "4.0.1", 278 | "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", 279 | "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" 280 | }, 281 | "lodash.once": { 282 | "version": "4.1.1", 283 | "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", 284 | "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=" 285 | }, 286 | "media-typer": { 287 | "version": "0.3.0", 288 | "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", 289 | "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=" 290 | }, 291 | "merge-descriptors": { 292 | "version": "1.0.1", 293 | "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", 294 | "integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=" 295 | }, 296 | "methods": { 297 | "version": "1.1.2", 298 | "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", 299 | "integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=" 300 | }, 301 | "mime": { 302 | "version": "1.6.0", 303 | "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", 304 | "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==" 305 | }, 306 | "mime-db": { 307 | "version": "1.40.0", 308 | "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.40.0.tgz", 309 | "integrity": "sha512-jYdeOMPy9vnxEqFRRo6ZvTZ8d9oPb+k18PKoYNYUe2stVEBPPwsln/qWzdbmaIvnhZ9v2P+CuecK+fpUfsV2mA==" 310 | }, 311 | "mime-types": { 312 | "version": "2.1.24", 313 | "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.24.tgz", 314 | "integrity": "sha512-WaFHS3MCl5fapm3oLxU4eYDw77IQM2ACcxQ9RIxfaC3ooc6PFuBMGZZsYpvoXS5D5QTWPieo1jjLdAm3TBP3cQ==", 315 | "requires": { 316 | "mime-db": "1.40.0" 317 | } 318 | }, 319 | "ms": { 320 | "version": "2.0.0", 321 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", 322 | "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" 323 | }, 324 | "negotiator": { 325 | "version": "0.6.2", 326 | "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", 327 | "integrity": "sha512-hZXc7K2e+PgeI1eDBe/10Ard4ekbfrrqG8Ep+8Jmf4JID2bNg7NvCPOZN+kfF574pFQI7mum2AUqDidoKqcTOw==" 328 | }, 329 | "on-finished": { 330 | "version": "2.3.0", 331 | "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", 332 | "integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", 333 | "requires": { 334 | "ee-first": "1.1.1" 335 | } 336 | }, 337 | "parseurl": { 338 | "version": "1.3.3", 339 | "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", 340 | "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==" 341 | }, 342 | "path-to-regexp": { 343 | "version": "0.1.7", 344 | "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", 345 | "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" 346 | }, 347 | "proxy-addr": { 348 | "version": "2.0.5", 349 | "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.5.tgz", 350 | "integrity": "sha512-t/7RxHXPH6cJtP0pRG6smSr9QJidhB+3kXu0KgXnbGYMgzEnUxRQ4/LDdfOwZEMyIh3/xHb8PX3t+lfL9z+YVQ==", 351 | "requires": { 352 | "forwarded": "~0.1.2", 353 | "ipaddr.js": "1.9.0" 354 | } 355 | }, 356 | "qs": { 357 | "version": "6.7.0", 358 | "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz", 359 | "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==" 360 | }, 361 | "range-parser": { 362 | "version": "1.2.1", 363 | "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", 364 | "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==" 365 | }, 366 | "raw-body": { 367 | "version": "2.4.0", 368 | "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.4.0.tgz", 369 | "integrity": "sha512-4Oz8DUIwdvoa5qMJelxipzi/iJIi40O5cGV1wNYp5hvZP8ZN0T+jiNkL0QepXs+EsQ9XJ8ipEDoiH70ySUJP3Q==", 370 | "requires": { 371 | "bytes": "3.1.0", 372 | "http-errors": "1.7.2", 373 | "iconv-lite": "0.4.24", 374 | "unpipe": "1.0.0" 375 | } 376 | }, 377 | "safe-buffer": { 378 | "version": "5.1.2", 379 | "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", 380 | "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" 381 | }, 382 | "safer-buffer": { 383 | "version": "2.1.2", 384 | "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", 385 | "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" 386 | }, 387 | "semver": { 388 | "version": "5.7.1", 389 | "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", 390 | "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" 391 | }, 392 | "send": { 393 | "version": "0.17.1", 394 | "resolved": "https://registry.npmjs.org/send/-/send-0.17.1.tgz", 395 | "integrity": "sha512-BsVKsiGcQMFwT8UxypobUKyv7irCNRHk1T0G680vk88yf6LBByGcZJOTJCrTP2xVN6yI+XjPJcNuE3V4fT9sAg==", 396 | "requires": { 397 | "debug": "2.6.9", 398 | "depd": "~1.1.2", 399 | "destroy": "~1.0.4", 400 | "encodeurl": "~1.0.2", 401 | "escape-html": "~1.0.3", 402 | "etag": "~1.8.1", 403 | "fresh": "0.5.2", 404 | "http-errors": "~1.7.2", 405 | "mime": "1.6.0", 406 | "ms": "2.1.1", 407 | "on-finished": "~2.3.0", 408 | "range-parser": "~1.2.1", 409 | "statuses": "~1.5.0" 410 | }, 411 | "dependencies": { 412 | "ms": { 413 | "version": "2.1.1", 414 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", 415 | "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" 416 | } 417 | } 418 | }, 419 | "serve-static": { 420 | "version": "1.14.1", 421 | "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.14.1.tgz", 422 | "integrity": "sha512-JMrvUwE54emCYWlTI+hGrGv5I8dEwmco/00EvkzIIsR7MqrHonbD9pO2MOfFnpFntl7ecpZs+3mW+XbQZu9QCg==", 423 | "requires": { 424 | "encodeurl": "~1.0.2", 425 | "escape-html": "~1.0.3", 426 | "parseurl": "~1.3.3", 427 | "send": "0.17.1" 428 | } 429 | }, 430 | "setprototypeof": { 431 | "version": "1.1.1", 432 | "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz", 433 | "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==" 434 | }, 435 | "statuses": { 436 | "version": "1.5.0", 437 | "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", 438 | "integrity": "sha1-Fhx9rBd2Wf2YEfQ3cfqZOBR4Yow=" 439 | }, 440 | "toidentifier": { 441 | "version": "1.0.0", 442 | "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", 443 | "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==" 444 | }, 445 | "type-is": { 446 | "version": "1.6.18", 447 | "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", 448 | "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", 449 | "requires": { 450 | "media-typer": "0.3.0", 451 | "mime-types": "~2.1.24" 452 | } 453 | }, 454 | "unpipe": { 455 | "version": "1.0.0", 456 | "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", 457 | "integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=" 458 | }, 459 | "utils-merge": { 460 | "version": "1.0.1", 461 | "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", 462 | "integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=" 463 | }, 464 | "vary": { 465 | "version": "1.1.2", 466 | "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", 467 | "integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=" 468 | } 469 | } 470 | } 471 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nodejs-jwt-authenticate-user", 3 | "version": "1.0.0", 4 | "description": "NodeJS authenticate user with JWT (JSON Web Tokens) - https://trungquandev.com", 5 | "main": "src/server.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/trungquan17/nodejs-jwt-authenticate-user.git" 12 | }, 13 | "keywords": [], 14 | "author": "", 15 | "license": "ISC", 16 | "bugs": { 17 | "url": "https://github.com/trungquan17/nodejs-jwt-authenticate-user/issues" 18 | }, 19 | "homepage": "https://github.com/trungquan17/nodejs-jwt-authenticate-user#readme", 20 | "dependencies": { 21 | "express": "^4.17.1", 22 | "jsonwebtoken": "^8.5.1" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/controllers/AuthController.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by trungquandev.com's author on 16/10/2019. 3 | * src/controllers/auth.js 4 | */ 5 | const jwtHelper = require("../helpers/jwt.helper"); 6 | const debug = console.log.bind(console); 7 | 8 | // Biến cục bộ trên server này sẽ lưu trữ tạm danh sách token 9 | // Trong dự án thực tế, nên lưu chỗ khác, có thể lưu vào Redis hoặc DB 10 | let tokenList = {}; 11 | 12 | // Thời gian sống của token 13 | const accessTokenLife = process.env.ACCESS_TOKEN_LIFE || "1h"; 14 | // Mã secretKey này phải được bảo mật tuyệt đối, các bạn có thể lưu vào biến môi trường hoặc file 15 | const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET || "access-token-secret-example-trungquandev.com-green-cat-a@"; 16 | 17 | // Thời gian sống của refreshToken 18 | const refreshTokenLife = process.env.REFRESH_TOKEN_LIFE || "3650d"; 19 | // Mã secretKey này phải được bảo mật tuyệt đối, các bạn có thể lưu vào biến môi trường hoặc file 20 | const refreshTokenSecret = process.env.REFRESH_TOKEN_SECRET || "refresh-token-secret-example-trungquandev.com-green-cat-a@"; 21 | 22 | /** 23 | * controller login 24 | * @param {*} req 25 | * @param {*} res 26 | */ 27 | let login = async (req, res) => { 28 | try { 29 | debug(`Đang giả lập hành động đăng nhập thành công với Email: ${req.body.email} và Password: ${req.body.password}`); 30 | // Mình sẽ comment mô tả lại một số bước khi làm thực tế cho các bạn như sau nhé: 31 | // - Đầu tiên Kiểm tra xem email người dùng đã tồn tại trong hệ thống hay chưa? 32 | // - Nếu chưa tồn tại thì reject: User not found. 33 | // - Nếu tồn tại user thì sẽ lấy password mà user truyền lên, băm ra và so sánh với mật khẩu của user lưu trong Database 34 | // - Nếu password sai thì reject: Password is incorrect. 35 | // - Nếu password đúng thì chúng ta bắt đầu thực hiện tạo mã JWT và gửi về cho người dùng. 36 | // Trong ví dụ demo này mình sẽ coi như tất cả các bước xác thực ở trên đều ok, mình chỉ xử lý phần JWT trở về sau thôi nhé: 37 | debug(`Thực hiện fake thông tin user...`); 38 | const userFakeData = { 39 | _id: "1234-5678-910JQK-tqd", 40 | name: "Trung Quân", 41 | email: req.body.email, 42 | }; 43 | 44 | debug(`Thực hiện tạo mã Token, [thời gian sống 1 giờ.]`); 45 | const accessToken = await jwtHelper.generateToken(userFakeData, accessTokenSecret, accessTokenLife); 46 | 47 | debug(`Thực hiện tạo mã Refresh Token, [thời gian sống 10 năm] =))`); 48 | const refreshToken = await jwtHelper.generateToken(userFakeData, refreshTokenSecret, refreshTokenLife); 49 | 50 | // Lưu lại 2 mã access & Refresh token, với key chính là cái refreshToken để đảm bảo unique và không sợ hacker sửa đổi dữ liệu truyền lên. 51 | // lưu ý trong dự án thực tế, nên lưu chỗ khác, có thể lưu vào Redis hoặc DB 52 | tokenList[refreshToken] = {accessToken, refreshToken}; 53 | 54 | debug(`Gửi Token và Refresh Token về cho client...`); 55 | return res.status(200).json({accessToken, refreshToken}); 56 | } catch (error) { 57 | return res.status(500).json(error); 58 | } 59 | } 60 | 61 | /** 62 | * controller refreshToken 63 | * @param {*} req 64 | * @param {*} res 65 | */ 66 | let refreshToken = async (req, res) => { 67 | // User gửi mã refresh token kèm theo trong body 68 | const refreshTokenFromClient = req.body.refreshToken; 69 | // debug("tokenList: ", tokenList); 70 | 71 | // Nếu như tồn tại refreshToken truyền lên và nó cũng nằm trong tokenList của chúng ta 72 | if (refreshTokenFromClient && (tokenList[refreshTokenFromClient])) { 73 | try { 74 | // Verify kiểm tra tính hợp lệ của cái refreshToken và lấy dữ liệu giải mã decoded 75 | const decoded = await jwtHelper.verifyToken(refreshTokenFromClient, refreshTokenSecret); 76 | 77 | // Thông tin user lúc này các bạn có thể lấy thông qua biến decoded.data 78 | // có thể mở comment dòng debug bên dưới để xem là rõ nhé. 79 | // debug("decoded: ", decoded); 80 | const userFakeData = decoded.data; 81 | 82 | debug(`Thực hiện tạo mã Token trong bước gọi refresh Token, [thời gian sống vẫn là 1 giờ.]`); 83 | const accessToken = await jwtHelper.generateToken(userFakeData, accessTokenSecret, accessTokenLife); 84 | 85 | // gửi token mới về cho người dùng 86 | return res.status(200).json({accessToken}); 87 | } catch (error) { 88 | // Lưu ý trong dự án thực tế hãy bỏ dòng debug bên dưới, mình để đây để debug lỗi cho các bạn xem thôi 89 | debug(error); 90 | 91 | res.status(403).json({ 92 | message: 'Invalid refresh token.', 93 | }); 94 | } 95 | } else { 96 | // Không tìm thấy token trong request 97 | return res.status(403).send({ 98 | message: 'No token provided.', 99 | }); 100 | } 101 | }; 102 | 103 | module.exports = { 104 | login: login, 105 | refreshToken: refreshToken, 106 | } 107 | -------------------------------------------------------------------------------- /src/controllers/FriendController.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by trungquandev.com's author on 16/10/2019. 3 | * src/controllers/Friend.js 4 | */ 5 | const debug = console.log.bind(console); 6 | 7 | let friendLists = (req, res) => { 8 | debug(`Xác thực token hợp lệ, thực hiện giả lập lấy danh sách bạn bè của user và trả về cho người dùng...`); 9 | // Lưu ý khi làm thực tế thì việc lấy danh sách này là query tới DB để lấy nhé. Ở đây mình chỉ mock thôi. 10 | const friends = [ 11 | { 12 | name: "Cat: Russian Blue", 13 | }, 14 | { 15 | name: "Cat: Maine Coon", 16 | }, 17 | { 18 | name: "Cat: Balinese", 19 | }, 20 | ]; 21 | return res.status(200).json(friends); 22 | } 23 | 24 | module.exports = { 25 | friendLists: friendLists, 26 | }; 27 | -------------------------------------------------------------------------------- /src/helpers/jwt.helper.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by trungquandev.com's author on 16/10/2019. 3 | * src/controllers/auth.js 4 | */ 5 | const jwt = require("jsonwebtoken"); 6 | 7 | /** 8 | * private function generateToken 9 | * @param user 10 | * @param secretSignature 11 | * @param tokenLife 12 | */ 13 | let generateToken = (user, secretSignature, tokenLife) => { 14 | return new Promise((resolve, reject) => { 15 | // Định nghĩa những thông tin của user mà bạn muốn lưu vào token ở đây 16 | const userData = { 17 | _id: user._id, 18 | name: user.name, 19 | email: user.email, 20 | } 21 | // Thực hiện ký và tạo token 22 | jwt.sign( 23 | {data: userData}, 24 | secretSignature, 25 | { 26 | algorithm: "HS256", 27 | expiresIn: tokenLife, 28 | }, 29 | (error, token) => { 30 | if (error) { 31 | return reject(error); 32 | } 33 | resolve(token); 34 | }); 35 | }); 36 | } 37 | 38 | /** 39 | * This module used for verify jwt token 40 | * @param {*} token 41 | * @param {*} secretKey 42 | */ 43 | let verifyToken = (token, secretKey) => { 44 | return new Promise((resolve, reject) => { 45 | jwt.verify(token, secretKey, (error, decoded) => { 46 | if (error) { 47 | return reject(error); 48 | } 49 | resolve(decoded); 50 | }); 51 | }); 52 | } 53 | 54 | module.exports = { 55 | generateToken: generateToken, 56 | verifyToken: verifyToken, 57 | }; 58 | -------------------------------------------------------------------------------- /src/middleware/AuthMiddleware.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by trungquandev.com's author on 16/10/2019. 3 | * src/controllers/auth.js 4 | */ 5 | const jwtHelper = require("../helpers/jwt.helper"); 6 | const debug = console.log.bind(console); 7 | 8 | // Mã secretKey này phải được bảo mật tuyệt đối, các bạn có thể lưu vào biến môi trường hoặc file 9 | const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET || "access-token-secret-example-trungquandev.com-green-cat-a@"; 10 | 11 | /** 12 | * Middleware: Authorization user by Token 13 | * @param {*} req 14 | * @param {*} res 15 | * @param {*} next 16 | */ 17 | let isAuth = async (req, res, next) => { 18 | // Lấy token được gửi lên từ phía client, thông thường tốt nhất là các bạn nên truyền token vào header 19 | const tokenFromClient = req.body.token || req.query.token || req.headers["x-access-token"]; 20 | 21 | if (tokenFromClient) { 22 | // Nếu tồn tại token 23 | try { 24 | // Thực hiện giải mã token xem có hợp lệ hay không? 25 | const decoded = await jwtHelper.verifyToken(tokenFromClient, accessTokenSecret); 26 | 27 | // Nếu token hợp lệ, lưu thông tin giải mã được vào đối tượng req, dùng cho các xử lý ở phía sau. 28 | req.jwtDecoded = decoded; 29 | 30 | // Cho phép req đi tiếp sang controller. 31 | next(); 32 | } catch (error) { 33 | // Nếu giải mã gặp lỗi: Không đúng, hết hạn...etc: 34 | // Lưu ý trong dự án thực tế hãy bỏ dòng debug bên dưới, mình để đây để debug lỗi cho các bạn xem thôi 35 | debug("Error while verify token:", error); 36 | return res.status(401).json({ 37 | message: 'Unauthorized.', 38 | }); 39 | } 40 | } else { 41 | // Không tìm thấy token trong request 42 | return res.status(403).send({ 43 | message: 'No token provided.', 44 | }); 45 | } 46 | } 47 | 48 | module.exports = { 49 | isAuth: isAuth, 50 | }; 51 | -------------------------------------------------------------------------------- /src/routes/api.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by trungquandev.com's author on 16/10/2019. 3 | * src/routes/api.js 4 | */ 5 | const express = require("express"); 6 | const router = express.Router(); 7 | const AuthMiddleWare = require("../middleware/AuthMiddleware"); 8 | const AuthController = require("../controllers/AuthController"); 9 | const FriendController = require("../controllers/FriendController"); 10 | 11 | /** 12 | * Init all APIs on your application 13 | * @param {*} app from express 14 | */ 15 | let initAPIs = (app) => { 16 | router.post("/login", AuthController.login); 17 | router.post("/refresh-token", AuthController.refreshToken); 18 | 19 | // Sử dụng authMiddleware.isAuth trước những api cần xác thực 20 | router.use(AuthMiddleWare.isAuth); 21 | // List Protect APIs: 22 | router.get("/friends", FriendController.friendLists); 23 | // router.get("/example-protect-api", ExampleController.someAction); 24 | 25 | return app.use("/", router); 26 | } 27 | 28 | module.exports = initAPIs; 29 | -------------------------------------------------------------------------------- /src/server.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by trungquandev.com's author on 16/10/2019. 3 | * src/server.js 4 | */ 5 | const express = require("express"); 6 | const app = express(); 7 | const initAPIs = require("./routes/api"); 8 | 9 | // Cho phép các api của ứng dụng xử lý dữ liệu từ body của request 10 | app.use(express.json()); 11 | 12 | // Khởi tạo các routes cho ứng dụng 13 | initAPIs(app); 14 | 15 | // chọn một port mà bạn muốn và sử dụng để chạy ứng dụng tại local 16 | let port = 8017; 17 | app.listen(port, () => { 18 | console.log(`Hello trungquandev.com, I'm running at localhost:${port}/`); 19 | }); 20 | --------------------------------------------------------------------------------