├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug.yml │ ├── docs.yml │ └── feature_request.yml ├── PULL_REQUEST_TEMPLATE │ └── pull_request_template.md ├── dependabot.yml └── workflows │ ├── auto-comment.yml │ ├── close_old_issues.yaml │ ├── codeql-analysis.yml │ └── linting.yml ├── .gitignore ├── 95698224.jpeg ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── SECURITY.md ├── common ├── dao │ └── index.js ├── logger │ └── index.js ├── responseHandler │ └── index.js ├── serverInitMethods │ └── index.js └── validators │ └── index.js ├── config └── db.js ├── constants └── index.js ├── controllers └── auth │ ├── user.signin.js │ └── user.signup.js ├── dev.dockerfile ├── images ├── clone.png └── fork.png ├── logs └── all-logs.log ├── middleware ├── auth.js ├── check_auth.js └── morgan │ └── index.js ├── models └── user.model.js ├── modules ├── oauthAccessToken │ └── oauthAccessToken.model.js └── user │ ├── user.controller.js │ └── user.model.js ├── package-lock.json ├── package.json ├── routes └── index.js └── server.js /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [sazamansari] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: https://openprofile.dev/profile/shadab1995 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 14 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug.yml: -------------------------------------------------------------------------------- 1 | name: 🐛 Bug 2 | description: Report an issue to help improve the project. 3 | labels: ["🛠 goal: fix", "🚦 status: awaiting triage"] 4 | body: 5 | - type: textarea 6 | id: description 7 | attributes: 8 | label: Description 9 | description: A brief description of the question or issue, also include what you tried and what didn't work 10 | validations: 11 | required: true 12 | - type: textarea 13 | id: screenshots 14 | attributes: 15 | label: Screenshots 16 | description: Please add screenshots if applicable 17 | validations: 18 | required: false 19 | - type: textarea 20 | id: extrainfo 21 | attributes: 22 | label: Additional information 23 | description: Is there anything else we should know about this bug? 24 | validations: 25 | required: false 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/docs.yml: -------------------------------------------------------------------------------- 1 | name: 📄 Documentation issue 2 | description: Found an issue in the documentation? You can use this one! 3 | title: "[DOCS] " 4 | labels: ["📄 aspect: text", "🚦 status: awaiting triage"] 5 | body: 6 | - type: textarea 7 | id: description 8 | attributes: 9 | label: Description 10 | description: A brief description of the question or issue, also include what you tried and what didn't work 11 | validations: 12 | required: true 13 | - type: textarea 14 | id: screenshots 15 | attributes: 16 | label: Screenshots 17 | description: Please add screenshots if applicable 18 | validations: 19 | required: false 20 | - type: textarea 21 | id: extrainfo 22 | attributes: 23 | label: Additional information 24 | description: Is there anything else we should know about this issue? 25 | validations: 26 | required: false 27 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.yml: -------------------------------------------------------------------------------- 1 | name: General Feature Request 💡 2 | description: Have a new idea/feature for Project Please suggest! 3 | title: "[FEATURE] " 4 | labels: ["⭐ goal: addition", "🚦 status: awaiting triage"] 5 | body: 6 | - type: textarea 7 | id: description 8 | attributes: 9 | label: Description 10 | description: A brief description of the enhancement you propose, also include what you tried and what worked. 11 | validations: 12 | required: true 13 | - type: textarea 14 | id: screenshots 15 | attributes: 16 | label: Screenshots 17 | description: Please add screenshots if applicable 18 | validations: 19 | required: false 20 | - type: textarea 21 | id: extrainfo 22 | attributes: 23 | label: Additional information 24 | description: Is there anything else we should know about this idea? 25 | validations: 26 | required: false 27 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Related Issue 4 | 5 | Closes #issue_number 6 | 7 | 8 | 9 | ## Description 10 | 11 | 13 | 14 | ## Screenshots 15 | 16 | 17 | 18 | ## Checklist 19 | 20 | 21 | 22 | 23 | - [ ] My code adheres to the established style guidelines of the project. 24 | - [ ] I have included comments in areas that may be difficult to understand. 25 | - [ ] My changes have not introduced any new warnings. 26 | - [ ] I have conducted a self-review of my code. 27 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | 13 | -------------------------------------------------------------------------------- /.github/workflows/auto-comment.yml: -------------------------------------------------------------------------------- 1 | name: Auto Comment 2 | on: [issues, pull_request] 3 | jobs: 4 | run: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: wow-actions/auto-comment@v1 8 | with: 9 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 10 | issuesOpened: | 11 | 👋 @{{ author }} 12 | Thank you for raising an issue. We will look into the matter and get back to you as soon as possible. Keep up the great work! 13 | 14 | pullRequestOpened: | 15 | 👋 @{{ author }} 16 | Thank you for raising your pull request. 17 | Please make sure you have followed our [contributing guidelines](https://github.com/sazamansari/node.js-_microservices/blob/521d9e292c09d136c0ac339f9f50340c9031b7a9/CONTRIBUTING.md). We will review it as soon as possible. 18 | 19 | issuesClosed: | 20 | 👋 @{{ author }}. This issue is closed. 21 | 22 | pullRequestMerged: | 23 | Great job, @${{ github.actor }}! 🎉 Thank you for submitting your pull request. Our dedicated team will review it diligently.Your contribution is valuable and we appreciate your efforts to improve our project. 24 | 25 | issuesAssigned: | 26 | 👋 @{{ author }} 27 | I have assigned the issue to you🙌 You can now start working on it.Should you have any queries or require guidance, do not hesitate to ask. 👍 28 | -------------------------------------------------------------------------------- /.github/workflows/close_old_issues.yaml: -------------------------------------------------------------------------------- 1 | name: Close Old Issues 2 | on: 3 | schedule: 4 | - cron: "0 0 * * *" 5 | 6 | jobs: 7 | close-issues: 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - name: Checkout Repository 12 | uses: actions/checkout@v3 13 | 14 | - name: Close Old Issues 15 | run: | 16 | open_issues=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ 17 | "https://api.github.com/repos/${{ github.repository }}/issues?state=open" \ 18 | | jq -r '.[] | .number') 19 | 20 | for issue in $open_issues; do 21 | # Get the last updated timestamp of the issue 22 | last_updated=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ 23 | "https://api.github.com/repos/${{ github.repository }}/issues/$issue" \ 24 | | jq -r '.updated_at') 25 | 26 | days_since_update=$(( ( $(date +%s) - $(date -d "$last_updated" +%s) ) / 86400 )) 27 | 28 | if [ $days_since_update -gt 7 ]; then # Modify the condition to check if days_since_update is greater than 7 29 | curl -s -X PATCH -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ 30 | -H "Accept: application/vnd.github.v3+json" \ 31 | -d '{"state":"closed"}' \ 32 | "https://api.github.com/repos/${{ github.repository }}/issues/$issue" 33 | fi 34 | done 35 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ "main" ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ "main" ] 20 | schedule: 21 | - cron: '18 12 * * 5' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'javascript' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 37 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 38 | 39 | steps: 40 | - name: Checkout repository 41 | uses: actions/checkout@v3 42 | 43 | # Initializes the CodeQL tools for scanning. 44 | - name: Initialize CodeQL 45 | uses: github/codeql-action/init@v2 46 | with: 47 | languages: ${{ matrix.language }} 48 | # If you wish to specify custom queries, you can do so here or in a config file. 49 | # By default, queries listed here will override any specified in a config file. 50 | # Prefix the list here with "+" to use these queries and those in the config file. 51 | 52 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 53 | # queries: security-extended,security-and-quality 54 | 55 | 56 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 57 | # If this step fails, then you should remove it and run the build manually (see below) 58 | - name: Autobuild 59 | uses: github/codeql-action/autobuild@v2 60 | 61 | # ℹ️ Command-line programs to run using the OS shell. 62 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 63 | 64 | # If the Autobuild fails above, remove it and uncomment the following three lines. 65 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. 66 | 67 | # - run: | 68 | # echo "Run, Build Application using script" 69 | # ./location_of_script_within_repo/buildscript.sh 70 | 71 | - name: Perform CodeQL Analysis 72 | uses: github/codeql-action/analyze@v2 73 | with: 74 | category: "/language:${{matrix.language}}" 75 | -------------------------------------------------------------------------------- /.github/workflows/linting.yml: -------------------------------------------------------------------------------- 1 | name: Linting 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | 7 | Linting: 8 | 9 | runs-on: ubuntu-latest 10 | 11 | steps: 12 | 13 | - name: Checkout 14 | uses: actions/checkout@v3 15 | with: 16 | ref: ${{ github.head_ref }} 17 | 18 | - name: Lint code with prettier 19 | uses: creyD/prettier_action@v4.3 20 | with: 21 | prettier_options: --write **/*.{js,md} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .env -------------------------------------------------------------------------------- /95698224.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sazamansari/node.js-_microservices/cd028f38038b845853b7c0e1bd9b236165a7454d/95698224.jpeg -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Code of Conduct 2 | 3 | We are dedicated to fostering a friendly, inclusive, and safe environment for all participants in our project repository. This code of conduct sets out our expectations for behavior, ensuring that everyone can collaborate positively and respectfully. By engaging in this project, you agree to uphold this code of conduct. 4 | 5 | ## 1. Be Respectful and Inclusive 6 | 7 | Treat all participants with respect and courtesy, regardless of their race, ethnicity, nationality, gender identity, sexual orientation, age, disability, religion, or any other personal characteristics. Create an inclusive and welcoming environment for everyone to contribute. 8 | 9 | ## 2. Foster a Collaborative Atmosphere 10 | 11 | Encourage open and constructive discussions. Be receptive to different ideas and perspectives. Avoid personal attacks, harassment, or any form of offensive or derogatory language or behavior. 12 | 13 | ## 3. Exercise Empathy and Understanding 14 | 15 | Take into account that participants may have different backgrounds and experiences. Be considerate and understanding when communicating with others. If a misunderstanding occurs, seek to resolve it in a peaceful and respectful manner. 16 | 17 | ## 4. Be Mindful of Language and Tone 18 | 19 | Use clear and inclusive language when communicating in discussions, comments, and documentation. Be mindful of how your words may be perceived by others. Refrain from using offensive, discriminatory, or inflammatory language. 20 | 21 | ## 5. Respect Privacy and Confidentiality 22 | 23 | Respect the privacy and confidentiality of others. Do not share personal information without consent. Be cautious when handling sensitive data and ensure compliance with relevant privacy laws and regulations. 24 | 25 | ## 6. Report Incidents 26 | 27 | If you witness or experience any behavior that violates this code of conduct, promptly report it to the project maintainers or administrators. Provide as much detail as possible to help in the investigation. All reports will be handled confidentially and with discretion. 28 | 29 | ## 7. Enforcement 30 | 31 | Violations of this code of conduct may lead to temporary or permanent restrictions on participation in the project repository. Project maintainers and administrators reserve the right to enforce this code of conduct and take appropriate action against misconduct or breaches of conduct. 32 | 33 | ## 8. Acknowledgment 34 | 35 | We value and appreciate everyone's contributions to our project repository. By following this code of conduct, we can create a supportive and inclusive environment where collaboration and growth thrive. 36 | 37 | Thank you for your dedication to maintaining a respectful and collaborative environment. Your commitment contributes to the success of our project. 38 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to User-Auth-Microservice 2 | 3 | Thank you for considering contributing to User-Auth-Microservice! We appreciate your interest in improving the project and welcome your contributions. By contributing, you can help us make the microservice better and more secure. Please take a moment to review the guidelines below to ensure a smooth contribution process. 4 | 5 | # How to **contribute**? 6 | 7 | _If you're not comfortable with command line, [here are tutorials using GUI tools.](#tutorials-using-other-tools)_ 8 | _If you don't have git on your machine, [install it](https://help.github.com/articles/set-up-git/)._ 9 | 10 | **1.** Fork [this](https://github.com/sazamansari/node.js-_microservices) repository. 11 | 12 | fork this repository 13 | 14 |
15 | 16 | **2.** Clone your forked copy of the project. 17 | 18 | clone forked repository 19 | 20 |
21 | 22 | ``` 23 | git clone https://github.com//node.js-_microservices.git 24 | ``` 25 | 26 | **3.** Navigate to the project directory :file_folder: . 27 | 28 | ``` 29 | cd node.js-_microservices 30 | ``` 31 | 32 | **4.** Add a reference(remote) to the original repository. 33 | 34 | ``` 35 | git remote add upstream https://github.com/sazamansari/node.js-_microservices.git 36 | ``` 37 | 38 | **5.** Check the remotes for this repository. 39 | 40 | ``` 41 | git remote -v 42 | ``` 43 | 44 | **6.** Always take a pull from the upstream repository to your master branch to keep it at par with the main project(updated repository). 45 | 46 | ``` 47 | git pull upstream main 48 | ``` 49 | 50 | **7.** Create a new branch. 51 | 52 | ``` 53 | git checkout -b 54 | ``` 55 | 56 | **8.** Perform your desired changes to the code base. 57 | 58 | **9.** Track your changes:heavy_check_mark: . 59 | 60 | ``` 61 | git add . 62 | ``` 63 | 64 | **10.** Commit your changes . 65 | 66 | ``` 67 | git commit -m "Your message" 68 | ``` 69 | 70 | **11.** Push the committed changes in your feature branch to your remote repo. 71 | 72 | ``` 73 | git push -u origin 74 | ``` 75 | 76 | **12.** To create a pull request, click on `compare and pull requests`. Please ensure you compare your feature branch to the desired branch of the repository you are supposed to make a PR to. 77 | 78 | **13.** Add appropriate title and description to your pull request explaining your changes and efforts done. 79 | 80 | **14.** Click on `Create Pull Request`. 81 | 82 | **15.** Congratulations! You have made a succsessful PR to the node.js-\_microservices. 83 | 84 |
85 | 86 | **16.** Now sit back patiently and relax while your PR is being reviewed. 87 | 88 | #### Note :- 89 | 90 | - **Please follow best code formatting and linting practices to assure good code quality. You should use tools such as Prettier or Eslint for the purpose.** 91 | 92 |
93 | 94 | ### Show some ❤ by starring ⭐ the repository. 95 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 mohammad shadab azam ansari 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![node.js-_microservices](https://socialify.git.ci/sazamansari/node.js-_microservices/image?font=Rokkitt&forks=1&issues=1&language=1&name=1&owner=1&pattern=Charlie%20Brown&pulls=1&stargazers=1&theme=Auto) 2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | ## Description 21 | 22 | Express.js is indeed a popular framework for building efficient and scalable server-side applications using Node.js. It is designed to work with modern JavaScript and can be used with pure JavaScript as well. Express.js combines elements of Object-Oriented Programming (OOP), Functional Programming (FP), and Functional Reactive Programming (FRP) to provide a flexible and robust development environment. 23 | 24 | While Node.js itself provides compatibility with various libraries, Express.js stands out as a lightweight and flexible framework that simplifies the development of server-side applications. It allows developers to handle routing, middleware, and other server-related tasks with ease. 25 | 26 | In recent years, JavaScript has gained significant popularity as a language for both front-end and back-end development, thanks to frameworks like Angular, React, and Vue. However, on the server-side, finding a suitable architecture for Node.js applications has been a challenge. 27 | 28 | User_Auth Microservices aims to address this problem by providing an out-of-the-box application architecture. This architecture focuses on creating highly testable, scalable, loosely coupled, and easily maintainable applications. It takes inspiration from the Node.js ecosystem and leverages the power of Express.js along with other libraries and tools to provide a robust solution. 29 | 30 | By using User_Auth Microservices, developers can benefit from a pre-defined architecture that promotes best practices and reduces the effort required to build complex server-side applications. This allows developers to focus more on application logic and functionality rather than spending time designing and implementing the underlying architecture. 31 | 32 | Overall, Express.js and User_Auth Microservices provide developers with powerful tools and frameworks to build efficient, scalable, and maintainable server-side applications using Node.js and JavaScript. 33 | 34 | 3. Make your Changes: Make the necessary changes and improvements to the codebase. 35 | 36 | 4. Commit your Changes: Once you're satisfied with your changes, commit them with a meaningful message describing your updates. 37 | 38 | ```bash 39 | git add . 40 | git commit -m 'Add a new feature: detailed explanation' 41 | ``` 42 | 43 | 5. Push to your Fork: Push your changes to your forked repository on GitHub. 44 | 45 | ```bash 46 | git push origin your-branch-name 47 | 48 | ``` 49 | 50 | ## License 51 | 52 | Include the license information for your project. For example, you can use the MIT License: 53 | 54 | This project is licensed under the terms of the [MIT License](LICENSE). 55 | Feel free to contribute to this repo. 56 | 57 | ## INSTALL 58 | 59 | locally, usually for use as a module: 60 | 61 | ```bash 62 | npm i user-auth-microservice 63 | ``` 64 | 65 | ## Authors 66 | 67 | - [@Md Shadab Azam Ansari](https://md-shadab-azam-ansari.vercel.app/) 68 | 69 | ## License 70 | 71 | [![MIT License](https://img.shields.io/badge/License-MIT-green.svg)](https://choosealicense.com/licenses/mit/) 72 | 73 | ## API Reference 74 | 75 | #### Get all items 76 | 77 | ```http 78 | GET /api/items 79 | ``` 80 | 81 | | Parameter | Type | Description | 82 | | :-------- | :------- | :------------------------- | 83 | | `api_key` | `string` | **Required**. Your API key | 84 | 85 | #### Get item 86 | 87 | ```http 88 | GET /api/items/${id} 89 | ``` 90 | 91 | | Parameter | Type | Description | 92 | | :-------- | :------- | :-------------------------------- | 93 | | `id` | `string` | **Required**. Id of item to fetch | 94 | 95 | ## Mongoose Connect 96 | 97 | config/db.js 98 | 99 | ````jsx 100 | import mongoose from "mongoose"; 101 | 102 | const connectDB = async () => { 103 | let uri = process.env.MONGO_URI; 104 | 105 | try { 106 | await mongoose 107 | .connect(uri, { 108 | useNewUrlParser: true, 109 | useUnifiedTopology: true, 110 | useCreateIndex: true, 111 | }) 112 | .catch((error) => { 113 | console.log("connection in error:::", error); 114 | }); 115 | 116 | console.log("mongo DB connected"); 117 | 118 | 119 | mongoose.set('debug', function(collectionName, method, query, doc, options) { 120 | 121 | console.log(collectionName + '.' + method, JSON.stringify(query), doc) 122 | 123 | // log.info({ 124 | // dbQuery: set 125 | // }); 126 | }); 127 | 128 | } catch (e) { 129 | console.error(e, "error"); 130 | } finally { 131 | // await client.close(); 132 | } 133 | }; 134 | 135 | export default connectDB; 136 | /> 137 | 138 | #### Get all items 139 | 140 | 141 | #### add(num1, num2) 142 | 143 | Takes two numbers and returns the sum. 144 | 145 | 146 | 147 | 148 | ## To Run The Project 149 | 150 | To Run The Project 151 | 152 | ```bash 153 | npm run dev 154 | ```` 155 | 156 | ## Contributing 157 | 158 | Contributions are always welcome! 159 | 160 | ## Note: 161 | 162 | 1. Don't Create Pull Request to update "readme.md" File. 163 | 2. Maintain proper folder structure. 164 | 3. In case you need to add an external package, install it by using npm. Don't push the complete package file here 165 | 166 | ### Steps to run the project 167 | 168 | - Fork the repo 169 | - Clone into local 170 | - Run npm install 171 | - Run npm run dev 172 | 173 | ### Issues to fix: 174 | 175 | - Fix all the buttons 176 | - Improve box-shadow in light mode 177 | - Make dark mode as default 178 | 179 | See `contributing.md` for ways to get started. 180 | 181 | Please adhere to this project's `code of conduct`. 182 | 183 | ## Tech Stack 184 | 185 | **Server:** Node.js, Express.js Auth, JwToken 186 | 187 | ### Examples 188 | 189 | ```jsx 190 | // Import necessary modules and routes 191 | import CONSTANTS from "../constants/index.js"; 192 | import UserRoutes from "../modules/user/user.routes"; 193 | 194 | /** 195 | * Configure routes for the Express.js app. 196 | * 197 | * @param {object} app - Express.js application instance 198 | */ 199 | const configureRoutes = (app) => { 200 | // Mount the UserRoutes under the specified API URI 201 | app.use(`${CONSTANTS.API_URI}/user`, UserRoutes); 202 | 203 | // You can add more routes here as needed 204 | // Example: app.use(`${CONSTANTS.API_URI}/posts`, PostsRoutes); 205 | }; 206 | 207 | // Export the configureRoutes function for usage 208 | export default configureRoutes; 209 | ``` 210 | 211 |

(Back to top)

212 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | We prioritize security and provide updates for the following versions of our project: 6 | 7 | | Version | Supported | 8 | | ------- | ------------------ | 9 | | 5.1.x | :white_check_mark: | 10 | | 5.0.x | :x: | 11 | | 4.0.x | :white_check_mark: | 12 | | < 4.0 | :x: | 13 | 14 | ## Reporting a Vulnerability 15 | 16 | We take security vulnerabilities seriously. If you discover a security issue within our project, please follow these steps: 17 | 18 | 1. Report: Email us at security@example.com with a detailed description of the vulnerability. 19 | 20 | 2. Expectation: You will receive an acknowledgment of your report within 24 hours. 21 | 22 | 3. Update: Our team will work to validate and reproduce the vulnerability. We'll provide updates on the progress within 7 days. 23 | 24 | 4. Fix: Once verified, we'll work on fixing the vulnerability. 25 | 26 | 5. Disclosure: We will coordinate the disclosure of the vulnerability and release a fix as soon as possible. 27 | 28 | We appreciate your responsible disclosure and will keep you informed throughout the process. Thank you for helping us maintain the security of our project! 29 | -------------------------------------------------------------------------------- /common/dao/index.js: -------------------------------------------------------------------------------- 1 | class BaseDao { 2 | constructor(dbModel) { 3 | //Get Model 4 | this.Model = dbModel; 5 | } 6 | 7 | save(object) { 8 | return this.Model.create(object); 9 | } 10 | 11 | findOne(query, projection) { 12 | return this.Model.findOne(query, projection).lean().exec(); 13 | } 14 | 15 | find(query, projection) { 16 | return this.Model.find(query, projection).lean().exec(); 17 | } 18 | 19 | findOneAndUpdate(query, update, options) { 20 | return this.Model.findOneAndUpdate(query, update, options).exec(); 21 | } 22 | 23 | findAndModify(query, update, options) { 24 | return this.Model.findAndModify(query, update, options).exec(); 25 | } 26 | 27 | findByIdAndUpdate(query, update, options) { 28 | return this.Model.findByIdAndUpdate(query, update, options).exec(); 29 | } 30 | 31 | /** 32 | * Update Given Model 33 | * @param query 34 | * @param toUpdate 35 | * @return Promise Object 36 | * @private 37 | */ 38 | update(query, update, options) { 39 | if (!options) { 40 | options = {}; 41 | } 42 | return this.Model.update(query, update, options).exec(); 43 | } 44 | 45 | updateMany(query, update, options) { 46 | if (!options) { 47 | options = {}; 48 | } 49 | return this.Model.updateMany(query, update, options).exec(); 50 | } 51 | 52 | remove(query, options) { 53 | return this.Model.remove(query, options).exec(); 54 | } 55 | 56 | deleteMany(query, options) { 57 | return this.Model.deleteMany(query, options).exec(); 58 | } 59 | 60 | findByIdAndRemove(query, options) { 61 | return this.Model.findByIdAndRemove(query, options).exec(); 62 | } 63 | 64 | findOneAndDelete(query, options) { 65 | return this.Model.findOneAndDelete(query, options).exec(); 66 | } 67 | 68 | aggregate(aggPipe, options) { 69 | if (!options) { 70 | options = {}; 71 | } 72 | return this.Model.aggregate(aggPipe) 73 | .allowDiskUse(true) 74 | .collation(options) 75 | .exec(); 76 | } 77 | 78 | insertMany(object) { 79 | return this.Model.insertMany(object); 80 | } 81 | 82 | countDocuments(query) { 83 | return this.Model.countDocuments(query); 84 | } 85 | 86 | findWithPagination(query, pageNo, count, projection) { 87 | return this.Model.find(query, projection) 88 | .skip(pageNo * count) 89 | .limit(count) 90 | .lean() 91 | .exec(); 92 | } 93 | } 94 | 95 | export default BaseDao; 96 | -------------------------------------------------------------------------------- /common/logger/index.js: -------------------------------------------------------------------------------- 1 | const { createLogger, transports, format } = require("winston"); 2 | 3 | const logger = createLogger({ 4 | format: format.combine( 5 | format.timestamp({ format: "YYYY-MM-DD HH:mm:ss:ms" }), 6 | format.printf((info) => `${info.timestamp} ${info.level}: ${info.message}`), 7 | ), 8 | transports: [ 9 | new transports.File({ 10 | filename: "./logs/all-logs.log", 11 | json: false, 12 | maxsize: 5242880, 13 | maxFiles: 5, 14 | }), 15 | new transports.Console(), 16 | ], 17 | }); 18 | 19 | module.exports = logger; 20 | -------------------------------------------------------------------------------- /common/responseHandler/index.js: -------------------------------------------------------------------------------- 1 | const RESPONSE = { 2 | Ok: (data, response) => { 3 | return response.status(500).send({ data, status: 200 }); 4 | }, 5 | 6 | Created: (data, response) => { 7 | return response.status(201).send({ data, status: 201 }); 8 | }, 9 | 10 | Unauthorized: (data, response) => { 11 | return response.status(400).send({ data, status: 401 }); 12 | }, 13 | ServerError: (response) => { 14 | return response.status(500).send({ message: "Server error", status: 500 }); 15 | }, 16 | }; 17 | 18 | // "eslintConfig": { 19 | // "extends": "airbnb-base", 20 | // "env": { 21 | // "es6": true, 22 | // "browser": true 23 | // }, 24 | 25 | // "rules": { 26 | // "brace-style": [ 27 | // "error", 28 | // "stroustrup" 29 | // ], 30 | // "comma-dangle": [ 31 | // "error", 32 | // "never" 33 | // ], 34 | // "no-unused-vars": [ 35 | // "warn" 36 | // ], 37 | // "no-var": [ 38 | // "off" 39 | // ], 40 | // "one-var": [ 41 | // "off" 42 | // ] 43 | // } 44 | // } 45 | 46 | module.exports = RESPONSE; 47 | -------------------------------------------------------------------------------- /common/serverInitMethods/index.js: -------------------------------------------------------------------------------- 1 | export const HelperMethods = {}; 2 | -------------------------------------------------------------------------------- /common/validators/index.js: -------------------------------------------------------------------------------- 1 | import moment from "moment"; 2 | 3 | const moment = require("moment"); 4 | const mongoose = require("mongoose"); 5 | 6 | const Validators = { 7 | isValidEmail: (email) => { 8 | var pattern = /(([a-zA-Z0-9\-?\.?]+)@(([a-zA-Z0-9\-_]+\.)+)([a-z]{2,3}))+$/; 9 | return new RegExp(pattern).test(email); 10 | }, 11 | 12 | isValidPhoneNumber: (num) => { 13 | if (Number.isInteger(num)) { 14 | num = num.toString(); 15 | } 16 | 17 | let pattern = /^([\+0]91)?\-?[5-9]{1}[0-9]{9}$/g; 18 | return new RegExp(pattern).test(num); 19 | }, 20 | 21 | isValidZipCode: (zipcode) => { 22 | var pattern = /^\d{5}(-\d{4})?$/; 23 | return new RegExp(pattern).test(zipcode); 24 | }, 25 | 26 | convertToObjectIds: (_id) => { 27 | return mongoose.Types.ObjectId(_id); 28 | }, 29 | 30 | isMongoObjectId: (_id) => { 31 | return mongoose.Types.ObjectId.isValid(_id); 32 | }, 33 | 34 | isJson: (str) => { 35 | try { 36 | JSON.parse(str); 37 | } catch (e) { 38 | return false; 39 | } 40 | return true; 41 | }, 42 | 43 | isValidPhone: (phone, verifyCountryCode) => { 44 | var reExp = verifyCountryCode ? /^\+\d{6,16}$/ : /^\d{6,16}$/; 45 | return reExp.test(phone); 46 | }, 47 | 48 | getWeekOfYear: (params) => { 49 | return moment().week(); 50 | }, 51 | 52 | getMonthOfYear: (params) => { 53 | return moment().month() + 1; 54 | }, 55 | 56 | validatePincode: (pin) => { 57 | return /^(\d{4}|\d{6})$/.test(pin); 58 | }, 59 | }; 60 | 61 | module.exports = Validators; 62 | -------------------------------------------------------------------------------- /config/db.js: -------------------------------------------------------------------------------- 1 | import mongoose from "mongoose"; 2 | 3 | const mongoose = require("mongoose"); 4 | 5 | const connectDB = async () => { 6 | let uri = process.env.MONGO_URI; 7 | 8 | try { 9 | await mongoose 10 | .connect(uri, { 11 | useNewUrlParser: true, 12 | useUnifiedTopology: true, 13 | useCreateIndex: true, 14 | }) 15 | .catch((error) => { 16 | console.log("connection in error:::", error); 17 | }); 18 | 19 | console.log("mongo DB connected"); 20 | 21 | mongoose.set( 22 | "debug", 23 | function (collectionName, method, query, doc, options) { 24 | console.log(collectionName + "." + method, JSON.stringify(query), doc); 25 | 26 | // log.info({ 27 | // dbQuery: set 28 | // }); 29 | }, 30 | ); 31 | } catch (e) { 32 | console.error(e, "error"); 33 | } finally { 34 | // await client.close(); 35 | } 36 | }; 37 | 38 | module.exports = connectDB; 39 | -------------------------------------------------------------------------------- /constants/index.js: -------------------------------------------------------------------------------- 1 | const CONSTANTS = { 2 | API_URI: "/api/v1", 3 | MESSAGES: { 4 | KEY_CANT_EMPTY: "{{key}} cannot be empty", 5 | KEY_LENGTH_EXCEEDED: 6 | "{{key}} length should cannot exceed {{length}} characters", 7 | INVALID_PINCODE: "Enter a valid Pincode having only 6 digits", 8 | KEY_MUST_BE_ARRAY: "{{key}} must be an array", 9 | INTERNAL_SERVER_ERROR: "Please try after some time.", 10 | TOKEN_GENERATE_EXCEPTION: "Error while generating access token.", 11 | EMAIL_ALREADY_EXISTS: "Email already exists.", 12 | INVALID_EMAIL: "Please fill valid email address.", 13 | USER_NOT_FOUND: "User not found.", 14 | INVALID_PASSWORD: 15 | "Password needs to have at least one lower case, one uppercase, one number, one special character, and must be at least 8 characters but no more than 35.", 16 | VALIDATION_ERROR: "Validation error.", 17 | UNAUTHORIZED_ACCESS_EXCEPTION: "Unauthorized access.", 18 | INVALID_PHONE: "Please fill valid phone number.", 19 | }, 20 | }; 21 | 22 | module.exports = CONSTANTS; 23 | -------------------------------------------------------------------------------- /controllers/auth/user.signin.js: -------------------------------------------------------------------------------- 1 | const bcrypt = require("bcrypt"); 2 | const jwt = require("jsonwebtoken"); 3 | const User = require("../../models/user.model"); 4 | const { MESSAGES } = require("../../constants"); 5 | 6 | const signin = async (req, res) => { 7 | try { 8 | const { email, password } = req.body; 9 | 10 | const user = await User.findOne({ email }); 11 | if (!user) { 12 | return res.status(404).json({ message: MESSAGES.USER_NOT_FOUND }); 13 | } 14 | 15 | const isPasswordValid = await bcrypt.compare(password, user.password); 16 | if (!isPasswordValid) { 17 | return res.status(401).json({ message: MESSAGES.INVALID_PASSWORD }); 18 | } 19 | 20 | const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { 21 | expiresIn: "1h", 22 | }); 23 | 24 | res.status(200).json({ message: "Signin successful.", token }); 25 | } catch (error) { 26 | res.status(500).json({ message: MESSAGES.INTERNAL_SERVER_ERROR }); 27 | } 28 | }; 29 | 30 | module.exports = signin; 31 | -------------------------------------------------------------------------------- /controllers/auth/user.signup.js: -------------------------------------------------------------------------------- 1 | const bcrypt = require("bcrypt"); 2 | const jwt = require("jsonwebtoken"); 3 | const User = require("../../models/user.model"); 4 | const { MESSAGES } = require("../../constants"); 5 | 6 | const signup = async (req, res) => { 7 | try { 8 | const { name, email, password } = req.body; 9 | 10 | const existingUser = await User.findOne({ email }); 11 | if (existingUser) { 12 | return res.status(409).json({ message: MESSAGES.EMAIL_ALREADY_EXISTS }); 13 | } 14 | 15 | const hashedPassword = await bcrypt.hash(password, 10); 16 | 17 | const user = await User.create({ name, email, password: hashedPassword }); 18 | 19 | res.status(201).json({ message: "User created successfully", user }); 20 | } catch (error) { 21 | res.status(500).json({ message: MESSAGES.INTERNAL_SERVER_ERROR }); 22 | } 23 | }; 24 | 25 | module.exports = signup; 26 | -------------------------------------------------------------------------------- /dev.dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:14.11.0-alpine3.10 2 | 3 | WORKDIR /src/server/app 4 | 5 | COPY package*.json ./ 6 | 7 | RUN npm install 8 | 9 | COPY . . 10 | 11 | CMD ["npm", "run", "dev"] 12 | 13 | -------------------------------------------------------------------------------- /images/clone.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sazamansari/node.js-_microservices/cd028f38038b845853b7c0e1bd9b236165a7454d/images/clone.png -------------------------------------------------------------------------------- /images/fork.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sazamansari/node.js-_microservices/cd028f38038b845853b7c0e1bd9b236165a7454d/images/fork.png -------------------------------------------------------------------------------- /logs/all-logs.log: -------------------------------------------------------------------------------- 1 | 2021-08-07 08:16:35:1635 info: SERVER STARTED 2 | 2022-01-03 14:02:14:214 info: SERVER STARTED 3 | 2022-01-03 14:02:37:237 info: GET / 200 4.508 ms - 11 4 | 2022-01-03 14:02:37:237 info: GET /favicon.ico 404 1.228 ms - 150 5 | 2022-01-03 17:07:52:752 info: SERVER STARTED 6 | 2022-01-29 19:49:08:498 info: SERVER STARTED 7 | 2022-01-29 19:49:50:4950 info: SERVER STARTED 8 | 2022-01-29 19:50:01:501 info: SERVER STARTED 9 | 2022-01-29 19:51:08:518 info: SERVER STARTED 10 | 2022-01-29 19:51:31:5131 info: SERVER STARTED 11 | 2022-01-29 19:52:00:520 info: SERVER STARTED 12 | 2022-01-29 19:53:30:5330 info: SERVER STARTED 13 | 2022-01-29 19:53:39:5339 info: SERVER STARTED 14 | 2022-01-29 19:54:20:5420 info: SERVER STARTED 15 | 2022-01-29 19:54:40:5440 info: SERVER STARTED 16 | 2022-01-29 19:55:04:554 info: SERVER STARTED 17 | 2022-01-29 19:55:58:5558 info: SERVER STARTED 18 | 2022-01-29 19:56:35:5635 info: SERVER STARTED 19 | 2022-01-29 19:58:13:5813 info: GET / 200 466.382 ms - 11 20 | 2022-01-29 19:59:07:597 info: POST /api/create 404 66.286 ms - 150 21 | 2022-01-29 20:05:55:555 info: SERVER STARTED 22 | 2022-01-29 20:05:58:558 info: POST /api/create 404 7.857 ms - 150 23 | 2022-01-29 20:06:48:648 info: POST /api/create 404 1.931 ms - 150 24 | 2022-01-29 20:07:36:736 info: SERVER STARTED 25 | 2022-01-29 20:07:38:738 info: POST /api/create 404 13.310 ms - 150 26 | 2022-01-29 20:08:08:88 info: POST /api/user/create 404 1.803 ms - 155 27 | 2022-01-29 20:08:11:811 info: POST /api/user/create 404 0.869 ms - 155 28 | 2022-01-29 20:08:49:849 info: POST /api/v1/user/create 500 146.326 ms - 32 29 | 2022-01-29 20:10:30:1030 info: SERVER STARTED 30 | 2022-01-29 20:10:45:1045 info: POST /api/v1/user/create 500 184.328 ms - 32 31 | 2022-01-29 20:11:31:1131 info: SERVER STARTED 32 | 2022-01-29 20:12:29:1229 info: SERVER STARTED 33 | 2022-01-29 20:12:46:1246 info: SERVER STARTED 34 | 2022-01-29 20:13:05:135 info: POST /api/v1/user/create 500 138.008 ms - 32 35 | 2022-01-29 20:14:16:1416 info: SERVER STARTED 36 | 2022-01-29 20:14:44:1444 info: POST /api/v1/user/create 500 159.961 ms - 32 37 | 2022-01-29 20:14:58:1458 info: POST /api/v1/user/create 500 10.018 ms - 32 38 | 2022-01-29 20:16:15:1615 info: SERVER STARTED 39 | 2022-01-29 20:16:37:1637 info: SERVER STARTED 40 | 2022-01-29 20:17:01:171 info: SERVER STARTED 41 | 2022-01-29 20:17:08:178 info: POST /api/v1/user/create 500 115.099 ms - 32 42 | 2022-01-29 20:20:31:2031 info: SERVER STARTED 43 | 2022-01-29 20:20:40:2040 info: POST /api/v1/user/create 500 80.053 ms - 32 44 | 2022-01-29 20:21:25:2125 info: SERVER STARTED 45 | 2022-01-29 20:22:05:225 info: SERVER STARTED 46 | 2022-01-29 20:22:06:226 info: POST /api/v1/user/create 500 98.743 ms - 32 47 | 2022-01-29 20:28:15:2815 info: SERVER STARTED 48 | 2022-01-29 20:28:31:2831 info: SERVER STARTED 49 | 2022-01-29 20:28:43:2843 info: POST /api/v1/user/create 500 117.744 ms - 32 50 | 2022-01-29 20:30:28:3028 info: SERVER STARTED 51 | 2022-01-29 20:31:13:3113 info: SERVER STARTED 52 | 2022-01-29 20:31:25:3125 info: SERVER STARTED 53 | 2022-01-29 20:31:37:3137 info: SERVER STARTED 54 | 2022-01-29 20:33:02:332 info: SERVER STARTED 55 | 2022-02-01 11:18:40:1840 info: SERVER STARTED 56 | 2022-02-01 11:18:43:1843 info: POST /api/v1/user/create 200 178.518 ms - 32 57 | 2022-02-01 11:24:48:2448 info: SERVER STARTED 58 | 2022-02-01 11:26:02:262 info: GET / 200 155.340 ms - 11 59 | 2022-02-01 11:26:54:2654 info: POST / 404 22.235 ms - 140 60 | 2023-07-08 23:49:46:4946 info: SERVER STARTED 61 | 2023-07-08 23:57:10:5710 info: SERVER STARTED 62 | 2023-07-08 23:57:53:5753 info: SERVER STARTED 63 | 2023-07-09 00:12:02:122 info: SERVER STARTED 64 | 2023-07-09 00:29:02:292 info: SERVER STARTED 65 | 2023-07-09 00:30:10:3010 info: SERVER STARTED 66 | 2023-07-09 00:31:27:3127 info: SERVER STARTED 67 | 2023-07-11 03:16:31:1631 info: SERVER STARTED 68 | 2023-07-11 03:34:44:3444 info: SERVER STARTED 69 | 2023-07-11 04:35:54:3554 info: SERVER STARTED 70 | 2023-07-11 04:40:59:4059 info: SERVER STARTED 71 | 2023-07-11 04:42:59:4259 info: SERVER STARTED 72 | 2023-07-12 02:35:55:3555 info: SERVER STARTED 73 | 2023-07-12 02:42:33:4233 info: SERVER STARTED 74 | 2023-07-12 02:45:04:454 info: SERVER STARTED 75 | 2023-07-12 02:47:35:4735 info: SERVER STARTED 76 | 2023-07-12 02:50:46:5046 info: SERVER STARTED 77 | 2023-07-12 02:50:51:5051 info: SERVER STARTED 78 | 2023-07-12 03:21:29:2129 info: SERVER STARTED 79 | 2023-07-12 03:26:42:2642 info: SERVER STARTED 80 | 2023-07-12 03:29:08:298 info: SERVER STARTED 81 | 2023-07-12 03:30:46:3046 info: SERVER STARTED 82 | 2023-07-12 03:35:13:3513 info: SERVER STARTED 83 | 2023-07-12 03:35:48:3548 info: SERVER STARTED 84 | 2023-07-12 03:38:35:3835 info: SERVER STARTED 85 | 2023-07-12 03:39:00:390 info: SERVER STARTED 86 | 2023-07-12 03:43:54:4354 info: SERVER STARTED 87 | 2023-07-12 03:44:02:442 info: GET / 200 4.958 ms - 11 88 | 2023-07-12 03:52:14:5214 info: SERVER STARTED 89 | 2023-07-12 03:53:53:5353 info: GET / 200 6.232 ms - 11 90 | 2023-07-12 03:56:15:5615 info: POST /api/v1/user/signup 201 861.665 ms - 219 91 | 2023-07-12 03:56:25:5625 info: POST /api/v1/user/signup 409 163.139 ms - 35 92 | 2023-07-12 03:59:04:594 info: POST /api/v1/user/signin 200 597.243 ms - 219 93 | 2023-07-12 04:01:38:138 info: POST /api/v1/user/signin 401 264.201 ms - 166 94 | 2023-07-12 04:02:27:227 info: POST /api/v1/user/signin 404 155.013 ms - 29 95 | 2023-07-26 01:00:48:048 info: SERVER STARTED 96 | 2023-07-26 16:10:29:1029 info: SERVER STARTED 97 | 2023-07-26 16:11:17:1117 info: GET /user 404 11.471 ms - 143 98 | 2023-07-26 16:11:38:1138 info: GET /api/v1/user/ 404 5.112 ms - 151 99 | 2023-07-26 16:12:02:122 info: GET /api/v1/user 404 1.755 ms - 150 100 | 2023-07-26 16:12:31:1231 info: GET / 200 6.591 ms - 11 101 | 2023-07-26 16:13:06:136 info: POST /api/v1/user/signup 409 265.341 ms - 35 102 | 2023-07-26 16:13:19:1319 info: POST /api/v1/user/signup 201 686.790 ms - 218 103 | -------------------------------------------------------------------------------- /middleware/auth.js: -------------------------------------------------------------------------------- 1 | const jwt = require("jsonwebtoken"); 2 | const config = require("config"); 3 | 4 | module.exports = (req, res, next) => { 5 | const token = req.header("x-auth-token"); 6 | 7 | if (!token) { 8 | return res.status(401).json({ 9 | message: "User Unauthorised", 10 | }); 11 | } 12 | 13 | try { 14 | const decoded = jwt.verify(token, config.get("jwtSecretKey")); 15 | 16 | req.user = decoded.user; 17 | next(); 18 | } catch (e) { 19 | return res.status(401).json({ 20 | message: "Server Error", 21 | }); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /middleware/check_auth.js: -------------------------------------------------------------------------------- 1 | import jwt from "jsonwebtoken"; 2 | 3 | import config from "config"; 4 | 5 | import { User } from "../modules/user/user.model"; 6 | 7 | import { OauthAccessToken } from "../modules/oauthAccessToken/oauthAccessToken.model"; 8 | 9 | import dotenv from "dotenv"; 10 | 11 | dotenv.config(); 12 | 13 | export const Authenticate = async (req, res, next) => { 14 | try { 15 | console.log(req.headers); 16 | 17 | const tokens = req.headers.authorization.split(" "); 18 | 19 | const tokenType = tokens[0]; 20 | 21 | if (tokenType !== "Bearer") { 22 | return res.status(401).json({ 23 | status: false, 24 | message: "user unauthorized", 25 | }); 26 | } 27 | 28 | const token = tokens[1]; 29 | 30 | console.log("token"); 31 | console.log(token); 32 | console.log(process.env.SECRET_KEY); 33 | 34 | const decoded = jwt.verify(token, config.get("jwtSecretKey")); 35 | console.log(decoded); 36 | 37 | let tokenData = await OauthAccessToken.findOne({ 38 | id: decoded.id, 39 | revoked: 0, 40 | }); 41 | 42 | console.log(tokenData); 43 | 44 | if (!tokenData) { 45 | return res.status(401).json({ 46 | status: false, 47 | message: "user unauthorized", 48 | }); 49 | } 50 | 51 | let user = await User.findOne({ _id: tokenData.user_id }); 52 | 53 | console.log(user); 54 | 55 | if (!user) { 56 | return res.status(401).json({ 57 | status: false, 58 | message: "user unauthorized00", 59 | }); 60 | } 61 | 62 | let authUser = { 63 | name: user.name, 64 | email: user.email, 65 | mobile: user.mobile, 66 | }; 67 | 68 | req.userData = authUser; 69 | 70 | return next(); 71 | } catch (error) { 72 | console.log("step 5"); 73 | console.log(error); 74 | 75 | return res.status(401).json({ 76 | status: false, 77 | message: "user unauthorized1", 78 | error, 79 | }); 80 | } 81 | }; 82 | -------------------------------------------------------------------------------- /middleware/morgan/index.js: -------------------------------------------------------------------------------- 1 | import morgan from "morgan"; 2 | const morgan = require("morgan"); 3 | 4 | import logger from "../../common/logger"; 5 | const logger = require("../../common/logger"); 6 | 7 | logger.stream = { 8 | write: (message) => 9 | logger.info(message.substring(0, message.lastIndexOf("\n"))), 10 | }; 11 | 12 | module.exports = morgan( 13 | ":method :url :status :response-time ms - :res[content-length]", 14 | { stream: logger.stream }, 15 | ); 16 | -------------------------------------------------------------------------------- /models/user.model.js: -------------------------------------------------------------------------------- 1 | const mongoose = require("mongoose"); 2 | 3 | const userSchema = new mongoose.Schema({ 4 | name: { 5 | type: String, 6 | required: true, 7 | }, 8 | 9 | email: { 10 | type: String, 11 | required: true, 12 | unique: true, 13 | }, 14 | 15 | password: { 16 | type: String, 17 | required: true, 18 | }, 19 | }); 20 | 21 | const User = mongoose.model("User", userSchema); 22 | 23 | module.exports = User; 24 | -------------------------------------------------------------------------------- /modules/oauthAccessToken/oauthAccessToken.model.js: -------------------------------------------------------------------------------- 1 | const mongoose = require("mongoose"); 2 | 3 | const OauthAccessTokenSchema = new mongoose.Schema({ 4 | user_id: { 5 | type: String, 6 | }, 7 | name: { 8 | type: String, 9 | }, 10 | scopes: { 11 | type: String, 12 | required: true, 13 | }, 14 | revoked: { 15 | type: Number, 16 | }, 17 | expires_at: { 18 | type: Date, 19 | // default: Date.now 20 | }, 21 | }); 22 | 23 | export const OauthAccessToken = mongoose.model( 24 | "OauthAccessToken", 25 | OauthAccessTokenSchema, 26 | ); 27 | -------------------------------------------------------------------------------- /modules/user/user.controller.js: -------------------------------------------------------------------------------- 1 | import { UserService } from "./user.service"; 2 | import { RESPONSE } from "../../common/responseHandler"; 3 | import logger from "../../common/logger"; 4 | const accountSid = "AC3c758e52f5f584338257a263039b5dc7"; 5 | const authToken = "f16f2063fcf85dc70d2efd814aaf652f"; 6 | const client = require("twilio")(accountSid, authToken); 7 | const otpGenerator = require("otp-generator"); 8 | 9 | export const createUser = async (req, res) => { 10 | try { 11 | let otp = otpGenerator.generate(4, { 12 | upperCaseAlphabets: false, 13 | specialChars: false, 14 | }); 15 | 16 | client.messages 17 | .create({ 18 | body: `otp for login is ${otp}`, 19 | from: "+17752565844", 20 | to: "+918882203153", 21 | }) 22 | .then((message) => console.log("messsage:::", message.sid, message)) 23 | .catch((err) => { 24 | console.log("err", err); 25 | }); 26 | 27 | // user model mai save 28 | 29 | return res.status(200).send({ data: "otp sent", status: 200 }); 30 | 31 | // let data = await UserService.createUser(req, res); 32 | 33 | // let result = await UserService.JwtSignIn(data); 34 | 35 | // return RESPONSE.Created(result, res); 36 | } catch (error) { 37 | // console.log(error.message); 38 | console.log(error); 39 | logger.info(error); 40 | return RESPONSE.ServerError(res); 41 | } 42 | }; 43 | 44 | export const login = async (req, res) => { 45 | try { 46 | let data = await UserService.login(req, res); 47 | 48 | let result = await UserService.JwtSignIn(data); 49 | 50 | return RESPONSE.Ok(result, res); 51 | } catch (error) { 52 | // console.log(error.message); 53 | logger.info(error); 54 | return RESPONSE.ServerError(res); 55 | } 56 | }; 57 | 58 | export const createTask = async (req, res) => { 59 | try { 60 | let data = await UserService.createTask(req, res); 61 | 62 | return RESPONSE.Ok(result, res); 63 | } catch (error) { 64 | // console.log(error.message); 65 | logger.info(error); 66 | return RESPONSE.ServerError(res); 67 | } 68 | }; 69 | -------------------------------------------------------------------------------- /modules/user/user.model.js: -------------------------------------------------------------------------------- 1 | const mongoose = require("mongoose"); 2 | 3 | const UserSchema = new mongoose.Schema({ 4 | name: { 5 | type: String, 6 | required: true, 7 | }, 8 | 9 | mobile: { 10 | type: String, 11 | required: true, 12 | unique: true, 13 | }, 14 | status: { 15 | type: Boolean, 16 | }, 17 | otp: { 18 | type: String, 19 | }, 20 | credit: { 21 | type: Number, 22 | }, 23 | usertype: { 24 | type: Number, 25 | // 1- admin , 2- user 26 | }, 27 | }); 28 | 29 | export const User = mongoose.model("User", UserSchema); 30 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "user-auth-microservice", 3 | "version": "3.0.0", 4 | "description": "User Authentication Microservice", 5 | "main": "server.js", 6 | "scripts": { 7 | "start": "nodemon --exec babel-node server.js ", 8 | "build": "babel server.js — out-file index-compiled.js", 9 | "server": "nodemon server", 10 | "dev": "nodemon --exec babel-node server.js " 11 | }, 12 | "author": "Shadab Azam Ansari", 13 | "license": "ISC", 14 | "dependencies": { 15 | "bcrypt": "^5.1.0", 16 | "bcryptjs": "^2.4.3", 17 | "compression": "^1.7.4", 18 | "config": "^3.3.8", 19 | "cors": "^2.8.5", 20 | "dotenv": "^8.2.0", 21 | "express": "^4.18.1", 22 | "express-validator": "^6.14.2", 23 | "generate-password": "^1.7.0", 24 | "gravatar": "^1.8.2", 25 | "jsonwebtoken": "^9.0.0", 26 | "moment": "^2.29.4", 27 | "mongoose": "^6.13.6", 28 | "morgan": "^1.10.0", 29 | "otp-generator": "^4.0.0", 30 | "request": "^2.88.2", 31 | "strategy": "^1.1.1", 32 | "twilio": "^3.82.1", 33 | "user-auth-microservice": "^3.1.0", 34 | "uuid": "^7.0.3", 35 | "winston": "^3.8.2" 36 | }, 37 | "devDependencies": { 38 | "@babel/core": "^7.19.1", 39 | "@babel/node": "^7.19.1", 40 | "@babel/preset-env": "^7.19.1", 41 | "eslint": "^7.32.0", 42 | "eslint-config-airbnb-base": "^14.2.1", 43 | "eslint-plugin-import": "^2.26.0", 44 | "nodemon": "^2.0.20" 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /routes/index.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const CONSTANTS = require("../constants/index.js"); 3 | const signup = require("../controllers/auth/user.signup.js"); 4 | const signin = require("../controllers/auth/user.signin.js"); 5 | 6 | const userMiddleware = (req, res, next) => { 7 | // Your middleware logic here 8 | // ... 9 | next(); 10 | }; 11 | 12 | const routes = (app) => { 13 | app.use(`${CONSTANTS.API_URI}/user`, userMiddleware); 14 | 15 | app.post(`${CONSTANTS.API_URI}/user/signup`, signup); 16 | app.post(`${CONSTANTS.API_URI}/user/signin`, signin); 17 | }; 18 | 19 | module.exports = routes; 20 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | // import express from "express"; 2 | const express = require("express"); 3 | 4 | // import dotenv from "dotenv"; 5 | const dotenv = require("dotenv"); 6 | 7 | // import cors from "cors"; 8 | const cors = require("cors"); 9 | 10 | // import compression from "compression"; 11 | const compression = require("compression"); 12 | 13 | // import httpLogger from "./middleware/morgan"; 14 | const httpLogger = require("./middleware/morgan"); 15 | 16 | // import logger from "./common/logger"; 17 | const logger = require("./common/logger"); 18 | 19 | // import connectDB from "./config/db"; 20 | const connectDB = require("./config/db"); 21 | 22 | // import routes from "./routes"; 23 | const routes = require("./routes"); 24 | 25 | const app = express(); 26 | 27 | dotenv.config(); 28 | 29 | // Connect Database 30 | connectDB(); 31 | 32 | // Init Middleware 33 | app.use(express.json({ extended: true })); 34 | app.use(cors()); 35 | app.use(httpLogger); 36 | 37 | const shouldCompress = (req, res) => { 38 | if (req.headers["x-no-compression"]) { 39 | // don't compress responses with this request header 40 | return false; 41 | } 42 | 43 | // fallback to standard filter function 44 | return compression.filter(req, res); 45 | }; 46 | 47 | app.use(compression({ filter: shouldCompress })); 48 | 49 | // Define Routes 50 | routes(app); 51 | 52 | app.get("/", (req, res) => res.send("API RUNNING")); 53 | 54 | const PORT = process.env.SERVER_PORT || 3009; 55 | 56 | // Error handler 57 | function errorHandler(err, req, res, next) { 58 | // Log the error to the console 59 | console.log(err); 60 | 61 | // Send a 500 error response to the client 62 | res.status(500).send("An error occurred"); 63 | } 64 | 65 | app.use(errorHandler); 66 | 67 | app.listen(PORT, () => { 68 | console.log(`SERVER STARTED ON PORT ${PORT}`); 69 | logger.info("SERVER STARTED"); 70 | }); 71 | --------------------------------------------------------------------------------