├── .dockerignore ├── .env.example ├── .eslintrc ├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── .huskyrc ├── .lintstagedrc ├── .nycrc.json ├── .prettierrc ├── .vscode └── settings.json ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE.md ├── README.md ├── collabcode.png ├── dev_private_key.pem ├── dev_public_key.pem ├── docker-compose.yml ├── nodemon.json ├── package-lock.json ├── package.json ├── src ├── app │ ├── components │ │ ├── auth │ │ │ ├── auth.controller.js │ │ │ ├── auth.middleware.js │ │ │ └── auth.route.js │ │ └── user │ │ │ ├── user.controller.js │ │ │ ├── user.middleware.js │ │ │ ├── user.model.js │ │ │ └── user.route.js │ ├── routes.js │ └── server.js ├── config │ ├── database.js │ └── winston.js ├── index.js └── lib │ ├── apis.lib.js │ └── jwt.lib.js ├── start.sh └── test ├── app └── components │ ├── auth │ └── auth.controller.test.js │ └── user │ ├── user.controller.test.js │ └── user.model.test.js ├── data-builders ├── index.js ├── token.builder.js └── user.builder.js ├── lib ├── apis.lib.test.js └── jwt.lib.test.js └── mocha.opts /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | #Server 2 | NODE_ENV=development 3 | HOST=http://localhost 4 | PORT=3001 5 | CORS=http://localhost:3000 #FrontEnd 6 | 7 | #Cookie 8 | #For development remove "Secure;" 9 | COOKIE_OPTIONS=SameSite=Strict; HttpOnly; 10 | 11 | # MongoDB 12 | MONGO_URI=mongodb://root:root@mongo:27017/training?authSource=admin 13 | 14 | # Auth 15 | ALGORITHM=RS256 16 | 17 | AUTH_PRIVATE_KEY_PATH=/app/dev_private_key.pem 18 | AUTH_PUBLIC_KEY_PATH=/app/dev_public_key.pem 19 | 20 | # APIs 21 | HOST_API_EMAIL=http://email:3002 -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "es6": true, 4 | "node": true, 5 | "mocha": true 6 | }, 7 | "extends": ["airbnb-base", "plugin:prettier/recommended"], 8 | "plugins": [], 9 | "globals": { 10 | "Atomics": "readonly", 11 | "SharedArrayBuffer": "readonly" 12 | }, 13 | "parserOptions": { 14 | "ecmaVersion": 2018, 15 | "sourceType": "module" 16 | }, 17 | "rules": {} 18 | } 19 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "" 5 | labels: bug 6 | assignees: "" 7 | --- 8 | 9 | **Describe the bug** 10 | A clear and concise description of what the bug is. 11 | 12 | **To Reproduce** 13 | Steps to reproduce the behavior: 14 | 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | 28 | - OS: [e.g. iOS] 29 | - Browser [e.g. chrome, safari] 30 | - Version [e.g. 22] 31 | 32 | **Smartphone (please complete the following information):** 33 | 34 | - Device: [e.g. iPhone6] 35 | - OS: [e.g. iOS8.1] 36 | - Browser [e.g. stock browser, safari] 37 | - Version [e.g. 22] 38 | 39 | **Additional context** 40 | Add any other context about the problem here. 41 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: "" 5 | labels: enhancement 6 | assignees: "" 7 | --- 8 | 9 | **Is your feature request related to a problem? Please describe.** 10 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 11 | 12 | **Describe the solution you'd like** 13 | A clear and concise description of what you want to happen. 14 | 15 | **Describe alternatives you've considered** 16 | A clear and concise description of any alternative solutions or features you've considered. 17 | 18 | **Additional context** 19 | Add any other context or screenshots about the feature request here. 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # mochawesome folder 2 | mochawesome-report/ 3 | 4 | # dotenv environment variables file 5 | .env 6 | 7 | # nyc reports 8 | .nyc_output/ 9 | coverage/ 10 | 11 | ### Linux ### 12 | *~ 13 | 14 | # temporary files which can be created if a process still has a handle open of a deleted file 15 | .fuse_hidden* 16 | 17 | # KDE directory preferences 18 | .directory 19 | 20 | # Linux trash folder which might appear on any partition or disk 21 | .Trash-* 22 | 23 | # .nfs files are created when an open file is removed but is still being accessed 24 | .nfs* 25 | 26 | ### macOS ### 27 | # General 28 | .DS_Store 29 | .AppleDouble 30 | .LSOverride 31 | 32 | # Icon must end with two \r 33 | Icon 34 | 35 | # Thumbnails 36 | ._* 37 | 38 | # Files that might appear in the root of a volume 39 | .DocumentRevisions-V100 40 | .fseventsd 41 | .Spotlight-V100 42 | .TemporaryItems 43 | .Trashes 44 | .VolumeIcon.icns 45 | .com.apple.timemachine.donotpresent 46 | 47 | # Directories potentially created on remote AFP share 48 | .AppleDB 49 | .AppleDesktop 50 | Network Trash Folder 51 | Temporary Items 52 | .apdisk 53 | 54 | ### Node ### 55 | # Logs 56 | logs 57 | *.log 58 | npm-debug.log* 59 | 60 | # Diagnostic reports (https://nodejs.org/api/report.html) 61 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 62 | 63 | # Runtime data 64 | pids 65 | *.pid 66 | *.seed 67 | *.pid.lock 68 | 69 | # Directory for instrumented libs generated by jscoverage/JSCover 70 | lib-cov 71 | 72 | # Dependency directories 73 | node_modules 74 | jspm_packages 75 | node_modules/ 76 | jspm_packages/ 77 | 78 | 79 | # Optional npm cache directory 80 | .npm 81 | 82 | # Optional eslint cache 83 | .eslintcache 84 | 85 | # Optional REPL history 86 | .node_repl_history 87 | 88 | ### Windows ### 89 | # Windows thumbnail cache files 90 | Thumbs.db 91 | Thumbs.db:encryptable 92 | ehthumbs.db 93 | ehthumbs_vista.db 94 | 95 | # Dump file 96 | *.stackdump 97 | 98 | # Folder config file 99 | [Dd]esktop.ini 100 | 101 | # Recycle Bin used on file shares 102 | $RECYCLE.BIN/ 103 | 104 | # Windows Installer files 105 | *.cab 106 | *.msi 107 | *.msix 108 | *.msm 109 | *.msp 110 | 111 | # Windows shortcuts 112 | *.lnk 113 | 114 | # Others 115 | dist -------------------------------------------------------------------------------- /.huskyrc: -------------------------------------------------------------------------------- 1 | { 2 | "hooks": { 3 | "pre-commit": "lint-staged" 4 | } 5 | } -------------------------------------------------------------------------------- /.lintstagedrc: -------------------------------------------------------------------------------- 1 | { 2 | "*.{js}": [ 3 | "eslint --fix", 4 | "git add" 5 | ] 6 | } -------------------------------------------------------------------------------- /.nycrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "reporter": ["html", "text-summary"] 3 | } 4 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true 3 | } 4 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.tabSize": 2, 3 | "editor.formatOnSave": true, 4 | "editor.codeActionsOnSave": { 5 | "source.fixAll.eslint": true 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to make participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | - Using welcoming and inclusive language 18 | - Being respectful of differing viewpoints and experiences 19 | - Gracefully accepting constructive criticism 20 | - Focusing on what is best for the community 21 | - Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | - The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | - Trolling, insulting/derogatory comments, and personal or political attacks 28 | - Public or private harassment 29 | - Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | - Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies within all project spaces, and it also applies when 49 | an individual is representing the project or its community in public spaces. 50 | Examples of representing a project or community include using an official 51 | project e-mail address, posting via an official social media account, or acting 52 | as an appointed representative at an online or offline event. Representation of 53 | a project may be further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at [gueio@collabcode.tech](mailto:gueio@collabcode.tech). All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing 2 | 3 | This project is released under the MPL 2.0 license. 4 | Before implementing new features and changes, feel free to [submit an issue](https://github.com/CollabCodeTech/collabcodetraining-api-auth/issues/new). We're going to talk here :stuck_out_tongue_winking_eye:. 5 | 6 | ### Code of Conduct 7 | 8 | This project adheres to the Contributor Covenant [code of conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to [gueio@collabcode.tech](mailto:gueio@collabcode.tech). 9 | 10 | ### Issues and Questions 11 | 12 | We have an official [Discord](https://discord.gg/YeeEAYj) server where we can give helpful advices if you have questions. 13 | 14 | ## How to submit a pull request? 15 | 16 | 1. Fork [this repository](https://github.com/CollabCodeTech/collabcodetraining-api-auth/fork). 17 | 2. Create a new branch with the feature name. (Eg: feature/chat-support, hotfix/website-header) 18 | 3. Make your changes. 19 | 4. Commit your changes. Please follow the [styleguides](#styleguides) 20 | 5. Push your changes. 21 | 6. Submit your pull request. 22 | 23 | We use [GitFlow](https://nvie.com/posts/a-successful-git-branching-model/) so unless your PR is a `hotfix`, your feature branch must be created from the `develop` branch. 24 | 25 | **TIP:** This [Git extension](https://github.com/nvie/gitflow) makes Git Flow a piece of cake. GitKraken also has [built-in support](https://support.gitkraken.com/git-workflows-and-extensions/git-flow/) for GitFlow 26 | 27 | ## Styleguides 28 | 29 | ### Git Commit Styleguide 30 | 31 | - Use the present tense ("Add feature" not "Added feature") 32 | - Use the imperative mood ("Move cursor to..." not "Moves cursor to...") 33 | - Limit the first line to 72 characters or less 34 | - Reference issues and pull requests liberally after the first line 35 | - Consider starting the commit message with an applicable emoji: 36 | - :art: `:art:` when improving the format/structure of the code 37 | - :zap: `:zap:` when improving performance 38 | - :pencil: `:pencil:` when writing docs 39 | - :penguin: `:penguin:` when fixing something on Linux 40 | - :apple: `:apple:` when fixing something on macOS 41 | - :checkered_flag: `:checkered_flag:` when fixing something on Windows 42 | - :bug: `:bug:` when fixing a bug 43 | - :fire: `:fire:` when removing code or files 44 | - :green_heart: `:green_heart:` when fixing the CI build 45 | - :white_check_mark: `:white_check_mark:` when adding or updating tests 46 | - :lock: `:lock:` when dealing with security 47 | - :arrow_up: `:arrow_up:` when upgrading dependencies 48 | - :arrow_down: `:arrow_down:` when downgrading dependencies 49 | - :rotating_light: `:rotating_light:` when removing linter warnings 50 | - Full emoji reference in [gitmoji](https://gitmoji.carloscuesta.me/) 51 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:12 as training-auth 2 | WORKDIR /app 3 | COPY . ./ 4 | RUN npm i --silent 5 | RUN chmod +x ./start.sh 6 | CMD ./start.sh -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # Mozilla Public License Version 2.0 2 | 3 | 1. Definitions 4 | 5 | --- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | 88 | --- 89 | 90 | 2.1. Grants 91 | 92 | Each Contributor hereby grants You a world-wide, royalty-free, 93 | non-exclusive license: 94 | 95 | (a) under intellectual property rights (other than patent or trademark) 96 | Licensable by such Contributor to use, reproduce, make available, 97 | modify, display, perform, distribute, and otherwise exploit its 98 | Contributions, either on an unmodified basis, with Modifications, or 99 | as part of a Larger Work; and 100 | 101 | (b) under Patent Claims of such Contributor to make, use, sell, offer 102 | for sale, have made, import, and otherwise transfer either its 103 | Contributions or its Contributor Version. 104 | 105 | 2.2. Effective Date 106 | 107 | The licenses granted in Section 2.1 with respect to any Contribution 108 | become effective for each Contribution on the date the Contributor first 109 | distributes such Contribution. 110 | 111 | 2.3. Limitations on Grant Scope 112 | 113 | The licenses granted in this Section 2 are the only rights granted under 114 | this License. No additional rights or licenses will be implied from the 115 | distribution or licensing of Covered Software under this License. 116 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 117 | Contributor: 118 | 119 | (a) for any code that a Contributor has removed from Covered Software; 120 | or 121 | 122 | (b) for infringements caused by: (i) Your and any other third party's 123 | modifications of Covered Software, or (ii) the combination of its 124 | Contributions with other software (except as part of its Contributor 125 | Version); or 126 | 127 | (c) under Patent Claims infringed by Covered Software in the absence of 128 | its Contributions. 129 | 130 | This License does not grant any rights in the trademarks, service marks, 131 | or logos of any Contributor (except as may be necessary to comply with 132 | the notice requirements in Section 3.4). 133 | 134 | 2.4. Subsequent Licenses 135 | 136 | No Contributor makes additional grants as a result of Your choice to 137 | distribute the Covered Software under a subsequent version of this 138 | License (see Section 10.2) or under the terms of a Secondary License (if 139 | permitted under the terms of Section 3.3). 140 | 141 | 2.5. Representation 142 | 143 | Each Contributor represents that the Contributor believes its 144 | Contributions are its original creation(s) or it has sufficient rights 145 | to grant the rights to its Contributions conveyed by this License. 146 | 147 | 2.6. Fair Use 148 | 149 | This License is not intended to limit any rights You have under 150 | applicable copyright doctrines of fair use, fair dealing, or other 151 | equivalents. 152 | 153 | 2.7. Conditions 154 | 155 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 156 | in Section 2.1. 157 | 158 | 3. Responsibilities 159 | 160 | --- 161 | 162 | 3.1. Distribution of Source Form 163 | 164 | All distribution of Covered Software in Source Code Form, including any 165 | Modifications that You create or to which You contribute, must be under 166 | the terms of this License. You must inform recipients that the Source 167 | Code Form of the Covered Software is governed by the terms of this 168 | License, and how they can obtain a copy of this License. You may not 169 | attempt to alter or restrict the recipients' rights in the Source Code 170 | Form. 171 | 172 | 3.2. Distribution of Executable Form 173 | 174 | If You distribute Covered Software in Executable Form then: 175 | 176 | (a) such Covered Software must also be made available in Source Code 177 | Form, as described in Section 3.1, and You must inform recipients of 178 | the Executable Form how they can obtain a copy of such Source Code 179 | Form by reasonable means in a timely manner, at a charge no more 180 | than the cost of distribution to the recipient; and 181 | 182 | (b) You may distribute such Executable Form under the terms of this 183 | License, or sublicense it under different terms, provided that the 184 | license for the Executable Form does not attempt to limit or alter 185 | the recipients' rights in the Source Code Form under this License. 186 | 187 | 3.3. Distribution of a Larger Work 188 | 189 | You may create and distribute a Larger Work under terms of Your choice, 190 | provided that You also comply with the requirements of this License for 191 | the Covered Software. If the Larger Work is a combination of Covered 192 | Software with a work governed by one or more Secondary Licenses, and the 193 | Covered Software is not Incompatible With Secondary Licenses, this 194 | License permits You to additionally distribute such Covered Software 195 | under the terms of such Secondary License(s), so that the recipient of 196 | the Larger Work may, at their option, further distribute the Covered 197 | Software under the terms of either this License or such Secondary 198 | License(s). 199 | 200 | 3.4. Notices 201 | 202 | You may not remove or alter the substance of any license notices 203 | (including copyright notices, patent notices, disclaimers of warranty, 204 | or limitations of liability) contained within the Source Code Form of 205 | the Covered Software, except that You may alter any license notices to 206 | the extent required to remedy known factual inaccuracies. 207 | 208 | 3.5. Application of Additional Terms 209 | 210 | You may choose to offer, and to charge a fee for, warranty, support, 211 | indemnity or liability obligations to one or more recipients of Covered 212 | Software. However, You may do so only on Your own behalf, and not on 213 | behalf of any Contributor. You must make it absolutely clear that any 214 | such warranty, support, indemnity, or liability obligation is offered by 215 | You alone, and You hereby agree to indemnify every Contributor for any 216 | liability incurred by such Contributor as a result of warranty, support, 217 | indemnity or liability terms You offer. You may include additional 218 | disclaimers of warranty and limitations of liability specific to any 219 | jurisdiction. 220 | 221 | 4. Inability to Comply Due to Statute or Regulation 222 | 223 | --- 224 | 225 | If it is impossible for You to comply with any of the terms of this 226 | License with respect to some or all of the Covered Software due to 227 | statute, judicial order, or regulation then You must: (a) comply with 228 | the terms of this License to the maximum extent possible; and (b) 229 | describe the limitations and the code they affect. Such description must 230 | be placed in a text file included with all distributions of the Covered 231 | Software under this License. Except to the extent prohibited by statute 232 | or regulation, such description must be sufficiently detailed for a 233 | recipient of ordinary skill to be able to understand it. 234 | 235 | 5. Termination 236 | 237 | --- 238 | 239 | 5.1. The rights granted under this License will terminate automatically 240 | if You fail to comply with any of its terms. However, if You become 241 | compliant, then the rights granted under this License from a particular 242 | Contributor are reinstated (a) provisionally, unless and until such 243 | Contributor explicitly and finally terminates Your grants, and (b) on an 244 | ongoing basis, if such Contributor fails to notify You of the 245 | non-compliance by some reasonable means prior to 60 days after You have 246 | come back into compliance. Moreover, Your grants from a particular 247 | Contributor are reinstated on an ongoing basis if such Contributor 248 | notifies You of the non-compliance by some reasonable means, this is the 249 | first time You have received notice of non-compliance with this License 250 | from such Contributor, and You become compliant prior to 30 days after 251 | Your receipt of the notice. 252 | 253 | 5.2. If You initiate litigation against any entity by asserting a patent 254 | infringement claim (excluding declaratory judgment actions, 255 | counter-claims, and cross-claims) alleging that a Contributor Version 256 | directly or indirectly infringes any patent, then the rights granted to 257 | You by any and all Contributors for the Covered Software under Section 258 | 2.1 of this License shall terminate. 259 | 260 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 261 | end user license agreements (excluding distributors and resellers) which 262 | have been validly granted by You or Your distributors under this License 263 | prior to termination shall survive termination. 264 | 265 | --- 266 | 267 | - * 268 | - 6. Disclaimer of Warranty \* 269 | - ------------------------- \* 270 | - * 271 | - Covered Software is provided under this License on an "as is" \* 272 | - basis, without warranty of any kind, either expressed, implied, or \* 273 | - statutory, including, without limitation, warranties that the \* 274 | - Covered Software is free of defects, merchantable, fit for a \* 275 | - particular purpose or non-infringing. The entire risk as to the \* 276 | - quality and performance of the Covered Software is with You. \* 277 | - Should any Covered Software prove defective in any respect, You \* 278 | - (not any Contributor) assume the cost of any necessary servicing, \* 279 | - repair, or correction. This disclaimer of warranty constitutes an \* 280 | - essential part of this License. No use of any Covered Software is \* 281 | - authorized under this License except under this disclaimer. \* 282 | - * 283 | 284 | --- 285 | 286 | --- 287 | 288 | - * 289 | - 7. Limitation of Liability \* 290 | - -------------------------- \* 291 | - * 292 | - Under no circumstances and under no legal theory, whether tort \* 293 | - (including negligence), contract, or otherwise, shall any \* 294 | - Contributor, or anyone who distributes Covered Software as \* 295 | - permitted above, be liable to You for any direct, indirect, \* 296 | - special, incidental, or consequential damages of any character \* 297 | - including, without limitation, damages for lost profits, loss of \* 298 | - goodwill, work stoppage, computer failure or malfunction, or any \* 299 | - and all other commercial damages or losses, even if such party \* 300 | - shall have been informed of the possibility of such damages. This \* 301 | - limitation of liability shall not apply to liability for death or \* 302 | - personal injury resulting from such party's negligence to the \* 303 | - extent applicable law prohibits such limitation. Some \* 304 | - jurisdictions do not allow the exclusion or limitation of \* 305 | - incidental or consequential damages, so this exclusion and \* 306 | - limitation may not apply to You. \* 307 | - * 308 | 309 | --- 310 | 311 | 8. Litigation 312 | 313 | --- 314 | 315 | Any litigation relating to this License may be brought only in the 316 | courts of a jurisdiction where the defendant maintains its principal 317 | place of business and such litigation shall be governed by laws of that 318 | jurisdiction, without reference to its conflict-of-law provisions. 319 | Nothing in this Section shall prevent a party's ability to bring 320 | cross-claims or counter-claims. 321 | 322 | 9. Miscellaneous 323 | 324 | --- 325 | 326 | This License represents the complete agreement concerning the subject 327 | matter hereof. If any provision of this License is held to be 328 | unenforceable, such provision shall be reformed only to the extent 329 | necessary to make it enforceable. Any law or regulation which provides 330 | that the language of a contract shall be construed against the drafter 331 | shall not be used to construe this License against a Contributor. 332 | 333 | 10. Versions of the License 334 | 335 | --- 336 | 337 | 10.1. New Versions 338 | 339 | Mozilla Foundation is the license steward. Except as provided in Section 340 | 10.3, no one other than the license steward has the right to modify or 341 | publish new versions of this License. Each version will be given a 342 | distinguishing version number. 343 | 344 | 10.2. Effect of New Versions 345 | 346 | You may distribute the Covered Software under the terms of the version 347 | of the License under which You originally received the Covered Software, 348 | or under the terms of any subsequent version published by the license 349 | steward. 350 | 351 | 10.3. Modified Versions 352 | 353 | If you create software not governed by this License, and you want to 354 | create a new license for such software, you may create and use a 355 | modified version of this License if you rename the license and remove 356 | any references to the name of the license steward (except to note that 357 | such modified license differs from this License). 358 | 359 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 360 | Licenses 361 | 362 | If You choose to distribute Source Code Form that is Incompatible With 363 | Secondary Licenses under the terms of this version of the License, the 364 | notice described in Exhibit B of this License must be attached. 365 | 366 | ## Exhibit A - Source Code Form License Notice 367 | 368 | This Source Code Form is subject to the terms of the Mozilla Public 369 | License, v. 2.0. If a copy of the MPL was not distributed with this 370 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 371 | 372 | If it is not possible or desirable to put the notice in a particular 373 | file, then You may include the notice in a location (such as a LICENSE 374 | file in a relevant directory) where a recipient would be likely to look 375 | for such a notice. 376 | 377 | You may add additional accurate notices of copyright ownership. 378 | 379 | ## Exhibit B - "Incompatible With Secondary Licenses" Notice 380 | 381 | This Source Code Form is "Incompatible With Secondary Licenses", as 382 | defined by the Mozilla Public License, v. 2.0. 383 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![CollabCode](collabcode.png 'Logo da CollabCode') 2 | 3 | # CollabCode Training 4 | 5 | An Open Source online course platform. 6 | 7 | ## Getting Started 8 | 9 | 1. Fork this repo and clone in your machine; 10 | 11 | 2. Change directory to `collabcodetraining-api-auth` where you cloned it; 12 | 13 | 3. At the terminal, run: 14 | 15 | ```bash 16 | npm install 17 | cp example.env .env 18 | npm run dev 19 | ``` 20 | 21 | 4. Open up [localhost:5000](http://localhost:5000) and start using it 22 | 23 | ### Prerequisites 24 | 25 | - Npm 26 | - Node (>=10.16.3) 27 | 28 | ## Running the tests 29 | 30 | ```bash 31 | npm test 32 | ``` 33 | 34 | ## Running MongoDB with docker 35 | 36 | #### Prerequisites 37 | 38 | - Docker (>=1.13.1) 39 | 40 | Run the following command on the project root directory: 41 | 42 | ```bash 43 | docker-compose up -d 44 | ``` 45 | 46 | ## Built With 47 | 48 | - [Restify](http://restify.com) 49 | 50 | ## Contributing 51 | 52 | Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us. 53 | 54 | ## Authors 55 | 56 | - **Joviane Jardim** - [@joviane](https://twitter.com/jovianejardim) 57 | - **Marco Bruno** - [@marcobrunobr](https://twitter.com/marcobrunobr) 58 | 59 | See also the list of [contributors](https://github.com/CollabCodeTech/collabcodetraining-api-auth/contributors) who participated in this project. 60 | 61 | ## License 62 | 63 | This project is licensed under the MPL 2.0 License - see the [LICENSE](LICENSE.md) file for details 64 | 65 | ## Acknowledgments 66 | 67 | Thanks to all members of CollabCode's community for the support! We love you! 68 | -------------------------------------------------------------------------------- /collabcode.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CollabCodeTech/training-auth/575cc9aede6acbb2c31333d3bdc957e9559e7c5c/collabcode.png -------------------------------------------------------------------------------- /dev_private_key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIEpQIBAAKCAQEAvkD1SrVjFWR7ijhR6uHTh1NCZacuIrOLX8bZySFMxFSu+BIt 3 | G860PC70vKtu3bv1oZzq9TifjVgkt1LpMwpq9tiJ1wM5BKl1F8m6gxEAjLAZgdYf 4 | 74OrC5Msh6sj/qKhOgNExj+BOgDhRyM9X6eNR85hM7Iw4VHvVGZaECDmaQE6GcTj 5 | ualkSaIji90Kji1dRRNe0lGO0tZiKeJZju1+syw+ZYSM1yjrfSDjWGcLrvfSCzv3 6 | G5uK92u4GPKEr5jPnnxMt/iOXHj6hcOAUkrPto2Rr1E1AYh/bfHV0SnnJbe1AnKw 7 | sBjwUEnqt99Jg7GBcqA8AC7pEf5tXDN0UUiWEwIDAQABAoIBAQCBbtvyKZjxMt1B 8 | WbORYnVwOVqQob4naZLGZBhCV19Mqngm2ObLZkMENsXVnaPdQkSH4KOQlScnF/JS 9 | rhts2AeRTBvqpYyi+U5qEpnLFUQUcrHHvQ8Y+bDiPQwseGgSkj2xpAuj/AxEk9iv 10 | dvAIJYtecK98ZhwPDpkOCFv5YQigIkNFKy6pidjYeQtSYNVA4stdcXNDzhvhTN0T 11 | nRloogA1vG8gCQJ9CnH7m3bsIgp375tdcipUHuFxWTUUC9I9bYcFUiN6zk9k9CI3 12 | TqjLPSoyBz4yKI7Ym2n8kMsJZgbbKEinBgXF4ub8FYA0LontXfxwYwti0yaFe+9W 13 | PvufUwHhAoGBAN1kYeD9R/Mmgl6YPZjK9HjM/3WHP0o3n+UwIC0tOTxlAIVY05Hu 14 | yA/mmVbQVIcRH9GgvQbeIyL7cOBkGKoOFhUwnZIzStnECK84DItgjbhuD/sKNRQC 15 | +AyHuixXKLWxuk+o+tLihCa1KFbn9D6YbEKlqV/OADe850ZSNFZSzso5AoGBANv+ 16 | fNZ/YLRtoRLqeyucqR5YGm4I0MqTSPZ9kHG7SiuXt+tGf4Sa7cPXCPnAsQsTfbMy 17 | BeeIttsGIKHRq1JQwrMnwc8IosK2e2RUREVxlXcDfWo4Egd4tkKlY5ahlPjPXk48 18 | wXtp4NNlS0iWCZOSg/3qyir+/HfL+cjfuWbsa5KrAoGBAMF5rVQK5Krol3wFface 19 | joFXXVSfaj7414JaCXSRlfhiqA7grpxU2X+T3aORkp0q6OywlSEAViKHLIDc2PUc 20 | NE42Wy3eJ2ahu5ks2UGgkpl/jfWsWPBxG8cPgjKnxMrsU86z9OcAz85n+KXiNX/S 21 | gqHH1noENAqByneY9WYPHep5AoGBAMHDnTrjyE5CvPtHMaNRAZfra6P8+cFjBoGs 22 | SJwTpRlOMTz1w/0M5Fx4urwXnxgtW6qIZbDvtnalJ/q/DJGc9lALtWVfqtOrHHVa 23 | zyMHDulbVoxGxIJ2LLn4qAWVXfvj0aFBW/0SXWZ0MmHFXLvw8Xak5NoH6mCtdN0b 24 | SFZB5+GvAoGAdsP+0SQrJzDuYjM3JgK/dqnZdzgexNXlucCStc0c6gHcBAyNphfG 25 | 5CzgzrF5MbhVYi04Uc59WwtFJVvdgFlUI1VB3brOuTPC29AWVeOF9H2UCAQSUc+B 26 | aeS1Bm0bq3gWKu61LctVRs5iTgXen+Kpjp1oMFj06LJR4OyHzP14U/Q= 27 | -----END RSA PRIVATE KEY----- 28 | -------------------------------------------------------------------------------- /dev_public_key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvkD1SrVjFWR7ijhR6uHT 3 | h1NCZacuIrOLX8bZySFMxFSu+BItG860PC70vKtu3bv1oZzq9TifjVgkt1LpMwpq 4 | 9tiJ1wM5BKl1F8m6gxEAjLAZgdYf74OrC5Msh6sj/qKhOgNExj+BOgDhRyM9X6eN 5 | R85hM7Iw4VHvVGZaECDmaQE6GcTjualkSaIji90Kji1dRRNe0lGO0tZiKeJZju1+ 6 | syw+ZYSM1yjrfSDjWGcLrvfSCzv3G5uK92u4GPKEr5jPnnxMt/iOXHj6hcOAUkrP 7 | to2Rr1E1AYh/bfHV0SnnJbe1AnKwsBjwUEnqt99Jg7GBcqA8AC7pEf5tXDN0UUiW 8 | EwIDAQAB 9 | -----END PUBLIC KEY----- 10 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.7' 2 | services: 3 | mongo: 4 | image: mongo 5 | environment: 6 | MONGO_INITDB_ROOT_USERNAME: root 7 | MONGO_INITDB_ROOT_PASSWORD: root 8 | ports: 9 | - '27017:27017' 10 | 11 | email: 12 | image: collabcode/training-email 13 | 14 | auth: 15 | build: . 16 | volumes: 17 | - .:/app 18 | ports: 19 | - '3001:${PORT}' 20 | environment: 21 | - NODE_ENV 22 | depends_on: 23 | - mongo 24 | - email 25 | -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- 1 | { 2 | "watch": ["src"], 3 | "ext": "js", 4 | "execMap": { 5 | "js": "sucrase-node src/index.js" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "api-auth", 3 | "version": "0.0.1", 4 | "description": "API Auth CollabCodeTraining", 5 | "main": "index.js", 6 | "scripts": { 7 | "dev": "nodemon src/index.js", 8 | "build": "sucrase ./src -d ./dist --transforms imports", 9 | "allTest": "NODE_ENV=test ./node_modules/.bin/nyc ./node_modules/.bin/_mocha", 10 | "test": "docker exec -it training-auth_auth_1 npm run allTest" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/CollabCodeTech/collabcodetraining-api-auth.git" 15 | }, 16 | "author": "CollabCode", 17 | "license": "MPL-2.0", 18 | "bugs": { 19 | "url": "https://github.com/CollabCodeTech/collabcodetraining-api-auth/issues" 20 | }, 21 | "homepage": "https://github.com/CollabCodeTech/collabcodetraining-api-auth#readme", 22 | "dependencies": { 23 | "app-root-path": "^2.2.1", 24 | "bcrypt": "^3.0.8", 25 | "dotenv": "^8.2.0", 26 | "helmet": "^3.21.3", 27 | "jsonwebtoken": "^8.5.1", 28 | "moment": "^2.24.0", 29 | "mongoose": "^5.9.3", 30 | "morgan": "^1.9.1", 31 | "restify": "^8.5.1", 32 | "restify-cors-middleware": "^1.1.1", 33 | "restify-errors": "^8.0.2", 34 | "restify-jwt-community": "^1.1.2", 35 | "saslprep": "^1.0.3", 36 | "superagent": "^5.2.2", 37 | "winston": "^3.2.1", 38 | "yup": "^0.27.0" 39 | }, 40 | "devDependencies": { 41 | "chai": "^4.2.0", 42 | "eslint": "^6.8.0", 43 | "eslint-config-airbnb-base": "^14.0.0", 44 | "eslint-config-prettier": "^6.10.0", 45 | "eslint-plugin-import": "^2.20.1", 46 | "eslint-plugin-prettier": "^3.1.2", 47 | "faker": "^4.1.0", 48 | "husky": "^3.1.0", 49 | "lint-staged": "^9.5.0", 50 | "mocha": "^6.2.2", 51 | "mochawesome": "^4.1.0", 52 | "nodemon": "^1.19.4", 53 | "nyc": "^14.1.1", 54 | "prettier": "^1.19.1", 55 | "sucrase": "^3.12.1", 56 | "supertest": "^4.0.2" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/app/components/auth/auth.controller.js: -------------------------------------------------------------------------------- 1 | import bcrypt from 'bcrypt'; 2 | import { UnauthorizedError, InternalServerError } from 'restify-errors'; 3 | 4 | import Jwt from '../../../lib/jwt.lib'; 5 | 6 | const setCookieJwt = (res, jwt) => { 7 | const { COOKIE_OPTIONS } = process.env; 8 | 9 | res.header('Set-Cookie', `jwt=${jwt}; ${COOKIE_OPTIONS}`); 10 | }; 11 | 12 | const login = async ({ body: { password } }, res) => { 13 | try { 14 | const { user } = res.locals; 15 | const match = await bcrypt.compare(password, user.password); 16 | 17 | if (!match) { 18 | return res.send( 19 | new UnauthorizedError({ 20 | toJSON: () => ({ field: 'password', error: 'Senha inválida' }) 21 | }) 22 | ); 23 | } 24 | 25 | const token = Jwt.encode({ name: user.name }, { expiresIn: '1day' }); 26 | 27 | setCookieJwt(res, token); 28 | 29 | return res.send(200, { 30 | message: 'Login efetuado com sucesso!', 31 | name: user.name 32 | }); 33 | } catch (error) { 34 | return res.send(new InternalServerError({ cause: error })); 35 | } 36 | }; 37 | 38 | const refreshToken = ({ headers: { cookie } }, res) => { 39 | try { 40 | const jwt = cookie.match(/jwt=([^;]+)/)[1]; 41 | const newToken = Jwt.refresh(jwt); 42 | 43 | setCookieJwt(res, newToken); 44 | 45 | return res.send(200, { 46 | msg: 'Token atualizado com sucesso' 47 | }); 48 | } catch (error) { 49 | if (error.name === 'TokenExpiredError') { 50 | return res.send(new UnauthorizedError('Token expirou')); 51 | } 52 | 53 | return res.send(new InternalServerError({ cause: error })); 54 | } 55 | }; 56 | 57 | export { login, refreshToken }; 58 | -------------------------------------------------------------------------------- /src/app/components/auth/auth.middleware.js: -------------------------------------------------------------------------------- 1 | import { BadRequestError, UnauthorizedError } from 'restify-errors'; 2 | 3 | import User from '../user/user.model'; 4 | 5 | const hasBody = (req, res, next) => { 6 | if (!req.body) { 7 | return res.send( 8 | new BadRequestError({ 9 | toJSON: () => ({ 10 | field: 'email', 11 | error: 'Email e senha não informados' 12 | }) 13 | }) 14 | ); 15 | } 16 | 17 | return next(); 18 | }; 19 | 20 | const loadUser = async (req, res, next) => { 21 | const { email } = req.body; 22 | const user = await User.findOne({ email }).select('+password'); 23 | 24 | if (!user) { 25 | return res.send( 26 | new UnauthorizedError({ 27 | toJSON: () => ({ field: 'email', error: 'Email não cadastrado' }) 28 | }) 29 | ); 30 | } 31 | 32 | res.locals = { user }; 33 | return next(); 34 | }; 35 | 36 | const hasCookieJwt = ({ headers: { cookie } }, res, next) => { 37 | if (/jwt/.test(cookie)) { 38 | return next(); 39 | } 40 | 41 | return res.send(new UnauthorizedError('Faltando o jwt no cookie')); 42 | }; 43 | 44 | export { hasBody, loadUser, hasCookieJwt }; 45 | -------------------------------------------------------------------------------- /src/app/components/auth/auth.route.js: -------------------------------------------------------------------------------- 1 | import { hasBody, loadUser, hasCookieJwt } from './auth.middleware'; 2 | import { login, refreshToken } from './auth.controller'; 3 | 4 | export default (server, prefix) => { 5 | server.post(`${prefix}/auth/login`, hasBody, loadUser, login); 6 | server.post(`${prefix}/auth/refresh`, hasCookieJwt, refreshToken); 7 | }; 8 | -------------------------------------------------------------------------------- /src/app/components/user/user.controller.js: -------------------------------------------------------------------------------- 1 | import { InternalServerError, UnauthorizedError } from 'restify-errors'; 2 | 3 | import User from './user.model'; 4 | import jwt from '../../../lib/jwt.lib'; 5 | import { sendUserConfirmationEmail } from '../../../lib/apis.lib'; 6 | 7 | const setCookieJwt = (res, jwt) => { 8 | const { COOKIE_OPTIONS } = process.env; 9 | 10 | res.header('Set-Cookie', `jwt=${jwt}; ${COOKIE_OPTIONS}`); 11 | }; 12 | 13 | const save = async ({ body }, res) => { 14 | try { 15 | const { email } = await User.create(body); 16 | 17 | const token = jwt.encode({ email }, { expiresIn: '1h' }); 18 | await sendUserConfirmationEmail(email, token); 19 | 20 | setCookieJwt(res, token); 21 | 22 | return res.send(201, { email }); 23 | } catch (error) { 24 | return res.send(new InternalServerError({ cause: error })); 25 | } 26 | }; 27 | 28 | const confirmationEmail = async ({ body }, res) => { 29 | try { 30 | const { token } = body; 31 | const { email } = jwt.decode(token); 32 | await User.updateOne({ email }, { $set: { emailConfirmed: true } }); 33 | 34 | return res.send(200, { email }); 35 | } catch (error) { 36 | const { name } = error; 37 | const errors = { 38 | TokenExpiredError: 'O token que você informou expirou', 39 | JsonWebTokenError: 'O token que você informou é inválido' 40 | }; 41 | 42 | if (errors[error.name]) { 43 | return res.send( 44 | new UnauthorizedError({ 45 | toJSON: () => ({ 46 | error: errors[name] 47 | }) 48 | }) 49 | ); 50 | } 51 | 52 | return res.send(500, error); 53 | } 54 | }; 55 | 56 | export { save, confirmationEmail }; 57 | -------------------------------------------------------------------------------- /src/app/components/user/user.middleware.js: -------------------------------------------------------------------------------- 1 | import { ConflictError, BadRequestError } from 'restify-errors'; 2 | import * as yup from 'yup'; 3 | 4 | import User from './user.model'; 5 | 6 | yup.setLocale({ 7 | mixed: { 8 | required: 'Campo obrigatório' 9 | }, 10 | string: { 11 | email: 'Por favor, preencha com email válido', 12 | min: ({ min }) => `Use no mínimo ${min} caracteres` 13 | } 14 | }); 15 | 16 | const schema = yup.object().shape({ 17 | name: yup 18 | .string() 19 | .min(2) 20 | .required(), 21 | email: yup 22 | .string() 23 | .email() 24 | .required(), 25 | password: yup 26 | .string() 27 | .min(8) 28 | .required() 29 | }); 30 | 31 | const userAlreadyExists = user => !!user.length; 32 | 33 | const hasBodyToSave = ({ body }, res, next) => { 34 | schema 35 | .validate(body, { abortEarly: false }) 36 | .then(async () => { 37 | const user = await User.find({ email: body.email }); 38 | 39 | if (userAlreadyExists(user)) { 40 | return res.send( 41 | new ConflictError({ 42 | toJSON: () => [{ field: 'email', error: 'Email já cadastrado' }] 43 | }) 44 | ); 45 | } 46 | 47 | return next(); 48 | }) 49 | .catch(error => { 50 | const msgError = error.inner.map(({ path, message }) => ({ 51 | field: path, 52 | error: message 53 | })); 54 | 55 | res.send(new BadRequestError({ toJSON: () => msgError })); 56 | }); 57 | }; 58 | 59 | const hasBodyToConfirmation = ({ body }, res, next) => { 60 | if (!body) { 61 | return res.send( 62 | new BadRequestError({ 63 | toJSON: () => ({ 64 | error: 'Não foi enviado um token no body' 65 | }) 66 | }) 67 | ); 68 | } 69 | 70 | return next(); 71 | }; 72 | 73 | export { hasBodyToSave, hasBodyToConfirmation }; 74 | -------------------------------------------------------------------------------- /src/app/components/user/user.model.js: -------------------------------------------------------------------------------- 1 | import bcrypt from 'bcrypt'; 2 | import { Schema, model } from 'mongoose'; 3 | 4 | const UserSchema = new Schema({ 5 | name: { 6 | type: String, 7 | required: true, 8 | minlength: 2, 9 | maxlength: 50 10 | }, 11 | email: { 12 | type: String, 13 | required: true, 14 | trim: true, 15 | lowercase: true, 16 | unique: true 17 | }, 18 | password: { 19 | type: String, 20 | required: true, 21 | minlength: 8, 22 | select: false 23 | }, 24 | emailConfirmed: { 25 | type: Boolean, 26 | required: true, 27 | default: false, 28 | select: false 29 | } 30 | }); 31 | 32 | async function bcryptPassword(next) { 33 | if (this.isModified('password')) { 34 | try { 35 | const hash = await bcrypt.hash(this.password, 10); 36 | this.password = hash; 37 | } catch (error) { 38 | return next(error); 39 | } 40 | } 41 | 42 | return next(); 43 | } 44 | 45 | UserSchema.pre('save', bcryptPassword); 46 | 47 | export default model('User', UserSchema); 48 | -------------------------------------------------------------------------------- /src/app/components/user/user.route.js: -------------------------------------------------------------------------------- 1 | import { hasBodyToSave, hasBodyToConfirmation } from './user.middleware'; 2 | import { save, confirmationEmail } from './user.controller'; 3 | 4 | export default (server, prefix) => { 5 | server.post( 6 | `${prefix}/user/confirmation`, 7 | hasBodyToConfirmation, 8 | confirmationEmail 9 | ); 10 | server.post(`${prefix}/user`, hasBodyToSave, save); 11 | }; 12 | -------------------------------------------------------------------------------- /src/app/routes.js: -------------------------------------------------------------------------------- 1 | import user from './components/user/user.route'; 2 | import auth from './components/auth/auth.route'; 3 | 4 | export default server => { 5 | const prefix = '/api'; 6 | 7 | user(server, prefix); 8 | auth(server, prefix); 9 | }; 10 | -------------------------------------------------------------------------------- /src/app/server.js: -------------------------------------------------------------------------------- 1 | import { config } from 'dotenv'; 2 | import restify from 'restify'; 3 | import helmet from 'helmet'; 4 | import morgan from 'morgan'; 5 | import winston from 'winston'; 6 | import corsMiddleware from 'restify-cors-middleware'; 7 | 8 | import database from '../config/database'; 9 | import routes from './routes'; 10 | 11 | config(); 12 | 13 | const server = restify.createServer(); 14 | 15 | database(); 16 | 17 | const { CORS } = process.env; 18 | 19 | const cors = corsMiddleware({ 20 | origins: [CORS], 21 | credentials: true 22 | }); 23 | 24 | server.pre(cors.preflight); 25 | 26 | server.use(cors.actual); 27 | server.use(helmet()); 28 | server.use( 29 | morgan('combined', { 30 | stream: winston.stream.write, 31 | // Skip request logging when running the tests 32 | skip: () => process.env.NODE_ENV === 'test' 33 | }) 34 | ); 35 | server.use(restify.plugins.bodyParser()); 36 | 37 | routes(server); 38 | 39 | export default server; 40 | -------------------------------------------------------------------------------- /src/config/database.js: -------------------------------------------------------------------------------- 1 | import { config } from 'dotenv'; 2 | import mongoose from 'mongoose'; 3 | 4 | import logger from './winston'; 5 | 6 | export default () => { 7 | config(); 8 | const { MONGO_URI } = process.env; 9 | 10 | mongoose 11 | .connect(MONGO_URI, { 12 | useNewUrlParser: true, 13 | useUnifiedTopology: true, 14 | useFindAndModify: false, 15 | }) 16 | .then(() => logger.info(`Connect to MongoDB at ${MONGO_URI}`)) 17 | .catch((error) => { 18 | logger.error('Failed to connect to MongoDB...', error); 19 | process.exit(); 20 | }); 21 | }; 22 | -------------------------------------------------------------------------------- /src/config/winston.js: -------------------------------------------------------------------------------- 1 | import appRoot from 'app-root-path'; 2 | import { createLogger, format, transports } from 'winston'; 3 | 4 | const options = { 5 | file: { 6 | level: 'info', 7 | filename: `${appRoot}/logs/app.log`, 8 | handleExceptions: true, 9 | json: true, 10 | maxsize: 5242880, // 5MB 11 | maxFiles: 5, 12 | colorize: false, 13 | }, 14 | console: { 15 | level: 'debug', 16 | handleExceptions: true, 17 | json: false, 18 | colorize: true, 19 | }, 20 | }; 21 | 22 | const logger = createLogger({ 23 | transports: [ 24 | new transports.File(options.file), 25 | new transports.Console(options.console), 26 | ], 27 | exitOnError: false, 28 | format: format.combine(format.colorize(), format.simple()), 29 | }); 30 | 31 | logger.stream = { 32 | write(message) { 33 | logger.info(message); 34 | }, 35 | }; 36 | 37 | export default logger; 38 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import { config } from 'dotenv'; 2 | 3 | import server from './app/server'; 4 | import logger from './config/winston'; 5 | 6 | config(); 7 | 8 | const { PORT } = process.env; 9 | 10 | server.listen(PORT, () => { 11 | logger.silly(); 12 | logger.info(`Listening at http://localhost:${PORT}`); 13 | logger.info('Turn off server: ctrl + c'); 14 | }); 15 | -------------------------------------------------------------------------------- /src/lib/apis.lib.js: -------------------------------------------------------------------------------- 1 | import { config } from 'dotenv'; 2 | import superagent from 'superagent'; 3 | 4 | config(); 5 | const { HOST, PORT, HOST_API_EMAIL } = process.env; 6 | 7 | async function sendUserConfirmationEmail(email, token) { 8 | const url = `${HOST_API_EMAIL}/user/confirmation`; 9 | const contentLink = `${HOST}:${PORT}/user/confirmation`; 10 | const link = `${contentLink}/${token}`; 11 | const res = await superagent.post(url).send({ 12 | email, 13 | contentLink, 14 | link 15 | }); 16 | 17 | return res; 18 | } 19 | 20 | // eslint-disable-next-line import/prefer-default-export 21 | export { sendUserConfirmationEmail }; 22 | -------------------------------------------------------------------------------- /src/lib/jwt.lib.js: -------------------------------------------------------------------------------- 1 | import { readFileSync } from 'fs'; 2 | import { config } from 'dotenv'; 3 | import jwt from 'jsonwebtoken'; 4 | 5 | config(); 6 | 7 | const { ALGORITHM, AUTH_PRIVATE_KEY_PATH, AUTH_PUBLIC_KEY_PATH } = process.env; 8 | const filePrivateKey = readFileSync(AUTH_PRIVATE_KEY_PATH); 9 | const filePublicKey = readFileSync(AUTH_PUBLIC_KEY_PATH); 10 | 11 | const sign = (data, jwtOptions = {}) => { 12 | const token = jwt.sign(data, filePrivateKey, { 13 | ...jwtOptions, 14 | algorithm: ALGORITHM 15 | }); 16 | 17 | return token; 18 | }; 19 | 20 | const encode = (data, options = {}) => { 21 | const token = sign(data, options); 22 | 23 | return token; 24 | }; 25 | 26 | const decode = token => { 27 | const data = jwt.verify(token, filePublicKey, { algorithms: [ALGORITHM] }); 28 | 29 | return data; 30 | }; 31 | 32 | const refresh = (token, options = {}) => { 33 | const data = decode(token); 34 | 35 | delete data.iat; 36 | delete data.exp; 37 | 38 | return encode(data, options); 39 | }; 40 | 41 | export default { encode, decode, refresh }; 42 | -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | if [ "$NODE_ENV" = "production" ] ; then 4 | npm run build 5 | else 6 | npm run dev 7 | fi -------------------------------------------------------------------------------- /test/app/components/auth/auth.controller.test.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable prefer-destructuring */ 2 | import request from 'supertest'; 3 | import { expect } from 'chai'; 4 | import moment from 'moment'; 5 | 6 | import server from '../../../../src/app/server'; 7 | import User from '../../../../src/app/components/user/user.model'; 8 | import Jwt from '../../../../src/lib/jwt.lib'; 9 | import { UserBuilder, TokenBuilder } from '../../../data-builders'; 10 | 11 | const path = '/api/auth'; 12 | 13 | after(() => User.db.close()); 14 | 15 | describe(path, () => { 16 | let plaintextPassword; 17 | let newUser; 18 | 19 | before(async () => { 20 | await User.deleteMany(); 21 | 22 | const newUserInfo = UserBuilder.randomUserInfo(); 23 | 24 | plaintextPassword = newUserInfo.password; 25 | newUser = await UserBuilder.createOne(newUserInfo); 26 | }); 27 | 28 | after(async () => { 29 | await User.deleteMany(); 30 | }); 31 | 32 | describe('POST /login', () => { 33 | it('should return status 400 and JSON error without email and password', async () => { 34 | const res = await request(server) 35 | .post(`${path}/login`) 36 | .send(); 37 | const { status, body } = res; 38 | 39 | expect(status).to.equal(400); 40 | expect(body).to.have.property('field'); 41 | expect(body).to.have.property('error'); 42 | }); 43 | 44 | it('should return status 401 and JSON error when email does not exist', async () => { 45 | const { status, body } = await request(server) 46 | .post(`${path}/login`) 47 | .send({ email: `no${newUser.email}`, password: plaintextPassword }); 48 | 49 | expect(status).to.equal(401); 50 | expect(body).to.have.property('field'); 51 | expect(body).to.have.property('error'); 52 | }); 53 | 54 | it('should return status 401 and JSON error when password is wrong', async () => { 55 | const { status, body } = await request(server) 56 | .post(`${path}/login`) 57 | .send({ 58 | email: newUser.email, 59 | password: `wrong${plaintextPassword}wrong` 60 | }); 61 | 62 | expect(status).to.equal(401); 63 | expect(body).to.have.property('field'); 64 | expect(body).to.have.property('error'); 65 | }); 66 | 67 | it('should return status 200 with valid user and login', async () => { 68 | const { status, body } = await request(server) 69 | .post(`${path}/login`) 70 | .send({ 71 | email: newUser.email, 72 | password: plaintextPassword 73 | }); 74 | 75 | expect(status).to.equal(200); 76 | expect(body).to.have.property('message'); 77 | expect(body).to.have.property('name'); 78 | }); 79 | 80 | it('should return set-cookie and JWT', async () => { 81 | const { headers } = await request(server) 82 | .post(`${path}/login`) 83 | .send({ 84 | email: newUser.email, 85 | password: plaintextPassword 86 | }); 87 | 88 | const cookies = headers['set-cookie'][0]; 89 | 90 | expect(headers).to.have.property('set-cookie'); 91 | expect(cookies).to.be.a('string'); 92 | expect(cookies).to.match(/jwt=/); 93 | }); 94 | 95 | it('should return JWT with expire date', async () => { 96 | const { headers } = await request(server) 97 | .post(`${path}/login`) 98 | .send({ 99 | email: newUser.email, 100 | password: plaintextPassword 101 | }); 102 | const cookies = headers['set-cookie'][0]; 103 | const jwt = cookies.match(/jwt=([^;]+)/)[1]; 104 | const dataDecode = Jwt.decode(jwt); 105 | 106 | expect(dataDecode).to.have.property('exp'); 107 | }); 108 | 109 | it('should have Set-Cookie with SameSite=Strict; Secure and HttpOnly', async () => { 110 | const { headers } = await request(server) 111 | .post(`${path}/login`) 112 | .send({ 113 | email: newUser.email, 114 | password: plaintextPassword 115 | }); 116 | const cookies = headers['set-cookie'][0]; 117 | 118 | expect(headers).to.have.property('set-cookie'); 119 | expect(cookies).to.be.a('string'); 120 | expect(cookies).to.match(/SameSite=Strict/); 121 | expect(cookies).to.match(/HttpOnly/); 122 | }); 123 | }); 124 | 125 | describe('POST /refresh', () => { 126 | let resRefresh; 127 | let headersRefresh; 128 | let cookiesRefresh; 129 | let cookiesLogin; 130 | let loginJwt; 131 | let refreshJwt; 132 | 133 | beforeEach(async () => { 134 | const resLogin = await request(server) 135 | .post(`${path}/login`) 136 | .send({ 137 | email: newUser.email, 138 | password: plaintextPassword 139 | }); 140 | cookiesLogin = resLogin.headers['set-cookie'][0]; 141 | loginJwt = cookiesLogin.match(/jwt=([^;]+)/)[1]; 142 | 143 | resRefresh = await request(server) 144 | .post(`${path}/refresh`) 145 | .set('Cookie', [cookiesLogin]) 146 | .send(); 147 | headersRefresh = resRefresh.headers; 148 | cookiesRefresh = headersRefresh['set-cookie'][0]; 149 | refreshJwt = cookiesRefresh.match(/jwt=([^;]+)/)[1]; 150 | }); 151 | 152 | it('should return status 200 when send valid token', () => { 153 | expect(resRefresh.status).to.equals(200); 154 | }); 155 | 156 | it('should return Set-cookie with SameSite=Strict; Secure and HttpOnly', () => { 157 | expect(headersRefresh).to.have.property('set-cookie'); 158 | expect(cookiesRefresh).to.be.a('string'); 159 | expect(cookiesRefresh).to.match(/SameSite=Strict/); 160 | expect(cookiesRefresh).to.match(/HttpOnly/); 161 | }); 162 | 163 | it('should return a new token when receiving a valid one', async () => { 164 | expect(cookiesRefresh).to.match(/jwt=/); 165 | expect(refreshJwt).to.not.be.equal(loginJwt); 166 | }); 167 | 168 | it('should return status 401 when send expired token', async () => { 169 | const iat = moment 170 | .utc() 171 | .subtract(20, 'days') 172 | .unix(); 173 | 174 | const token = Jwt.encode( 175 | { name: newUser.name, iat }, 176 | { expiresIn: '1day' } 177 | ); 178 | 179 | const cookie = cookiesLogin.replace(loginJwt, token); 180 | 181 | const { status, body } = await request(server) 182 | .post(`${path}/refresh`) 183 | .set('Cookie', [cookie]) 184 | .send(); 185 | 186 | expect(status).to.equals(401); 187 | expect(body).to.have.property('message'); 188 | }); 189 | 190 | it('should return status 401 when not send token', async () => { 191 | const { status } = await request(server) 192 | .post(`${path}/refresh`) 193 | .send(); 194 | 195 | expect(status).to.equals(401); 196 | }); 197 | 198 | it('should return status 401 when send invalided token', async () => { 199 | const invalidToken = TokenBuilder.generateRandom(); 200 | const { status } = await request(server) 201 | .post(`${path}/refresh`) 202 | .set('Cookie', [invalidToken]) 203 | .send(); 204 | 205 | expect(status).to.equals(401); 206 | }); 207 | }); 208 | }); 209 | -------------------------------------------------------------------------------- /test/app/components/user/user.controller.test.js: -------------------------------------------------------------------------------- 1 | import request from 'supertest'; 2 | import { expect } from 'chai'; 3 | import moment from 'moment'; 4 | 5 | import jwt from '../../../../src/lib/jwt.lib'; 6 | import User from '../../../../src/app/components/user/user.model'; 7 | import server from '../../../../src/app/server'; 8 | import { UserBuilder, TokenBuilder } from '../../../data-builders'; 9 | 10 | const prefix = '/api/user'; 11 | 12 | describe(`${prefix}`, () => { 13 | before(() => User.deleteMany()); 14 | after(() => User.deleteMany()); 15 | 16 | describe('POST /', () => { 17 | it("should return 400 when the body doesn't have name, email and password", async () => { 18 | const { status } = await request(server).post(`${prefix}`); 19 | 20 | expect(status).to.equals(400); 21 | }); 22 | 23 | it("should return an array with keys field and error when the body doesn't have name, email and password", async () => { 24 | const { body } = await request(server).post(`${prefix}`); 25 | 26 | expect(body).to.be.an('array'); 27 | expect(body.length).to.equal(3); 28 | expect(body[0]).to.have.property('field'); 29 | expect(body[0]).to.have.property('error'); 30 | expect(body[1]).to.have.property('field'); 31 | expect(body[1]).to.have.property('error'); 32 | expect(body[2]).to.have.property('field'); 33 | expect(body[2]).to.have.property('error'); 34 | }); 35 | 36 | it('should return an array with key field filled by name when name smaller than 2 chars', async () => { 37 | const newUser = UserBuilder.randomUserInfo(); 38 | const nameInvalid = UserBuilder.nameInvalid(); 39 | 40 | const { body } = await request(server) 41 | .post(`${prefix}`) 42 | .send({ ...newUser, ...nameInvalid }); 43 | 44 | const errorName = () => body.find(error => error.field === 'name'); 45 | 46 | expect(body).to.be.an('array'); 47 | expect(errorName().field).to.equal('name'); 48 | }); 49 | 50 | it('should return an array with key field filled by email when email is invalid', async () => { 51 | const emailInvalid = UserBuilder.emailInvalid(); 52 | 53 | const { body } = await request(server) 54 | .post(`${prefix}`) 55 | .send(emailInvalid); 56 | 57 | const errorEmail = () => body.find(error => error.field === 'email'); 58 | 59 | expect(body).to.be.an('array'); 60 | expect(errorEmail().field).to.equal('email'); 61 | }); 62 | 63 | it('should return status 409 and an array with key field filled by email when send registered email', async () => { 64 | const newUser = UserBuilder.randomUserInfo(); 65 | 66 | await request(server) 67 | .post(`${prefix}`) 68 | .send(newUser); 69 | 70 | const { status, body } = await request(server) 71 | .post(`${prefix}`) 72 | .send(newUser); 73 | 74 | const errorEmail = () => body.find(error => error.field === 'email'); 75 | 76 | expect(status).to.equal(409); 77 | expect(errorEmail().field).to.equal('email'); 78 | }); 79 | 80 | it('should return an array with key field filled by password when password is smaller than 8 chars', async () => { 81 | const passwordInvalid = UserBuilder.passwordInvalid(); 82 | 83 | const { body } = await request(server) 84 | .post(`${prefix}`) 85 | .send(passwordInvalid); 86 | 87 | const errorPassword = () => 88 | body.find(error => error.field === 'password'); 89 | 90 | expect(body).to.be.an('array'); 91 | expect(errorPassword().field).to.equal('password'); 92 | }); 93 | 94 | it('should return a user when the all request body is valid', async () => { 95 | const newUser = UserBuilder.randomUserInfo(); 96 | 97 | const { status, body } = await request(server) 98 | .post(`${prefix}`) 99 | .send(newUser); 100 | 101 | expect(status).to.equal(201); 102 | expect(body).to.have.property('email', newUser.email.toLowerCase()); 103 | }); 104 | }); 105 | 106 | describe('POST /confirmation', () => { 107 | it(`should return status 400 when the body does't have token`, async () => { 108 | const { status } = await request(server).post(`${prefix}/confirmation`); 109 | 110 | expect(status).to.equal(400); 111 | }); 112 | 113 | it('should return status 401 when send invalided token', async () => { 114 | const invalidToken = TokenBuilder.generateRandom(); 115 | const { status } = await request(server) 116 | .post(`${prefix}/confirmation`) 117 | .send({ token: invalidToken }); 118 | 119 | expect(status).to.equal(401); 120 | }); 121 | 122 | it('should return status 401 when send expired token', async () => { 123 | const newUser = UserBuilder.randomUserInfo(); 124 | const iat = moment 125 | .utc() 126 | .subtract(20, 'days') 127 | .unix(); 128 | const token = jwt.encode( 129 | { name: newUser.name, iat }, 130 | { expiresIn: '1day' } 131 | ); 132 | const { status } = await request(server) 133 | .post(`${prefix}/confirmation`) 134 | .send({ token }); 135 | 136 | expect(status).to.equal(401); 137 | }); 138 | 139 | it('should return status 200 and email in body when send a valid token in body', async () => { 140 | const newUser = UserBuilder.randomUserInfo(); 141 | const { body: email } = await request(server) 142 | .post(`${prefix}`) 143 | .send(newUser); 144 | const token = jwt.encode(email, { expiresIn: '1h' }); 145 | const { status, body } = await request(server) 146 | .post(`${prefix}/confirmation`) 147 | .send({ token }); 148 | 149 | expect(status).to.equal(200); 150 | expect(body).to.have.property('email'); 151 | }); 152 | 153 | it('should return set-cookie and JWT', async () => { 154 | const newUser = UserBuilder.randomUserInfo(); 155 | const { headers } = await request(server) 156 | .post(`${prefix}`) 157 | .send(newUser); 158 | 159 | const cookies = headers['set-cookie'][0]; 160 | 161 | expect(headers).to.have.property('set-cookie'); 162 | expect(cookies).to.be.a('string'); 163 | expect(cookies).to.match(/jwt=/); 164 | }); 165 | }); 166 | }); 167 | -------------------------------------------------------------------------------- /test/app/components/user/user.model.test.js: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | 3 | import User from '../../../../src/app/components/user/user.model'; 4 | 5 | import UserBuilder from '../../../data-builders/user.builder'; 6 | 7 | describe('User model', () => { 8 | describe('when creating a new user', () => { 9 | let userInfo; 10 | beforeEach(async () => { 11 | await User.deleteMany(); 12 | 13 | userInfo = UserBuilder.randomUserInfo(); 14 | }); 15 | 16 | it('should store password encrypted', async () => { 17 | const newUser = await User.create(userInfo); 18 | 19 | expect(newUser.password).to.not.be.equal(userInfo.password); 20 | expect(newUser.password.length).to.be.equal(60); 21 | }); 22 | }); 23 | 24 | describe('when updating an existing user', () => { 25 | let user = {}; 26 | beforeEach(async () => { 27 | await User.deleteMany(); 28 | 29 | user = await UserBuilder.createOne(); 30 | }); 31 | 32 | it("shouldn't re-encrypt password if it didn't change", async () => { 33 | const oldEncryptedPassword = `${user.password}`; 34 | 35 | user.name = 'Some Other Name'; 36 | const updatedUser = await user.save(); 37 | 38 | expect(updatedUser.password).to.be.equal(oldEncryptedPassword); 39 | }); 40 | }); 41 | }); 42 | -------------------------------------------------------------------------------- /test/data-builders/index.js: -------------------------------------------------------------------------------- 1 | export { default as UserBuilder } from './user.builder'; 2 | export { default as TokenBuilder } from './token.builder'; 3 | -------------------------------------------------------------------------------- /test/data-builders/token.builder.js: -------------------------------------------------------------------------------- 1 | import faker from 'faker'; 2 | import jwt from 'jsonwebtoken'; 3 | 4 | const generateRandom = (data = {}) => 5 | jwt.sign( 6 | data, 7 | faker.lorem 8 | .sentence() 9 | .split(' ') 10 | .join('') 11 | ); 12 | 13 | export default { generateRandom }; 14 | -------------------------------------------------------------------------------- /test/data-builders/user.builder.js: -------------------------------------------------------------------------------- 1 | import faker from 'faker'; 2 | 3 | import User from '../../src/app/components/user/user.model'; 4 | 5 | const generateName = () => { 6 | const firstName = faker.name.firstName(); 7 | const lastName = faker.name.lastName(); 8 | 9 | return `${firstName} ${lastName}`; 10 | }; 11 | 12 | const randomUserInfo = (options = {}) => { 13 | const blank = {}; 14 | 15 | return Object.assign( 16 | blank, 17 | { 18 | name: generateName(), 19 | email: faker.internet.email(), 20 | password: faker.internet.password() 21 | }, 22 | { ...options } 23 | ); 24 | }; 25 | 26 | const createOne = options => User.create(randomUserInfo(options)); 27 | const emailInvalid = () => ({ email: faker.lorem.word() }); 28 | const passwordInvalid = () => ({ password: faker.internet.password(7) }); 29 | const nameInvalid = () => ({ name: faker.internet.password(1) }); 30 | const emailValid = () => ({ email: faker.internet.email() }); 31 | 32 | export default { 33 | randomUserInfo, 34 | createOne, 35 | emailInvalid, 36 | passwordInvalid, 37 | nameInvalid, 38 | emailValid 39 | }; 40 | -------------------------------------------------------------------------------- /test/lib/apis.lib.test.js: -------------------------------------------------------------------------------- 1 | import { expect } from 'chai'; 2 | import { UserBuilder } from '../data-builders'; 3 | 4 | import jwt from '../../src/lib/jwt.lib'; 5 | import { sendUserConfirmationEmail } from '../../src/lib/apis.lib'; 6 | 7 | describe('apis.lib', () => { 8 | describe('#sendUserConfirmationEmail(email, token)', () => { 9 | it('should return status 200 when sended email in parameter', async () => { 10 | const { email } = UserBuilder.emailValid(); 11 | const token = jwt.encode({ email }, { expiresIn: '1h' }); 12 | const res = await sendUserConfirmationEmail(email, token); 13 | 14 | expect(res.status).to.equal(200); 15 | }); 16 | }); 17 | }); 18 | -------------------------------------------------------------------------------- /test/lib/jwt.lib.test.js: -------------------------------------------------------------------------------- 1 | import moment from 'moment'; 2 | import { expect } from 'chai'; 3 | 4 | import Jwt from '../../src/lib/jwt.lib'; 5 | 6 | const data = { name: 'Marco Bruno', email: 'marco.bruno.br@gmail.com' }; 7 | 8 | describe('jwt.lib', () => { 9 | describe('#encode()', () => { 10 | let token; 11 | 12 | before(() => { 13 | token = Jwt.encode(data, { expiresIn: '1day' }); 14 | }); 15 | 16 | it('should encode the data', () => { 17 | expect(token).to.be.a('string'); 18 | expect(token).to.match(/^([^.]+\.){2}[^.]+$/); 19 | }); 20 | 21 | it('should set expire time', () => { 22 | const dataDecode = Jwt.decode(token); 23 | 24 | expect(dataDecode).to.have.property('exp'); 25 | }); 26 | }); 27 | 28 | describe('#decode()', () => { 29 | let token; 30 | 31 | before(() => { 32 | token = Jwt.encode(data); 33 | }); 34 | 35 | after(() => delete data.iat); 36 | 37 | it('should decode the data', () => { 38 | const dataDecode = Jwt.decode(token); 39 | 40 | delete dataDecode.iat; 41 | 42 | expect(dataDecode).to.have.property('name'); 43 | expect(dataDecode).to.have.property('email'); 44 | expect(dataDecode).to.deep.equals(data); 45 | }); 46 | 47 | it('should reject expired token', () => { 48 | data.iat = moment 49 | .utc() 50 | .subtract(20, 'days') 51 | .unix(); 52 | 53 | token = Jwt.encode(data, { expiresIn: '1day' }); 54 | 55 | expect(() => Jwt.decode(token)).to.throw(); 56 | }); 57 | }); 58 | 59 | describe('#refresh()', () => { 60 | afterEach(() => delete data.iat); 61 | 62 | it('should return new token when send valid token', () => { 63 | data.iat = moment 64 | .utc() 65 | .subtract(1, 'hour') 66 | .unix(); 67 | 68 | const token = Jwt.encode(data); 69 | const newToken = Jwt.refresh(token); 70 | const dataDecode = Jwt.decode(newToken); 71 | 72 | delete dataDecode.iat; 73 | delete data.iat; 74 | 75 | expect(dataDecode).to.have.property('name'); 76 | expect(dataDecode).to.have.property('email'); 77 | expect(dataDecode).to.deep.equals(data); 78 | expect(newToken).to.not.be.equals(token); 79 | }); 80 | 81 | it('should not return new token when send expired token', () => { 82 | data.iat = moment 83 | .utc() 84 | .subtract(2, 'days') 85 | .unix(); 86 | 87 | const token = Jwt.encode(data, { expiresIn: '1day' }); 88 | 89 | expect(() => Jwt.refresh(token)).to.throw(); 90 | }); 91 | 92 | it('should return new token with expire date when send valid token', () => { 93 | const token = Jwt.encode(data, { expiresIn: '1day' }); 94 | const newToken = Jwt.refresh(token, { expiresIn: '1day' }); 95 | const dataDecode = Jwt.decode(newToken); 96 | 97 | expect(dataDecode).to.have.property('exp'); 98 | }); 99 | }); 100 | }); 101 | -------------------------------------------------------------------------------- /test/mocha.opts: -------------------------------------------------------------------------------- 1 | --reporter mochawesome 2 | --recursive 3 | --require sucrase/register 4 | --------------------------------------------------------------------------------