├── .env.example ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.yml │ ├── config.yml │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md ├── labeler.yml └── workflows │ ├── apply-issue-labels-to-pr.yml │ ├── labeler.yml │ ├── merge-conflict.yml │ └── semantic-pull-requests.yml ├── .gitignore ├── .prettierrc.json ├── .vscode └── settings.json ├── CONTRIBUTING.md ├── LICENCE ├── README.md ├── db └── index.ts ├── docker-compose.yml ├── errors ├── AccessDeniedError.ts └── BadRequestError.ts ├── functions └── graphql │ ├── RequestHandler.ts │ ├── form │ ├── index.ts │ ├── interfaces.ts │ ├── mutations.ts │ ├── queries.ts │ ├── resolver.ts │ └── types.ts │ ├── interfaces.ts │ ├── project │ ├── index.ts │ ├── interfaces.ts │ ├── mutations.ts │ ├── queries.ts │ ├── resolvers.ts │ └── types.ts │ ├── resolvers.ts │ ├── server.ts │ ├── typeDefs.ts │ └── user │ ├── index.ts │ ├── interfaces.ts │ ├── mutations.ts │ ├── queries.ts │ ├── resolvers.ts │ └── types.ts ├── package.json ├── prisma ├── migrations │ ├── 20231009043955_ │ │ └── migration.sql │ └── migration_lock.toml └── schema.prisma ├── scripts └── deploy.sh ├── serverless.yml ├── services ├── form.ts ├── project.ts └── user.ts ├── tsconfig.json ├── utils └── auth.ts └── yarn.lock /.env.example: -------------------------------------------------------------------------------- 1 | DATABASE_URL= 2 | JWT_SECRET= -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.yml: -------------------------------------------------------------------------------- 1 | name: Bug Report 2 | description: File a bug report 3 | title: '[Bug]: ' 4 | labels: ['bug'] 5 | 6 | body: 7 | - type: textarea 8 | attributes: 9 | label: Describe the bug 10 | description: A clear and concise description of what the bug is. 11 | validations: 12 | required: true 13 | - type: textarea 14 | attributes: 15 | label: To Reproduce 16 | description: Steps to reproduce the behavior 17 | value: "1. Go to '...'\n2. Click on '....'\n3. Scroll down to '....'\n4. See error\n" 18 | validations: 19 | required: true 20 | - type: textarea 21 | attributes: 22 | label: Expected behavior 23 | description: A clear and concise description of what you expected to happen. 24 | validations: 25 | required: true 26 | - type: textarea 27 | attributes: 28 | label: Screenshots/Videos 29 | description: Drag n Drop Screenshots or videos which would help us to view the bug visually 30 | validations: 31 | required: false 32 | - type: textarea 33 | attributes: 34 | label: Additional context 35 | description: Add any other context about the problem here. 36 | validations: 37 | required: false 38 | - type: checkboxes 39 | attributes: 40 | label: Please checkmark the following checklist 41 | options: 42 | - label: I make sure that similar issue is not opened 43 | required: true 44 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: Questions 4 | url: https://discord.gg/YuUjtrufmT 5 | about: Ask a general question about the project on our discord community 6 | - name: Updates 7 | url: https://twitter.com/piyushgarg_dev 8 | about: Follow me for updates on this project 9 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest a feature or idea 4 | title: '' 5 | labels: feature 6 | assignees: '' 7 | --- 8 | 9 | ### Is your proposal related to a problem? 10 | 11 | 15 | 16 | (Write your answer here.) 17 | 18 | ### Describe the solution you'd like 19 | 20 | 23 | 24 | (Describe your proposed solution here.) 25 | 26 | ### Describe alternatives you've considered 27 | 28 | 31 | 32 | (Write your answer here.) 33 | 34 | ### Additional context 35 | 36 | 40 | 41 | (Write your answer here.) 42 | 43 | ### Requirement/Document 44 | 45 | 48 | 49 | (Share it here.) 50 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## What does this PR do? 2 | 3 | 4 | 5 | Fixes # (issue) 6 | 7 | 10 | 11 | ## Requirement/Documentation 12 | 13 | 14 | 15 | - If there is a requirement document, please, share it here. 16 | - If there is ab UI/UX design document, please, share it here. 17 | 18 | ## Type of change 19 | 20 | 21 | 22 | - [ ] Bug fix (non-breaking change which fixes an issue) 23 | - [ ] Chore (refactoring code, technical debt, workflow improvements) 24 | - [ ] New feature (non-breaking change which adds functionality) 25 | - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) 26 | - [ ] This change requires a documentation update 27 | 28 | ## How should this be tested? 29 | 30 | 31 | 32 | - Are there environment variables that should be set? 33 | - What are the minimal test data to have? 34 | - What is expected (happy path) to have (input and output)? 35 | - Any other important info that could help to test that PR 36 | 37 | ## Mandatory Tasks 38 | 39 | - [ ] Make sure you have self-reviewed the code. A decent size PR without self-review might be rejected. 40 | 41 | ## Checklist 42 | 43 | 44 | 45 | - My code doesn't follow the style guidelines of this project 46 | - I haven't commented my code, particularly in hard-to-understand areas 47 | - I haven't checked if my PR needs changes to the documentation 48 | - I haven't checked if my changes generate no new warnings 49 | - I haven't added tests that prove my fix is effective or that my feature works 50 | - I haven't checked if new and existing unit tests pass locally with my changes 51 | -------------------------------------------------------------------------------- /.github/labeler.yml: -------------------------------------------------------------------------------- 1 | '❗️ migrations': 2 | - packages/prisma/migrations/**/migration.sql 3 | 4 | '❗️ .env changes': 5 | - .env.example 6 | -------------------------------------------------------------------------------- /.github/workflows/apply-issue-labels-to-pr.yml: -------------------------------------------------------------------------------- 1 | name: 'Apply issue labels to PR' 2 | 3 | on: 4 | pull_request_target: 5 | types: 6 | - opened 7 | 8 | jobs: 9 | label_on_pr: 10 | runs-on: ubuntu-latest 11 | 12 | permissions: 13 | contents: none 14 | issues: read 15 | pull-requests: write 16 | 17 | steps: 18 | - name: Apply labels from linked issue to PR 19 | uses: actions/github-script@v5 20 | with: 21 | github-token: ${{ secrets.GITHUB_TOKEN }} 22 | script: | 23 | async function getLinkedIssues(owner, repo, prNumber) { 24 | const query = `query GetLinkedIssues($owner: String!, $repo: String!, $prNumber: Int!) { 25 | repository(owner: $owner, name: $repo) { 26 | pullRequest(number: $prNumber) { 27 | closingIssuesReferences(first: 10) { 28 | nodes { 29 | number 30 | labels(first: 10) { 31 | nodes { 32 | name 33 | } 34 | } 35 | } 36 | } 37 | } 38 | } 39 | }`; 40 | 41 | const variables = { 42 | owner: owner, 43 | repo: repo, 44 | prNumber: prNumber, 45 | }; 46 | 47 | const result = await github.graphql(query, variables); 48 | return result.repository.pullRequest.closingIssuesReferences.nodes; 49 | } 50 | 51 | const pr = context.payload.pull_request; 52 | const linkedIssues = await getLinkedIssues( 53 | context.repo.owner, 54 | context.repo.repo, 55 | pr.number 56 | ); 57 | 58 | const labelsToAdd = new Set(); 59 | for (const issue of linkedIssues) { 60 | if (issue.labels && issue.labels.nodes) { 61 | for (const label of issue.labels.nodes) { 62 | labelsToAdd.add(label.name); 63 | } 64 | } 65 | } 66 | 67 | if (labelsToAdd.size) { 68 | await github.rest.issues.addLabels({ 69 | owner: context.repo.owner, 70 | repo: context.repo.repo, 71 | issue_number: pr.number, 72 | labels: Array.from(labelsToAdd), 73 | }); 74 | } 75 | -------------------------------------------------------------------------------- /.github/workflows/labeler.yml: -------------------------------------------------------------------------------- 1 | name: 'Pull Request Labeler' 2 | on: 3 | - pull_request_target 4 | concurrency: 5 | group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} 6 | cancel-in-progress: true 7 | jobs: 8 | labeler: 9 | permissions: 10 | contents: read 11 | pull-requests: write 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/labeler@v4 15 | with: 16 | repo-token: '${{ secrets.GITHUB_TOKEN }}' 17 | # https://github.com/actions/labeler/issues/442#issuecomment-1297359481 18 | sync-labels: '' 19 | -------------------------------------------------------------------------------- /.github/workflows/merge-conflict.yml: -------------------------------------------------------------------------------- 1 | name: Auto Comment Merge Conflicts 2 | on: push 3 | 4 | permissions: 5 | pull-requests: write 6 | 7 | jobs: 8 | auto-comment-merge-conflicts: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: codytseng/auto-comment-merge-conflicts@v1 12 | with: 13 | token: ${{ secrets.GITHUB_TOKEN }} 14 | comment-body: 'Hey there, there is a merge conflict, can you take a look?' 15 | wait-ms: 3000 16 | max-retries: 5 17 | label-name: '🚨 merge conflict' 18 | ignore-authors: dependabot,otherAuthor 19 | -------------------------------------------------------------------------------- /.github/workflows/semantic-pull-requests.yml: -------------------------------------------------------------------------------- 1 | name: 'Validate PRs' 2 | 3 | on: 4 | pull_request_target: 5 | types: 6 | - opened 7 | - reopened 8 | - edited 9 | - synchronize 10 | 11 | permissions: 12 | pull-requests: write 13 | 14 | jobs: 15 | validate-pr: 16 | name: Validate PR title 17 | runs-on: ubuntu-latest 18 | steps: 19 | - uses: amannn/action-semantic-pull-request@v5 20 | id: lint_pr_title 21 | env: 22 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 23 | 24 | - uses: marocchino/sticky-pull-request-comment@v2 25 | # When the previous steps fails, the workflow would stop. By adding this 26 | # condition you can continue the execution with the populated error message. 27 | if: always() && (steps.lint_pr_title.outputs.error_message != null) 28 | with: 29 | header: pr-title-lint-error 30 | message: | 31 | Hey there and thank you for opening this pull request! 👋🏼 32 | 33 | We require pull request titles to follow the [Conventional Commits specification](https://www.conventionalcommits.org/en/v1.0.0/) and it looks like your proposed title needs to be adjusted. 34 | 35 | Details: 36 | 37 | ``` 38 | ${{ steps.lint_pr_title.outputs.error_message }} 39 | ``` 40 | 41 | # Delete a previous comment when the issue has been resolved 42 | - if: ${{ steps.lint_pr_title.outputs.error_message == null }} 43 | uses: marocchino/sticky-pull-request-comment@v2 44 | with: 45 | header: pr-title-lint-error 46 | message: | 47 | Thank you for following the naming conventions! 🙏 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | .env.development 82 | .env.production 83 | 84 | # parcel-bundler cache (https://parceljs.org/) 85 | .cache 86 | .parcel-cache 87 | 88 | # Next.js build output 89 | .next 90 | out 91 | 92 | # Nuxt.js build / generate output 93 | .nuxt 94 | dist 95 | .esbuild 96 | 97 | # Gatsby files 98 | .cache/ 99 | # Comment in the public line in if your project uses Gatsby and not Next.js 100 | # https://nextjs.org/blog/next-9-1#public-directory-support 101 | # public 102 | 103 | # vuepress build output 104 | .vuepress/dist 105 | 106 | # vuepress v2.x temp and cache directory 107 | .temp 108 | .cache 109 | 110 | # Docusaurus cache and generated files 111 | .docusaurus 112 | 113 | # Serverless directories 114 | .serverless/ 115 | 116 | # FuseBox cache 117 | .fusebox/ 118 | 119 | # DynamoDB Local files 120 | .dynamodb/ 121 | 122 | # TernJS port file 123 | .tern-port 124 | 125 | # Stores VSCode versions used for testing VSCode extensions 126 | .vscode-test 127 | 128 | # yarn v2 129 | .yarn/cache 130 | .yarn/unplugged 131 | .yarn/build-state.yml 132 | .yarn/install-state.gz 133 | .pnp.* 134 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "trailingComma": "es5", 3 | "tabWidth": 2, 4 | "semi": false, 5 | "singleQuote": true 6 | } 7 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.bracketPairColorization.enabled": true, 3 | "editor.formatOnSave": true, 4 | "editor.defaultFormatter": "esbenp.prettier-vscode", 5 | "[prisma]": { 6 | "editor.defaultFormatter": "Prisma.prisma" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Review App API 2 | 3 | Thank you for your interest in contributing to the Review App API! 4 | We appreciate your support and welcome your contributions to help 5 | enhance and improve the project. Please read through the following 6 | guidelines to get started. 7 | 8 | ## Table of Contents 9 | - [Contributing to Review App API](#contributing-to-review-app-api) 10 | - [Table of Contents](#table-of-contents) 11 | - [Prerequisites](#prerequisites) 12 | - [Contributing Guidelines](#contributing-guidelines) 13 | - [Setting Up the Development Environment](#setting-up-the-development-environment) 14 | - [Submitting a Pull Request (PR)](#submitting-a-pull-request-pr) 15 | - [`.env Configuration`](#env-configuration) 16 | - [Process](#process) 17 | - [Code of Conduct](#code-of-conduct) 18 | - [We appreciate your contributions and look forward to 19 | collaborating with you to improve the Review App API!] 20 | (#we-appreciate-your-contributions-and-look-forward-to-collaborating-with-you-to-improve-the-review-app-api) 21 | 22 | ## Prerequisites 23 | 24 | Before you begin contributing to the backend of the Review App, 25 | please ensure you have the following prerequisites installed and 26 | configured on your local machine: 27 | 28 | - Docker: To set up and manage the development environment. 29 | - Git: To clone and manage the project repository. 30 | - Node.js and npm: To install project dependencies. 31 | - Yarn: To manage Node.js packages effectively. 32 | 33 | ## Contributing Guidelines 34 | 35 | We follow these guidelines for contributing: 36 | 37 | 1. Fork the backend repository to your GitHub account. 38 | 39 | 2. Clone your forked repository to your local machine: 40 | 41 | ```bash 42 | git clone https://github.com/yourusername/review-app-api.git 43 | 44 | 3. Navigate to the backend project directory: 45 | ```bash 46 | cd review-app-api 47 | 48 | 4. Create a new branch for your contribution: 49 | ```bash 50 | git checkout -b feature-name 51 | 52 | 5. Make your changes and ensure your code follows our coding 53 | standards and practices. 54 | 55 | 6. Test your changes locally to ensure they work as expected. 56 | 57 | 7. Commit your changes with clear and concise commit messages: 58 | ```bash 59 | git commit -m "Add feature: your feature description" 60 | 61 | 8. Create a pull request (PR) to the `main` repository's `main` branch. 62 | 63 | ## Setting Up the Development Environment 64 | To set up the development environment locally, follow these steps: 65 | 66 | 1. Clone the backend repository: 67 | ```bash 68 | git clone https://github.com/yourusername/review-app-api.git cd review-app-api 69 | 70 | 2. Run Docker Compose to set up the development environment: 71 | ```bash 72 | docker-compose up -d 73 | 74 | 3. Install project dependencies using Yarn: 75 | ```bash 76 | yarn 77 | 78 | 4. Copy the `.env.example` file to .`env.local` and configure the 79 | 5. following environment variables in the `.env.local` file: 80 | ```env 81 | DATABASE_URL=postgresql://postgres:password@localhost:5432/review 82 | JWT_SECRET=superman123 83 | 84 | You can replace superman123 with any secret of your choice. 85 | 86 | 5. Run database migrations to set up the database: 87 | ```bash 88 | yarn migrate:latest 89 | 90 | 6. Start the local development server: 91 | ```bash 92 | yarn local 93 | 94 | 7. The backend will be up and running on port 8000. 95 | 96 | ## Submitting a Pull Request (PR) 97 | 98 | When you're ready to submit your changes, create a pull request 99 | (PR) to the `main` repository's main branch following our guidelines. 100 | Be sure to provide a clear description of your changes in the PR, and 101 | one of our maintainers will review it. 102 | 103 | ## `.env Configuration` 104 | - Instructions on how to configure the environment variables for the 105 | Review App API. 106 | 107 | 1. You need to copy the `.env.example` file to 108 | `.env.local` 109 | 110 | 2. Then configure the necessary environment variables in the `.env.local` 111 | file. 112 | 113 | 4. In this case, the required environment variables are `DATABASE_URL` and 114 | `JWT_SECRET`. 115 | 116 | 6. The example shows the format for these variables and provides a placeholder 117 | value for `JWT_SECRET`. 118 | 119 | 8. You are instructed to replace this placeholder value with a secret of your choice. 120 | 121 | ### Process 122 | 123 | - Copy the `.env.example` file to `.env.local` and configure the following 124 | environment variables in the `.env.local` file: 125 | ```env 126 | DATABASE_URL=postgresql://postgres:password@localhost:5432/review 127 | JWT_SECRET=superman123 128 | 129 | - You can replace superman123 with any secret of your choice. 130 | 131 | ## Code of Conduct 132 | 133 | Please be aware that we have a Code of Conduct (CODE_OF_CONDUCT.md) that all 134 | contributors are expected to follow. Please read and adhere to it throughout 135 | your contribution journey. 136 | 137 | ## We appreciate your contributions and look forward to collaborating with you 138 | to improve the Review App API! 139 | 140 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Review App - Backend Repo 2 | 3 | This repository contains the backend code for the Review App project. 4 | 5 | ![Screenshot-86.png](https://i.postimg.cc/pXzH9rcC/Screenshot-86.png) 6 | 7 | **Please Note**: This project is divided into two repositories: 8 | 9 | 1. [Review App Frontend](https://github.com/piyushgarg-dev/review-app) 10 | 2. Review App Backend (You are here) 11 | 12 | For more information about the project, visit the [frontend repository](https://github.com/piyushgarg-dev/review-app). 13 | 14 | ## Environment Setup: 15 | 16 | ### Prerequisites: 17 | 18 | 1. Clone the repository: 19 | 20 | ```shell 21 | git clone https://github.com/piyushgarg-dev/review-app-api.git 22 | ``` 23 | 24 | 2. Move to the backend folder: 25 | 26 | ```shell 27 | cd review-app-api 28 | ``` 29 | 30 | 3. Install and set up Docker. 31 | 32 | 4. Run Docker in the background. If you have an older version of Docker, use the following command to run the `docker-compose.yml` file in detached mode: 33 | 34 | ```shell 35 | docker-compose up -d 36 | ``` 37 | 38 | Otherwise, run: 39 | 40 | ```shell 41 | docker compose up -d 42 | ``` 43 | 44 | 5. Set up the backend by running the following command: 45 | ```shell 46 | yarn 47 | ``` 48 | 49 | ### Create a `.env.local` file in the project's root directory. 50 | 51 | The `.env.local` file should contain the following environment variables: 52 | 53 | ```shell 54 | DATABASE_URL=postgresql://postgres:password@localhost:5432/review 55 | JWT_SECRET=superman123 56 | ``` 57 | 58 | ### Run Migrations: 59 | 60 | Run database migrations with the following command: 61 | 62 | ```shell 63 | yarn migrate:latest 64 | ``` 65 | 66 | ### Start the Backend Server: 67 | 68 | To start the backend server, run the following command: 69 | 70 | ```shell 71 | yarn local 72 | ``` 73 | 74 | Congratulations! Your backend is now running at http://localhost:8000/development/graphql. 75 | 76 | ## Communication Channels: 77 | 78 | If you have any questions, need clarifications, or want to discuss ideas, feel free to reach out through the following channels: 79 | 80 | - [Discord Server](https://discord.com/invite/YuUjtrufmT) 81 | - [Twitter](https://twitter.com/piyushgarg_dev) (formerly X) 82 | 83 | We appreciate your contributions and look forward to working with you to make this project even better! 84 | 85 | ## Best Contributors: 86 | 87 |
88 | 89 | 90 | 91 |
92 | 93 | ## Thanks To All Our Contributors: 94 | 95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /db/index.ts: -------------------------------------------------------------------------------- 1 | import { PrismaClient } from '@prisma/client' 2 | 3 | const isLocalEnv = process.env.NODE_ENV === 'local' 4 | 5 | const prismaClient = new PrismaClient({ 6 | log: isLocalEnv ? ['query'] : undefined, 7 | }) 8 | 9 | export default prismaClient 10 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | 3 | services: 4 | postgres: 5 | container_name: postgres-database 6 | image: postgres:15 7 | volumes: 8 | - postgres_data:/var/lib/postgresql/data 9 | ports: 10 | - '5432:5432' 11 | environment: 12 | POSTGRES_USER: postgres 13 | POSTGRES_DB: review 14 | POSTGRES_PASSWORD: password 15 | 16 | volumes: 17 | postgres_data: 18 | -------------------------------------------------------------------------------- /errors/AccessDeniedError.ts: -------------------------------------------------------------------------------- 1 | import { GraphQLError, GraphQLErrorOptions } from 'graphql' 2 | 3 | class AccessDeniedError extends GraphQLError { 4 | constructor(message?: string, options?: GraphQLErrorOptions) { 5 | super(message ?? 'AccessDeniedError', { 6 | extensions: { 7 | code: 'UNAUTHORIZED', 8 | }, 9 | ...options, 10 | }) 11 | } 12 | } 13 | 14 | export default AccessDeniedError 15 | -------------------------------------------------------------------------------- /errors/BadRequestError.ts: -------------------------------------------------------------------------------- 1 | import { GraphQLError, GraphQLErrorOptions } from 'graphql' 2 | 3 | class BadRequestError extends GraphQLError { 4 | constructor(message?: string, options?: GraphQLErrorOptions) { 5 | super(message ?? 'BadRequestError', { 6 | ...options, 7 | }) 8 | } 9 | } 10 | 11 | export default BadRequestError 12 | -------------------------------------------------------------------------------- /functions/graphql/RequestHandler.ts: -------------------------------------------------------------------------------- 1 | import { HeaderMap } from '@apollo/server' 2 | import type { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda' 3 | import { createRequestHandler } from '@as-integrations/aws-lambda/dist/request-handlers/_create' 4 | 5 | export const createAPIGatewayProxyEventRequestHandler = < 6 | Event extends APIGatewayProxyEvent = APIGatewayProxyEvent, 7 | >() => { 8 | return createRequestHandler( 9 | { 10 | parseHttpMethod(event) { 11 | return event.httpMethod 12 | }, 13 | parseHeaders(event) { 14 | const headerMap = new HeaderMap() 15 | for (const [key, value] of Object.entries(event.headers ?? {})) { 16 | headerMap.set(key, value ?? '') 17 | } 18 | return headerMap 19 | }, 20 | parseBody(event, headers) { 21 | if (event.body) { 22 | const contentType = headers.get('content-type') 23 | const parsedBody = event.isBase64Encoded 24 | ? Buffer.from(event.body, 'base64').toString('utf8') 25 | : event.body 26 | if (contentType?.startsWith('application/json')) { 27 | return JSON.parse(parsedBody) 28 | } 29 | if (contentType?.startsWith('text/plain')) { 30 | return parsedBody 31 | } 32 | } 33 | return '' 34 | }, 35 | parseQueryParams(event) { 36 | const params = new URLSearchParams() 37 | for (const [key, value] of Object.entries( 38 | event.multiValueQueryStringParameters ?? {} 39 | )) { 40 | for (const v of value ?? []) { 41 | params.append(key, v) 42 | } 43 | } 44 | return params.toString() 45 | }, 46 | }, 47 | { 48 | success({ body, headers, status }) { 49 | if (body.kind !== 'complete') { 50 | throw new Error('Only complete body type supported') 51 | } 52 | 53 | return { 54 | statusCode: status ?? 200, 55 | headers: { 56 | ...Object.fromEntries(headers), 57 | 'content-length': Buffer.byteLength(body.string).toString(), 58 | 'Access-Control-Allow-Origin': '*', 59 | 'Access-Control-Allow-Credentials': true, 60 | }, 61 | body: body.string, 62 | } 63 | }, 64 | error(error) { 65 | return { 66 | statusCode: 400, 67 | body: (error as Error).message, 68 | } 69 | }, 70 | } 71 | ) 72 | } 73 | -------------------------------------------------------------------------------- /functions/graphql/form/index.ts: -------------------------------------------------------------------------------- 1 | import { types } from './types' 2 | import { resolvers } from './resolver' 3 | import { mutations } from './mutations' 4 | import { queries } from './queries' 5 | 6 | export const Form = { types, resolvers, mutations, queries } 7 | -------------------------------------------------------------------------------- /functions/graphql/form/interfaces.ts: -------------------------------------------------------------------------------- 1 | export interface CreateFormData { 2 | name: string 3 | slug: string 4 | projectId: string 5 | } 6 | 7 | export interface GetFormsInput { 8 | projectId: string 9 | } 10 | 11 | export interface UpdateFormData { 12 | id: string 13 | 14 | name?: string 15 | introTitle?: string 16 | introMessage?: string 17 | promptTitle?: string 18 | promptDescription?: string 19 | 20 | thankyouTitle?: string 21 | thankyouMessage?: string 22 | 23 | enableCTA?: boolean 24 | ctaTitle?: string 25 | ctaURL?: string 26 | 27 | isActive?: boolean 28 | 29 | primaryColor?: string 30 | backgroundColor?: string 31 | 32 | lang?: string 33 | 34 | collectVideoTestimonials?: boolean 35 | collectTextTestimonials?: boolean 36 | collectRatings?: boolean 37 | collectImages?: boolean 38 | collectEmail?: boolean 39 | collectJobTitle?: boolean 40 | collectUserImage?: boolean 41 | collectWebsiteURL?: boolean 42 | collectCompany?: boolean 43 | 44 | autoApproveTestimonials?: boolean 45 | autoAddTags?: [string] 46 | } 47 | 48 | export interface SubmitFormResponseData { 49 | id: string 50 | formId: string 51 | name: string 52 | email?: string 53 | imageURL?: string 54 | rating?: number 55 | testimonial: string 56 | jobTitle?: string 57 | websiteUrl?: string 58 | company?: string 59 | } 60 | 61 | export interface GetFormResponsesByFormIdInput { 62 | formId: string 63 | } 64 | 65 | export interface GetFormResponsesByProjectId { 66 | projectId: string 67 | itemsPerPage?: number 68 | cursor?: string 69 | } 70 | 71 | export interface GetPublicFormDataInput { 72 | domain: string 73 | formSlug: string 74 | } 75 | -------------------------------------------------------------------------------- /functions/graphql/form/mutations.ts: -------------------------------------------------------------------------------- 1 | export const mutations = `#graphql 2 | createForm(data: CreateFormData!): String 3 | updateForm(data: UpdateFormInput!): Boolean 4 | submitFormResponse(data: SubmitFormResponseData!): String 5 | ` 6 | -------------------------------------------------------------------------------- /functions/graphql/form/queries.ts: -------------------------------------------------------------------------------- 1 | export const queries = `#graphql 2 | getForms(input: GetFormsInput!): [Form] 3 | getFormById(id: ID!): Form 4 | getFormResponsesByFormId(input: GetFormResponsesByFormIdInput!): [FormResponse] 5 | getFormResponsesByProjectId(input: GetFormResponsesByProjectIdInput!): [FormResponse] 6 | getPublicFormData(input: GetPublicFormDataInput!): FormPublicData 7 | ` 8 | -------------------------------------------------------------------------------- /functions/graphql/form/resolver.ts: -------------------------------------------------------------------------------- 1 | import slugify from 'slugify' 2 | import FormService from '../../../services/form' 3 | import { ensureAuthenticated } from '../../../utils/auth' 4 | import { ServerContext } from '../interfaces' 5 | import { 6 | CreateFormData, 7 | GetFormResponsesByFormIdInput, 8 | GetFormResponsesByProjectId, 9 | GetFormsInput, 10 | GetPublicFormDataInput, 11 | SubmitFormResponseData, 12 | UpdateFormData, 13 | } from './interfaces' 14 | import BadRequestError from '../../../errors/BadRequestError' 15 | import prismaClient from '../../../db' 16 | 17 | const queries = { 18 | getForms: async ( 19 | _: any, 20 | { input }: { input: GetFormsInput }, 21 | ctx: ServerContext 22 | ) => { 23 | ensureAuthenticated(ctx) 24 | return FormService.getFormsByProjectId(input.projectId) 25 | }, 26 | getFormById: async (_: any, { id }: { id: string }, ctx: ServerContext) => { 27 | ensureAuthenticated(ctx) 28 | return FormService.getFormById(id) 29 | }, 30 | getFormResponsesByFormId: async ( 31 | _: any, 32 | { input }: { input: GetFormResponsesByFormIdInput }, 33 | ctx: ServerContext 34 | ) => { 35 | return FormService.getFormResponsesByFormId(input.formId) 36 | }, 37 | getFormResponsesByProjectId: async ( 38 | _: any, 39 | { input }: { input: GetFormResponsesByProjectId }, 40 | ctx: ServerContext 41 | ) => { 42 | ensureAuthenticated(ctx) 43 | const { projectId, itemsPerPage = 10, cursor } = input 44 | return FormService.getFormResponsesByProjectId(projectId, ctx, { 45 | cursor, 46 | itemsPerPage, 47 | }) 48 | }, 49 | getPublicFormData: async ( 50 | _: any, 51 | { input }: { input: GetPublicFormDataInput } 52 | ) => { 53 | return FormService.getPublicFormData({ 54 | domain: input.domain, 55 | slug: input.formSlug, 56 | }) 57 | }, 58 | } 59 | 60 | const mutations = { 61 | createForm: async ( 62 | _: any, 63 | { data }: { data: CreateFormData }, 64 | ctx: ServerContext 65 | ) => { 66 | ensureAuthenticated(ctx) 67 | const { name, slug, projectId } = data 68 | const form = await FormService.createForm({ 69 | data: { 70 | name, 71 | slug: slugify(slug), 72 | introTitle: 'Share a testimonial!', 73 | introMessage: `Do you love using our product? We'd love to hear about it! - Share your experience with a quick video or text testimonial - Recording a video? Don't forget to smile 😊`, 74 | promptTitle: 'Write a testimonial', 75 | promptDescription: `- What do you like most about us?\n- Would you recommend us to a friend?`, 76 | thankyouTitle: 'Thank you 🙏', 77 | thankyouMessage: 78 | 'Thank you so much for your support! We appreciate your support and we hope you enjoy using our product.', 79 | autoApproveTestimonials: false, 80 | autoAddTags: [], 81 | primaryColor: '#8B41F2', 82 | backgroundColor: '#FFFFFF', 83 | createdBy: { connect: { id: ctx.user?.id! } }, 84 | project: { connect: { id: projectId } }, 85 | }, 86 | }) 87 | return form.id 88 | }, 89 | updateForm: async ( 90 | _: any, 91 | { data }: { data: UpdateFormData }, 92 | ctx: ServerContext 93 | ) => { 94 | ensureAuthenticated(ctx) 95 | await FormService.updateFormById(data.id, data) 96 | return true 97 | }, 98 | 99 | submitFormResponse: async ( 100 | _: any, 101 | { data }: { data: SubmitFormResponseData }, 102 | ctx: ServerContext 103 | ) => { 104 | const { formId } = data 105 | 106 | //Check if form exist with given id 107 | const form = await prismaClient.form.findUnique({ 108 | where: { id: formId }, 109 | select: { id: true, autoAddTags: true, autoApproveTestimonials: true }, 110 | }) 111 | 112 | if (!form || !form.id) { 113 | throw new BadRequestError(`Form with id ${formId} does not exists`) 114 | } 115 | 116 | const formResponse = await FormService.createFormResponse({ 117 | data: { 118 | //required field 119 | name: data.name, 120 | form: { connect: { id: formId } }, 121 | testimonial: data.testimonial, 122 | 123 | email: data.email, 124 | imageURL: data.imageURL, 125 | rating: data.rating, 126 | jobTitle: data.jobTitle, 127 | websiteUrl: data.websiteUrl, 128 | company: data.company, 129 | 130 | approved: Boolean(form.autoApproveTestimonials), 131 | tags: form.autoAddTags, 132 | }, 133 | }) 134 | return formResponse.id 135 | }, 136 | } 137 | 138 | export const resolvers = { queries, mutations } 139 | -------------------------------------------------------------------------------- /functions/graphql/form/types.ts: -------------------------------------------------------------------------------- 1 | export const types = `#graphql 2 | input CreateFormData { 3 | name: String! 4 | slug: String! 5 | projectId: String! 6 | } 7 | 8 | input GetPublicFormDataInput { 9 | domain: String! 10 | formSlug: String! 11 | } 12 | 13 | input UpdateFormInput { 14 | id: ID! 15 | 16 | name: String 17 | introTitle: String 18 | introMessage: String 19 | promptTitle: String 20 | promptDescription: String 21 | 22 | thankyouTitle: String 23 | thankyouMessage: String 24 | 25 | enableCTA: Boolean 26 | ctaTitle: String 27 | ctaURL: String 28 | 29 | isActive: Boolean 30 | 31 | primaryColor: String 32 | backgroundColor: String 33 | 34 | lang: String 35 | 36 | collectVideoTestimonials: Boolean 37 | collectTextTestimonials: Boolean 38 | collectRatings: Boolean 39 | collectImages: Boolean 40 | collectEmail: Boolean 41 | collectJobTitle: Boolean 42 | collectUserImage: Boolean 43 | collectWebsiteURL: Boolean 44 | collectCompany: Boolean 45 | 46 | autoApproveTestimonials: Boolean 47 | autoAddTags: [String] 48 | } 49 | 50 | input GetFormsInput { 51 | projectId: ID! 52 | } 53 | 54 | type FormPublicData { 55 | id: ID! 56 | primaryColor: String! 57 | backgroundColor: String! 58 | 59 | introTitle: String! 60 | introMessage: String 61 | 62 | promptTitle: String! 63 | promptDescription: String 64 | 65 | thankyouTitle: String! 66 | thankyouMessage: String 67 | 68 | name: String! 69 | 70 | enableCTA: Boolean! 71 | ctaTitle: String 72 | ctaURL: String 73 | 74 | collectVideoTestimonials: Boolean! 75 | collectTextTestimonials: Boolean! 76 | collectRatings: Boolean! 77 | collectImages: Boolean! 78 | collectEmail: Boolean! 79 | collectJobTitle: Boolean! 80 | collectUserImage: Boolean! 81 | collectWebsiteURL: Boolean! 82 | collectCompany: Boolean! 83 | lang: String 84 | } 85 | 86 | type Form { 87 | id: ID! 88 | name: String! 89 | slug: String! 90 | 91 | introTitle: String! 92 | introMessage: String 93 | 94 | promptTitle: String! 95 | promptDescription: String 96 | 97 | thankyouTitle: String! 98 | thankyouMessage: String 99 | 100 | enableCTA: Boolean! 101 | ctaTitle: String 102 | ctaURL: String 103 | 104 | project: Project 105 | projectId: String! 106 | 107 | createdBy: User 108 | createdByUserId: String 109 | 110 | isActive: Boolean! 111 | 112 | primaryColor: String! 113 | backgroundColor: String! 114 | 115 | lang: String 116 | 117 | collectVideoTestimonials: Boolean! 118 | collectTextTestimonials: Boolean! 119 | collectRatings: Boolean! 120 | collectImages: Boolean! 121 | collectEmail: Boolean! 122 | collectJobTitle: Boolean! 123 | collectUserImage: Boolean! 124 | collectWebsiteURL: Boolean! 125 | collectCompany: Boolean! 126 | 127 | autoApproveTestimonials: Boolean! 128 | autoAddTags: [String] 129 | 130 | createdAt: Date 131 | updatedAt: Date 132 | 133 | } 134 | 135 | type FormResponse { 136 | id: ID! 137 | 138 | formId: String! 139 | 140 | name: String! 141 | email: String 142 | imageURL: String 143 | rating: Int 144 | testimonial: String! 145 | jobTitle: String 146 | websiteUrl: String 147 | company: String 148 | 149 | tags: [String] 150 | approved: Boolean 151 | 152 | createdAt: Date 153 | updatedAt: Date 154 | } 155 | 156 | input SubmitFormResponseData { 157 | formId: String! 158 | 159 | name: String! 160 | email: String 161 | imageURL: String 162 | rating: Int 163 | testimonial: String! 164 | jobTitle: String 165 | websiteUrl: String 166 | company: String 167 | } 168 | 169 | input GetFormResponsesByFormIdInput { 170 | formId: ID! 171 | } 172 | 173 | input GetFormResponsesByProjectIdInput { 174 | projectId: ID! 175 | itemsPerPage: Int 176 | cursor: String 177 | } 178 | ` 179 | -------------------------------------------------------------------------------- /functions/graphql/interfaces.ts: -------------------------------------------------------------------------------- 1 | import { APIGatewayProxyEventV2, Context } from 'aws-lambda' 2 | import { UserJWTPayload } from '../../services/user' 3 | 4 | export interface ServerContext { 5 | event?: APIGatewayProxyEventV2 6 | context?: Context 7 | user?: UserJWTPayload 8 | headers?: { 9 | 'CloudFront-Viewer-Country'?: string 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /functions/graphql/project/index.ts: -------------------------------------------------------------------------------- 1 | import { types } from './types' 2 | import { queries } from './queries' 3 | import { mutations } from './mutations' 4 | import { resolvers } from './resolvers' 5 | 6 | export const Project = { types, queries, mutations, resolvers } 7 | -------------------------------------------------------------------------------- /functions/graphql/project/interfaces.ts: -------------------------------------------------------------------------------- 1 | export interface CreateProjectData { 2 | name: string 3 | subdomain: string 4 | customDomain?: string 5 | } 6 | -------------------------------------------------------------------------------- /functions/graphql/project/mutations.ts: -------------------------------------------------------------------------------- 1 | export const mutations = `#graphql 2 | createProject(data: CreateProjectData!): Project 3 | ` 4 | -------------------------------------------------------------------------------- /functions/graphql/project/queries.ts: -------------------------------------------------------------------------------- 1 | export const queries = `#graphql 2 | getUserProjects: [Project] 3 | getProjectByDomain(domain: String!): Project 4 | ` 5 | -------------------------------------------------------------------------------- /functions/graphql/project/resolvers.ts: -------------------------------------------------------------------------------- 1 | import ProjectService from '../../../services/project' 2 | import { ensureAuthenticated } from '../../../utils/auth' 3 | import { ServerContext } from '../interfaces' 4 | import { CreateProjectData } from './interfaces' 5 | import { Project } from '@prisma/client' 6 | import FormService from '../../../services/form' 7 | 8 | const queries = { 9 | getUserProjects: (_: any, data: any, ctx: ServerContext) => { 10 | ensureAuthenticated(ctx) 11 | return ProjectService.getUserProjects(ctx.user?.id!) 12 | }, 13 | getProjectByDomain: async ( 14 | _: any, 15 | { domain }: { domain: string }, 16 | ctx: ServerContext 17 | ) => { 18 | ensureAuthenticated(ctx) 19 | const project = await ProjectService.getProjectByDomain({ 20 | domain, 21 | userId: ctx.user?.id!, 22 | }) 23 | return project 24 | }, 25 | } 26 | const mutations = { 27 | createProject: async ( 28 | _: any, 29 | { data }: { data: CreateProjectData }, 30 | ctx: ServerContext 31 | ) => { 32 | ensureAuthenticated(ctx) 33 | const project = await ProjectService.create({ 34 | data: { 35 | name: data.name, 36 | customDomain: data.customDomain, 37 | subdomain: data.subdomain, 38 | ProjectAccessMapping: { 39 | create: { 40 | role: 'OWNER', 41 | user: { 42 | connect: { 43 | id: ctx.user?.id!, 44 | }, 45 | }, 46 | }, 47 | }, 48 | }, 49 | }) 50 | return project 51 | }, 52 | } 53 | 54 | const extraResolvers = { 55 | // Project: { 56 | // forms: async (parent: Project, variables: any, ctx: ServerContext) => { 57 | // ensureAuthenticated(ctx) 58 | // console.log(parent) 59 | // return FormService.getFormsByProjectId(parent.id) 60 | // }, 61 | // }, 62 | } 63 | 64 | export const resolvers = { queries, mutations, extraResolvers } 65 | -------------------------------------------------------------------------------- /functions/graphql/project/types.ts: -------------------------------------------------------------------------------- 1 | export const types = `#graphql 2 | input CreateProjectData { 3 | name: String! 4 | subdomain: String! 5 | customDomain: String 6 | } 7 | 8 | type Project { 9 | id: ID! 10 | name: String! 11 | subdomain: String! 12 | customDomain: String 13 | createdAt: Date 14 | updatedAt: Date 15 | } 16 | ` 17 | -------------------------------------------------------------------------------- /functions/graphql/resolvers.ts: -------------------------------------------------------------------------------- 1 | import { User } from './user' 2 | import { Project } from './project' 3 | import { Form } from './form' 4 | 5 | export const resolvers = { 6 | Query: { 7 | ...User.resolvers.queries, 8 | ...Project.resolvers.queries, 9 | ...Form.resolvers.queries, 10 | }, 11 | Mutation: { 12 | ...User.resolvers.mutations, 13 | ...Project.resolvers.mutations, 14 | ...Form.resolvers.mutations, 15 | }, 16 | ...Project.resolvers.extraResolvers, 17 | } 18 | 19 | export default resolvers 20 | -------------------------------------------------------------------------------- /functions/graphql/server.ts: -------------------------------------------------------------------------------- 1 | import { ApolloServer } from '@apollo/server' 2 | import { startServerAndCreateLambdaHandler } from '@as-integrations/aws-lambda' 3 | import { createAPIGatewayProxyEventRequestHandler } from './RequestHandler' 4 | import UserService from '../../services/user' 5 | 6 | import typeDefs from './typeDefs' 7 | import resolvers from './resolvers' 8 | import { ServerContext } from './interfaces' 9 | 10 | const server = new ApolloServer({ 11 | typeDefs, 12 | resolvers, 13 | introspection: true, 14 | allowBatchedHttpRequests: true, 15 | }) 16 | 17 | export const graphqlHandler = startServerAndCreateLambdaHandler( 18 | server, 19 | createAPIGatewayProxyEventRequestHandler(), 20 | { 21 | context: async ({ event, context }) => { 22 | context.callbackWaitsForEmptyEventLoop = false 23 | const authorizationHeaderValue = event.headers 24 | ? event.headers['authorization'] ?? event.headers['Authorization'] 25 | : undefined 26 | 27 | const authorizationToken = 28 | authorizationHeaderValue && authorizationHeaderValue.includes('Bearer') 29 | ? authorizationHeaderValue?.split('Bearer')[1].trim() 30 | : null 31 | 32 | const tokenResult = authorizationToken 33 | ? UserService.verifyToken(authorizationToken) 34 | : null 35 | 36 | return { 37 | event, 38 | context, 39 | user: tokenResult, 40 | headers: { 41 | 'CloudFront-Viewer-Country': 42 | event.headers['CloudFront-Viewer-Country'], 43 | }, 44 | } 45 | }, 46 | } 47 | ) 48 | -------------------------------------------------------------------------------- /functions/graphql/typeDefs.ts: -------------------------------------------------------------------------------- 1 | import { User } from './user' 2 | import { Project } from './project' 3 | import { Form } from './form' 4 | 5 | const typeDefs = `#graphql 6 | scalar Date 7 | 8 | ${User.types} 9 | ${Project.types} 10 | ${Form.types} 11 | 12 | type Query { 13 | ${User.queries} 14 | ${Project.queries} 15 | ${Form.queries} 16 | } 17 | 18 | type Mutation { 19 | ${User.mutations} 20 | ${Project.mutations} 21 | ${Form.mutations} 22 | } 23 | 24 | ` 25 | 26 | export default typeDefs 27 | -------------------------------------------------------------------------------- /functions/graphql/user/index.ts: -------------------------------------------------------------------------------- 1 | import { types } from './types' 2 | import { queries } from './queries' 3 | import { mutations } from './mutations' 4 | import { resolvers } from './resolvers' 5 | 6 | export const User = { types, queries, resolvers, mutations } 7 | -------------------------------------------------------------------------------- /functions/graphql/user/interfaces.ts: -------------------------------------------------------------------------------- 1 | export interface CreateUserData { 2 | firstName: string 3 | lastName?: string 4 | email: string 5 | password: string 6 | } 7 | -------------------------------------------------------------------------------- /functions/graphql/user/mutations.ts: -------------------------------------------------------------------------------- 1 | export const mutations = `#graphql 2 | createUser(data: CreateUserData!): User 3 | ` 4 | -------------------------------------------------------------------------------- /functions/graphql/user/queries.ts: -------------------------------------------------------------------------------- 1 | export const queries = `#graphql 2 | getSessionUser: User 3 | verifyGoogleAuthToken(googleToken: String!): String 4 | singinwithEmailPassword(email: String!, password: String): String 5 | ` 6 | -------------------------------------------------------------------------------- /functions/graphql/user/resolvers.ts: -------------------------------------------------------------------------------- 1 | import { nanoid } from 'nanoid' 2 | import crypto from 'crypto' 3 | import BadRequestError from '../../../errors/BadRequestError' 4 | import UserService from '../../../services/user' 5 | import { ServerContext } from '../interfaces' 6 | import { CreateUserData } from './interfaces' 7 | 8 | const queries = { 9 | getSessionUser: async (_: any, agrs: any, ctx: ServerContext) => { 10 | if (!ctx.user) return null 11 | const user = UserService.getUserById(ctx.user.id) 12 | return user 13 | }, 14 | singinwithEmailPassword: async ( 15 | _: any, 16 | { email, password }: { email: string; password: string }, 17 | ctx: ServerContext 18 | ) => { 19 | return UserService.signinWithEmailAndPassword(email, password) 20 | }, 21 | verifyGoogleAuthToken: async ( 22 | _: any, 23 | { googleToken }: { googleToken: string }, 24 | ctx: ServerContext 25 | ) => { 26 | // const tokenResult = await GoogleAPIService.verifyUserToken(googleToken); 27 | // if (!tokenResult) throw new AccessDeniedError("Invalid Token"); 28 | // const { email, email_verified, given_name, family_name, picture } = 29 | // tokenResult; 30 | // const checkUserExist = await UserService.getUserByEmail(email); 31 | // if (!checkUserExist) 32 | // await UserService.createUser({ 33 | // data: { 34 | // firstName: given_name, 35 | // lastName: family_name, 36 | // email, 37 | // profileImageURL: picture, 38 | // emailVerified: email_verified === "true", 39 | // authenticationType: "GOOGLE", 40 | // }, 41 | // }); 42 | // const token = await UserService.generateTokenForUser(email); 43 | // return token; 44 | }, 45 | } 46 | 47 | const mutations = { 48 | createUser: async ( 49 | _: any, 50 | { data }: { data: CreateUserData }, 51 | ctx: ServerContext 52 | ) => { 53 | const { firstName, lastName, email, password } = data 54 | 55 | const checkExistsingUser = await UserService.getUserByEmail(email) 56 | if (checkExistsingUser) 57 | throw new BadRequestError(`User with email ${data.email} already exists!`) 58 | 59 | const salt = nanoid(12) 60 | const hashedPassword = crypto 61 | .createHmac('sha256', salt) 62 | .update(password) 63 | .digest('hex') 64 | 65 | const user = await UserService.createUser({ 66 | data: { 67 | firstName, 68 | lastName, 69 | email, 70 | password: hashedPassword, 71 | salt, 72 | authenticationType: 'EMAIL_PASSWORD', 73 | }, 74 | }) 75 | 76 | return user 77 | }, 78 | } 79 | 80 | export const resolvers = { queries, mutations } 81 | -------------------------------------------------------------------------------- /functions/graphql/user/types.ts: -------------------------------------------------------------------------------- 1 | export const types = `#graphql 2 | 3 | input CreateUserData { 4 | firstName: String! 5 | lastName: String 6 | email: String! 7 | password: String! 8 | } 9 | 10 | type User { 11 | id: ID! 12 | firstName: String! 13 | lastName: String 14 | email: String! 15 | emailVerified: Boolean! 16 | authenticationType: String 17 | profileImageURL: String 18 | role: String 19 | 20 | createdAt: Date 21 | updatedAt: Date 22 | } 23 | ` 24 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "review-app-api", 3 | "version": "1.0.0", 4 | "main": "index.js", 5 | "repository": "git@github.com:piyushgarg-dev/review-app-api.git", 6 | "author": "Piyush Garg ", 7 | "scripts": { 8 | "local": "dotenv -c development -- npm run prisma:generate && concurrently \"serverless offline --stage development --disableCookieValidation\"", 9 | "migrate:latest": "dotenv -c development -- prisma migrate deploy", 10 | "prisma:migrate:local": "dotenv -c development -- prisma migrate dev", 11 | "prisma:generate": "prisma generate", 12 | "prisma:studio": "dotenv -c development -- prisma studio", 13 | "deploy:prod": "dotenv -c production -- sh scripts/deploy.sh production" 14 | }, 15 | "devDependencies": { 16 | "@types/jsonwebtoken": "^9.0.2", 17 | "concurrently": "^8.2.0", 18 | "dotenv": "^16.3.1", 19 | "dotenv-cli": "^7.2.1", 20 | "esbuild": "^0.19.1", 21 | "prisma": "^5.1.1", 22 | "serverless": "^3.34.0", 23 | "serverless-dotenv-plugin": "^6.0.0", 24 | "serverless-esbuild": "^1.46.0", 25 | "serverless-offline": "^12.0.4", 26 | "serverless-prune-plugin": "^2.0.2", 27 | "typescript": "^5.1.6" 28 | }, 29 | "dependencies": { 30 | "@apollo/server": "^4.9.1", 31 | "@as-integrations/aws-lambda": "^3.1.0", 32 | "@prisma/client": "5.1.1", 33 | "graphql": "^16.8.0", 34 | "jsonwebtoken": "^9.0.1", 35 | "nanoid": "^4.0.2", 36 | "slugify": "^1.6.6" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /prisma/migrations/20231009043955_/migration.sql: -------------------------------------------------------------------------------- 1 | -- CreateEnum 2 | CREATE TYPE "AuthenticationType" AS ENUM ('EMAIL_PASSWORD', 'GOOGLE'); 3 | 4 | -- CreateEnum 5 | CREATE TYPE "UserRole" AS ENUM ('ADMIN', 'USER'); 6 | 7 | -- CreateEnum 8 | CREATE TYPE "ProjectAccessRole" AS ENUM ('OWNER', 'ADMIN'); 9 | 10 | -- CreateTable 11 | CREATE TABLE "users" ( 12 | "id" TEXT NOT NULL, 13 | "first_name" TEXT NOT NULL, 14 | "last_name" TEXT, 15 | "email" TEXT NOT NULL, 16 | "email_verified" BOOLEAN NOT NULL DEFAULT false, 17 | "password" TEXT, 18 | "salt" TEXT, 19 | "authentication_type" "AuthenticationType" NOT NULL, 20 | "profileImageURL" TEXT, 21 | "role" "UserRole" NOT NULL DEFAULT 'USER', 22 | "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, 23 | "updated_at" TIMESTAMP(3) NOT NULL, 24 | 25 | CONSTRAINT "users_pkey" PRIMARY KEY ("id") 26 | ); 27 | 28 | -- CreateTable 29 | CREATE TABLE "projects" ( 30 | "id" TEXT NOT NULL, 31 | "name" TEXT NOT NULL, 32 | "subdomain" TEXT NOT NULL, 33 | "custom_domain" TEXT, 34 | "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, 35 | "updated_at" TIMESTAMP(3) NOT NULL, 36 | 37 | CONSTRAINT "projects_pkey" PRIMARY KEY ("id") 38 | ); 39 | 40 | -- CreateTable 41 | CREATE TABLE "project_access_mapping" ( 42 | "project_id" TEXT NOT NULL, 43 | "user_id" TEXT NOT NULL, 44 | "role" "ProjectAccessRole" NOT NULL DEFAULT 'OWNER' 45 | ); 46 | 47 | -- CreateTable 48 | CREATE TABLE "forms" ( 49 | "id" TEXT NOT NULL, 50 | "name" TEXT NOT NULL, 51 | "slug" TEXT NOT NULL, 52 | "intro_title" TEXT NOT NULL, 53 | "intro_message" TEXT, 54 | "prompt_title" TEXT NOT NULL, 55 | "prompt_description" TEXT, 56 | "thankyou_title" TEXT NOT NULL, 57 | "thankyou_message" TEXT, 58 | "enable_cta" BOOLEAN NOT NULL DEFAULT false, 59 | "cta_title" TEXT, 60 | "cta_url" TEXT, 61 | "project_id" TEXT NOT NULL, 62 | "created_by" TEXT NOT NULL, 63 | "is_active" BOOLEAN NOT NULL DEFAULT true, 64 | "primary_color_hex_code" TEXT NOT NULL DEFAULT '#6701E6', 65 | "background_color_hex_code" TEXT NOT NULL DEFAULT '#FFFFFF', 66 | "lang" TEXT NOT NULL DEFAULT 'en', 67 | "collect_video_testimonials" BOOLEAN NOT NULL DEFAULT false, 68 | "collect_text_testimonials" BOOLEAN NOT NULL DEFAULT true, 69 | "collect_ratings" BOOLEAN NOT NULL DEFAULT true, 70 | "collect_images" BOOLEAN NOT NULL DEFAULT true, 71 | "collect_email" BOOLEAN NOT NULL DEFAULT true, 72 | "collect_job_title" BOOLEAN NOT NULL DEFAULT true, 73 | "collect_user_image" BOOLEAN NOT NULL DEFAULT true, 74 | "collect_website_url" BOOLEAN NOT NULL DEFAULT true, 75 | "collect_company" BOOLEAN NOT NULL DEFAULT true, 76 | "auto_approve_testimonials" BOOLEAN NOT NULL DEFAULT false, 77 | "auto_add_tags" TEXT[] DEFAULT ARRAY[]::TEXT[], 78 | "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, 79 | "updated_at" TIMESTAMP(3) NOT NULL, 80 | 81 | CONSTRAINT "forms_pkey" PRIMARY KEY ("id") 82 | ); 83 | 84 | -- CreateTable 85 | CREATE TABLE "form_responses" ( 86 | "id" TEXT NOT NULL, 87 | "form_id" TEXT NOT NULL, 88 | "name" TEXT NOT NULL, 89 | "email" TEXT, 90 | "image_url" TEXT, 91 | "rating" INTEGER, 92 | "testimonial" TEXT NOT NULL, 93 | "job_title" TEXT, 94 | "website_url" TEXT, 95 | "company" TEXT, 96 | "tags" TEXT[] DEFAULT ARRAY[]::TEXT[], 97 | "approved" BOOLEAN NOT NULL DEFAULT false, 98 | "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, 99 | "updated_at" TIMESTAMP(3) NOT NULL, 100 | 101 | CONSTRAINT "form_responses_pkey" PRIMARY KEY ("id") 102 | ); 103 | 104 | -- CreateIndex 105 | CREATE UNIQUE INDEX "users_email_key" ON "users"("email"); 106 | 107 | -- CreateIndex 108 | CREATE UNIQUE INDEX "projects_subdomain_key" ON "projects"("subdomain"); 109 | 110 | -- CreateIndex 111 | CREATE UNIQUE INDEX "projects_custom_domain_key" ON "projects"("custom_domain"); 112 | 113 | -- CreateIndex 114 | CREATE UNIQUE INDEX "project_access_mapping_project_id_user_id_key" ON "project_access_mapping"("project_id", "user_id"); 115 | 116 | -- CreateIndex 117 | CREATE UNIQUE INDEX "forms_slug_project_id_key" ON "forms"("slug", "project_id"); 118 | 119 | -- AddForeignKey 120 | ALTER TABLE "project_access_mapping" ADD CONSTRAINT "project_access_mapping_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE RESTRICT ON UPDATE CASCADE; 121 | 122 | -- AddForeignKey 123 | ALTER TABLE "project_access_mapping" ADD CONSTRAINT "project_access_mapping_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE; 124 | 125 | -- AddForeignKey 126 | ALTER TABLE "forms" ADD CONSTRAINT "forms_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE RESTRICT ON UPDATE CASCADE; 127 | 128 | -- AddForeignKey 129 | ALTER TABLE "forms" ADD CONSTRAINT "forms_created_by_fkey" FOREIGN KEY ("created_by") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE; 130 | 131 | -- AddForeignKey 132 | ALTER TABLE "form_responses" ADD CONSTRAINT "form_responses_form_id_fkey" FOREIGN KEY ("form_id") REFERENCES "forms"("id") ON DELETE RESTRICT ON UPDATE CASCADE; 133 | -------------------------------------------------------------------------------- /prisma/migrations/migration_lock.toml: -------------------------------------------------------------------------------- 1 | # Please do not edit this file manually 2 | # It should be added in your version-control system (i.e. Git) 3 | provider = "postgresql" -------------------------------------------------------------------------------- /prisma/schema.prisma: -------------------------------------------------------------------------------- 1 | // This is your Prisma schema file, 2 | // learn more about it in the docs: https://pris.ly/d/prisma-schema 3 | 4 | generator client { 5 | provider = "prisma-client-js" 6 | binaryTargets = ["native", "rhel-openssl-1.0.x"] 7 | } 8 | 9 | datasource db { 10 | provider = "postgresql" 11 | url = env("DATABASE_URL") 12 | } 13 | 14 | enum AuthenticationType { 15 | EMAIL_PASSWORD 16 | GOOGLE 17 | } 18 | 19 | enum UserRole { 20 | ADMIN 21 | USER 22 | } 23 | 24 | enum ProjectAccessRole { 25 | OWNER 26 | ADMIN 27 | } 28 | 29 | model User { 30 | id String @id @default(uuid()) 31 | firstName String @map("first_name") 32 | lastName String? @map("last_name") 33 | email String @unique 34 | emailVerified Boolean @default(false) @map("email_verified") 35 | password String? 36 | salt String? 37 | authenticationType AuthenticationType @map("authentication_type") 38 | profileImageURL String? 39 | role UserRole @default(USER) 40 | createdAt DateTime @default(now()) @map("created_at") 41 | updatedAt DateTime @updatedAt @map("updated_at") 42 | ProjectAccessMapping ProjectAccessMapping[] 43 | Forms Form[] 44 | 45 | @@map("users") 46 | } 47 | 48 | model Project { 49 | id String @id @default(uuid()) 50 | name String 51 | subdomain String @unique 52 | customDomain String? @unique @map("custom_domain") 53 | createdAt DateTime @default(now()) @map("created_at") 54 | updatedAt DateTime @updatedAt @map("updated_at") 55 | ProjectAccessMapping ProjectAccessMapping[] 56 | Forms Form[] 57 | 58 | @@map("projects") 59 | } 60 | 61 | model ProjectAccessMapping { 62 | project Project @relation(fields: [projectId], references: [id]) 63 | projectId String @map("project_id") 64 | 65 | user User @relation(fields: [userId], references: [id]) 66 | userId String @map("user_id") 67 | 68 | role ProjectAccessRole @default(OWNER) 69 | 70 | @@unique([projectId, userId]) 71 | @@map("project_access_mapping") 72 | } 73 | 74 | model Form { 75 | id String @id @default(uuid()) 76 | name String 77 | slug String 78 | 79 | introTitle String @map("intro_title") 80 | introMessage String? @map("intro_message") 81 | 82 | promptTitle String @map("prompt_title") 83 | promptDescription String? @map("prompt_description") 84 | 85 | thankyouTitle String @map("thankyou_title") 86 | thankyouMessage String? @map("thankyou_message") 87 | 88 | enableCTA Boolean @default(false) @map("enable_cta") 89 | ctaTitle String? @map("cta_title") 90 | ctaURL String? @map("cta_url") 91 | 92 | // Foreign Relations 93 | project Project @relation(fields: [projectId], references: [id]) 94 | projectId String @map("project_id") 95 | createdBy User @relation(fields: [createdByUserId], references: [id]) 96 | createdByUserId String @map("created_by") 97 | 98 | isActive Boolean @default(true) @map("is_active") 99 | 100 | // Design 101 | primaryColor String @default("#6701E6") @map("primary_color_hex_code") 102 | backgroundColor String @default("#FFFFFF") @map("background_color_hex_code") 103 | 104 | // Prefrences 105 | lang String @default("en") 106 | collectVideoTestimonials Boolean @default(false) @map("collect_video_testimonials") 107 | collectTextTestimonials Boolean @default(true) @map("collect_text_testimonials") 108 | collectRatings Boolean @default(true) @map("collect_ratings") 109 | collectImages Boolean @default(true) @map("collect_images") 110 | collectEmail Boolean @default(true) @map("collect_email") 111 | collectJobTitle Boolean @default(true) @map("collect_job_title") 112 | collectUserImage Boolean @default(true) @map("collect_user_image") 113 | collectWebsiteURL Boolean @default(true) @map("collect_website_url") 114 | collectCompany Boolean @default(true) @map("collect_company") 115 | 116 | autoApproveTestimonials Boolean @default(false) @map("auto_approve_testimonials") 117 | autoAddTags String[] @default([]) @map("auto_add_tags") 118 | 119 | createdAt DateTime @default(now()) @map("created_at") 120 | updatedAt DateTime @updatedAt @map("updated_at") 121 | responses FormResponse[] 122 | 123 | @@unique([slug, projectId]) 124 | @@map("forms") 125 | } 126 | 127 | model FormResponse { 128 | id String @id @default(uuid()) 129 | 130 | // Relations 131 | form Form @relation(fields: [formId], references: [id]) 132 | formId String @map("form_id") 133 | 134 | // Form filler details 135 | name String 136 | email String? 137 | imageURL String? @map("image_url") 138 | rating Int? 139 | testimonial String @map("testimonial") 140 | jobTitle String? @map("job_title") 141 | websiteUrl String? @map("website_url") 142 | company String? 143 | 144 | tags String[] @default([]) @map("tags") 145 | approved Boolean @default(false) 146 | 147 | createdAt DateTime @default(now()) @map("created_at") 148 | updatedAt DateTime @updatedAt @map("updated_at") 149 | 150 | @@map("form_responses") 151 | } 152 | -------------------------------------------------------------------------------- /scripts/deploy.sh: -------------------------------------------------------------------------------- 1 | STAGE="$1" 2 | 3 | echo "[$STAGE]: Migrate Primsa" 4 | dotenv -c $STAGE -- prisma migrate deploy 5 | 6 | echo "[$STAGE]: Generate Primsa Client" 7 | npm run prisma:generate 8 | 9 | echo "[$STAGE]: Start Serverless Deployment" 10 | sls deploy --stage $STAGE 11 | -------------------------------------------------------------------------------- /serverless.yml: -------------------------------------------------------------------------------- 1 | service: review-app 2 | 3 | plugins: 4 | - serverless-dotenv-plugin 5 | - serverless-esbuild 6 | - serverless-prune-plugin 7 | - serverless-offline 8 | 9 | package: 10 | patterns: 11 | - 'node_modules/.prisma/**' 12 | 13 | custom: 14 | esbuild: 15 | bundle: true 16 | minify: true 17 | prune: 18 | automatic: true 19 | number: 2 20 | serverless-offline: 21 | httpPort: 8000 22 | 23 | provider: 24 | name: aws 25 | stage: ${opt:stage} 26 | runtime: nodejs18.x 27 | timeout: 25 28 | lambdaHashingVersion: 20201221 29 | region: ap-south-1 30 | profile: melonreviews 31 | environment: 32 | STAGE: ${self:provider.stage} 33 | NODE_ENV: ${self:provider.stage} 34 | 35 | functions: 36 | graphql: 37 | handler: functions/graphql/server.graphqlHandler 38 | events: 39 | - http: 40 | path: /graphql 41 | method: POST 42 | cors: true 43 | - http: 44 | path: /graphql 45 | method: GET 46 | cors: true 47 | -------------------------------------------------------------------------------- /services/form.ts: -------------------------------------------------------------------------------- 1 | import prismaClient from '../db' 2 | import AccessDeniedError from '../errors/AccessDeniedError' 3 | import { UpdateFormData } from '../functions/graphql/form/interfaces' 4 | import { ServerContext } from '../functions/graphql/interfaces' 5 | 6 | interface GetFormResponsesByProjectIdOptions { 7 | itemsPerPage?: number 8 | cursor?: string 9 | } 10 | 11 | class FormService { 12 | public static createForm = prismaClient.form.create 13 | 14 | public static getFormsByProjectId(projectId: string) { 15 | return prismaClient.form.findMany({ where: { project: { id: projectId } } }) 16 | } 17 | 18 | public static getFormById(id: string) { 19 | return prismaClient.form.findUnique({ where: { id } }) 20 | } 21 | 22 | public static getPublicFormData({ 23 | domain, 24 | slug, 25 | }: { 26 | domain: string 27 | slug: string 28 | }) { 29 | return prismaClient.form.findFirst({ 30 | where: { 31 | AND: [ 32 | { 33 | project: { OR: [{ subdomain: domain }, { customDomain: domain }] }, 34 | }, 35 | { slug }, 36 | ], 37 | }, 38 | select: { 39 | backgroundColor: true, 40 | collectCompany: true, 41 | collectEmail: true, 42 | collectImages: true, 43 | collectJobTitle: true, 44 | collectRatings: true, 45 | collectUserImage: true, 46 | collectTextTestimonials: true, 47 | collectVideoTestimonials: true, 48 | collectWebsiteURL: true, 49 | ctaTitle: true, 50 | enableCTA: true, 51 | ctaURL: true, 52 | introMessage: true, 53 | introTitle: true, 54 | name: true, 55 | primaryColor: true, 56 | promptDescription: true, 57 | promptTitle: true, 58 | thankyouMessage: true, 59 | thankyouTitle: true, 60 | id: true, 61 | }, 62 | }) 63 | } 64 | 65 | public static updateFormById(id: string, formData: UpdateFormData) { 66 | return prismaClient.form.update({ 67 | data: { 68 | ...formData, 69 | // Excude following fields from getting updated 70 | slug: undefined, 71 | createdBy: undefined, 72 | createdAt: undefined, 73 | updatedAt: undefined, 74 | project: undefined, 75 | id: undefined, 76 | }, 77 | where: { id }, 78 | }) 79 | } 80 | 81 | public static createFormResponse = prismaClient.formResponse.create 82 | 83 | public static getFormResponsesByProjectId( 84 | projectId: string, 85 | ctx: ServerContext, 86 | options?: GetFormResponsesByProjectIdOptions 87 | ) { 88 | if (!ctx.user?.id) throw new AccessDeniedError() 89 | 90 | return prismaClient.formResponse.findMany({ 91 | where: { 92 | form: { 93 | project: { 94 | id: projectId, 95 | ProjectAccessMapping: { every: { user: { id: ctx.user.id } } }, // TODO: Need to test more deeply 96 | }, 97 | }, 98 | }, 99 | cursor: options?.cursor 100 | ? { 101 | id: options?.cursor, 102 | } 103 | : undefined, 104 | take: options?.itemsPerPage ?? 10, 105 | skip: options?.cursor ? 1 : 0, // Skip the cursor 106 | orderBy: { createdAt: 'desc' }, 107 | }) 108 | } 109 | 110 | public static getFormResponsesByFormId(formId: string) { 111 | return prismaClient.formResponse.findMany({ 112 | where: { 113 | formId, 114 | }, 115 | orderBy: { 116 | updatedAt: 'desc', 117 | }, 118 | select: { 119 | approved: true, 120 | company: true, 121 | createdAt: true, 122 | email: true, 123 | imageURL: true, 124 | id: true, 125 | jobTitle: true, 126 | rating: true, 127 | testimonial: true, 128 | name: true, 129 | websiteUrl: true, 130 | formId: true, 131 | }, 132 | }) 133 | } 134 | } 135 | 136 | export default FormService 137 | -------------------------------------------------------------------------------- /services/project.ts: -------------------------------------------------------------------------------- 1 | import prismaClient from '../db' 2 | class ProjectService { 3 | public static create = prismaClient.project.create 4 | 5 | public static getUserProjects(userId: string) { 6 | return prismaClient.project.findMany({ 7 | where: { ProjectAccessMapping: { every: { user: { id: userId } } } }, 8 | }) 9 | } 10 | 11 | public static async getProjectByDomain({ 12 | domain, 13 | userId, 14 | }: { 15 | domain: string 16 | userId: string 17 | }) { 18 | const [project] = await prismaClient.project.findMany({ 19 | where: { 20 | OR: [{ subdomain: domain }, { customDomain: domain }], 21 | ProjectAccessMapping: { every: { user: { id: userId } } }, 22 | }, 23 | }) 24 | return project 25 | } 26 | } 27 | 28 | export default ProjectService 29 | -------------------------------------------------------------------------------- /services/user.ts: -------------------------------------------------------------------------------- 1 | import { User, UserRole } from '@prisma/client' 2 | import crypto from 'crypto' 3 | import JWT from 'jsonwebtoken' 4 | import BadRequestError from '../errors/BadRequestError' 5 | import prismaClient from '../db/index' 6 | 7 | const JWT_SECRET = process.env.JWT_SECRET 8 | 9 | if (!JWT_SECRET) 10 | throw new Error( 11 | 'JWT_SECRET is undefined, Please include JWT_SECRET in .env file' 12 | ) 13 | 14 | export interface UserJWTPayload { 15 | id: string 16 | email: string 17 | role: UserRole 18 | } 19 | 20 | class UserService { 21 | public static createUser = prismaClient.user.create 22 | 23 | public static getUserByEmail(email: string) { 24 | return prismaClient.user.findUnique({ where: { email } }) 25 | } 26 | 27 | public static getUserById(id: string) { 28 | return prismaClient.user.findUnique({ where: { id } }) 29 | } 30 | 31 | public static async signinWithEmailAndPassword( 32 | email: string, 33 | password: string 34 | ) { 35 | const user = await this.getUserByEmail(email) 36 | if (!user) 37 | throw new BadRequestError(`User with email ${email} does not exists!`) 38 | 39 | if (user.authenticationType !== 'EMAIL_PASSWORD') 40 | throw new BadRequestError(`Invalid Authentication Method`) 41 | 42 | const userSalt = user.salt 43 | 44 | if (!userSalt) 45 | throw new BadRequestError( 46 | `Something went wrong with salt! Please contact site admin` 47 | ) 48 | 49 | const hashPassword = crypto 50 | .createHmac('sha256', userSalt) 51 | .update(password) 52 | .digest('hex') 53 | 54 | if (user.password !== hashPassword) 55 | throw new BadRequestError(`Invalid email or password!`) 56 | 57 | return this.generateTokenForUser(user.email) 58 | } 59 | 60 | public static verifyToken(token: string) { 61 | try { 62 | return JWT.verify(token, JWT_SECRET as string) as UserJWTPayload 63 | } catch (error) { 64 | return null 65 | } 66 | } 67 | 68 | public static async generateTokenForUser(email: string) { 69 | const user = await this.getUserByEmail(email) 70 | if (!user) throw new BadRequestError(`user with ${email} does not exists`) 71 | 72 | const payload: UserJWTPayload = { 73 | id: user.id, 74 | email: user.email, 75 | role: user.role, 76 | } 77 | 78 | const token = JWT.sign(payload, JWT_SECRET as string) 79 | return token 80 | } 81 | } 82 | 83 | export default UserService 84 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 26 | 27 | /* Modules */ 28 | "module": "commonjs" /* Specify what module code is generated. */, 29 | "rootDir": "./" /* Specify the root folder within your source files. */, 30 | // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ 31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ 35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ 39 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ 40 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ 41 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ 42 | // "resolveJsonModule": true, /* Enable importing .json files. */ 43 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ 44 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */ 45 | 46 | /* JavaScript Support */ 47 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 48 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 49 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 50 | 51 | /* Emit */ 52 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 53 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 54 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 55 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 56 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 57 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ 58 | "outDir": "./dist" /* Specify an output folder for all emitted files. */, 59 | // "removeComments": true, /* Disable emitting comments. */ 60 | // "noEmit": true, /* Disable emitting files from a compilation. */ 61 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 62 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ 63 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 64 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 65 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 66 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 67 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 68 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 69 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 70 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 71 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 72 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 73 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 74 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 75 | 76 | /* Interop Constraints */ 77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ 79 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 80 | "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, 81 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 82 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, 83 | 84 | /* Type Checking */ 85 | "strict": true /* Enable all strict type-checking options. */, 86 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ 87 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 88 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 89 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 90 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 91 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ 92 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 93 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 94 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 95 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 96 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 97 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 98 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 99 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 100 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 101 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 102 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 103 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 104 | 105 | /* Completeness */ 106 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 107 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /utils/auth.ts: -------------------------------------------------------------------------------- 1 | import { UserRole } from '@prisma/client' 2 | import AccessDeniedError from '../errors/AccessDeniedError' 3 | import { ServerContext } from '../functions/graphql/interfaces' 4 | 5 | interface Options { 6 | allowedRoles?: UserRole[] 7 | } 8 | 9 | export const ensureAuthenticated = (ctx: ServerContext, options?: Options) => { 10 | if (!ctx.user) 11 | throw new AccessDeniedError(`Please make sure you are authenticated!`) 12 | if (options && options.allowedRoles) 13 | if (!options.allowedRoles.includes(ctx.user.role)) 14 | throw new AccessDeniedError('Permission Denied!') 15 | return 16 | } 17 | --------------------------------------------------------------------------------