diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md index 2155855c8..8bde700a0 100644 --- a/.github/ISSUE_TEMPLATE/bug.md +++ b/.github/ISSUE_TEMPLATE/bug.md @@ -8,7 +8,6 @@ labels: 'bug' (A clear and concise description of what the bug is) - ## Useful informations (Write what happened. Add screenshots, stacktraces, videos, anything that can help) diff --git a/.github/ISSUE_TEMPLATE/feature.md b/.github/ISSUE_TEMPLATE/feature.md index fb5232149..c76c88696 100644 --- a/.github/ISSUE_TEMPLATE/feature.md +++ b/.github/ISSUE_TEMPLATE/feature.md @@ -10,4 +10,5 @@ labels: 'enhancement' ## Implementation details -(Please outline any details about how this feature would e implemented. If you don't know, you can just skip this section.) +(Please outline any details about how this feature would e implemented. If you don't know, you can just skip this +section.) diff --git a/.github/ISSUE_TEMPLATE/release.md b/.github/ISSUE_TEMPLATE/release.md index cdc02f194..9b3acc1bb 100644 --- a/.github/ISSUE_TEMPLATE/release.md +++ b/.github/ISSUE_TEMPLATE/release.md @@ -6,37 +6,38 @@ labels: # 📅 Checklist -## 🔶 Staging +## 🔶 Staging ### Dev Tag - - [supertokens-core:X.Y](https://github.com/supertokens/supertokens-core/tree/X.Y) - - [ ] core + +- [supertokens-core:X.Y](https://github.com/supertokens/supertokens-core/tree/X.Y) + - [ ] core - [ ] check CDI, plugin interface list - [ ] Add migration script for psql / mysql - - [ ] Make sure no memory leak - - [ ] plugin-interface + - [ ] Make sure no memory leak + - [ ] plugin-interface + - [ ] check plugin interface list + - [ ] mysql-plugin + - [ ] check plugin interface list + - [ ] Add migration script for mysql + - [ ] postgresql-plugin + - [ ] check plugin interface list + - [ ] Add migration script for psql + - [ ] mongodb-plugin - [ ] check plugin interface list - - [ ] mysql-plugin - - [ ] check plugin interface list - - [ ] Add migration script for mysql - - [ ] postgresql-plugin - - [ ] check plugin interface list - - [ ] Add migration script for psql - - [ ] mongodb-plugin - - [ ] check plugin interface list - - [ ] [supertokens-node:X.Y](https://github.com/supertokens/supertokens-node/tree/X.Y) - - [ ] check CDI, FDI list - - [ ] [supertokens-golang:X.Y](https://github.com/supertokens/supertokens-golang/tree/X.Y) - - [ ] check CDI, FDI list - - [ ] [supertokens-python:X.Y](https://github.com/supertokens/supertokens-python/tree/X.Y) - - [ ] check CDI, FDI list - - [ ] [supertokens-website:X.Y](https://github.com/supertokens/supertokens-website/X.Y) - - [ ] check FDI list - - [ ] [supertokens-web-js:X.Y](https://github.com/supertokens/supertokens-web-js/X.Y) - - [ ] check FDI list - - [ ] check web-js interface version - - [ ] Update dependency version of supertokens-website in package.json from npm registry - - [ ] [supertokens-auth-react:X.Y](https://github.com/supertokens/supertokens-auth-react/tree/X.Y) +- [ ] [supertokens-node:X.Y](https://github.com/supertokens/supertokens-node/tree/X.Y) + - [ ] check CDI, FDI list +- [ ] [supertokens-golang:X.Y](https://github.com/supertokens/supertokens-golang/tree/X.Y) + - [ ] check CDI, FDI list +- [ ] [supertokens-python:X.Y](https://github.com/supertokens/supertokens-python/tree/X.Y) + - [ ] check CDI, FDI list +- [ ] [supertokens-website:X.Y](https://github.com/supertokens/supertokens-website/X.Y) + - [ ] check FDI list +- [ ] [supertokens-web-js:X.Y](https://github.com/supertokens/supertokens-web-js/X.Y) + - [ ] check FDI list + - [ ] check web-js interface version + - [ ] Update dependency version of supertokens-website in package.json from npm registry +- [ ] [supertokens-auth-react:X.Y](https://github.com/supertokens/supertokens-auth-react/tree/X.Y) - [ ] check FDI list - [ ] check web-js interface version - [ ] Updated dependencies to use supertokens-web-js in package.json from npm registry @@ -44,74 +45,75 @@ labels: - [ ] Mobile responsiveness - [ ] Make sure using with-typescript example that types are correct for every new configs exposed to users - [ ] Make sure frontend login UI shows even if backend is not working. - - [ ] [supertokens-react-native:X.Y](https://github.com/supertokens/supertokens-react-native/X.Y) +- [ ] [supertokens-react-native:X.Y](https://github.com/supertokens/supertokens-react-native/X.Y) + - [ ] check FDI list +- [ ] [supertokens-android:X.Y](https://github.com/supertokens/supertokens-android/X.Y) - [ ] check FDI list - - [ ] [supertokens-android:X.Y](https://github.com/supertokens/supertokens-android/X.Y) - - [ ] check FDI list - - [ ] [supertokens-ios:X.Y](https://github.com/supertokens/supertokens-ios/X.Y) - - [ ] check FDI list - - [ ] [supertokens-flutter:X.Y](https://github.com/supertokens/supertokens-flutter/X.Y) - - [ ] check FDI list - - [ ] [supertokens-dashboard](https://github.com/supertokens/dashboard) - - [ ] Tested all items mentioned in this? https://github.com/supertokens/dashboard/blob/master/.github/PULL_REQUEST_TEMPLATE.md - - [ ] Test day with team. Get people in the team to read the docs and implement something with the new feature. +- [ ] [supertokens-ios:X.Y](https://github.com/supertokens/supertokens-ios/X.Y) + - [ ] check FDI list +- [ ] [supertokens-flutter:X.Y](https://github.com/supertokens/supertokens-flutter/X.Y) + - [ ] check FDI list +- [ ] [supertokens-dashboard](https://github.com/supertokens/dashboard) + - [ ] Tested all items mentioned in + this? https://github.com/supertokens/dashboard/blob/master/.github/PULL_REQUEST_TEMPLATE.md +- [ ] Test day with team. Get people in the team to read the docs and implement something with the new feature. ### Others - [ ] Example apps in create-supertokens-app CLI - [ ] Create new example app in create-supertokens-app CLI? - - [ ] Examples apps in supertokens-auth-react. Update try.supertokens and rerun the pr checklist - - [ ] Examples apps in supertokens-web-js - - [ ] Examples apps in supertokens-react-native - - [ ] Examples apps in supertokens-golang - - [ ] Examples apps in supertokens-python - - [ ] Examples apps in supertokens-node. Update try.supertokens and rerun the pr checklist - - [ ] Examples apps in android - - [ ] Example apps in ios - - [ ] Example apps in flutter - - [ ] [next.js:canary](https://github.com/supertokens/next.js/tree/canary/examples/with-supertokens) - - [ ] RedwoodJS and playground-auth - - [ ] Run on netlify (and hence AWS lambda) to check if it works fine there - - [ ] Test on vercel (with-emailpassword-vercel app) - - [ ] SuperTokens Jackson SAML example update - - [ ] Supabase docs - - [ ] Capacitor template app: https://github.com/RobSchilderr/capacitor-supertokens-nextjs-turborepo - - [ ] T4 App: https://github.com/timothymiller/t4-app +- [ ] Examples apps in supertokens-auth-react. Update try.supertokens and rerun the pr checklist +- [ ] Examples apps in supertokens-web-js +- [ ] Examples apps in supertokens-react-native +- [ ] Examples apps in supertokens-golang +- [ ] Examples apps in supertokens-python +- [ ] Examples apps in supertokens-node. Update try.supertokens and rerun the pr checklist +- [ ] Examples apps in android +- [ ] Example apps in ios +- [ ] Example apps in flutter +- [ ] [next.js:canary](https://github.com/supertokens/next.js/tree/canary/examples/with-supertokens) +- [ ] RedwoodJS and playground-auth +- [ ] Run on netlify (and hence AWS lambda) to check if it works fine there +- [ ] Test on vercel (with-emailpassword-vercel app) +- [ ] SuperTokens Jackson SAML example update +- [ ] Supabase docs +- [ ] Capacitor template app: https://github.com/RobSchilderr/capacitor-supertokens-nextjs-turborepo +- [ ] T4 App: https://github.com/timothymiller/t4-app ### 📚 Documentation (test site) - [ ] All recipe main documentation update - [ ] Code type checking versions are pointing to X.Y - - [ ] jsEnv - - [ ] goEnv - - [ ] pythonEnv + - [ ] jsEnv + - [ ] goEnv + - [ ] pythonEnv - [ ] Update table schema in mysql / postgresql section for self hosted - [ ] community documentation update - [ ] website changes (test.supertokens.io) - - [ ] homepage - - [ ] pricing page feature list - - [ ] comparison chart in the pricing page - - [ ] product roadmap page - - [ ] Update API key code snippet in SaaS dashboard - - [ ] Update recipe list and links to the docs for supertokens.com dashboard + - [ ] homepage + - [ ] pricing page feature list + - [ ] comparison chart in the pricing page + - [ ] product roadmap page + - [ ] Update API key code snippet in SaaS dashboard + - [ ] Update recipe list and links to the docs for supertokens.com dashboard -## 🔥 Production +## 🔥 Production ### 💻 NPM and core release - - core +- core - [ ] [supertokens-core:X.Y](https://github.com/supertokens/supertokens-core/tree/X.Y) - [ ] plugin-interface - [ ] mysql-plugin - [ ] postgresql-plugin - [ ] mongodb-plugin - Docker update - - [ ] MySQL - - [ ] check if new env cnofigs need to be added - - [ ] Postgres - - [ ] check if new env cnofigs need to be added - - [ ] MongoDB - - [ ] check if new env cnofigs need to be added + - [ ] MySQL + - [ ] check if new env cnofigs need to be added + - [ ] Postgres + - [ ] check if new env cnofigs need to be added + - [ ] MongoDB + - [ ] check if new env cnofigs need to be added - [ ] try.supertokens.io ``` docker rm try-supertokens -f @@ -124,27 +126,29 @@ labels: - [ ] Run tests against golang sdk (all compatible versions) - [ ] Update SaaS config - [ ] Update to tables checked for user count / or to know if a deployment is being used or not - - [ ] Update logic for deleting all data in dev env if a new table was added and if the data should be removed from it too + - [ ] Update logic for deleting all data in dev env if a new table was added and if the data should be removed from + it too - [ ] Update logic for exporting csv file for registered users - [ ] Update SaaS instances to use the latest docker images. - - [ ] Change [checklist in contributing guide for which tables to pick when migrating data from dev to prod instance](https://test.supertokens.com/docs/contribute/checklists/saas/tables-to-consider-for-data-migration-dev-to-prod). + - [ ] + Change [checklist in contributing guide for which tables to pick when migrating data from dev to prod instance](https://test.supertokens.com/docs/contribute/checklists/saas/tables-to-consider-for-data-migration-dev-to-prod). - [ ] Update license key used for cores to include nea feature. - [ ] Update table schema in mysql / postgresql section for self hosted in docs. - [ ] Update paid feature to min version mapping in /st/features GET. - [ ] Update API that returns the list of paid features in saas dashboard - [ ] Update logic for core to core migration for new saas architecture: - - [ ] transfer of master database information - - [ ] deletion of master database information related to the CUD being transferred - - [ ] [supertokens-node:X.Y](https://github.com/supertokens/supertokens-node/tree/X.Y) - - [ ] [supertokens-golang:X.Y](https://github.com/supertokens/supertokens-golang/tree/X.Y) - - [ ] [supertokens-website:X.Y](https://github.com/supertokens/supertokens-website/tree/X.Y) - - [ ] [supertokens-web-js:X.Y](https://github.com/supertokens/supertokens-web-js/tree/X.Y) - - [ ] [supertokens-auth-react:X.Y](https://github.com/supertokens/supertokens-auth-react/tree/X.Y) - - [ ] [supertokens-python:X.Y](https://github.com/supertokens/supertokens-python/tree/X.Y) - - [ ] [supertokens-react-native:X.Y](https://github.com/supertokens/supertokens-react-native/X.Y) - - [ ] [supertokens-android:X.Y](https://github.com/supertokens/supertokens-android/X.Y) - - [ ] [supertokens-ios:X.Y](https://github.com/supertokens/supertokens-ios/X.Y) - - [ ] [supertokens-flutter:X.Y](https://github.com/supertokens/supertokens-flutter/X.Y) + - [ ] transfer of master database information + - [ ] deletion of master database information related to the CUD being transferred +- [ ] [supertokens-node:X.Y](https://github.com/supertokens/supertokens-node/tree/X.Y) +- [ ] [supertokens-golang:X.Y](https://github.com/supertokens/supertokens-golang/tree/X.Y) +- [ ] [supertokens-website:X.Y](https://github.com/supertokens/supertokens-website/tree/X.Y) +- [ ] [supertokens-web-js:X.Y](https://github.com/supertokens/supertokens-web-js/tree/X.Y) +- [ ] [supertokens-auth-react:X.Y](https://github.com/supertokens/supertokens-auth-react/tree/X.Y) +- [ ] [supertokens-python:X.Y](https://github.com/supertokens/supertokens-python/tree/X.Y) +- [ ] [supertokens-react-native:X.Y](https://github.com/supertokens/supertokens-react-native/X.Y) +- [ ] [supertokens-android:X.Y](https://github.com/supertokens/supertokens-android/X.Y) +- [ ] [supertokens-ios:X.Y](https://github.com/supertokens/supertokens-ios/X.Y) +- [ ] [supertokens-flutter:X.Y](https://github.com/supertokens/supertokens-flutter/X.Y) - [ ] [supertokens-dashboard](https://github.com/supertokens/dashboard) ### 📚 Documentation @@ -161,24 +165,25 @@ labels: - [ ] Algolia search update for docs - [ ] robots.txt, sitemap.xml, noindex page update - Auto generate release note on github: - - [ ] supertokens-core - - [ ] supertokens-plugin-interface - - [ ] supertokens-mysql-plugin - - [ ] supertokens-postgresql-plugin - - [ ] supertokens-mongodb-plugin - - [ ] supertokens-node - - [ ] supertokens-golang - - [ ] supertokens-python - - [ ] supertokens-website - - [ ] supertokens-web-js - - [ ] supertokens-auth-react - - [ ] supertokens-react-native - - [ ] supertokens-android - - [ ] supertokens-ios - - [ ] supertokens-flutter - - [ ] supertokens-dashboard + - [ ] supertokens-core + - [ ] supertokens-plugin-interface + - [ ] supertokens-mysql-plugin + - [ ] supertokens-postgresql-plugin + - [ ] supertokens-mongodb-plugin + - [ ] supertokens-node + - [ ] supertokens-golang + - [ ] supertokens-python + - [ ] supertokens-website + - [ ] supertokens-web-js + - [ ] supertokens-auth-react + - [ ] supertokens-react-native + - [ ] supertokens-android + - [ ] supertokens-ios + - [ ] supertokens-flutter + - [ ] supertokens-dashboard ### Contents of running try.supertokens.com script: + ```bash docker run -d \ --restart=always \ diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 94c0f5211..fa8708570 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -29,12 +29,15 @@ highlighting the necessary changes) - [ ] Had installed and ran the pre-commit hook - [ ] If there are new dependencies that have been added in `build.gradle`, please make sure to add them in `implementationDependencies.json`. -- [ ] Update function `getValidFields` in `io/supertokens/config/CoreConfig.java` if new aliases were added for any core config (similar to the `access_token_signing_key_update_interval` config alias). +- [ ] Update function `getValidFields` in `io/supertokens/config/CoreConfig.java` if new aliases were added for any core + config (similar to the `access_token_signing_key_update_interval` config alias). - [ ] Issue this PR against the latest non released version branch. - To know which one it is, run find the latest released tag (`git tag`) in the format `vX.Y.Z`, and then find the latest branch (`git branch --all`) whose `X.Y` is greater than the latest released tag. - If no such branch exists, then create one from the latest released branch. -- [ ] If added a foreign key constraint on `app_id_to_user_id` table, make sure to delete from this table when deleting the user as well if `deleteUserIdMappingToo` is false. +- [ ] If added a foreign key constraint on `app_id_to_user_id` table, make sure to delete from this table when deleting + the user as well if `deleteUserIdMappingToo` is false. + ## Remaining TODOs for this PR - [ ] Item1 diff --git a/.github/workflows/github-actions-changelog.yml b/.github/workflows/github-actions-changelog.yml index 0007ca9a0..47aaf4a24 100644 --- a/.github/workflows/github-actions-changelog.yml +++ b/.github/workflows/github-actions-changelog.yml @@ -1,15 +1,15 @@ name: "Enforcing changelog in PRs Workflow" on: pull_request: - types: [opened, synchronize, reopened, ready_for_review, labeled, unlabeled] + types: [ opened, synchronize, reopened, ready_for_review, labeled, unlabeled ] jobs: # Enforces the update of a changelog file on every pull request changelog: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: dangoslen/changelog-enforcer@v2 - with: - changeLogPath: 'CHANGELOG.md' - skipLabels: 'Skip-Changelog' \ No newline at end of file + - uses: actions/checkout@v2 + - uses: dangoslen/changelog-enforcer@v2 + with: + changeLogPath: 'CHANGELOG.md' + skipLabels: 'Skip-Changelog' \ No newline at end of file diff --git a/.github/workflows/lint-pr-title.yml b/.github/workflows/lint-pr-title.yml index 904efde8b..96281a745 100644 --- a/.github/workflows/lint-pr-title.yml +++ b/.github/workflows/lint-pr-title.yml @@ -1,20 +1,20 @@ name: "Lint PR Title" on: - pull_request: - types: - - opened - - reopened - - edited - - synchronize + pull_request: + types: + - opened + - reopened + - edited + - synchronize jobs: - pr-title: - name: Lint PR title - runs-on: ubuntu-latest - steps: - - uses: amannn/action-semantic-pull-request@v3 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - validateSingleCommit: true \ No newline at end of file + pr-title: + name: Lint PR title + runs-on: ubuntu-latest + steps: + - uses: amannn/action-semantic-pull-request@v3 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + validateSingleCommit: true \ No newline at end of file diff --git a/.github/workflows/tests-pass-check-pr.yml b/.github/workflows/tests-pass-check-pr.yml index 4f03705b4..07467d9d4 100644 --- a/.github/workflows/tests-pass-check-pr.yml +++ b/.github/workflows/tests-pass-check-pr.yml @@ -1,24 +1,24 @@ name: "Check if \"Run tests\" action succeeded" on: - pull_request: - types: - - opened - - reopened - - edited - - synchronize + pull_request: + types: + - opened + - reopened + - edited + - synchronize jobs: - pr-run-test-action: - name: Check if "Run tests" action succeeded - timeout-minutes: 60 - concurrency: - group: ${{ github.head_ref }} - cancel-in-progress: true - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: node install - run: cd ./.github/helpers && npm i - - name: Calling github API - run: cd ./.github/helpers && GITHUB_TOKEN=${{ github.token }} REPO=${{ github.repository }} RUN_ID=${{ github.run_id }} BRANCH=${{ github.head_ref }} JOB_ID=${{ github.job }} SOURCE_OWNER=${{ github.event.pull_request.head.repo.owner.login }} CURRENT_SHA=${{ github.event.pull_request.head.sha }} node node_modules/github-workflow-helpers/test-pass-check-pr.js \ No newline at end of file + pr-run-test-action: + name: Check if "Run tests" action succeeded + timeout-minutes: 60 + concurrency: + group: ${{ github.head_ref }} + cancel-in-progress: true + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: node install + run: cd ./.github/helpers && npm i + - name: Calling github API + run: cd ./.github/helpers && GITHUB_TOKEN=${{ github.token }} REPO=${{ github.repository }} RUN_ID=${{ github.run_id }} BRANCH=${{ github.head_ref }} JOB_ID=${{ github.job }} SOURCE_OWNER=${{ github.event.pull_request.head.repo.owner.login }} CURRENT_SHA=${{ github.event.pull_request.head.sha }} node node_modules/github-workflow-helpers/test-pass-check-pr.js \ No newline at end of file diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index f0160e94f..d4255461e 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -4,11 +4,11 @@ on: inputs: pluginRepoOwnerName: description: 'supertokens-plugin-interface repo owner name' - default: supertokens + default: supertokens required: true pluginInterfaceBranch: description: 'supertokens-plugin-interface repos branch name' - default: master + default: master required: true jobs: diff --git a/CHANGELOG.md b/CHANGELOG.md index 46f44b2a6..7df71a213 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,24 +10,25 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [9.1.0] - 2024-05-24 - Adds new core API for fetching all the core properties for a tenant - - GET `/appid-//recipe/dashboard/tenant/core-config` + - GET `/appid-//recipe/dashboard/tenant/core-config` - Deprecated the following APIs - - PUT `/recipe/multitenancy/connectionuridomain` - - GET `/recipe/multitenancy/connectionuridomain/list` - - PUT `/recipe/multitenancy/app` - - GET `/recipe/multitenancy/app/list` - - PUT `/appid-/recipe/multitenancy/tenant` - - GET `/appid-//recipe/multitenancy/tenant` - - GET `/appid-//recipe/multitenancy/tenant/list` + - PUT `/recipe/multitenancy/connectionuridomain` + - GET `/recipe/multitenancy/connectionuridomain/list` + - PUT `/recipe/multitenancy/app` + - GET `/recipe/multitenancy/app/list` + - PUT `/appid-/recipe/multitenancy/tenant` + - GET `/appid-//recipe/multitenancy/tenant` + - GET `/appid-//recipe/multitenancy/tenant/list` - Adds the following APIs to replace the deprecated APIs - - PUT `/recipe/multitenancy/connectionuridomain/v2` - - GET `/recipe/multitenancy/connectionuridomain/list/v2` - - PUT `/recipe/multitenancy/app/v2` - - GET `/recipe/multitenancy/app/list/v2` - - PUT `/appid-/recipe/multitenancy/tenant/v2` - - GET `/appid-//recipe/multitenancy/tenant/v2` - - GET `/appid-//recipe/multitenancy/tenant/list/v2` -- Backward compatible recipe enabled boolean computations based on - https://github.com/supertokens/supertokens-core/issues/979#issuecomment-2099971371 + - PUT `/recipe/multitenancy/connectionuridomain/v2` + - GET `/recipe/multitenancy/connectionuridomain/list/v2` + - PUT `/recipe/multitenancy/app/v2` + - GET `/recipe/multitenancy/app/list/v2` + - PUT `/appid-/recipe/multitenancy/tenant/v2` + - GET `/appid-//recipe/multitenancy/tenant/v2` + - GET `/appid-//recipe/multitenancy/tenant/list/v2` +- Backward compatible recipe enabled boolean computations based + on - https://github.com/supertokens/supertokens-core/issues/979#issuecomment-2099971371 ## [9.0.2] - 2024-04-17 @@ -54,20 +55,22 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Tenant APIs - Adds `deviceName` in the response of `CreateOrUpdateTotpDeviceAPI` `POST` - `VerifyTOTPAPI` changes - - Removes `allowUnverifiedDevices` from request body and unverified devices are not allowed - - Adds `currentNumberOfFailedAttempts` and `maxNumberOfFailedAttempts` in response when status is - `INVALID_TOTP_ERROR` or `LIMIT_REACHED_ERROR` - - Adds status `UNKNOWN_USER_ID_ERROR` + - Removes `allowUnverifiedDevices` from request body and unverified devices are not allowed + - Adds `currentNumberOfFailedAttempts` and `maxNumberOfFailedAttempts` in response when status is + `INVALID_TOTP_ERROR` or `LIMIT_REACHED_ERROR` + - Adds status `UNKNOWN_USER_ID_ERROR` - `VerifyTotpDeviceAPI` changes - - Adds `currentNumberOfFailedAttempts` and `maxNumberOfFailedAttempts` in response when status is - `INVALID_TOTP_ERROR` or `LIMIT_REACHED_ERROR` + - Adds `currentNumberOfFailedAttempts` and `maxNumberOfFailedAttempts` in response when status is + `INVALID_TOTP_ERROR` or `LIMIT_REACHED_ERROR` - Adds `consumedDevice` in the success response of the `ConsumeCodeAPI` - Adds `preAuthSessionId` input to `DeleteCodeAPI` to be able to delete codes for a device - Adds a new `useDynamicSigningKey` into the request body of `RefreshSessionAPI` - - This enables smooth switching between `useDynamicAccessTokenSigningKey` settings by allowing refresh calls to change the signing key type of a session - - This is available after CDI3.0 - - This is required in&after CDI5.0 and optional before -- Adds optional `firstFactors` and `requiredSecondaryFactors` to the create or update connectionUriDomain, app and tenant APIs + - This enables smooth switching between `useDynamicAccessTokenSigningKey` settings by allowing refresh calls to + change the signing key type of a session + - This is available after CDI3.0 + - This is required in&after CDI5.0 and optional before +- Adds optional `firstFactors` and `requiredSecondaryFactors` to the create or update connectionUriDomain, app and + tenant APIs - Updates Last active while linking accounts - Marks fake email in email password sign up as verified - Fixes slow down in useridmapping queries @@ -105,23 +108,26 @@ DROP INDEX all_auth_recipe_users_pagination_index4 ON all_auth_recipe_users; ### Breaking changes -- The following app specific APIs return a 403 when they are called with a tenant ID other than the `public` one. For example, if the path is `/users/count/active`, and you call it with `/tenant1/users/count/active`, it will return a 403. But if you call it with `/public/users/count/active`, or just `/users/count/active`, it will work. - - GET `/recipe/accountlinking/user/primary/check` - - GET `/recipe/accountlinking/user/link/check` - - POST `/recipe/accountlinking/user/primary` - - POST `/recipe/accountlinking/user/link` - - POST `/recipe/accountlinking/user/unlink` - - GET `/users/count/active` - - POST `/user/remove` - - GET `/ee/featureflag` - - GET `/user/id` - - PUT `/ee/license` - - DELETE `/ee/license` - - GET `/ee/license` - - GET `/requests/stats` - - GET `/recipe/user` when querying by `userId` - - GET `/recipe/jwt/jwks` - - POST `/recipe/jwt` +- The following app specific APIs return a 403 when they are called with a tenant ID other than the `public` one. For + example, if the path is `/users/count/active`, and you call it with `/tenant1/users/count/active`, it will return a + 403. But if you call it with `/public/users/count/active`, or just `/users/count/active`, it will work. + + - GET `/recipe/accountlinking/user/primary/check` + - GET `/recipe/accountlinking/user/link/check` + - POST `/recipe/accountlinking/user/primary` + - POST `/recipe/accountlinking/user/link` + - POST `/recipe/accountlinking/user/unlink` + - GET `/users/count/active` + - POST `/user/remove` + - GET `/ee/featureflag` + - GET `/user/id` + - PUT `/ee/license` + - DELETE `/ee/license` + - GET `/ee/license` + - GET `/requests/stats` + - GET `/recipe/user` when querying by `userId` + - GET `/recipe/jwt/jwks` + - POST `/recipe/jwt` ### Fixes @@ -130,11 +136,13 @@ DROP INDEX all_auth_recipe_users_pagination_index4 ON all_auth_recipe_users; ### Migration For Postgresql: + ```sql ALTER TABLE user_roles DROP CONSTRAINT IF EXISTS user_roles_role_fkey; ``` For MySQL: + ```sql ALTER TABLE user_roles DROP FOREIGN KEY user_roles_ibfk_1; ALTER TABLE user_roles DROP FOREIGN KEY user_roles_ibfk_2; @@ -152,7 +160,8 @@ ALTER TABLE user_roles ## [7.0.17] - 2024-02-06 - Fixes issue where error logs were printed to StdOut instead of StdErr. -- Adds new config `supertokens_saas_load_only_cud` that makes the core instance load a particular CUD only, irrespective of the CUDs present in the db. +- Adds new config `supertokens_saas_load_only_cud` that makes the core instance load a particular CUD only, irrespective + of the CUDs present in the db. - Fixes connection pool handling when connection pool size changes for a tenant. ## [7.0.16] - 2023-12-04 @@ -190,19 +199,26 @@ CREATE INDEX IF NOT EXISTS app_id_to_user_id_primary_user_id_index ON app_id_to_ ## [7.0.12] - 2023-11-16 -In this release, the core API routes have been updated to incorporate phone number normalization before processing. Consequently, existing entries in the database also need to undergo normalization. To facilitate this, we have included a migration script to normalize phone numbers for all the existing entries. +In this release, the core API routes have been updated to incorporate phone number normalization before processing. +Consequently, existing entries in the database also need to undergo normalization. To facilitate this, we have included +a migration script to normalize phone numbers for all the existing entries. **NOTE**: You can skip the migration if you are not using passwordless via phone number. ### Migration steps -This script updates the `phone_number` column in the `passwordless_users`, `passwordless_user_to_tenant`, and `passwordless_devices` tables with their respective normalized values. This script is idempotent and can be run multiple times without any issue. Follow the steps below to run the script: +This script updates the `phone_number` column in the `passwordless_users`, `passwordless_user_to_tenant`, +and `passwordless_devices` tables with their respective normalized values. This script is idempotent and can be run +multiple times without any issue. Follow the steps below to run the script: 1. Ensure that the core is already upgraded to version 7.0.12 (CDI version 4.0) 2. Run the migration script - Make sure your Node.js version is 16 or above to run the script. Locate the migration script at `supertokens-core/migration_scripts/to_version_7_0_12/index.js`. Modify the script by updating the `DB_HOST`, `DB_USER`, `DB_PASSWORD`, and `DB_NAME` variables with the correct values. Subsequently, run the following commands to initiate the script: - + Make sure your Node.js version is 16 or above to run the script. Locate the migration script + at `supertokens-core/migration_scripts/to_version_7_0_12/index.js`. Modify the script by updating + the `DB_HOST`, `DB_USER`, `DB_PASSWORD`, and `DB_NAME` variables with the correct values. Subsequently, run the + following commands to initiate the script: + ```bash $ git clone https://github.com/supertokens/supertokens-core.git $ cd supertokens-core/migration_scripts/to_version_7_0_12 @@ -210,7 +226,9 @@ This script updates the `phone_number` column in the `passwordless_users`, `pass $ npm start ``` - Performance Note: On average, the script takes 19s for every 1000 rows with a maximum of 1 connection, 4.7s with a maximum of 5 connections (default), and 4.5s with a maximum of 10 connections. Increasing the `MAX_POOL_SIZE` allows the script to leverage more connections simultaneously, potentially improving execution speed. + Performance Note: On average, the script takes 19s for every 1000 rows with a maximum of 1 connection, 4.7s with a + maximum of 5 connections (default), and 4.5s with a maximum of 10 connections. Increasing the `MAX_POOL_SIZE` allows + the script to leverage more connections simultaneously, potentially improving execution speed. ## [7.0.11] - 2023-11-10 @@ -256,7 +274,8 @@ This script updates the `phone_number` column in the `passwordless_users`, `pass ## [7.0.1] - 2023-10-04 -- Remove padding from link codes and pre-auth session ids in passwordless, but keep support for old format that included padding (`=` signs) +- Remove padding from link codes and pre-auth session ids in passwordless, but keep support for old format that included + padding (`=` signs) ## [7.0.0] - 2023-09-19 @@ -265,17 +284,19 @@ This script updates the `phone_number` column in the `passwordless_users`, `pass ### Session recipe changes -- New access token version: v5, which contains a required prop: `rsub`. This contains the recipe user ID that belongs to the login method that the user used to login. The `sub` claim in the access token payload is now the primary user ID. +- New access token version: v5, which contains a required prop: `rsub`. This contains the recipe user ID that belongs to + the login method that the user used to login. The `sub` claim in the access token payload is now the primary user ID. - APIs that return `SessionInformation` (like GET `/recipe/session`) contains userId, recipeUserId in the response. - Apis that create / modify / refresh a session return the `recipeUserId` in the `session` object in the response. - Token theft detected response returns userId and recipeUserId ### Db Schema changes -- Adds columns `primary_or_recipe_user_id`, `is_linked_or_is_a_primary_user` and `primary_or_recipe_user_time_joined` to `all_auth_recipe_users` table +- Adds columns `primary_or_recipe_user_id`, `is_linked_or_is_a_primary_user` and `primary_or_recipe_user_time_joined` + to `all_auth_recipe_users` table - Adds columns `primary_or_recipe_user_id` and `is_linked_or_is_a_primary_user` to `app_id_to_user_id` table -- Removes index `all_auth_recipe_users_pagination_index` and addes `all_auth_recipe_users_pagination_index1`, - `all_auth_recipe_users_pagination_index2`, `all_auth_recipe_users_pagination_index3` and +- Removes index `all_auth_recipe_users_pagination_index` and addes `all_auth_recipe_users_pagination_index1`, + `all_auth_recipe_users_pagination_index2`, `all_auth_recipe_users_pagination_index3` and `all_auth_recipe_users_pagination_index4` indexes instead on `all_auth_recipe_users` table - Adds `all_auth_recipe_users_recipe_id_index` on `all_auth_recipe_users` table - Adds `all_auth_recipe_users_primary_user_id_index` on `all_auth_recipe_users` table @@ -458,7 +479,7 @@ This script updates the `phone_number` column in the `passwordless_users`, `pass ## [6.0.9] - 2023-08-14 -- Now using decimal notation to add numbers into the access token payload (instead of scientific notation) +- Now using decimal notation to add numbers into the access token payload (instead of scientific notation) ## [6.0.8] - 2023-08-01 @@ -2308,9 +2329,9 @@ This script updates the `phone_number` column in the `passwordless_users`, `pass from session_access_token_signing_keys; ``` - If using `access_token_signing_key_dynamic` true or not set: - - ```sql - ALTER TABLE session_info ADD COLUMN use_static_key BOOLEAN NOT NULL DEFAULT(false); - ALTER TABLE session_info ALTER COLUMN use_static_key DROP DEFAULT; + - ```sql + ALTER TABLE session_info ADD COLUMN use_static_key BOOLEAN NOT NULL DEFAULT(false); + ALTER TABLE session_info ALTER COLUMN use_static_key DROP DEFAULT; ``` #### Migration steps for MongoDB diff --git a/LICENSE.md b/LICENSE.md index 728963a30..c32eac68e 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -7,194 +7,193 @@ Portions of this software are licensed as follows: * Content outside of the above mentioned directories or restrictions above is available under the "Apache 2.0" license as defined below. - Apache License Version 2.0, January 2004 https://www.apache.org/licenses/ - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2020-2023 SuperTokens, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +Copyright 2020-2023 SuperTokens, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. \ No newline at end of file +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md index 77edda287..4d05352b7 100644 --- a/README.md +++ b/README.md @@ -7,16 +7,20 @@ alt="chat on Discord"> Docker pull stats -Add **secure login and session management** to your apps. [SDKs available](https://supertokens.com/docs/community/sdks) for popular languages and front-end frameworks e.g. Node.js, Go, Python, React.js, React Native, Vanilla JS, etc. +Add **secure login and session management** to your apps. [SDKs available](https://supertokens.com/docs/community/sdks) +for popular languages and front-end frameworks e.g. Node.js, Go, Python, React.js, React Native, Vanilla JS, etc. ![Architecture Diagram](https://supertokens.com/img/architecture/self_hosted_generic.png) -Supertokens architecture is optimized to add secure authentication for your users without compromising on user and developer experience +Supertokens architecture is optimized to add secure authentication for your users without compromising on user and +developer experience **Three building blocks of SuperTokens architecture** 1. Frontend SDK: Manages session tokens and renders login UI widgets -2. Backend SDK: Provides APIs for sign-up, sign-in, signout, session refreshing, etc. Your Frontend will talk to these APIs -3. SuperTokens Core: The HTTP service for the core auth logic and database operations. This service is used by the Backend SDK +2. Backend SDK: Provides APIs for sign-up, sign-in, signout, session refreshing, etc. Your Frontend will talk to these + APIs +3. SuperTokens Core: The HTTP service for the core auth logic and database operations. This service is used by the + Backend SDK ## Features @@ -32,15 +36,15 @@ Supertokens architecture is optimized to add secure authentication for your user * User Roles * Microservice Authentication - ## Learn more + - [🚀 What is SuperTokens?](https://github.com/supertokens/supertokens-core#-what-is-supertokens) - [Philosophy](https://github.com/supertokens/supertokens-core#philosophy) - [Features + Demo app](https://github.com/supertokens/supertokens-core#features---click-here-to-see-the-demo-app) - [Documentation](https://github.com/supertokens/supertokens-core#documentation) - [🏗️ Architecture](https://github.com/supertokens/supertokens-core#%EF%B8%8F-architecture) - [☕ Why Java?](https://github.com/supertokens/supertokens-core#-why-java) -- [⌨️ User Management Dashboard](https://github.com/supertokens/supertokens-core#-user-management-dashboard) +- [⌨️ User Management Dashboard](https://github.com/supertokens/supertokens-core#-user-management-dashboard) - [🔥 SuperTokens vs Others](https://github.com/supertokens/supertokens-core#-supertokens-vs-others) - [🛠️ Building from source](https://github.com/supertokens/supertokens-core#%EF%B8%8F-building-from-source) - [👥 Community](https://github.com/supertokens/supertokens-core#-community) @@ -51,57 +55,74 @@ Supertokens architecture is optimized to add secure authentication for your user ### If you like our project, please :star2: this repository! For feedback, feel free to join our [Discord](https://supertokens.io/discord), or create an issue on this repo ## 🚀 What is SuperTokens? + SuperTokens is an open-core alternative to proprietary login providers like Auth0 or AWS Cognito. We are - different because we offer: +different because we offer: + - Open source: SuperTokens can be used for free, forever, with no limits on the number of users. - An on-premises deployment so that you control 100% of your user data, using your own database. -- An end-to-end solution with login, sign-ups, user and session management, without all the complexities of OAuth protocols. +- An end-to-end solution with login, sign-ups, user and session management, without all the complexities of OAuth + protocols. - Ease of implementation and higher security. - Extensibility: Anyone can contribute and make SuperTokens better! ### Philosophy + Authentication directly affects the UX, dev experience, and security of any app. We believe that - current solutions cannot optimize for all three "pillars", leading to many - applications hand-rolling their own auth. This not only leads to security issues but is also a massive - time drain. - +current solutions cannot optimize for all three "pillars", leading to many +applications hand-rolling their own auth. This not only leads to security issues but is also a massive +time drain. + We want to change that - we believe the only way is to provide a solution that has the right level of - abstraction gives you maximum control, is secure, and is simple to use - just like if you build it yourself, - from scratch (minus the time to learn, build, and maintain). - -We also believe in the principle of least vendor lock-in. Your having full control of your user's data means that you can switch away from SuperTokens without forcing your existing users to logout, reset their passwords, or in the worst case, sign up again. +abstraction gives you maximum control, is secure, and is simple to use - just like if you build it yourself, +from scratch (minus the time to learn, build, and maintain). + +We also believe in the principle of least vendor lock-in. Your having full control of your user's data means that you +can switch away from SuperTokens without forcing your existing users to logout, reset their passwords, or in the worst +case, sign up again. ### [Click here](https://thirdpartyemailpassword.demo.supertokens.io/) to see the demo app. -- Please visit [our website](https://supertokens.io/pricing) to see the list of features. -- We want to make features as decoupled as possible. This means you can use SuperTokens for just login, or just session management, or both. In fact, we also offer session management integrations with other login providers like Auth0. +- Please visit [our website](https://supertokens.io/pricing) to see the list of features. +- We want to make features as decoupled as possible. This means you can use SuperTokens for just login, or just session + management, or both. In fact, we also offer session management integrations with other login providers like Auth0. ### Documentation + The docs can be seen [on our website](https://supertokens.io/docs/community/introduction). -There is more information about SuperTokens on the [GitHub wiki section](https://github.com/supertokens/supertokens-core/wiki). +There is more information about SuperTokens on +the [GitHub wiki section](https://github.com/supertokens/supertokens-core/wiki). ## 🏗️ Architecture + Please find an [architecture diagram here](https://supertokens.io/docs/community/architecture) -**For more information, please visit our [GitHub wiki section](https://github.com/supertokens/supertokens-core/wiki/SuperTokens-Architecture).** +**For more information, please visit +our [GitHub wiki section](https://github.com/supertokens/supertokens-core/wiki/SuperTokens-Architecture).** ## ☕ Why Java? -- ✅ Whilst running Java can seem difficult, we provide the JDK along with the binary/docker image when distributing it. This makes running SuperTokens just like running any other HTTP microservice. + +- ✅ Whilst running Java can seem difficult, we provide the JDK along with the binary/docker image when distributing it. + This makes running SuperTokens just like running any other HTTP microservice. - ✅ Java has a very mature ecosystem. This implies that third-party libraries have been battle-tested. -- ✅ Java's strong type system ensures fewer bugs and easier maintainability. This is especially important when many people are expected to work on the same project. +- ✅ Java's strong type system ensures fewer bugs and easier maintainability. This is especially important when many + people are expected to work on the same project. - ✅ Our team is most comfortable with Java and hiring great Java developers is relatively easy as well. -- ✅ One of the biggest criticisms of Java is memory usage. We have three solutions to this: - - The most frequent auth-related operation is session verification - this happens within the backend SDK (node, python, Go) without contacting the Java core. Therefore, a single instance of the core can handle several 10s of thousands of users fairly easily. - - We have carefully chosen our dependencies. For eg: we use an embedded tomcat server instead of a higher-level web framework. - - We also plan on using [GraalVM](https://www.graalvm.org/) in the future and this can reduce memory usage by 95%! -- ✅ If you require any modifications to the auth APIs, those would need to be done on the backend SDK level (for example Node, Golang, Python..). So you’d rarely need to directly modify/work with the Java code in this repo. +- ✅ One of the biggest criticisms of Java is memory usage. We have three solutions to this: + - The most frequent auth-related operation is session verification - this happens within the backend SDK (node, + python, Go) without contacting the Java core. Therefore, a single instance of the core can handle several 10s of + thousands of users fairly easily. + - We have carefully chosen our dependencies. For eg: we use an embedded tomcat server instead of a higher-level web + framework. + - We also plan on using [GraalVM](https://www.graalvm.org/) in the future and this can reduce memory usage by 95%! +- ✅ If you require any modifications to the auth APIs, those would need to be done on the backend SDK level (for example + Node, Golang, Python..). So you’d rarely need to directly modify/work with the Java code in this repo. ## ⌨️ User Management Dashboard Oversee your users with the [SuperTokens User Management Dashboard](https://supertokens.com/docs/userdashboard/about) - ### List users List all the users who have signed up to your application. @@ -110,23 +131,27 @@ List all the users who have signed up to your application. ### Manage users -Manage users by modifying or deleting their sessions, metadata, roles and account info. +Manage users by modifying or deleting their sessions, metadata, roles and account info. ![Manage users](.github/user-info.png) ## 🔥 SuperTokens vs others + Please find a detailed comparison chart [on our website](https://supertokens.io/pricing#comparison-chart) ## 🛠️ Building from source + Please see our [wiki](https://github.com/supertokens/supertokens-core/wiki/Building-from-source) for instructions. ## 👥 Community + - [Discord](https://supertokens.io/discord) - [Email](mailto:team@supertokens.io) If you think this is a project you could use in the future, please :star2: this repository! ### Contributors (across all SuperTokens repositories) + @@ -237,9 +262,12 @@ If you think this is a project you could use in the future, please :star2: this

Rishabh Poddar
## 👩‍💻 Contributing -Please see the [CONTRIBUTING.md](https://github.com/supertokens/supertokens-core/blob/master/CONTRIBUTING.md) file for instructions. + +Please see the [CONTRIBUTING.md](https://github.com/supertokens/supertokens-core/blob/master/CONTRIBUTING.md) file for +instructions. ## 📝 License + © 2020-2023 SuperTokens Inc and its contributors. All rights reserved. Portions of this software are licensed as follows: diff --git a/cli/src/main/java/io/supertokens/cli/Main.java b/cli/src/main/java/io/supertokens/cli/Main.java index a9b5b2775..f0578357a 100644 --- a/cli/src/main/java/io/supertokens/cli/Main.java +++ b/cli/src/main/java/io/supertokens/cli/Main.java @@ -87,7 +87,7 @@ private static void start(String[] args) { installationDir = args[1]; if (args.length == 2) { - args = new String[] { args[0], args[1], "--help" }; + args = new String[]{args[0], args[1], "--help"}; } command = args[2]; diff --git a/cli/src/main/java/io/supertokens/cli/commandHandler/hashingCalibrate/HashingCalibrateHandler.java b/cli/src/main/java/io/supertokens/cli/commandHandler/hashingCalibrate/HashingCalibrateHandler.java index ca10b5b76..f399910d6 100644 --- a/cli/src/main/java/io/supertokens/cli/commandHandler/hashingCalibrate/HashingCalibrateHandler.java +++ b/cli/src/main/java/io/supertokens/cli/commandHandler/hashingCalibrate/HashingCalibrateHandler.java @@ -109,7 +109,8 @@ public String getShortDescription() { @Override public String getUsage() { return "supertokens hashingCalibrate --with_alg= [--with_argon2_hashing_pool_size=1] " - + "[--with_argon2_max_memory_mb=1024] [--with_argon2_parallelism=] [--with_time_per_hash_ms=300]"; + + + "[--with_argon2_max_memory_mb=1024] [--with_argon2_parallelism=] [--with_time_per_hash_ms=300]"; } @Override diff --git a/cli/src/main/java/io/supertokens/cli/commandHandler/install/InstallHandler.java b/cli/src/main/java/io/supertokens/cli/commandHandler/install/InstallHandler.java index cec96cfa9..d5f47adaf 100644 --- a/cli/src/main/java/io/supertokens/cli/commandHandler/install/InstallHandler.java +++ b/cli/src/main/java/io/supertokens/cli/commandHandler/install/InstallHandler.java @@ -82,7 +82,7 @@ private VersionFile getVersionFileForAlreadyInstalled() throws IOException { Process process = pb.start(); String result = ""; try (InputStreamReader in = new InputStreamReader(process.getInputStream()); - BufferedReader reader = new BufferedReader(in)) { + BufferedReader reader = new BufferedReader(in)) { StringBuilder builder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { diff --git a/cli/src/main/java/io/supertokens/cli/commandHandler/start/StartHandler.java b/cli/src/main/java/io/supertokens/cli/commandHandler/start/StartHandler.java index 1bd092b40..645608dd6 100644 --- a/cli/src/main/java/io/supertokens/cli/commandHandler/start/StartHandler.java +++ b/cli/src/main/java/io/supertokens/cli/commandHandler/start/StartHandler.java @@ -97,7 +97,7 @@ public void doCommand(String installationDir, boolean viaInstaller, String[] arg pb.redirectErrorStream(true); Process process = pb.start(); try (InputStreamReader in = new InputStreamReader(process.getInputStream()); - BufferedReader reader = new BufferedReader(in)) { + BufferedReader reader = new BufferedReader(in)) { String line; boolean success = false; while ((line = reader.readLine()) != null) { diff --git a/ee/src/main/java/io/supertokens/ee/EEFeatureFlag.java b/ee/src/main/java/io/supertokens/ee/EEFeatureFlag.java index ea5d9313b..202de8626 100644 --- a/ee/src/main/java/io/supertokens/ee/EEFeatureFlag.java +++ b/ee/src/main/java/io/supertokens/ee/EEFeatureFlag.java @@ -61,7 +61,7 @@ public class EEFeatureFlag implements io.supertokens.featureflag.EEFeatureFlagIn private static List licenseCheckRequests = new ArrayList<>(); - private static final String[] ENTERPRISE_THIRD_PARTY_IDS = new String[] { + private static final String[] ENTERPRISE_THIRD_PARTY_IDS = new String[]{ "google-workspaces", "okta", "active-directory", @@ -106,7 +106,8 @@ public void constructor(Main main, AppIdentifier appIdentifier) { try { this.syncFeatureFlagWithLicenseKey(); } catch (HttpResponseException | IOException e) { - Logging.error(main, appIdentifier.getAsPublicTenantIdentifier(), "API Error during constructor sync", false, e); + Logging.error(main, appIdentifier.getAsPublicTenantIdentifier(), "API Error during constructor sync", false, + e); // server request failed. we ignore for now as later on it will sync up anyway. } catch (InvalidLicenseKeyException ignored) { // the license key that was in the db was invalid. If this error is thrown, @@ -179,7 +180,8 @@ public Boolean getIsLicenseKeyPresent() { private JsonObject getDashboardLoginStats() throws TenantOrAppNotFoundException, StorageQueryException { JsonObject stats = new JsonObject(); - int userCount = ((DashboardSQLStorage) StorageLayer.getStorage(this.appIdentifier.getAsPublicTenantIdentifier(), main)) + int userCount = ((DashboardSQLStorage) StorageLayer.getStorage(this.appIdentifier.getAsPublicTenantIdentifier(), + main)) .getAllDashboardUsers(this.appIdentifier).length; stats.addProperty("user_count", userCount); return stats; @@ -242,7 +244,8 @@ private JsonObject getMultiTenancyStats() Storage storage = StorageLayer.getStorage(tenantConfig.tenantIdentifier, main); long usersCount = ((AuthRecipeStorage) storage).getUsersCount(tenantConfig.tenantIdentifier, null); boolean hasUsersOrSessions = (usersCount > 0); - hasUsersOrSessions = hasUsersOrSessions || ((SessionSQLStorage) storage).getNumberOfSessions(tenantConfig.tenantIdentifier) > 0; + hasUsersOrSessions = hasUsersOrSessions || + ((SessionSQLStorage) storage).getNumberOfSessions(tenantConfig.tenantIdentifier) > 0; tenantStat.addProperty("usersCount", usersCount); tenantStat.addProperty("hasUsersOrSessions", hasUsersOrSessions); if (tenantConfig.firstFactors != null) { @@ -295,7 +298,7 @@ private JsonObject getAccountLinkingStats() throws StorageQueryException, Tenant boolean usesAccountLinking = false; for (Storage storage : storages) { - if (((AuthRecipeStorage)storage).checkIfUsesAccountLinking(this.appIdentifier)) { + if (((AuthRecipeStorage) storage).checkIfUsesAccountLinking(this.appIdentifier)) { usesAccountLinking = true; break; } @@ -318,13 +321,15 @@ private JsonObject getAccountLinkingStats() throws StorageQueryException, Tenant long now = System.currentTimeMillis(); for (Storage storage : storages) { - totalUserCountWithMoreThanOneLoginMethod += ((AuthRecipeStorage)storage).getUsersCountWithMoreThanOneLoginMethod(this.appIdentifier); + totalUserCountWithMoreThanOneLoginMethod += ((AuthRecipeStorage) storage).getUsersCountWithMoreThanOneLoginMethod( + this.appIdentifier); for (int i = 1; i <= 31; i++) { long timestamp = now - (i * 24 * 60 * 60 * 1000L); // `maus[i-1]` because i starts from 1 - maus[i-1] += ((ActiveUsersStorage)storage).countUsersThatHaveMoreThanOneLoginMethodAndActiveSince(appIdentifier, timestamp); + maus[i - 1] += ((ActiveUsersStorage) storage).countUsersThatHaveMoreThanOneLoginMethodAndActiveSince( + appIdentifier, timestamp); } } @@ -351,16 +356,18 @@ private JsonArray getMAUs() throws StorageQueryException, TenantOrAppNotFoundExc public JsonObject getPaidFeatureStats() throws StorageQueryException, TenantOrAppNotFoundException { JsonObject usageStats = new JsonObject(); - if (StorageLayer.getStorage(this.appIdentifier.getAsPublicTenantIdentifier(), main).getType() != STORAGE_TYPE.SQL) { + if (StorageLayer.getStorage(this.appIdentifier.getAsPublicTenantIdentifier(), main).getType() != + STORAGE_TYPE.SQL) { return usageStats; } EE_FEATURES[] features = getEnabledEEFeaturesFromDbOrCache(); - if (!this.appIdentifier.equals(new AppIdentifier(null, null)) && !Arrays.asList(features).contains(EE_FEATURES.MULTI_TENANCY)) { // Check for multitenancy on the base app + if (!this.appIdentifier.equals(new AppIdentifier(null, null)) && !Arrays.asList(features) + .contains(EE_FEATURES.MULTI_TENANCY)) { // Check for multitenancy on the base app EE_FEATURES[] baseFeatures = FeatureFlag.getInstance(main, new AppIdentifier(null, null)) .getEnabledFeatures(); - for (EE_FEATURES feature: baseFeatures) { + for (EE_FEATURES feature : baseFeatures) { if (feature == EE_FEATURES.MULTI_TENANCY) { features = Arrays.copyOf(features, features.length + 1); features[features.length - 1] = EE_FEATURES.MULTI_TENANCY; @@ -456,7 +463,8 @@ private EE_FEATURES[] doServerCall(String licenseKey) throws StorageQueryException, HttpResponseException, IOException, InvalidLicenseKeyException, TenantOrAppNotFoundException { try { - Logging.debug(main, appIdentifier.getAsPublicTenantIdentifier(), "Making API call to server with licenseKey: " + licenseKey); + Logging.debug(main, appIdentifier.getAsPublicTenantIdentifier(), + "Making API call to server with licenseKey: " + licenseKey); JsonObject json = new JsonObject(); KeyValueInfo info = Telemetry.getTelemetryId(main, this.appIdentifier); String telemetryId = info == null ? null : info.value; @@ -470,7 +478,8 @@ private EE_FEATURES[] doServerCall(String licenseKey) if (Main.isTesting) { licenseCheckRequests.add(json); } - ProcessState.getInstance(main).addState(ProcessState.PROCESS_STATE.LICENSE_KEY_CHECK_NETWORK_CALL, null, json); + ProcessState.getInstance(main) + .addState(ProcessState.PROCESS_STATE.LICENSE_KEY_CHECK_NETWORK_CALL, null, json); JsonObject licenseCheckResponse = HttpRequest.sendJsonPOSTRequest(this.main, REQUEST_ID, "https://api.supertokens.io/0/st/license/check", json, 10000, 10000, 0); @@ -502,7 +511,8 @@ private void setEnabledEEFeaturesInDb(EE_FEATURES[] features) throws StorageQueryException, TenantOrAppNotFoundException { JsonArray json = new JsonArray(); Arrays.stream(features).forEach(ee_features -> json.add(new JsonPrimitive(ee_features.toString()))); - Logging.debug(main, appIdentifier.getAsPublicTenantIdentifier(), "Saving new feature flag in database: " + json); + Logging.debug(main, appIdentifier.getAsPublicTenantIdentifier(), + "Saving new feature flag in database: " + json); StorageLayer.getStorage(this.appIdentifier.getAsPublicTenantIdentifier(), main) .setKeyValue(this.appIdentifier.getAsPublicTenantIdentifier(), FEATURE_FLAG_KEY_IN_DB, new KeyValueInfo(json.toString())); diff --git a/ee/src/test/java/io/supertokens/ee/test/api/DeleteLicenseKeyAPITest.java b/ee/src/test/java/io/supertokens/ee/test/api/DeleteLicenseKeyAPITest.java index c45cbf70b..6f9b5123f 100644 --- a/ee/src/test/java/io/supertokens/ee/test/api/DeleteLicenseKeyAPITest.java +++ b/ee/src/test/java/io/supertokens/ee/test/api/DeleteLicenseKeyAPITest.java @@ -38,7 +38,7 @@ public void beforeEach() { @Test public void testDeletingLicenseKeyWhenItIsNotSet() throws Exception { - String[] args = { "../../" }; + String[] args = {"../../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); Assert.assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -69,7 +69,7 @@ public void testDeletingLicenseKeyWhenItIsNotSet() throws Exception { @Test public void testDeletingLicenseKey() throws Exception { - String[] args = { "../../" }; + String[] args = {"../../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); Assert.assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); diff --git a/migration_scripts/to_version_7_0_12/index.js b/migration_scripts/to_version_7_0_12/index.js index eb0a908d9..8e361b959 100644 --- a/migration_scripts/to_version_7_0_12/index.js +++ b/migration_scripts/to_version_7_0_12/index.js @@ -28,100 +28,115 @@ const MAX_POOL_SIZE = 5; const QUERY_TIMEOUT = 60000; if (!DB_HOST || !CLIENT) { - console.error('Please update the DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE and CLIENT variables before running the script.'); - return; + console.error('Please update the DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE and CLIENT variables before running the script.'); + return; } const knex = require('knex')({ - client: CLIENT, - connection: { - host: DB_HOST, - user: DB_USER, - password: DB_PASSWORD, - database: DB_NAME, - }, - pool: { min: MIN_POOL_SIZE, max: MAX_POOL_SIZE } + client: CLIENT, + connection: { + host: DB_HOST, + user: DB_USER, + password: DB_PASSWORD, + database: DB_NAME, + }, + pool: {min: MIN_POOL_SIZE, max: MAX_POOL_SIZE} }); function getUpdatePromise(table, entry, normalizedPhoneNumber) { - if (table === 'passwordless_devices') { - return knex.raw(`UPDATE ${table} SET phone_number = ? WHERE app_id = ? AND tenant_id = ? AND device_id_hash = ?`, [normalizedPhoneNumber, entry.app_id, entry.tenant_id, entry.device_id_hash]).timeout(QUERY_TIMEOUT, { cancel: true }); - } else if (table === 'passwordless_users') { - // Since passwordless_users and passwordless_user_to_tenant are consistent. We can update both tables at the same time. For consistency, we will use a transaction. - return knex.transaction(async trx => { - await trx.raw(`UPDATE passwordless_users SET phone_number = ? WHERE app_id = ? AND user_id = ?`, [normalizedPhoneNumber, entry.app_id, entry.user_id]).timeout(QUERY_TIMEOUT, { cancel: true }); - await trx.raw(`UPDATE passwordless_user_to_tenant SET phone_number = ? WHERE app_id = ? AND user_id = ?`, [normalizedPhoneNumber, entry.app_id, entry.user_id]).timeout(QUERY_TIMEOUT, { cancel: true }); - }); - } else { - throw new Error(`Invalid table name: ${table}`); - } + if (table === 'passwordless_devices') { + return knex.raw(`UPDATE ${table} + SET phone_number = ? + WHERE app_id = ? + AND tenant_id = ? + AND device_id_hash = ?`, [normalizedPhoneNumber, entry.app_id, entry.tenant_id, entry.device_id_hash]).timeout(QUERY_TIMEOUT, {cancel: true}); + } else if (table === 'passwordless_users') { + // Since passwordless_users and passwordless_user_to_tenant are consistent. We can update both tables at the same time. For consistency, we will use a transaction. + return knex.transaction(async trx => { + await trx.raw(`UPDATE passwordless_users + SET phone_number = ? + WHERE app_id = ? + AND user_id = ?`, [normalizedPhoneNumber, entry.app_id, entry.user_id]).timeout(QUERY_TIMEOUT, {cancel: true}); + await trx.raw(`UPDATE passwordless_user_to_tenant + SET phone_number = ? + WHERE app_id = ? + AND user_id = ?`, [normalizedPhoneNumber, entry.app_id, entry.user_id]).timeout(QUERY_TIMEOUT, {cancel: true}); + }); + } else { + throw new Error(`Invalid table name: ${table}`); + } } function getNormalizedPhoneNumber(phoneNumber) { - try { - return libphonenumber.parsePhoneNumber(phoneNumber, { extract: false }).format('E.164'); - } catch (error) { - return null; - } + try { + return libphonenumber.parsePhoneNumber(phoneNumber, {extract: false}).format('E.164'); + } catch (error) { + return null; + } } async function updatePhoneNumbers(table) { - const batchSize = 1000; - let offset = 0; - let totalUpdatedRows = 0; - - try { - let totalRows = await knex.raw(`SELECT COUNT(*) as count FROM ${table} WHERE phone_number is NOT NULL`); - totalRows = totalRows.rows ? totalRows.rows[0].count : totalRows[0][0].count; - - while (true) { - const entries = await knex.raw(`SELECT * FROM ${table} WHERE phone_number is NOT NULL LIMIT ${batchSize} OFFSET ${offset}`); - // In PostgreSQL, all rows are returned in `entries.rows`, whereas in MySQL, they can be found in `entries[0]`. - const rows = entries.rows ? entries.rows : entries[0]; - - const batchUpdates = []; - - for (const entry of rows) { - const currentPhoneNumber = entry.phone_number; - const normalizedPhoneNumber = getNormalizedPhoneNumber(currentPhoneNumber); - - if (normalizedPhoneNumber && normalizedPhoneNumber !== currentPhoneNumber) { - const updatePromise = getUpdatePromise(table, entry, normalizedPhoneNumber); - batchUpdates.push(updatePromise); + const batchSize = 1000; + let offset = 0; + let totalUpdatedRows = 0; + + try { + let totalRows = await knex.raw(`SELECT COUNT(*) as count + FROM ${table} + WHERE phone_number is NOT NULL`); + totalRows = totalRows.rows ? totalRows.rows[0].count : totalRows[0][0].count; + + while (true) { + const entries = await knex.raw(`SELECT * + FROM ${table} + WHERE phone_number is NOT NULL LIMIT ${batchSize} + OFFSET ${offset}`); + // In PostgreSQL, all rows are returned in `entries.rows`, whereas in MySQL, they can be found in `entries[0]`. + const rows = entries.rows ? entries.rows : entries[0]; + + const batchUpdates = []; + + for (const entry of rows) { + const currentPhoneNumber = entry.phone_number; + const normalizedPhoneNumber = getNormalizedPhoneNumber(currentPhoneNumber); + + if (normalizedPhoneNumber && normalizedPhoneNumber !== currentPhoneNumber) { + const updatePromise = getUpdatePromise(table, entry, normalizedPhoneNumber); + batchUpdates.push(updatePromise); + } + } + + await Promise.all(batchUpdates); + + offset += rows.length; + totalUpdatedRows += batchUpdates.length; + + console.log(`Processed ${offset} out of ${totalRows} rows in table ${table}; ${totalUpdatedRows} rows updated`); + + if (rows.length < batchSize) { + break; + } } - } - - await Promise.all(batchUpdates); - - offset += rows.length; - totalUpdatedRows += batchUpdates.length; - - console.log(`Processed ${offset} out of ${totalRows} rows in table ${table}; ${totalUpdatedRows} rows updated`); - - if (rows.length < batchSize) { - break; - } + } catch (error) { + console.error(`Error normalising phone numbers for table ${table}: Retry running the script and if the error persists after retrying then create an issue at https://github.com/supertokens/supertokens-core/issues`); + throw error; } - } catch (error) { - console.error(`Error normalising phone numbers for table ${table}: Retry running the script and if the error persists after retrying then create an issue at https://github.com/supertokens/supertokens-core/issues`); - throw error; - } } async function runScript() { - const tables = ['passwordless_users', 'passwordless_devices']; + const tables = ['passwordless_users', 'passwordless_devices']; - try { - for (const table of tables) { - await updatePhoneNumbers(table); - console.log(`\n\n\n`); + try { + for (const table of tables) { + await updatePhoneNumbers(table); + console.log(`\n\n\n`); + } + console.log('Finished normalising phone numbers!'); + } catch (error) { + console.error(error); + } finally { + knex.destroy(); } - console.log('Finished normalising phone numbers!'); - } catch (error) { - console.error(error); - } finally { - knex.destroy(); - } } diff --git a/src/main/java/io/supertokens/ActiveUsers.java b/src/main/java/io/supertokens/ActiveUsers.java index 231b069ca..0bd6f51f3 100644 --- a/src/main/java/io/supertokens/ActiveUsers.java +++ b/src/main/java/io/supertokens/ActiveUsers.java @@ -41,7 +41,8 @@ public static void updateLastActiveAfterLinking(Main main, AppIdentifier appIden String recipeUserId) throws StorageQueryException, TenantOrAppNotFoundException, StorageTransactionLogicException { ActiveUsersSQLStorage activeUsersStorage = - (ActiveUsersSQLStorage) StorageUtils.getActiveUsersStorage(StorageLayer.getStorage(appIdentifier.getAsPublicTenantIdentifier(), main)); + (ActiveUsersSQLStorage) StorageUtils.getActiveUsersStorage( + StorageLayer.getStorage(appIdentifier.getAsPublicTenantIdentifier(), main)); activeUsersStorage.startTransaction(con -> { activeUsersStorage.deleteUserActive_Transaction(con, appIdentifier, recipeUserId); diff --git a/src/main/java/io/supertokens/Main.java b/src/main/java/io/supertokens/Main.java index f23078440..f6e9f29ea 100644 --- a/src/main/java/io/supertokens/Main.java +++ b/src/main/java/io/supertokens/Main.java @@ -206,7 +206,8 @@ private void init() throws IOException, StorageQueryException { if (!StorageLayer.isInMemDb(this)) { // we want to init storage connection once again so that the base storage also contains the right - // tenant identifier set passed to the init. So we call the resetPostConnectCallbackForBaseTenantStorage. + // tenant identifier set passed to the init. So we call the + // resetPostConnectCallbackForBaseTenantStorage. StorageLayer.getBaseStorage(this).close(); } diff --git a/src/main/java/io/supertokens/ProcessState.java b/src/main/java/io/supertokens/ProcessState.java index 94a938d43..100b622ac 100644 --- a/src/main/java/io/supertokens/ProcessState.java +++ b/src/main/java/io/supertokens/ProcessState.java @@ -68,7 +68,8 @@ public synchronized void clear() { /** * INIT: Initialization started INIT_FAILURE: Initialization failed * STARTED: Initialized successfully SHUTTING_DOWN: Shut down signal received STOPPED - * RETRYING_ACCESS_TOKEN_JWT_VERIFICATION: When access token verification fails due to change in signing key, so we retry it + * RETRYING_ACCESS_TOKEN_JWT_VERIFICATION: When access token verification fails due to change in signing key, so + * we retry it * CRON_TASK_ERROR_LOGGING: When an exception is thrown from a Cronjob * DEVICE_DRIVER_INFO_LOGGED:When program is saving deviceDriverInfo into ping * SERVER_PING: When program is pinging the server with information diff --git a/src/main/java/io/supertokens/ResourceDistributor.java b/src/main/java/io/supertokens/ResourceDistributor.java index 82f5caa91..c2cace681 100644 --- a/src/main/java/io/supertokens/ResourceDistributor.java +++ b/src/main/java/io/supertokens/ResourceDistributor.java @@ -105,7 +105,7 @@ public synchronized SingletonResource setResource(TenantIdentifier tenantIdentif } public synchronized SingletonResource removeResource(TenantIdentifier tenantIdentifier, - @Nonnull String key) { + @Nonnull String key) { SingletonResource singletonResource = resources.get(new KeyClass(tenantIdentifier, key)); if (singletonResource == null) { return null; diff --git a/src/main/java/io/supertokens/authRecipe/AuthRecipe.java b/src/main/java/io/supertokens/authRecipe/AuthRecipe.java index 271b93d52..5f36f43cb 100644 --- a/src/main/java/io/supertokens/authRecipe/AuthRecipe.java +++ b/src/main/java/io/supertokens/authRecipe/AuthRecipe.java @@ -86,8 +86,10 @@ public static boolean unlinkAccounts(Main main, AppIdentifier appIdentifier, if (primaryUser.getSupertokensUserId().equals(recipeUserId)) { // we are trying to unlink the user ID which is the same as the primary one. if (primaryUser.loginMethods.length == 1) { - authRecipeStorage.unlinkAccounts_Transaction(appIdentifier, con, primaryUser.getSupertokensUserId(), recipeUserId); - return new UnlinkResult(mappingResult == null ? recipeUserId : mappingResult.externalUserId, false); + authRecipeStorage.unlinkAccounts_Transaction(appIdentifier, con, + primaryUser.getSupertokensUserId(), recipeUserId); + return new UnlinkResult(mappingResult == null ? recipeUserId : mappingResult.externalUserId, + false); } else { // Here we delete the recipe user id cause if we just unlink, then there will be two // distinct users with the same ID - which is a broken state. @@ -95,10 +97,12 @@ public static boolean unlinkAccounts(Main main, AppIdentifier appIdentifier, // We need to make sure that it only deletes sessions for recipeUserId and not other linked // users who have their sessions for primaryUserId (that is equal to the recipeUserId) deleteUserHelper(con, appIdentifier, storage, recipeUserId, false, mappingResult); - return new UnlinkResult(mappingResult == null ? recipeUserId : mappingResult.externalUserId, true); + return new UnlinkResult(mappingResult == null ? recipeUserId : mappingResult.externalUserId, + true); } } else { - authRecipeStorage.unlinkAccounts_Transaction(appIdentifier, con, primaryUser.getSupertokensUserId(), recipeUserId); + authRecipeStorage.unlinkAccounts_Transaction(appIdentifier, con, primaryUser.getSupertokensUserId(), + recipeUserId); return new UnlinkResult(mappingResult == null ? recipeUserId : mappingResult.externalUserId, false); } }); @@ -153,7 +157,8 @@ public static CanLinkAccountsResult canLinkAccounts(Main main, String recipeUser throws StorageQueryException, UnknownUserIdException, InputUserIdIsNotAPrimaryUserException, RecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException, AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException { - return canLinkAccounts(new AppIdentifier(null, null), StorageLayer.getStorage(main), recipeUserId, primaryUserId); + return canLinkAccounts(new AppIdentifier(null, null), StorageLayer.getStorage(main), recipeUserId, + primaryUserId); } public static CanLinkAccountsResult canLinkAccounts(AppIdentifier appIdentifier, Storage storage, @@ -218,7 +223,8 @@ private static CanLinkAccountsResult canLinkAccountsHelper(TransactionConnection if (recipeUser.isPrimaryUser) { if (recipeUser.getSupertokensUserId().equals(primaryUser.getSupertokensUserId())) { - return new CanLinkAccountsResult(recipeUser.getSupertokensUserId(), primaryUser.getSupertokensUserId(), true); + return new CanLinkAccountsResult(recipeUser.getSupertokensUserId(), primaryUser.getSupertokensUserId(), + true); } else { throw new RecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException(recipeUser, "The input recipe user ID is already linked to another user ID"); @@ -261,7 +267,8 @@ private static CanLinkAccountsResult canLinkAccountsHelper(TransactionConnection continue; } if (user.isPrimaryUser && !user.getSupertokensUserId().equals(primaryUser.getSupertokensUserId())) { - throw new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException(user.getSupertokensUserId(), + throw new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException( + user.getSupertokensUserId(), "This user's email is already associated with another user ID"); } } @@ -276,7 +283,8 @@ private static CanLinkAccountsResult canLinkAccountsHelper(TransactionConnection continue; } if (user.isPrimaryUser && !user.getSupertokensUserId().equals(primaryUser.getSupertokensUserId())) { - throw new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException(user.getSupertokensUserId(), + throw new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException( + user.getSupertokensUserId(), "This user's phone number is already associated with another user" + " ID"); } @@ -342,7 +350,8 @@ public static LinkAccountsResult linkAccounts(Main main, AppIdentifier appIdenti authRecipeStorage, _recipeUserId, _primaryUserId); if (canLinkAccounts.alreadyLinked) { - return new LinkAccountsResult(getUserById(appIdentifier, authRecipeStorage, canLinkAccounts.primaryUserId), true); + return new LinkAccountsResult( + getUserById(appIdentifier, authRecipeStorage, canLinkAccounts.primaryUserId), true); } // now we can link accounts in the db. authRecipeStorage.linkAccounts_Transaction(appIdentifier, con, canLinkAccounts.recipeUserId, @@ -350,7 +359,8 @@ public static LinkAccountsResult linkAccounts(Main main, AppIdentifier appIdenti authRecipeStorage.commitTransaction(con); - return new LinkAccountsResult(getUserById(appIdentifier, authRecipeStorage, canLinkAccounts.primaryUserId), false); + return new LinkAccountsResult( + getUserById(appIdentifier, authRecipeStorage, canLinkAccounts.primaryUserId), false); } catch (UnknownUserIdException | InputUserIdIsNotAPrimaryUserException | RecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException | AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException e) { @@ -468,7 +478,8 @@ private static CreatePrimaryUserResult canCreatePrimaryUserHelper(TransactionCon continue; } if (user.isPrimaryUser) { - throw new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException(user.getSupertokensUserId(), + throw new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException( + user.getSupertokensUserId(), "This user's email is already associated with another user ID"); } } @@ -483,7 +494,8 @@ private static CreatePrimaryUserResult canCreatePrimaryUserHelper(TransactionCon continue; } if (user.isPrimaryUser) { - throw new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException(user.getSupertokensUserId(), + throw new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException( + user.getSupertokensUserId(), "This user's phone number is already associated with another user" + " ID"); } @@ -548,7 +560,8 @@ public static CreatePrimaryUserResult createPrimaryUser(Main main, if (result.wasAlreadyAPrimaryUser) { return result; } - authRecipeStorage.makePrimaryUser_Transaction(appIdentifier, con, result.user.getSupertokensUserId()); + authRecipeStorage.makePrimaryUser_Transaction(appIdentifier, con, + result.user.getSupertokensUserId()); authRecipeStorage.commitTransaction(con); @@ -863,13 +876,14 @@ private static void deleteUserHelper(TransactionConnection con, AppIdentifier ap } } else { for (LoginMethod lM : userToDelete.loginMethods) { - io.supertokens.pluginInterface.useridmapping.UserIdMapping mappingResult = lM.getSupertokensUserId().equals( - userIdToDeleteForAuthRecipe) ? userIdMapping : - io.supertokens.useridmapping.UserIdMapping.getUserIdMapping( - con, - appIdentifier, - storage, - lM.getSupertokensUserId(), UserIdType.SUPERTOKENS); + io.supertokens.pluginInterface.useridmapping.UserIdMapping mappingResult = + lM.getSupertokensUserId().equals( + userIdToDeleteForAuthRecipe) ? userIdMapping : + io.supertokens.useridmapping.UserIdMapping.getUserIdMapping( + con, + appIdentifier, + storage, + lM.getSupertokensUserId(), UserIdType.SUPERTOKENS); deleteUserHelper(con, appIdentifier, storage, lM.getSupertokensUserId(), false, mappingResult); } } diff --git a/src/main/java/io/supertokens/authRecipe/exception/RecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException.java b/src/main/java/io/supertokens/authRecipe/exception/RecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException.java index 737929a62..c6a8658eb 100644 --- a/src/main/java/io/supertokens/authRecipe/exception/RecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException.java +++ b/src/main/java/io/supertokens/authRecipe/exception/RecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException.java @@ -21,7 +21,8 @@ public class RecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException extends Exception { public final AuthRecipeUserInfo recipeUser; - public RecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException(AuthRecipeUserInfo recipeUser, String description) { + public RecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException(AuthRecipeUserInfo recipeUser, + String description) { super(description); this.recipeUser = recipeUser; } diff --git a/src/main/java/io/supertokens/config/CoreConfig.java b/src/main/java/io/supertokens/config/CoreConfig.java index f56509afd..04b485973 100644 --- a/src/main/java/io/supertokens/config/CoreConfig.java +++ b/src/main/java/io/supertokens/config/CoreConfig.java @@ -48,7 +48,7 @@ public class CoreConfig { @IgnoreForAnnotationCheck - public static final String[] PROTECTED_CONFIGS = new String[] { + public static final String[] PROTECTED_CONFIGS = new String[]{ "ip_allow_regex", "ip_deny_regex", }; @@ -65,7 +65,10 @@ public class CoreConfig { @NotConflictingInApp @JsonProperty - @ConfigDescription("Deprecated, please see changelog. Only used in CDI<=2.18 If true, allows for immediate revocation of any access token. Keep in mind that setting this to true will result in a db query for each API call that requires authentication. (Default: false)") + @ConfigDescription( + "Deprecated, please see changelog. Only used in CDI<=2.18 If true, allows for immediate revocation of any" + + " access token. Keep in mind that setting this to true will result in a db query for each API " + + "call that requires authentication. (Default: false)") private boolean access_token_blacklisting = false; @NotConflictingInApp @@ -75,22 +78,27 @@ public class CoreConfig { @IgnoreForAnnotationCheck @JsonProperty - @ConfigDescription("Time in milliseconds for how long a password reset token / link is valid for. [Default: 3600000 (1 hour)]") + @ConfigDescription( + "Time in milliseconds for how long a password reset token / link is valid for. [Default: 3600000 (1 hour)]") private long password_reset_token_lifetime = 3600000; // in MS @IgnoreForAnnotationCheck @JsonProperty - @ConfigDescription("Time in milliseconds for how long an email verification token / link is valid for. [Default: 24 * 3600 * 1000 (1 day)]") + @ConfigDescription( + "Time in milliseconds for how long an email verification token / link is valid for. [Default: 24 * 3600 *" + + " 1000 (1 day)]") private long email_verification_token_lifetime = 24 * 3600 * 1000; // in MS @IgnoreForAnnotationCheck @JsonProperty - @ConfigDescription("The maximum number of code input attempts per login before the user needs to restart. (Default: 5)") + @ConfigDescription( + "The maximum number of code input attempts per login before the user needs to restart. (Default: 5)") private int passwordless_max_code_input_attempts = 5; @IgnoreForAnnotationCheck @JsonProperty - @ConfigDescription("Time in milliseconds for how long a passwordless code is valid for. [Default: 900000 (15 mins)]") + @ConfigDescription( + "Time in milliseconds for how long a passwordless code is valid for. [Default: 900000 (15 mins)]") private long passwordless_code_lifetime = 900000; // in MS @IgnoreForAnnotationCheck @@ -100,7 +108,9 @@ public class CoreConfig { @IgnoreForAnnotationCheck @JsonProperty - @ConfigDescription("The time in seconds for which the user will be rate limited once totp_max_attempts is crossed. [Default: 900 (15 mins)]") + @ConfigDescription( + "The time in seconds for which the user will be rate limited once totp_max_attempts is crossed. [Default:" + + " 900 (15 mins)]") private int totp_rate_limit_cooldown_sec = 900; // in seconds (Default 15 mins) @IgnoreForAnnotationCheck @@ -108,22 +118,30 @@ public class CoreConfig { @ConfigYamlOnly @JsonProperty - @ConfigDescription("Give the path to a file (on your local system) in which the SuperTokens service can write INFO logs to. Set it to \"null\" if you want it to log to standard output instead. (Default: installation directory/logs/info.log)") + @ConfigDescription( + "Give the path to a file (on your local system) in which the SuperTokens service can write INFO logs to. " + + "Set it to \"null\" if you want it to log to standard output instead. (Default: installation " + + "directory/logs/info.log)") private String info_log_path = logDefault; @ConfigYamlOnly @JsonProperty - @ConfigDescription("Give the path to a file (on your local system) in which the SuperTokens service can write ERROR logs to. Set it to \"null\" if you want it to log to standard error instead. (Default: installation directory/logs/error.log)") + @ConfigDescription( + "Give the path to a file (on your local system) in which the SuperTokens service can write ERROR logs to." + + " Set it to \"null\" if you want it to log to standard error instead. (Default: installation " + + "directory/logs/error.log)") private String error_log_path = logDefault; @NotConflictingInApp @JsonProperty - @ConfigDescription("Deprecated, please see changelog. If this is set to true, the access tokens created using CDI<=2.18 will be signed using a static signing key. (Default: true)") + @ConfigDescription( + "Deprecated, please see changelog. If this is set to true, the access tokens created using CDI<=2.18 will" + + " be signed using a static signing key. (Default: true)") private boolean access_token_signing_key_dynamic = true; @NotConflictingInApp @JsonProperty("access_token_dynamic_signing_key_update_interval") - @JsonAlias({ "access_token_dynamic_signing_key_update_interval", "access_token_signing_key_update_interval" }) + @JsonAlias({"access_token_dynamic_signing_key_update_interval", "access_token_signing_key_update_interval"}) @ConfigDescription("Time in hours for how frequently the dynamic signing key will change. [Default: 168 (1 week)]") private double access_token_dynamic_signing_key_update_interval = 168; // in hours @@ -134,7 +152,9 @@ public class CoreConfig { @ConfigYamlOnly @JsonProperty - @ConfigDescription("The host on which SuperTokens service runs. Values here can be localhost, example.com, 0.0.0.0 or any IP address associated with your machine. (Default: localhost)") + @ConfigDescription( + "The host on which SuperTokens service runs. Values here can be localhost, example.com, 0.0.0.0 or any IP" + + " address associated with your machine. (Default: localhost)") private String host = "localhost"; @ConfigYamlOnly @@ -144,18 +164,23 @@ public class CoreConfig { @NotConflictingInApp @JsonProperty - @ConfigDescription("The API keys to query an instance using this config file. The format is \"key1,key2,key3\". Keys can only contain '=', '-' and alpha-numeric (including capital) chars. Each key must have a minimum length of 20 chars. (Default: null)") + @ConfigDescription( + "The API keys to query an instance using this config file. The format is \"key1,key2,key3\". Keys can " + + "only contain '=', '-' and alpha-numeric (including capital) chars. Each key must have a minimum " + + "length of 20 chars. (Default: null)") private String api_keys = null; @NotConflictingInApp @JsonProperty - @ConfigDescription("Learn more about Telemetry here: https://github.com/supertokens/supertokens-core/wiki/Telemetry. (Default: false)") + @ConfigDescription( + "Learn more about Telemetry here: https://github.com/supertokens/supertokens-core/wiki/Telemetry. " + + "(Default: false)") private boolean disable_telemetry = false; @NotConflictingInApp @JsonProperty @ConfigDescription("The password hashing algorithm to use. Values are \"ARGON2\" | \"BCRYPT\". (Default: BCRYPT)") - @EnumProperty({ "ARGON2", "BCRYPT" }) + @EnumProperty({"ARGON2", "BCRYPT"}) private String password_hashing_alg = "BCRYPT"; @ConfigYamlOnly @@ -175,12 +200,16 @@ public class CoreConfig { @ConfigYamlOnly @JsonProperty - @ConfigDescription("Number of concurrent argon2 hashes that can happen at the same time for sign up or sign in requests. (Default: 1)") + @ConfigDescription( + "Number of concurrent argon2 hashes that can happen at the same time for sign up or sign in requests. " + + "(Default: 1)") private int argon2_hashing_pool_size = 1; @ConfigYamlOnly @JsonProperty - @ConfigDescription("Number of concurrent firebase scrypt hashes that can happen at the same time for sign in requests. (Default: 1)") + @ConfigDescription( + "Number of concurrent firebase scrypt hashes that can happen at the same time for sign in requests. " + + "(Default: 1)") private int firebase_password_hashing_pool_size = 1; @ConfigYamlOnly @@ -207,8 +236,10 @@ public class CoreConfig { @ConfigYamlOnly @JsonProperty - @ConfigDescription("Logging level for the core. Values are \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"NONE\". (Default: INFO)") - @EnumProperty({ "DEBUG", "INFO", "WARN", "ERROR", "NONE" }) + @ConfigDescription( + "Logging level for the core. Values are \"DEBUG\" | \"INFO\" | \"WARN\" | \"ERROR\" | \"NONE\". (Default:" + + " INFO)") + @EnumProperty({"DEBUG", "INFO", "WARN", "ERROR", "NONE"}) private String log_level = "INFO"; @NotConflictingInApp @@ -218,27 +249,40 @@ public class CoreConfig { @IgnoreForAnnotationCheck @JsonProperty - @ConfigDescription("Regex for allowing requests from IP addresses that match with the value. For example, use the value of 127\\.\\d+\\.\\d+\\.\\d+|::1|0:0:0:0:0:0:0:1 to allow only localhost to query the core") + @ConfigDescription( + "Regex for allowing requests from IP addresses that match with the value. For example, use the value of " + + "127\\.\\d+\\.\\d+\\.\\d+|::1|0:0:0:0:0:0:0:1 to allow only localhost to query the core") private String ip_allow_regex = null; @IgnoreForAnnotationCheck @JsonProperty - @ConfigDescription("Regex for denying requests from IP addresses that match with the value. Comment this value to deny no IP address.") + @ConfigDescription( + "Regex for denying requests from IP addresses that match with the value. Comment this value to deny no IP" + + " address.") private String ip_deny_regex = null; @ConfigYamlOnly @JsonProperty - @ConfigDescription("This is used when deploying the core in SuperTokens SaaS infrastructure. If set, limits what database information is shown to / modifiable by the dev when they query the core to get the information about their tenants. It only exposes that information when this key is used instead of the regular api_keys config.") + @ConfigDescription( + "This is used when deploying the core in SuperTokens SaaS infrastructure. If set, limits what database " + + "information is shown to / modifiable by the dev when they query the core to get the information " + + "about their tenants. It only exposes that information when this key is used instead of the " + + "regular api_keys config.") private String supertokens_saas_secret = null; @NotConflictingInApp @JsonProperty - @ConfigDescription("This is used when the core needs to assume a specific CDI version when CDI version is not specified in the request. When set to null, the core will assume the latest version of the CDI. (Default: null)") + @ConfigDescription( + "This is used when the core needs to assume a specific CDI version when CDI version is not specified in " + + "the request. When set to null, the core will assume the latest version of the CDI. (Default: " + + "null)") private String supertokens_max_cdi_version = null; @ConfigYamlOnly @JsonProperty - @ConfigDescription("If specified, the supertokens service will only load the specified CUD even if there are more CUDs in the database and block all other CUDs from being used from this instance.") + @ConfigDescription( + "If specified, the supertokens service will only load the specified CUD even if there are more CUDs in " + + "the database and block all other CUDs from being used from this instance.") private String supertokens_saas_load_only_cud = null; @IgnoreForAnnotationCheck @@ -636,7 +680,8 @@ void normalizeAndValidate(Main main, boolean includeConfigFilePath) throws Inval String[] allowedValues = field.getAnnotation(EnumProperty.class).value(); try { String value = field.get(this) != null ? field.get(this).toString() : null; - if (!Arrays.asList(Arrays.stream(allowedValues).map(str -> str.toLowerCase()).toArray()).contains(value.toLowerCase())) { + if (!Arrays.asList(Arrays.stream(allowedValues).map(str -> str.toLowerCase()).toArray()) + .contains(value.toLowerCase())) { throw new InvalidConfigException( fieldId + " property is not set correctly. It must be one of " + Arrays.toString(allowedValues)); @@ -786,7 +831,8 @@ static void assertThatCertainConfigIsNotSetForAppOrTenants(JsonObject config) th } } - public static ArrayList getConfigFieldsInfoForDashboard(Main main, TenantIdentifier tenantIdentifier) + public static ArrayList getConfigFieldsInfoForDashboard(Main main, + TenantIdentifier tenantIdentifier) throws IOException, TenantOrAppNotFoundException { JsonObject tenantConfig = new Gson().toJsonTree(Config.getConfig(tenantIdentifier, main)).getAsJsonObject(); @@ -799,7 +845,7 @@ public static ArrayList getConfigFieldsInfoForDashboard(Main ma Field field = CoreConfig.class.getDeclaredField(fieldId); // If fieldId is not annotated with JsonProperty // or is annotated with ConfigYamlOnly, then skip - if ( !field.isAnnotationPresent(JsonProperty.class) + if (!field.isAnnotationPresent(JsonProperty.class) || field.isAnnotationPresent(ConfigYamlOnly.class) || fieldId.equals("core_config_version")) { continue; diff --git a/src/main/java/io/supertokens/config/annotations/ConfigDescription.java b/src/main/java/io/supertokens/config/annotations/ConfigDescription.java index e7119b860..5652ba4fd 100644 --- a/src/main/java/io/supertokens/config/annotations/ConfigDescription.java +++ b/src/main/java/io/supertokens/config/annotations/ConfigDescription.java @@ -14,7 +14,7 @@ * under the License. */ - package io.supertokens.config.annotations; +package io.supertokens.config.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -25,8 +25,9 @@ * Annotation to provide a description for a configuration fields. To be used on the fields of `CoreConfig` and config * class in the plugin like `PostgreSQLConfig`, `MysqlConfig`, etc. */ -@Retention(RetentionPolicy.RUNTIME) // Make annotation accessible at runtime so that config descriptions can be read from API +@Retention(RetentionPolicy.RUNTIME) +// Make annotation accessible at runtime so that config descriptions can be read from API @Target(ElementType.FIELD) // Annotation can only be applied to fields public @interface ConfigDescription { - String value(); // String value that provides a description for the configuration field + String value(); // String value that provides a description for the configuration field } diff --git a/src/main/java/io/supertokens/cronjobs/CronTask.java b/src/main/java/io/supertokens/cronjobs/CronTask.java index 45beb65d7..98afd250b 100644 --- a/src/main/java/io/supertokens/cronjobs/CronTask.java +++ b/src/main/java/io/supertokens/cronjobs/CronTask.java @@ -82,7 +82,8 @@ public void run() { doTaskForTargetTenant(this.targetTenant); } catch (Exception e) { ProcessState.getInstance(main).addState(ProcessState.PROCESS_STATE.CRON_TASK_ERROR_LOGGING, e); - Logging.error(main, this.targetTenant, "Cronjob threw an exception: " + this.jobName, Main.isTesting, e); + Logging.error(main, this.targetTenant, "Cronjob threw an exception: " + this.jobName, Main.isTesting, + e); if (e instanceof QuitProgramException) { main.wakeUpMainThreadToShutdown(); } @@ -114,7 +115,8 @@ public void run() { doTaskPerApp(app); } catch (Exception e) { ProcessState.getInstance(main).addState(ProcessState.PROCESS_STATE.CRON_TASK_ERROR_LOGGING, e); - Logging.error(main, app.getAsPublicTenantIdentifier(), "Cronjob threw an exception: " + this.jobName, Main.isTesting, e); + Logging.error(main, app.getAsPublicTenantIdentifier(), + "Cronjob threw an exception: " + this.jobName, Main.isTesting, e); if (e instanceof QuitProgramException) { main.wakeUpMainThreadToShutdown(); } @@ -131,7 +133,8 @@ public void run() { } catch (Exception e) { ProcessState.getInstance(main) .addState(ProcessState.PROCESS_STATE.CRON_TASK_ERROR_LOGGING, e); - Logging.error(main, t.get(0), "Cronjob threw an exception: " + this.jobName, Main.isTesting, e); + Logging.error(main, t.get(0), "Cronjob threw an exception: " + this.jobName, Main.isTesting, + e); if (e instanceof QuitProgramException) { threwQuitProgramException.set(true); } @@ -143,7 +146,8 @@ public void run() { } catch (Exception e) { ProcessState.getInstance(main) .addState(ProcessState.PROCESS_STATE.CRON_TASK_ERROR_LOGGING, e); - Logging.error(main, tenant, "Cronjob threw an exception: " + this.jobName, Main.isTesting, e); + Logging.error(main, tenant, "Cronjob threw an exception: " + this.jobName, + Main.isTesting, e); if (e instanceof QuitProgramException) { threwQuitProgramException.set(true); } diff --git a/src/main/java/io/supertokens/cronjobs/deleteExpiredTotpTokens/DeleteExpiredTotpTokens.java b/src/main/java/io/supertokens/cronjobs/deleteExpiredTotpTokens/DeleteExpiredTotpTokens.java index 44e6e4da8..be43a4a65 100644 --- a/src/main/java/io/supertokens/cronjobs/deleteExpiredTotpTokens/DeleteExpiredTotpTokens.java +++ b/src/main/java/io/supertokens/cronjobs/deleteExpiredTotpTokens/DeleteExpiredTotpTokens.java @@ -50,7 +50,8 @@ protected void doTaskPerTenant(TenantIdentifier tenantIdentifier) throws Excepti // doesn't delete totp codes that keep the rate limiting active for // the expected cooldown duration. int deletedCount = storage.removeExpiredCodes(tenantIdentifier, expiredBefore); - Logging.debug(this.main, tenantIdentifier, "Cron DeleteExpiredTotpTokens deleted " + deletedCount + " expired TOTP codes"); + Logging.debug(this.main, tenantIdentifier, + "Cron DeleteExpiredTotpTokens deleted " + deletedCount + " expired TOTP codes"); } @Override diff --git a/src/main/java/io/supertokens/dashboard/Dashboard.java b/src/main/java/io/supertokens/dashboard/Dashboard.java index ce9486891..a987fe9eb 100644 --- a/src/main/java/io/supertokens/dashboard/Dashboard.java +++ b/src/main/java/io/supertokens/dashboard/Dashboard.java @@ -62,7 +62,8 @@ public static DashboardUser signUpDashboardUser(Main main, String email, } } - public static DashboardUser signUpDashboardUser(AppIdentifier appIdentifier, Storage storage, Main main, String email, + public static DashboardUser signUpDashboardUser(AppIdentifier appIdentifier, Storage storage, Main main, + String email, String password) throws StorageQueryException, DuplicateEmailException, FeatureNotEnabledException, TenantOrAppNotFoundException { @@ -167,7 +168,8 @@ public static boolean deleteUserWithUserId(AppIdentifier appIdentifier, Storage .deleteDashboardUserWithUserId(appIdentifier, userId); } - private static boolean isUserSuspended(AppIdentifier appIdentifier, Storage storage, Main main, @Nullable String email, + private static boolean isUserSuspended(AppIdentifier appIdentifier, Storage storage, Main main, + @Nullable String email, @Nullable String userId) throws StorageQueryException { if (!isDashboardFeatureFlagEnabled(main, appIdentifier)) { @@ -239,7 +241,8 @@ public static DashboardUser updateUsersCredentialsWithUserId(AppIdentifier appId dashboardStorage.startTransaction(transaction -> { if (newEmail != null) { try { - dashboardStorage.updateDashboardUsersEmailWithUserId_Transaction(appIdentifier, transaction, userId, + dashboardStorage.updateDashboardUsersEmailWithUserId_Transaction(appIdentifier, transaction, + userId, newEmail); } catch (DuplicateEmailException | UserIdNotFoundException e) { throw new StorageTransactionLogicException(e); @@ -250,7 +253,8 @@ public static DashboardUser updateUsersCredentialsWithUserId(AppIdentifier appId try { String hashedPassword = PasswordHashing.getInstance(main) .createHashWithSalt(appIdentifier, newPassword); - dashboardStorage.updateDashboardUsersPasswordWithUserId_Transaction(appIdentifier, transaction, userId, + dashboardStorage.updateDashboardUsersPasswordWithUserId_Transaction(appIdentifier, transaction, + userId, hashedPassword); } catch (UserIdNotFoundException | TenantOrAppNotFoundException e) { throw new StorageTransactionLogicException(e); @@ -403,14 +407,16 @@ public static boolean isValidUserSession(AppIdentifier appIdentifier, Storage st return false; } - public static String getEmailFromSessionId(AppIdentifier appIdentifier, Storage storage, String sessionId) throws StorageQueryException { + public static String getEmailFromSessionId(AppIdentifier appIdentifier, Storage storage, String sessionId) + throws StorageQueryException { DashboardSessionInfo sessionInfo = StorageUtils.getDashboardStorage(storage) .getSessionInfoWithSessionId(appIdentifier, sessionId); if (sessionInfo != null) { String userId = sessionInfo.userId; - DashboardUser user = StorageUtils.getDashboardStorage(storage).getDashboardUserByUserId(appIdentifier, userId); + DashboardUser user = StorageUtils.getDashboardStorage(storage) + .getDashboardUserByUserId(appIdentifier, userId); if (user != null) { return user.email; diff --git a/src/main/java/io/supertokens/emailpassword/EmailPassword.java b/src/main/java/io/supertokens/emailpassword/EmailPassword.java index ec5495998..5b907c47f 100644 --- a/src/main/java/io/supertokens/emailpassword/EmailPassword.java +++ b/src/main/java/io/supertokens/emailpassword/EmailPassword.java @@ -262,7 +262,8 @@ public static AuthRecipeUserInfo signIn(TenantIdentifier tenantIdentifier, Stora LoginMethod lM = null; for (AuthRecipeUserInfo currUser : users) { for (LoginMethod currLM : currUser.loginMethods) { - if (currLM.recipeId == RECIPE_ID.EMAIL_PASSWORD && currLM.email.equals(email) && currLM.tenantIds.contains(tenantIdentifier.getTenantId())) { + if (currLM.recipeId == RECIPE_ID.EMAIL_PASSWORD && currLM.email.equals(email) && + currLM.tenantIds.contains(tenantIdentifier.getTenantId())) { user = currUser; lM = currLM; } @@ -622,7 +623,8 @@ public static void updateUsersEmailOrPassword(AppIdentifier appIdentifier, Stora if (!userWithSameEmail.tenantIds.contains(tenantId)) { continue; } - if (userWithSameEmail.isPrimaryUser && !userWithSameEmail.getSupertokensUserId().equals(user.getSupertokensUserId())) { + if (userWithSameEmail.isPrimaryUser && !userWithSameEmail.getSupertokensUserId() + .equals(user.getSupertokensUserId())) { throw new StorageTransactionLogicException( new EmailChangeNotAllowedException()); } diff --git a/src/main/java/io/supertokens/emailpassword/ParsedFirebaseSCryptResponse.java b/src/main/java/io/supertokens/emailpassword/ParsedFirebaseSCryptResponse.java index e016b1a6b..f36e33e2b 100644 --- a/src/main/java/io/supertokens/emailpassword/ParsedFirebaseSCryptResponse.java +++ b/src/main/java/io/supertokens/emailpassword/ParsedFirebaseSCryptResponse.java @@ -30,7 +30,7 @@ public class ParsedFirebaseSCryptResponse { private static final String FIREBASE_SCRYPT_SALT_SEPARATOR = "s="; public ParsedFirebaseSCryptResponse(String passwordHash, String salt, String saltSeparator, int rounds, - int memCost) { + int memCost) { this.passwordHash = passwordHash; this.salt = salt; this.saltSeparator = saltSeparator; diff --git a/src/main/java/io/supertokens/emailpassword/PasswordHashingUtils.java b/src/main/java/io/supertokens/emailpassword/PasswordHashingUtils.java index beb03266b..99d2e4fa5 100644 --- a/src/main/java/io/supertokens/emailpassword/PasswordHashingUtils.java +++ b/src/main/java/io/supertokens/emailpassword/PasswordHashingUtils.java @@ -51,7 +51,7 @@ public static String replaceUnsupportedIdentifierForBcryptPasswordHashVerificati public static void assertSuperTokensSupportInputPasswordHashFormat(AppIdentifier appIdentifier, Main main, String passwordHash, @Nullable - CoreConfig.PASSWORD_HASHING_ALG hashingAlgorithm) + CoreConfig.PASSWORD_HASHING_ALG hashingAlgorithm) throws UnsupportedPasswordHashingFormatException, TenantOrAppNotFoundException { if (hashingAlgorithm == null) { if (ParsedFirebaseSCryptResponse.fromHashString(passwordHash) != null) { diff --git a/src/main/java/io/supertokens/httpRequest/HttpRequest.java b/src/main/java/io/supertokens/httpRequest/HttpRequest.java index b9a781eb1..7ae1b5843 100644 --- a/src/main/java/io/supertokens/httpRequest/HttpRequest.java +++ b/src/main/java/io/supertokens/httpRequest/HttpRequest.java @@ -62,7 +62,8 @@ private static boolean isJsonValid(String jsonInString) { @SuppressWarnings("unchecked") public static T sendGETRequest(Main main, String requestID, String url, Map params, - int connectionTimeoutMS, int readTimeoutMS, Integer version) throws IOException, HttpResponseException { + int connectionTimeoutMS, int readTimeoutMS, Integer version) + throws IOException, HttpResponseException { StringBuilder paramBuilder = new StringBuilder(); if (params != null) { @@ -122,8 +123,11 @@ public static T sendGETRequest(Main main, String requestID, String url, Map< } @SuppressWarnings("unchecked") - public static T sendGETRequestWithResponseHeaders(Main main, String requestID, String url, Map params, - int connectionTimeoutMS, int readTimeoutMS, Integer version, Map responseHeaders) throws IOException, HttpResponseException { + public static T sendGETRequestWithResponseHeaders(Main main, String requestID, String url, + Map params, + int connectionTimeoutMS, int readTimeoutMS, Integer version, + Map responseHeaders) + throws IOException, HttpResponseException { StringBuilder paramBuilder = new StringBuilder(); if (params != null) { @@ -189,7 +193,7 @@ public static T sendGETRequestWithResponseHeaders(Main main, String requestI } private static T sendJsonRequest(Main main, String requestID, String url, JsonElement requestBody, - int connectionTimeoutMS, int readTimeoutMS, Integer version, String method) + int connectionTimeoutMS, int readTimeoutMS, Integer version, String method) throws IOException, HttpResponseException { URL obj = getURL(main, requestID, url); InputStream inputStream = null; @@ -247,17 +251,20 @@ private static T sendJsonRequest(Main main, String requestID, String url, Js } public static T sendJsonPOSTRequest(Main main, String requestID, String url, JsonElement requestBody, - int connectionTimeoutMS, int readTimeoutMS, Integer version) throws IOException, HttpResponseException { + int connectionTimeoutMS, int readTimeoutMS, Integer version) + throws IOException, HttpResponseException { return sendJsonRequest(main, requestID, url, requestBody, connectionTimeoutMS, readTimeoutMS, version, "POST"); } public static T sendJsonPUTRequest(Main main, String requestID, String url, JsonElement requestBody, - int connectionTimeoutMS, int readTimeoutMS, Integer version) throws IOException, HttpResponseException { + int connectionTimeoutMS, int readTimeoutMS, Integer version) + throws IOException, HttpResponseException { return sendJsonRequest(main, requestID, url, requestBody, connectionTimeoutMS, readTimeoutMS, version, "PUT"); } public static T sendJsonDELETERequest(Main main, String requestID, String url, JsonElement requestBody, - int connectionTimeoutMS, int readTimeoutMS, Integer version) throws IOException, HttpResponseException { + int connectionTimeoutMS, int readTimeoutMS, Integer version) + throws IOException, HttpResponseException { return sendJsonRequest(main, requestID, url, requestBody, connectionTimeoutMS, readTimeoutMS, version, "DELETE"); } diff --git a/src/main/java/io/supertokens/inmemorydb/ConnectionWithLocks.java b/src/main/java/io/supertokens/inmemorydb/ConnectionWithLocks.java index d74aa2239..4bb2a87c1 100644 --- a/src/main/java/io/supertokens/inmemorydb/ConnectionWithLocks.java +++ b/src/main/java/io/supertokens/inmemorydb/ConnectionWithLocks.java @@ -219,13 +219,13 @@ public Statement createStatement(int resultSetType, int resultSetConcurrency, in @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability) throws SQLException { + int resultSetHoldability) throws SQLException { return con.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, - int resultSetHoldability) throws SQLException { + int resultSetHoldability) throws SQLException { return con.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability); } diff --git a/src/main/java/io/supertokens/inmemorydb/QueryExecutorTemplate.java b/src/main/java/io/supertokens/inmemorydb/QueryExecutorTemplate.java index e8ee83547..266e5d6e4 100644 --- a/src/main/java/io/supertokens/inmemorydb/QueryExecutorTemplate.java +++ b/src/main/java/io/supertokens/inmemorydb/QueryExecutorTemplate.java @@ -26,14 +26,14 @@ public interface QueryExecutorTemplate { public static T execute(Start start, String QUERY, PreparedStatementValueSetter setter, - ResultSetValueExtractor mapper) throws SQLException, StorageQueryException { + ResultSetValueExtractor mapper) throws SQLException, StorageQueryException { try (Connection con = ConnectionPool.getConnection(start)) { return execute(con, QUERY, setter, mapper); } } public static T execute(Connection con, String QUERY, PreparedStatementValueSetter setter, - ResultSetValueExtractor mapper) throws SQLException, StorageQueryException { + ResultSetValueExtractor mapper) throws SQLException, StorageQueryException { if (setter == null) setter = PreparedStatementValueSetter.NO_OP_SETTER; try (PreparedStatement pst = con.prepareStatement(QUERY)) { diff --git a/src/main/java/io/supertokens/inmemorydb/Start.java b/src/main/java/io/supertokens/inmemorydb/Start.java index d838ef42f..4398107bb 100644 --- a/src/main/java/io/supertokens/inmemorydb/Start.java +++ b/src/main/java/io/supertokens/inmemorydb/Start.java @@ -688,7 +688,8 @@ public void addInfoToNonAuthRecipesBasedOnUserId(TenantIdentifier tenantIdentifi } } else if (className.equals(TOTPStorage.class.getName())) { try { - TOTPDevice device = new TOTPDevice(userId, "testDevice", "secret", 0, 30, false, System.currentTimeMillis()); + TOTPDevice device = new TOTPDevice(userId, "testDevice", "secret", 0, 30, false, + System.currentTimeMillis()); this.startTransaction(con -> { try { long now = System.currentTimeMillis(); @@ -731,7 +732,7 @@ public String[] getProtectedConfigsFromSuperTokensSaaSUsers() { @Override public AuthRecipeUserInfo signUp(TenantIdentifier tenantIdentifier, String id, String email, String passwordHash, - long timeJoined) + long timeJoined) throws StorageQueryException, DuplicateUserIdException, DuplicateEmailException, TenantOrAppNotFoundException { try { @@ -1060,8 +1061,10 @@ public boolean isEmailVerified(AppIdentifier appIdentifier, String userId, Strin } @Override - public void updateIsEmailVerifiedToExternalUserId(AppIdentifier appIdentifier, String supertokensUserId, String externalUserId) throws StorageQueryException { - EmailVerificationQueries.updateIsEmailVerifiedToExternalUserId(this, appIdentifier, supertokensUserId, externalUserId); + public void updateIsEmailVerifiedToExternalUserId(AppIdentifier appIdentifier, String supertokensUserId, + String externalUserId) throws StorageQueryException { + EmailVerificationQueries.updateIsEmailVerifiedToExternalUserId(this, appIdentifier, supertokensUserId, + externalUserId); } @Override @@ -1189,7 +1192,8 @@ public boolean doesUserIdExist(AppIdentifier appIdentifier, String userId) throw } @Override - public boolean doesUserIdExist_Transaction(TransactionConnection con, AppIdentifier appIdentifier, String userId) throws StorageQueryException { + public boolean doesUserIdExist_Transaction(TransactionConnection con, AppIdentifier appIdentifier, String userId) + throws StorageQueryException { try { Connection sqlCon = (Connection) con.getConnection(); return GeneralQueries.doesUserIdExist_Transaction(this, sqlCon, appIdentifier, userId); @@ -1648,10 +1652,10 @@ public void createCode(TenantIdentifier tenantIdentifier, PasswordlessCode code) @Override public AuthRecipeUserInfo createUser(TenantIdentifier tenantIdentifier, - String id, - @javax.annotation.Nullable String email, - @javax.annotation.Nullable - String phoneNumber, long timeJoined) + String id, + @javax.annotation.Nullable String email, + @javax.annotation.Nullable + String phoneNumber, long timeJoined) throws StorageQueryException, DuplicateEmailException, DuplicatePhoneNumberException, DuplicateUserIdException, TenantOrAppNotFoundException { @@ -2288,7 +2292,8 @@ public TenantConfig[] getAllTenants() throws StorageQueryException { } @Override - public boolean addUserIdToTenant_Transaction(TenantIdentifier tenantIdentifier, TransactionConnection con, String userId) + public boolean addUserIdToTenant_Transaction(TenantIdentifier tenantIdentifier, TransactionConnection con, + String userId) throws StorageQueryException, TenantOrAppNotFoundException, DuplicateEmailException, DuplicateThirdPartyUserException, DuplicatePhoneNumberException, UnknownUserIdException { Connection sqlCon = (Connection) con.getConnection(); @@ -2594,7 +2599,8 @@ public void createDevice(AppIdentifier appIdentifier, TOTPDevice device) } @Override - public TOTPDevice createDevice_Transaction(TransactionConnection con, AppIdentifier appIdentifier, TOTPDevice device) + public TOTPDevice createDevice_Transaction(TransactionConnection con, AppIdentifier appIdentifier, + TOTPDevice device) throws DeviceAlreadyExistsException, TenantOrAppNotFoundException, StorageQueryException { Connection sqlCon = (Connection) con.getConnection(); try { @@ -2616,7 +2622,8 @@ public TOTPDevice createDevice_Transaction(TransactionConnection con, AppIdentif } @Override - public TOTPDevice getDeviceByName_Transaction(TransactionConnection con, AppIdentifier appIdentifier, String userId, String deviceName) throws StorageQueryException { + public TOTPDevice getDeviceByName_Transaction(TransactionConnection con, AppIdentifier appIdentifier, String userId, + String deviceName) throws StorageQueryException { Connection sqlCon = (Connection) con.getConnection(); try { return TOTPQueries.getDeviceByName_Transaction(this, sqlCon, appIdentifier, userId, deviceName); @@ -2903,7 +2910,8 @@ public void linkAccounts_Transaction(AppIdentifier appIdentifier, TransactionCon } @Override - public void unlinkAccounts_Transaction(AppIdentifier appIdentifier, TransactionConnection con, String primaryUserId, String recipeUserId) + public void unlinkAccounts_Transaction(AppIdentifier appIdentifier, TransactionConnection con, String primaryUserId, + String recipeUserId) throws StorageQueryException { try { Connection sqlCon = (Connection) con.getConnection(); @@ -2925,7 +2933,8 @@ public boolean checkIfUsesAccountLinking(AppIdentifier appIdentifier) throws Sto } @Override - public int countUsersThatHaveMoreThanOneLoginMethodAndActiveSince(AppIdentifier appIdentifier, long sinceTime) throws StorageQueryException { + public int countUsersThatHaveMoreThanOneLoginMethodAndActiveSince(AppIdentifier appIdentifier, long sinceTime) + throws StorageQueryException { try { return ActiveUsersQueries.countUsersActiveSinceAndHasMoreThanOneLoginMethod(this, appIdentifier, sinceTime); } catch (SQLException e) { @@ -2944,23 +2953,27 @@ public int getUsersCountWithMoreThanOneLoginMethod(AppIdentifier appIdentifier) @Override - public UserIdMapping getUserIdMapping_Transaction(TransactionConnection con, AppIdentifier appIdentifier, String userId, boolean isSuperTokensUserId) + public UserIdMapping getUserIdMapping_Transaction(TransactionConnection con, AppIdentifier appIdentifier, + String userId, boolean isSuperTokensUserId) throws StorageQueryException { try { Connection sqlCon = (Connection) con.getConnection(); if (isSuperTokensUserId) { - return UserIdMappingQueries.getuseraIdMappingWithSuperTokensUserId_Transaction(this, sqlCon, appIdentifier, + return UserIdMappingQueries.getuseraIdMappingWithSuperTokensUserId_Transaction(this, sqlCon, + appIdentifier, userId); } - return UserIdMappingQueries.getUserIdMappingWithExternalUserId_Transaction(this, sqlCon, appIdentifier, userId); + return UserIdMappingQueries.getUserIdMappingWithExternalUserId_Transaction(this, sqlCon, appIdentifier, + userId); } catch (SQLException e) { throw new StorageQueryException(e); } } @Override - public UserIdMapping[] getUserIdMapping_Transaction(TransactionConnection con, AppIdentifier appIdentifier, String userId) + public UserIdMapping[] getUserIdMapping_Transaction(TransactionConnection con, AppIdentifier appIdentifier, + String userId) throws StorageQueryException { try { Connection sqlCon = (Connection) con.getConnection(); @@ -2974,7 +2987,8 @@ public UserIdMapping[] getUserIdMapping_Transaction(TransactionConnection con, A } @Override - public int getUsersCountWithMoreThanOneLoginMethodOrTOTPEnabled(AppIdentifier appIdentifier) throws StorageQueryException { + public int getUsersCountWithMoreThanOneLoginMethodOrTOTPEnabled(AppIdentifier appIdentifier) + throws StorageQueryException { try { return GeneralQueries.getUsersCountWithMoreThanOneLoginMethodOrTOTPEnabled(this, appIdentifier); } catch (SQLException e) { @@ -2983,9 +2997,12 @@ public int getUsersCountWithMoreThanOneLoginMethodOrTOTPEnabled(AppIdentifier ap } @Override - public int countUsersThatHaveMoreThanOneLoginMethodOrTOTPEnabledAndActiveSince(AppIdentifier appIdentifier, long sinceTime) throws StorageQueryException { + public int countUsersThatHaveMoreThanOneLoginMethodOrTOTPEnabledAndActiveSince(AppIdentifier appIdentifier, + long sinceTime) + throws StorageQueryException { try { - return ActiveUsersQueries.countUsersThatHaveMoreThanOneLoginMethodOrTOTPEnabledAndActiveSince(this, appIdentifier, sinceTime); + return ActiveUsersQueries.countUsersThatHaveMoreThanOneLoginMethodOrTOTPEnabledAndActiveSince(this, + appIdentifier, sinceTime); } catch (SQLException e) { throw new StorageQueryException(e); } diff --git a/src/main/java/io/supertokens/inmemorydb/queries/ActiveUsersQueries.java b/src/main/java/io/supertokens/inmemorydb/queries/ActiveUsersQueries.java index 37635e1b8..3daf34809 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/ActiveUsersQueries.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/ActiveUsersQueries.java @@ -39,7 +39,8 @@ public static int countUsersActiveSince(Start start, AppIdentifier appIdentifier }); } - public static int countUsersActiveSinceAndHasMoreThanOneLoginMethod(Start start, AppIdentifier appIdentifier, long sinceTime) + public static int countUsersActiveSinceAndHasMoreThanOneLoginMethod(Start start, AppIdentifier appIdentifier, + long sinceTime) throws SQLException, StorageQueryException { // TODO: Active users are present only on public tenant and MFA users may be present on different storages String QUERY = "SELECT count(1) as c FROM (" @@ -90,7 +91,9 @@ public static void deleteUserActive_Transaction(Connection con, Start start, App }); } - public static int countUsersThatHaveMoreThanOneLoginMethodOrTOTPEnabledAndActiveSince(Start start, AppIdentifier appIdentifier, long sinceTime) + public static int countUsersThatHaveMoreThanOneLoginMethodOrTOTPEnabledAndActiveSince(Start start, + AppIdentifier appIdentifier, + long sinceTime) throws SQLException, StorageQueryException { // TODO: Active users are present only on public tenant and MFA users may be present on different storages String QUERY = diff --git a/src/main/java/io/supertokens/inmemorydb/queries/DashboardQueries.java b/src/main/java/io/supertokens/inmemorydb/queries/DashboardQueries.java index 425768e39..c57036d44 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/DashboardQueries.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/DashboardQueries.java @@ -102,7 +102,8 @@ public static boolean deleteDashboardUserWithUserId(Start start, AppIdentifier a } - public static DashboardUser[] getAllDashBoardUsers(Start start, AppIdentifier appIdentifier) throws SQLException, StorageQueryException { + public static DashboardUser[] getAllDashBoardUsers(Start start, AppIdentifier appIdentifier) + throws SQLException, StorageQueryException { String QUERY = "SELECT * FROM " + Config.getConfig(start).getDashboardUsersTable() + " WHERE app_id = ? ORDER BY time_joined ASC"; return execute(start, QUERY, @@ -155,7 +156,8 @@ public static boolean updateDashboardUsersPasswordWithUserId_Transaction(Start s return rowsUpdated > 0; } - public static void createDashboardSession(Start start, AppIdentifier appIdentifier, String userId, String sessionId, long timeCreated, + public static void createDashboardSession(Start start, AppIdentifier appIdentifier, String userId, String sessionId, + long timeCreated, long expiry) throws SQLException, StorageQueryException { String QUERY = "INSERT INTO " + Config.getConfig(start).getDashboardSessionsTable() + "(app_id, user_id, session_id, time_created, expiry)" + " VALUES(?, ?, ?, ?, ?)"; @@ -168,7 +170,8 @@ public static void createDashboardSession(Start start, AppIdentifier appIdentifi }); } - public static DashboardSessionInfo getSessionInfoWithSessionId(Start start, AppIdentifier appIdentifier, String sessionId) + public static DashboardSessionInfo getSessionInfoWithSessionId(Start start, AppIdentifier appIdentifier, + String sessionId) throws SQLException, StorageQueryException { String QUERY = "SELECT * FROM " + Config.getConfig(start).getDashboardSessionsTable() + " WHERE app_id = ? AND session_id = ?"; @@ -183,7 +186,8 @@ public static DashboardSessionInfo getSessionInfoWithSessionId(Start start, AppI }); } - public static DashboardSessionInfo[] getAllSessionsForUserId(Start start, AppIdentifier appIdentifier, String userId) + public static DashboardSessionInfo[] getAllSessionsForUserId(Start start, AppIdentifier appIdentifier, + String userId) throws SQLException, StorageQueryException { String QUERY = "SELECT * FROM " + Config.getConfig(start).getDashboardSessionsTable() + " WHERE app_id = ? AND user_id = ?"; @@ -217,7 +221,8 @@ public static DashboardUser getDashboardUserByEmail(Start start, AppIdentifier a }); } - public static boolean deleteDashboardUserSessionWithSessionId(Start start, AppIdentifier appIdentifier, String sessionId) + public static boolean deleteDashboardUserSessionWithSessionId(Start start, AppIdentifier appIdentifier, + String sessionId) throws SQLException, StorageQueryException { String QUERY = "DELETE FROM " + Config.getConfig(start).getDashboardSessionsTable() + " WHERE app_id = ? AND session_id = ?"; diff --git a/src/main/java/io/supertokens/inmemorydb/queries/EmailPasswordQueries.java b/src/main/java/io/supertokens/inmemorydb/queries/EmailPasswordQueries.java index 7434d8226..f45e16758 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/EmailPasswordQueries.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/EmailPasswordQueries.java @@ -154,8 +154,8 @@ public static PasswordResetTokenInfo[] getAllPasswordResetTokenInfoForUser(Start String userId) throws StorageQueryException, SQLException { String QUERY = - "SELECT user_id, token, token_expiry, email FROM " + getConfig(start).getPasswordResetTokensTable() - + " WHERE app_id = ? AND user_id = ?"; + "SELECT user_id, token, token_expiry, email FROM " + getConfig(start).getPasswordResetTokensTable() + + " WHERE app_id = ? AND user_id = ?"; return execute(start, QUERY, pst -> { pst.setString(1, appIdentifier.getAppId()); @@ -206,8 +206,8 @@ public static PasswordResetTokenInfo getPasswordResetTokenInfo(Start start, AppI String token) throws SQLException, StorageQueryException { String QUERY = - "SELECT user_id, token, token_expiry, email FROM " + getConfig(start).getPasswordResetTokensTable() - + " WHERE app_id = ? AND token = ?"; + "SELECT user_id, token, token_expiry, email FROM " + getConfig(start).getPasswordResetTokensTable() + + " WHERE app_id = ? AND token = ?"; return execute(start, QUERY, pst -> { pst.setString(1, appIdentifier.getAppId()); pst.setString(2, token); @@ -265,7 +265,9 @@ public static AuthRecipeUserInfo signUp(Start start, TenantIdentifier tenantIden { // all_auth_recipe_users String QUERY = "INSERT INTO " + getConfig(start).getUsersTable() - + "(app_id, tenant_id, user_id, primary_or_recipe_user_id, recipe_id, time_joined, primary_or_recipe_user_time_joined)" + + + + "(app_id, tenant_id, user_id, primary_or_recipe_user_id, recipe_id, time_joined, " + + "primary_or_recipe_user_time_joined)" + " VALUES(?, ?, ?, ?, ?, ?, ?)"; update(sqlCon, QUERY, pst -> { pst.setString(1, tenantIdentifier.getAppId()); @@ -315,7 +317,7 @@ public static AuthRecipeUserInfo signUp(Start start, TenantIdentifier tenantIden } public static void deleteUser_Transaction(Connection sqlCon, Start start, AppIdentifier appIdentifier, - String userId, boolean deleteUserIdMappingToo) + String userId, boolean deleteUserIdMappingToo) throws StorageQueryException, SQLException { if (deleteUserIdMappingToo) { String QUERY = "DELETE FROM " + getConfig(start).getAppIdToUserIdTable() @@ -355,10 +357,12 @@ public static void deleteUser_Transaction(Connection sqlCon, Start start, AppIde } } - private static UserInfoPartial getUserInfoUsingId_Transaction(Start start, Connection sqlCon, AppIdentifier appIdentifier, - String id) throws SQLException, StorageQueryException { + private static UserInfoPartial getUserInfoUsingId_Transaction(Start start, Connection sqlCon, + AppIdentifier appIdentifier, + String id) + throws SQLException, StorageQueryException { // we don't need a FOR UPDATE here because this is already part of a transaction, and locked on - // app_id_to_user_id table + // app_id_to_user_id table String QUERY = "SELECT user_id, email, password_hash, time_joined FROM " + getConfig(start).getEmailPasswordUsersTable() + " WHERE app_id = ? AND user_id = ?"; @@ -380,8 +384,8 @@ public static List getUsersInfoUsingIdList(Start start, Set // No need to filter based on tenantId because the id list is already filtered for a tenant String QUERY = "SELECT user_id, email, password_hash, time_joined " + "FROM " + getConfig(start).getEmailPasswordUsersTable() - + " WHERE user_id IN (" + Utils.generateCommaSeperatedQuestionMarks(ids.size()) + - " ) AND app_id = ?"; + + " WHERE user_id IN (" + Utils.generateCommaSeperatedQuestionMarks(ids.size()) + + " ) AND app_id = ?"; List userInfos = execute(start, QUERY, pst -> { int index = 1; @@ -436,10 +440,11 @@ public static List getUsersInfoUsingIdList_Transaction(Start start, } return Collections.emptyList(); } + public static String lockEmail_Transaction(Start start, Connection con, - AppIdentifier appIdentifier, + AppIdentifier appIdentifier, String email) - throws StorageQueryException, SQLException { + throws StorageQueryException, SQLException { String QUERY = "SELECT user_id FROM " + getConfig(start).getEmailPasswordUsersTable() + " WHERE app_id = ? AND email = ?"; return execute(con, QUERY, pst -> { @@ -474,8 +479,9 @@ public static String getPrimaryUserIdUsingEmail(Start start, TenantIdentifier te }); } - public static List getPrimaryUserIdsUsingEmail_Transaction(Start start, Connection con, AppIdentifier appIdentifier, - String email) + public static List getPrimaryUserIdsUsingEmail_Transaction(Start start, Connection con, + AppIdentifier appIdentifier, + String email) throws StorageQueryException, SQLException { String QUERY = "SELECT DISTINCT all_users.primary_or_recipe_user_id AS user_id " + "FROM " + getConfig(start).getEmailPasswordUsersTable() + " AS ep" + @@ -505,11 +511,14 @@ public static boolean addUserIdToTenant_Transaction(Start start, Connection sqlC throw new UnknownUserIdException(); } - GeneralQueries.AccountLinkingInfo accountLinkingInfo = GeneralQueries.getAccountLinkingInfo_Transaction(start, sqlCon, tenantIdentifier.toAppIdentifier(), userId); + GeneralQueries.AccountLinkingInfo accountLinkingInfo = GeneralQueries.getAccountLinkingInfo_Transaction(start, + sqlCon, tenantIdentifier.toAppIdentifier(), userId); { // all_auth_recipe_users String QUERY = "INSERT INTO " + getConfig(start).getUsersTable() - + "(app_id, tenant_id, user_id, primary_or_recipe_user_id, is_linked_or_is_a_primary_user, recipe_id, time_joined, primary_or_recipe_user_time_joined)" + + + "(app_id, tenant_id, user_id, primary_or_recipe_user_id, is_linked_or_is_a_primary_user, " + + "recipe_id, time_joined, primary_or_recipe_user_time_joined)" + " VALUES(?, ?, ?, ?, ?, ?, ?, ?)" + " ON CONFLICT DO NOTHING"; GeneralQueries.AccountLinkingInfo finalAccountLinkingInfo = accountLinkingInfo; @@ -524,7 +533,8 @@ public static boolean addUserIdToTenant_Transaction(Start start, Connection sqlC pst.setLong(8, userInfo.timeJoined); }); - GeneralQueries.updateTimeJoinedForPrimaryUser_Transaction(start, sqlCon, tenantIdentifier.toAppIdentifier(), finalAccountLinkingInfo.primaryUserId); + GeneralQueries.updateTimeJoinedForPrimaryUser_Transaction(start, sqlCon, tenantIdentifier.toAppIdentifier(), + finalAccountLinkingInfo.primaryUserId); } { // emailpassword_user_to_tenant @@ -590,27 +600,27 @@ private static List fillUserInfoWithVerified_transaction(Start return userInfos; } - private static List fillUserInfoWithVerified(Start start, - AppIdentifier appIdentifier, - List userInfos) - throws SQLException, StorageQueryException { - List userIdsAndEmails = new ArrayList<>(); - for (UserInfoPartial userInfo : userInfos) { - userIdsAndEmails.add(new EmailVerificationQueries.UserIdAndEmail(userInfo.id, userInfo.email)); - } - List userIdsThatAreVerified = EmailVerificationQueries.isEmailVerified(start, - appIdentifier, - userIdsAndEmails); - Set verifiedUserIdsSet = new HashSet<>(userIdsThatAreVerified); - for (UserInfoPartial userInfo : userInfos) { - if (verifiedUserIdsSet.contains(userInfo.id)) { - userInfo.verified = true; - } else { - userInfo.verified = false; - } - } - return userInfos; - } + private static List fillUserInfoWithVerified(Start start, + AppIdentifier appIdentifier, + List userInfos) + throws SQLException, StorageQueryException { + List userIdsAndEmails = new ArrayList<>(); + for (UserInfoPartial userInfo : userInfos) { + userIdsAndEmails.add(new EmailVerificationQueries.UserIdAndEmail(userInfo.id, userInfo.email)); + } + List userIdsThatAreVerified = EmailVerificationQueries.isEmailVerified(start, + appIdentifier, + userIdsAndEmails); + Set verifiedUserIdsSet = new HashSet<>(userIdsThatAreVerified); + for (UserInfoPartial userInfo : userInfos) { + if (verifiedUserIdsSet.contains(userInfo.id)) { + userInfo.verified = true; + } else { + userInfo.verified = false; + } + } + return userInfos; + } private static UserInfoPartial fillUserInfoWithTenantIds_transaction(Start start, Connection sqlCon, AppIdentifier appIdentifier, diff --git a/src/main/java/io/supertokens/inmemorydb/queries/EmailVerificationQueries.java b/src/main/java/io/supertokens/inmemorydb/queries/EmailVerificationQueries.java index 78684eeac..8a6292529 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/EmailVerificationQueries.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/EmailVerificationQueries.java @@ -226,7 +226,8 @@ public static boolean isEmailVerified(Start start, AppIdentifier appIdentifier, }, result -> result.next()); } - public static void updateIsEmailVerifiedToExternalUserId(Start start, AppIdentifier appIdentifier, String supertokensUserId, String externalUserId) + public static void updateIsEmailVerifiedToExternalUserId(Start start, AppIdentifier appIdentifier, + String supertokensUserId, String externalUserId) throws StorageQueryException { try { start.startTransaction((TransactionConnection con) -> { @@ -288,7 +289,9 @@ public static List isEmailVerified_transaction(Start start, Connection s // We have external user id stored in the email verification table, so we need to fetch the mapped userids for // calculating the verified emails - HashMap supertokensUserIdToExternalUserIdMap = UserIdMappingQueries.getUserIdMappingWithUserIds_Transaction(start, + HashMap supertokensUserIdToExternalUserIdMap = + UserIdMappingQueries.getUserIdMappingWithUserIds_Transaction( + start, sqlCon, appIdentifier, supertokensUserIds); HashMap externalUserIdToSupertokensUserIdMap = new HashMap<>(); @@ -316,7 +319,8 @@ public static List isEmailVerified_transaction(Start start, Connection s } String QUERY = "SELECT * FROM " + getConfig(start).getEmailVerificationTable() - + " WHERE app_id = ? AND user_id IN (" + Utils.generateCommaSeperatedQuestionMarks(supertokensOrExternalUserIdsToQuery.size()) + + + " WHERE app_id = ? AND user_id IN (" + + Utils.generateCommaSeperatedQuestionMarks(supertokensOrExternalUserIdsToQuery.size()) + ") AND email IN (" + Utils.generateCommaSeperatedQuestionMarks(emails.size()) + ")"; return execute(sqlCon, QUERY, pst -> { @@ -356,7 +360,8 @@ public static List isEmailVerified(Start start, AppIdentifier appIdentif } // We have external user id stored in the email verification table, so we need to fetch the mapped userids for // calculating the verified emails - HashMap supertokensUserIdToExternalUserIdMap = UserIdMappingQueries.getUserIdMappingWithUserIds(start, + HashMap supertokensUserIdToExternalUserIdMap = UserIdMappingQueries.getUserIdMappingWithUserIds( + start, appIdentifier, supertokensUserIds); HashMap externalUserIdToSupertokensUserIdMap = new HashMap<>(); List supertokensOrExternalUserIdsToQuery = new ArrayList<>(); @@ -382,7 +387,8 @@ public static List isEmailVerified(Start start, AppIdentifier appIdentif supertokensOrExternalUserIdToEmailMap.put(supertokensOrExternalUserId, ue.email); } String QUERY = "SELECT * FROM " + getConfig(start).getEmailVerificationTable() - + " WHERE app_id = ? AND user_id IN (" + Utils.generateCommaSeperatedQuestionMarks(supertokensOrExternalUserIdsToQuery.size()) + + + " WHERE app_id = ? AND user_id IN (" + + Utils.generateCommaSeperatedQuestionMarks(supertokensOrExternalUserIdsToQuery.size()) + ") AND email IN (" + Utils.generateCommaSeperatedQuestionMarks(emails.size()) + ")"; return execute(start, QUERY, pst -> { pst.setString(1, appIdentifier.getAppId()); diff --git a/src/main/java/io/supertokens/inmemorydb/queries/GeneralQueries.java b/src/main/java/io/supertokens/inmemorydb/queries/GeneralQueries.java index 46fc162af..57b11eafd 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/GeneralQueries.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/GeneralQueries.java @@ -81,7 +81,8 @@ static String getQueryToCreateUsersTable(Start start) { + "PRIMARY KEY (app_id, tenant_id, user_id)," + "FOREIGN KEY (app_id, tenant_id) REFERENCES " + Config.getConfig(start).getTenantsTable() + " (app_id, tenant_id) ON DELETE CASCADE," - + "FOREIGN KEY (app_id, primary_or_recipe_user_id) REFERENCES " + Config.getConfig(start).getAppIdToUserIdTable() + + "FOREIGN KEY (app_id, primary_or_recipe_user_id) REFERENCES " + + Config.getConfig(start).getAppIdToUserIdTable() + " (app_id, user_id) ON DELETE CASCADE," + "FOREIGN KEY (app_id, user_id) REFERENCES " + Config.getConfig(start).getAppIdToUserIdTable() + " (app_id, user_id) ON DELETE CASCADE" @@ -110,15 +111,19 @@ static String getQueryToCreateUserPaginationIndex2(Start start) { static String getQueryToCreateUserPaginationIndex3(Start start) { return "CREATE INDEX all_auth_recipe_users_pagination_index3 ON " + Config.getConfig(start).getUsersTable() - + "(recipe_id, app_id, tenant_id, primary_or_recipe_user_time_joined DESC, primary_or_recipe_user_id DESC);"; + + + "(recipe_id, app_id, tenant_id, primary_or_recipe_user_time_joined DESC, primary_or_recipe_user_id " + + "DESC);"; } static String getQueryToCreateUserPaginationIndex4(Start start) { return "CREATE INDEX all_auth_recipe_users_pagination_index4 ON " + Config.getConfig(start).getUsersTable() - + "(recipe_id, app_id, tenant_id, primary_or_recipe_user_time_joined ASC, primary_or_recipe_user_id DESC);"; + + + "(recipe_id, app_id, tenant_id, primary_or_recipe_user_time_joined ASC, primary_or_recipe_user_id " + + "DESC);"; } - - static String getQueryToCreatePrimaryUserId(Start start) { + + static String getQueryToCreatePrimaryUserId(Start start) { /* * Used in: * - does user exist @@ -132,7 +137,7 @@ static String getQueryToCreateRecipeIdIndex(Start start) { /* * Used in: * - user count query - * */ + * */ return "CREATE INDEX all_auth_recipe_users_recipe_id_index ON " + Config.getConfig(start).getUsersTable() + "(app_id, recipe_id, tenant_id);"; @@ -192,7 +197,8 @@ private static String getQueryToCreateAppIdToUserIdTable(Start start) { + "primary_or_recipe_user_id CHAR(36) NOT NULL," + "is_linked_or_is_a_primary_user BOOLEAN NOT NULL DEFAULT FALSE," + "PRIMARY KEY (app_id, user_id), " - + "FOREIGN KEY (app_id, primary_or_recipe_user_id) REFERENCES " + Config.getConfig(start).getAppIdToUserIdTable() + + "FOREIGN KEY (app_id, primary_or_recipe_user_id) REFERENCES " + + Config.getConfig(start).getAppIdToUserIdTable() + " (app_id, user_id) ON DELETE CASCADE," + "FOREIGN KEY(app_id) REFERENCES " + Config.getConfig(start).getAppsTable() + " (app_id) ON DELETE CASCADE" @@ -596,11 +602,11 @@ public static boolean doesUserIdExist(Start start, TenantIdentifier tenantIdenti }, ResultSet::next); } - public static AuthRecipeUserInfo[] getUsers(Start start, TenantIdentifier tenantIdentifier, @NotNull Integer limit, - @NotNull String timeJoinedOrder, - @Nullable RECIPE_ID[] includeRecipeIds, @Nullable String userId, - @Nullable Long timeJoined, - @Nullable DashboardSearchTags dashboardSearchTags) + public static AuthRecipeUserInfo[] getUsers(Start start, TenantIdentifier tenantIdentifier, @NotNull Integer limit, + @NotNull String timeJoinedOrder, + @Nullable RECIPE_ID[] includeRecipeIds, @Nullable String userId, + @Nullable Long timeJoined, + @Nullable DashboardSearchTags dashboardSearchTags) throws SQLException, StorageQueryException { // This list will be used to keep track of the result's order from the db @@ -778,8 +784,11 @@ public static AuthRecipeUserInfo[] getUsers(Start start, TenantIdentifier tenant usersFromQuery = new ArrayList<>(); } else { - String finalQuery = "SELECT DISTINCT primary_or_recipe_user_id, primary_or_recipe_user_time_joined FROM ( " + USER_SEARCH_TAG_CONDITION.toString() + " )" - + " AS finalResultTable ORDER BY primary_or_recipe_user_time_joined " + timeJoinedOrder + ", primary_or_recipe_user_id DESC "; + String finalQuery = + "SELECT DISTINCT primary_or_recipe_user_id, primary_or_recipe_user_time_joined FROM ( " + + USER_SEARCH_TAG_CONDITION.toString() + " )" + + " AS finalResultTable ORDER BY primary_or_recipe_user_time_joined " + + timeJoinedOrder + ", primary_or_recipe_user_id DESC "; usersFromQuery = execute(start, finalQuery, pst -> { for (int i = 1; i <= queryList.size(); i++) { pst.setString(i, queryList.get(i - 1)); @@ -815,9 +824,12 @@ public static AuthRecipeUserInfo[] getUsers(Start start, TenantIdentifier tenant recipeIdCondition = recipeIdCondition + " AND"; } String timeJoinedOrderSymbol = timeJoinedOrder.equals("ASC") ? ">" : "<"; - String QUERY = "SELECT DISTINCT primary_or_recipe_user_id, primary_or_recipe_user_time_joined FROM " + getConfig(start).getUsersTable() + " WHERE " + String QUERY = "SELECT DISTINCT primary_or_recipe_user_id, primary_or_recipe_user_time_joined FROM " + + getConfig(start).getUsersTable() + " WHERE " + recipeIdCondition + " (primary_or_recipe_user_time_joined " + timeJoinedOrderSymbol - + " ? OR (primary_or_recipe_user_time_joined = ? AND primary_or_recipe_user_id <= ?)) AND app_id = ? AND tenant_id = ?" + + + " ? OR (primary_or_recipe_user_time_joined = ? AND primary_or_recipe_user_id <= ?)) AND " + + "app_id = ? AND tenant_id = ?" + " ORDER BY primary_or_recipe_user_time_joined " + timeJoinedOrder + ", primary_or_recipe_user_id DESC LIMIT ?"; usersFromQuery = execute(start, QUERY, pst -> { @@ -843,7 +855,8 @@ public static AuthRecipeUserInfo[] getUsers(Start start, TenantIdentifier tenant }); } else { String recipeIdCondition = RECIPE_ID_CONDITION.toString(); - String QUERY = "SELECT DISTINCT primary_or_recipe_user_id, primary_or_recipe_user_time_joined FROM " + getConfig(start).getUsersTable() + " WHERE "; + String QUERY = "SELECT DISTINCT primary_or_recipe_user_id, primary_or_recipe_user_time_joined FROM " + + getConfig(start).getUsersTable() + " WHERE "; if (!recipeIdCondition.equals("")) { QUERY += recipeIdCondition + " AND"; } @@ -1014,9 +1027,9 @@ public static AuthRecipeUserInfo[] listPrimaryUsersByThirdPartyInfo(Start start, } public static AuthRecipeUserInfo[] listPrimaryUsersByThirdPartyInfo_Transaction(Start start, Connection sqlCon, - AppIdentifier appIdentifier, - String thirdPartyId, - String thirdPartyUserId) + AppIdentifier appIdentifier, + String thirdPartyId, + String thirdPartyUserId) throws SQLException, StorageQueryException { // we first lock on the table based on thirdparty info and tenant - this will ensure that any other // query happening related to the account linking on this third party info / tenant will wait for this to @@ -1029,7 +1042,8 @@ public static AuthRecipeUserInfo[] listPrimaryUsersByThirdPartyInfo_Transaction( // now that we have locks on all the relevant tables, we can read from them safely List userIds = ThirdPartyQueries.listUserIdsByThirdPartyInfo_Transaction(start, sqlCon, appIdentifier, thirdPartyId, thirdPartyUserId); - List result = getPrimaryUserInfoForUserIds_Transaction(start, sqlCon, appIdentifier, userIds); + List result = getPrimaryUserInfoForUserIds_Transaction(start, sqlCon, appIdentifier, + userIds); // this is going to order them based on oldest that joined to newest that joined. result.sort(Comparator.comparingLong(o -> o.timeJoined)); @@ -1127,87 +1141,91 @@ public static AuthRecipeUserInfo[] listPrimaryUsersByPhoneNumber(Start start, } public static AuthRecipeUserInfo getPrimaryUserByThirdPartyInfo(Start start, - TenantIdentifier tenantIdentifier, - String thirdPartyId, - String thirdPartyUserId) + TenantIdentifier tenantIdentifier, + String thirdPartyId, + String thirdPartyUserId) throws StorageQueryException, SQLException { String userId = ThirdPartyQueries.getUserIdByThirdPartyInfo(start, tenantIdentifier, - thirdPartyId, thirdPartyUserId); + thirdPartyId, thirdPartyUserId); return getPrimaryUserInfoForUserId(start, tenantIdentifier.toAppIdentifier(), userId); } public static String getPrimaryUserIdStrForUserId(Start start, AppIdentifier appIdentifier, String id) throws SQLException, StorageQueryException { - String QUERY = "SELECT primary_or_recipe_user_id FROM " + getConfig(start).getUsersTable() + - " WHERE user_id = ? AND app_id = ?"; - return execute(start, QUERY, pst -> { - pst.setString(1, id); - pst.setString(2, appIdentifier.getAppId()); - }, result -> { - if (result.next()) { - return result.getString("primary_or_recipe_user_id"); - } - return null; - }); - } + String QUERY = "SELECT primary_or_recipe_user_id FROM " + getConfig(start).getUsersTable() + + " WHERE user_id = ? AND app_id = ?"; + return execute(start, QUERY, pst -> { + pst.setString(1, id); + pst.setString(2, appIdentifier.getAppId()); + }, result -> { + if (result.next()) { + return result.getString("primary_or_recipe_user_id"); + } + return null; + }); + } public static AuthRecipeUserInfo getPrimaryUserInfoForUserId(Start start, AppIdentifier appIdentifier, String id) throws SQLException, StorageQueryException { - List ids = new ArrayList<>(); - ids.add(id); - List result = getPrimaryUserInfoForUserIds(start, appIdentifier, ids); - if (result.isEmpty()) { - return null; - } - return result.get(0); - } - - public static AuthRecipeUserInfo getPrimaryUserInfoForUserId_Transaction(Start start, Connection con, - AppIdentifier appIdentifier, String id) + List ids = new ArrayList<>(); + ids.add(id); + List result = getPrimaryUserInfoForUserIds(start, appIdentifier, ids); + if (result.isEmpty()) { + return null; + } + return result.get(0); + } + + public static AuthRecipeUserInfo getPrimaryUserInfoForUserId_Transaction(Start start, Connection con, + AppIdentifier appIdentifier, String id) throws SQLException, StorageQueryException { - List ids = new ArrayList<>(); - ids.add(id); - List result = getPrimaryUserInfoForUserIds_Transaction(start, con, appIdentifier, ids); - if (result.isEmpty()) { - return null; - } - return result.get(0); - } + List ids = new ArrayList<>(); + ids.add(id); + List result = getPrimaryUserInfoForUserIds_Transaction(start, con, appIdentifier, ids); + if (result.isEmpty()) { + return null; + } + return result.get(0); + } private static List getPrimaryUserInfoForUserIds(Start start, - AppIdentifier appIdentifier, - List userIds) + AppIdentifier appIdentifier, + List userIds) throws StorageQueryException, SQLException { if (userIds.size() == 0) { - return new ArrayList<>(); - } - - // We check both user_id and primary_or_recipe_user_id because the input may have a recipe userId - // which is linked to a primary user ID in which case it won't be in the primary_or_recipe_user_id column, - // or the input may have a primary user ID whose recipe user ID was removed, so it won't be in the user_id - // column - String QUERY = "SELECT au.user_id, au.primary_or_recipe_user_id, au.is_linked_or_is_a_primary_user, au.recipe_id, aaru.tenant_id, aaru.time_joined FROM " + getConfig(start).getAppIdToUserIdTable() + " as au " + - "LEFT JOIN " + getConfig(start).getUsersTable() + " as aaru ON au.app_id = aaru.app_id AND au.user_id = aaru.user_id" + - " WHERE au.primary_or_recipe_user_id IN (SELECT primary_or_recipe_user_id FROM " + - getConfig(start).getAppIdToUserIdTable() + " WHERE (user_id IN (" - + Utils.generateCommaSeperatedQuestionMarks(userIds.size()) + - ") OR primary_or_recipe_user_id IN (" + - Utils.generateCommaSeperatedQuestionMarks(userIds.size()) + - ")) AND app_id = ?) AND au.app_id = ?"; + return new ArrayList<>(); + } + + // We check both user_id and primary_or_recipe_user_id because the input may have a recipe userId + // which is linked to a primary user ID in which case it won't be in the primary_or_recipe_user_id column, + // or the input may have a primary user ID whose recipe user ID was removed, so it won't be in the user_id + // column + String QUERY = + "SELECT au.user_id, au.primary_or_recipe_user_id, au.is_linked_or_is_a_primary_user, au.recipe_id, " + + "aaru.tenant_id, aaru.time_joined FROM " + + getConfig(start).getAppIdToUserIdTable() + " as au " + + "LEFT JOIN " + getConfig(start).getUsersTable() + + " as aaru ON au.app_id = aaru.app_id AND au.user_id = aaru.user_id" + + " WHERE au.primary_or_recipe_user_id IN (SELECT primary_or_recipe_user_id FROM " + + getConfig(start).getAppIdToUserIdTable() + " WHERE (user_id IN (" + + Utils.generateCommaSeperatedQuestionMarks(userIds.size()) + + ") OR primary_or_recipe_user_id IN (" + + Utils.generateCommaSeperatedQuestionMarks(userIds.size()) + + ")) AND app_id = ?) AND au.app_id = ?"; List allAuthUsersResult = execute(start, QUERY, pst -> { - // IN user_id - int index = 1; - for (int i = 0; i < userIds.size(); i++, index++) { - pst.setString(index, userIds.get(i)); - } - // IN primary_or_recipe_user_id - for (int i = 0; i < userIds.size(); i++, index++) { - pst.setString(index, userIds.get(i)); - } - // for app_id - pst.setString(index, appIdentifier.getAppId()); - pst.setString(index + 1, appIdentifier.getAppId()); + // IN user_id + int index = 1; + for (int i = 0; i < userIds.size(); i++, index++) { + pst.setString(index, userIds.get(i)); + } + // IN primary_or_recipe_user_id + for (int i = 0; i < userIds.size(); i++, index++) { + pst.setString(index, userIds.get(i)); + } + // for app_id + pst.setString(index, appIdentifier.getAppId()); + pst.setString(index + 1, appIdentifier.getAppId()); }, result -> { List parsedResult = new ArrayList<>(); while (result.next()) { @@ -1231,7 +1249,7 @@ private static List getPrimaryUserInfoForUserIds(Start start List loginMethods = new ArrayList<>(); loginMethods.addAll( EmailPasswordQueries.getUsersInfoUsingIdList(start, recipeUserIdsToFetch, appIdentifier)); - loginMethods.addAll(ThirdPartyQueries.getUsersInfoUsingIdList(start, recipeUserIdsToFetch, appIdentifier)); + loginMethods.addAll(ThirdPartyQueries.getUsersInfoUsingIdList(start, recipeUserIdsToFetch, appIdentifier)); loginMethods.addAll( PasswordlessQueries.getUsersInfoUsingIdList(start, recipeUserIdsToFetch, appIdentifier)); @@ -1241,7 +1259,7 @@ private static List getPrimaryUserInfoForUserIds(Start start } Map userIdToAuthRecipeUserInfo = new HashMap<>(); - + for (AllAuthRecipeUsersResultHolder authRecipeUsersResultHolder : allAuthUsersResult) { String recipeUserId = authRecipeUsersResultHolder.userId; LoginMethod loginMethod = recipeUserIdToLoginMethodMap.get(recipeUserId); @@ -1252,7 +1270,7 @@ private static List getPrimaryUserInfoForUserIds(Start start } String primaryUserId = authRecipeUsersResultHolder.primaryOrRecipeUserId; - AuthRecipeUserInfo curr = userIdToAuthRecipeUserInfo.get(primaryUserId); + AuthRecipeUserInfo curr = userIdToAuthRecipeUserInfo.get(primaryUserId); if (curr == null) { curr = AuthRecipeUserInfo.create(primaryUserId, authRecipeUsersResultHolder.isLinkedOrIsAPrimaryUser, loginMethod); @@ -1263,12 +1281,12 @@ private static List getPrimaryUserInfoForUserIds(Start start } return userIdToAuthRecipeUserInfo.keySet().stream().map(userIdToAuthRecipeUserInfo::get) - .collect(Collectors.toList()); + .collect(Collectors.toList()); } private static List getPrimaryUserInfoForUserIds_Transaction(Start start, Connection sqlCon, - AppIdentifier appIdentifier, - List userIds) + AppIdentifier appIdentifier, + List userIds) throws StorageQueryException, SQLException { if (userIds.size() == 0) { return new ArrayList<>(); @@ -1278,14 +1296,18 @@ private static List getPrimaryUserInfoForUserIds_Transaction // which is linked to a primary user ID in which case it won't be in the primary_or_recipe_user_id column, // or the input may have a primary user ID whose recipe user ID was removed, so it won't be in the user_id // column - String QUERY = "SELECT au.user_id, au.primary_or_recipe_user_id, au.is_linked_or_is_a_primary_user, au.recipe_id, aaru.tenant_id, aaru.time_joined FROM " + getConfig(start).getAppIdToUserIdTable() + " as au" + - " LEFT JOIN " + getConfig(start).getUsersTable() + " as aaru ON au.app_id = aaru.app_id AND au.user_id = aaru.user_id" + - " WHERE au.primary_or_recipe_user_id IN (SELECT primary_or_recipe_user_id FROM " + - getConfig(start).getAppIdToUserIdTable() + " WHERE (user_id IN (" - + Utils.generateCommaSeperatedQuestionMarks(userIds.size()) + - ") OR primary_or_recipe_user_id IN (" + - Utils.generateCommaSeperatedQuestionMarks(userIds.size()) + - ")) AND app_id = ?) AND au.app_id = ?"; + String QUERY = + "SELECT au.user_id, au.primary_or_recipe_user_id, au.is_linked_or_is_a_primary_user, au.recipe_id, " + + "aaru.tenant_id, aaru.time_joined FROM " + + getConfig(start).getAppIdToUserIdTable() + " as au" + + " LEFT JOIN " + getConfig(start).getUsersTable() + + " as aaru ON au.app_id = aaru.app_id AND au.user_id = aaru.user_id" + + " WHERE au.primary_or_recipe_user_id IN (SELECT primary_or_recipe_user_id FROM " + + getConfig(start).getAppIdToUserIdTable() + " WHERE (user_id IN (" + + Utils.generateCommaSeperatedQuestionMarks(userIds.size()) + + ") OR primary_or_recipe_user_id IN (" + + Utils.generateCommaSeperatedQuestionMarks(userIds.size()) + + ")) AND app_id = ?) AND au.app_id = ?"; List allAuthUsersResult = execute(sqlCon, QUERY, pst -> { // IN user_id @@ -1322,10 +1344,13 @@ private static List getPrimaryUserInfoForUserIds_Transaction List loginMethods = new ArrayList<>(); loginMethods.addAll( - EmailPasswordQueries.getUsersInfoUsingIdList_Transaction(start, sqlCon, recipeUserIdsToFetch, appIdentifier)); - loginMethods.addAll(ThirdPartyQueries.getUsersInfoUsingIdList_Transaction(start, sqlCon, recipeUserIdsToFetch, appIdentifier)); + EmailPasswordQueries.getUsersInfoUsingIdList_Transaction(start, sqlCon, recipeUserIdsToFetch, + appIdentifier)); + loginMethods.addAll(ThirdPartyQueries.getUsersInfoUsingIdList_Transaction(start, sqlCon, recipeUserIdsToFetch, + appIdentifier)); loginMethods.addAll( - PasswordlessQueries.getUsersInfoUsingIdList_Transaction(start, sqlCon, recipeUserIdsToFetch, appIdentifier)); + PasswordlessQueries.getUsersInfoUsingIdList_Transaction(start, sqlCon, recipeUserIdsToFetch, + appIdentifier)); Map recipeUserIdToLoginMethodMap = new HashMap<>(); for (LoginMethod loginMethod : loginMethods) { @@ -1397,49 +1422,49 @@ public static Map> getTenantIdsForUserIds_transaction(Start return execute(sqlCon, QUERY.toString(), pst -> { for (int i = 0; i < userIds.length; i++) { // i+1 cause this starts with 1 and not 0, and 1 is appId - pst.setString(i + 1, userIds[i]); - } - pst.setString(userIds.length + 1, appIdentifier.getAppId()); - }, result -> { - Map> finalResult = new HashMap<>(); - for (String userId : userIds) { - finalResult.put(userId, new ArrayList<>()); - } - - while (result.next()) { - String userId = result.getString("user_id").trim(); - String tenantId = result.getString("tenant_id"); - - finalResult.get(userId).add(tenantId); - } - return finalResult; - }); - } - - return new HashMap<>(); - } - - public static Map> getTenantIdsForUserIds(Start start, - AppIdentifier appIdentifier, - String[] userIds) - throws SQLException, StorageQueryException { - if (userIds != null && userIds.length > 0) { - StringBuilder QUERY = new StringBuilder("SELECT user_id, tenant_id " - + "FROM " + getConfig(start).getUsersTable()); - QUERY.append(" WHERE user_id IN ("); - for (int i = 0; i < userIds.length; i++) { - - QUERY.append("?"); - if (i != userIds.length - 1) { - // not the last element - QUERY.append(","); - } - } - QUERY.append(") AND app_id = ?"); - - return execute(start, QUERY.toString(), pst -> { - for (int i = 0; i < userIds.length; i++) { - // i+1 cause this starts with 1 and not 0, and 1 is appId + pst.setString(i + 1, userIds[i]); + } + pst.setString(userIds.length + 1, appIdentifier.getAppId()); + }, result -> { + Map> finalResult = new HashMap<>(); + for (String userId : userIds) { + finalResult.put(userId, new ArrayList<>()); + } + + while (result.next()) { + String userId = result.getString("user_id").trim(); + String tenantId = result.getString("tenant_id"); + + finalResult.get(userId).add(tenantId); + } + return finalResult; + }); + } + + return new HashMap<>(); + } + + public static Map> getTenantIdsForUserIds(Start start, + AppIdentifier appIdentifier, + String[] userIds) + throws SQLException, StorageQueryException { + if (userIds != null && userIds.length > 0) { + StringBuilder QUERY = new StringBuilder("SELECT user_id, tenant_id " + + "FROM " + getConfig(start).getUsersTable()); + QUERY.append(" WHERE user_id IN ("); + for (int i = 0; i < userIds.length; i++) { + + QUERY.append("?"); + if (i != userIds.length - 1) { + // not the last element + QUERY.append(","); + } + } + QUERY.append(") AND app_id = ?"); + + return execute(start, QUERY.toString(), pst -> { + for (int i = 0; i < userIds.length; i++) { + // i+1 cause this starts with 1 and not 0, and 1 is appId pst.setString(i + 1, userIds[i]); } pst.setString(userIds.length + 1, appIdentifier.getAppId()); @@ -1560,7 +1585,8 @@ public static boolean checkIfUsesAccountLinking(Start start, AppIdentifier appId }); } - public static AccountLinkingInfo getAccountLinkingInfo_Transaction(Start start, Connection sqlCon, AppIdentifier appIdentifier, String userId) + public static AccountLinkingInfo getAccountLinkingInfo_Transaction(Start start, Connection sqlCon, + AppIdentifier appIdentifier, String userId) throws SQLException, StorageQueryException { GeneralQueries.AccountLinkingInfo accountLinkingInfo = new GeneralQueries.AccountLinkingInfo(userId, false); { @@ -1583,7 +1609,8 @@ public static AccountLinkingInfo getAccountLinkingInfo_Transaction(Start start, return accountLinkingInfo; } - public static boolean doesUserIdExist_Transaction(Start start, Connection sqlCon, AppIdentifier appIdentifier, String userId) + public static boolean doesUserIdExist_Transaction(Start start, Connection sqlCon, AppIdentifier appIdentifier, + String userId) throws SQLException, StorageQueryException { // We query both tables cause there is a case where a primary user ID exists, but its associated // recipe user ID has been deleted AND there are other recipe user IDs linked to this primary user ID already. @@ -1595,7 +1622,8 @@ public static boolean doesUserIdExist_Transaction(Start start, Connection sqlCon }, ResultSet::next); } - public static void updateTimeJoinedForPrimaryUser_Transaction(Start start, Connection sqlCon, AppIdentifier appIdentifier, String primaryUserId) + public static void updateTimeJoinedForPrimaryUser_Transaction(Start start, Connection sqlCon, + AppIdentifier appIdentifier, String primaryUserId) throws SQLException, StorageQueryException { String QUERY = "UPDATE " + getConfig(start).getUsersTable() + " SET primary_or_recipe_user_time_joined = (SELECT MIN(time_joined) FROM " + diff --git a/src/main/java/io/supertokens/inmemorydb/queries/MultitenancyQueries.java b/src/main/java/io/supertokens/inmemorydb/queries/MultitenancyQueries.java index 84c069089..488c682a7 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/MultitenancyQueries.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/MultitenancyQueries.java @@ -112,7 +112,8 @@ static String getQueryToCreateTenantThirdPartyProvidersTable(Start start) { + "user_info_map_from_user_info_endpoint_email_verified VARCHAR(64)," + "PRIMARY KEY (connection_uri_domain, app_id, tenant_id, third_party_id)," + "FOREIGN KEY(connection_uri_domain, app_id, tenant_id)" - + " REFERENCES " + Config.getConfig(start).getTenantConfigsTable() + " (connection_uri_domain, app_id, tenant_id) ON DELETE CASCADE" + + " REFERENCES " + Config.getConfig(start).getTenantConfigsTable() + + " (connection_uri_domain, app_id, tenant_id) ON DELETE CASCADE" + ");"; // @formatter:on } @@ -132,7 +133,8 @@ static String getQueryToCreateTenantThirdPartyProviderClientsTable(Start start) + "additional_config TEXT," + " PRIMARY KEY (connection_uri_domain, app_id, tenant_id, third_party_id, client_type)," + "FOREIGN KEY(connection_uri_domain, app_id, tenant_id, third_party_id)" - + " REFERENCES " + Config.getConfig(start).getTenantThirdPartyProvidersTable() + " (connection_uri_domain, app_id, tenant_id, third_party_id) ON DELETE CASCADE" + + " REFERENCES " + Config.getConfig(start).getTenantThirdPartyProvidersTable() + + " (connection_uri_domain, app_id, tenant_id, third_party_id) ON DELETE CASCADE" + ");"; } @@ -152,10 +154,12 @@ private static void executeCreateTenantQueries(Start start, Connection sqlCon, T } MfaSqlHelper.createFirstFactors(start, sqlCon, tenantConfig.tenantIdentifier, tenantConfig.firstFactors); - MfaSqlHelper.createRequiredSecondaryFactors(start, sqlCon, tenantConfig.tenantIdentifier, tenantConfig.requiredSecondaryFactors); + MfaSqlHelper.createRequiredSecondaryFactors(start, sqlCon, tenantConfig.tenantIdentifier, + tenantConfig.requiredSecondaryFactors); } - public static void createTenantConfig(Start start, TenantConfig tenantConfig) throws StorageQueryException, StorageTransactionLogicException { + public static void createTenantConfig(Start start, TenantConfig tenantConfig) + throws StorageQueryException, StorageTransactionLogicException { start.startTransaction(con -> { Connection sqlCon = (Connection) con.getConnection(); { @@ -171,7 +175,8 @@ public static void createTenantConfig(Start start, TenantConfig tenantConfig) th }); } - public static boolean deleteTenantConfig(Start start, TenantIdentifier tenantIdentifier) throws StorageQueryException { + public static boolean deleteTenantConfig(Start start, TenantIdentifier tenantIdentifier) + throws StorageQueryException { try { String QUERY = "DELETE FROM " + Config.getConfig(start).getTenantConfigsTable() + " WHERE connection_uri_domain = ? AND app_id = ? AND tenant_id = ?"; @@ -189,7 +194,8 @@ public static boolean deleteTenantConfig(Start start, TenantIdentifier tenantIde } } - public static void overwriteTenantConfig(Start start, TenantConfig tenantConfig) throws StorageQueryException, StorageTransactionLogicException { + public static void overwriteTenantConfig(Start start, TenantConfig tenantConfig) + throws StorageQueryException, StorageTransactionLogicException { start.startTransaction(con -> { Connection sqlCon = (Connection) con.getConnection(); { @@ -203,7 +209,8 @@ public static void overwriteTenantConfig(Start start, TenantConfig tenantConfig) pst.setString(3, tenantConfig.tenantIdentifier.getTenantId()); }); if (rowsAffected == 0) { - throw new StorageTransactionLogicException(new TenantOrAppNotFoundException(tenantConfig.tenantIdentifier)); + throw new StorageTransactionLogicException( + new TenantOrAppNotFoundException(tenantConfig.tenantIdentifier)); } } @@ -226,16 +233,21 @@ public static TenantConfig[] getAllTenants(Start start) throws StorageQueryExcep try { // Map TenantIdentifier -> thirdPartyId -> clientType - HashMap>> providerClientsMap = ThirdPartyProviderClientSQLHelper.selectAll(start); + HashMap>> providerClientsMap = ThirdPartyProviderClientSQLHelper.selectAll( + start); // Map (tenantIdentifier) -> thirdPartyId -> provider - HashMap> providerMap = ThirdPartyProviderSQLHelper.selectAll(start, providerClientsMap); + HashMap> providerMap = + ThirdPartyProviderSQLHelper.selectAll( + start, providerClientsMap); // Map (tenantIdentifier) -> firstFactors HashMap firstFactorsMap = MfaSqlHelper.selectAllFirstFactors(start); // Map (tenantIdentifier) -> requiredSecondaryFactors - HashMap requiredSecondaryFactorsMap = MfaSqlHelper.selectAllRequiredSecondaryFactors(start); + HashMap requiredSecondaryFactorsMap = + MfaSqlHelper.selectAllRequiredSecondaryFactors( + start); return TenantConfigSQLHelper.selectAll(start, providerMap, firstFactorsMap, requiredSecondaryFactorsMap); } catch (SQLException throwables) { @@ -255,7 +267,7 @@ public static void addTenantIdInTargetStorage(Start start, TenantIdentifier tena + "(app_id, created_at_time)" + " VALUES(?, ?) ON CONFLICT DO NOTHING"; update(sqlCon, QUERY, pst -> { pst.setString(1, tenantIdentifier.getAppId()); - pst.setLong(2, currentTime); + pst.setLong(2, currentTime); }); } @@ -266,7 +278,7 @@ public static void addTenantIdInTargetStorage(Start start, TenantIdentifier tena update(sqlCon, QUERY, pst -> { pst.setString(1, tenantIdentifier.getAppId()); pst.setString(2, tenantIdentifier.getTenantId()); - pst.setLong(3, currentTime); + pst.setLong(3, currentTime); }); } @@ -280,7 +292,7 @@ public static void addTenantIdInTargetStorage(Start start, TenantIdentifier tena } public static void deleteTenantIdInTargetStorage(Start start, TenantIdentifier tenantIdentifier) - throws StorageQueryException { + throws StorageQueryException { try { if (tenantIdentifier.getTenantId().equals(TenantIdentifier.DEFAULT_TENANT_ID)) { // Delete the app diff --git a/src/main/java/io/supertokens/inmemorydb/queries/PasswordlessQueries.java b/src/main/java/io/supertokens/inmemorydb/queries/PasswordlessQueries.java index e6eee9155..e9589301d 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/PasswordlessQueries.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/PasswordlessQueries.java @@ -366,7 +366,8 @@ public static void deleteCode_Transaction(Start start, Connection con, TenantIde }); } - public static AuthRecipeUserInfo createUser(Start start, TenantIdentifier tenantIdentifier, String id, @Nullable String email, + public static AuthRecipeUserInfo createUser(Start start, TenantIdentifier tenantIdentifier, String id, + @Nullable String email, @Nullable String phoneNumber, long timeJoined) throws StorageTransactionLogicException, StorageQueryException { return start.startTransaction(con -> { @@ -385,7 +386,9 @@ public static AuthRecipeUserInfo createUser(Start start, TenantIdentifier tenant { // all_auth_recipe_users String QUERY = "INSERT INTO " + getConfig(start).getUsersTable() - + "(app_id, tenant_id, user_id, primary_or_recipe_user_id, recipe_id, time_joined, primary_or_recipe_user_time_joined)" + + + + "(app_id, tenant_id, user_id, primary_or_recipe_user_id, recipe_id, time_joined, " + + "primary_or_recipe_user_time_joined)" + " VALUES(?, ?, ?, ?, ?, ?, ?)"; update(sqlCon, QUERY, pst -> { pst.setString(1, tenantIdentifier.getAppId()); @@ -435,7 +438,7 @@ public static AuthRecipeUserInfo createUser(Start start, TenantIdentifier tenant } private static UserInfoWithTenantId[] getUserInfosWithTenant_Transaction(Start start, Connection con, - AppIdentifier appIdentifier, String userId) + AppIdentifier appIdentifier, String userId) throws StorageQueryException, SQLException { String QUERY = "SELECT pl_users.user_id as user_id, pl_users.email as email, " + "pl_users.phone_number as phone_number, pl_users_to_tenant.tenant_id as tenant_id " @@ -750,7 +753,7 @@ public static List getUsersInfoUsingIdList_Transaction(Start start, } private static UserInfoPartial getUserById_Transaction(Start start, Connection sqlCon, AppIdentifier appIdentifier, - String userId) + String userId) throws StorageQueryException, SQLException { // we don't need a LOCK here because this is already part of a transaction, and locked on app_id_to_user_id // table @@ -789,8 +792,8 @@ public static List lockEmail_Transaction(Start start, Connection con, Ap } public static List lockPhone_Transaction(Start start, Connection con, - AppIdentifier appIdentifier, - String phoneNumber) + AppIdentifier appIdentifier, + String phoneNumber) throws SQLException, StorageQueryException { // normally the query below will use a for update, but sqlite doesn't support it. ((ConnectionWithLocks) con).lock( @@ -832,8 +835,9 @@ public static String getPrimaryUserIdUsingEmail(Start start, TenantIdentifier te }); } - public static List getPrimaryUserIdsUsingEmail_Transaction(Start start, Connection con, AppIdentifier appIdentifier, - String email) + public static List getPrimaryUserIdsUsingEmail_Transaction(Start start, Connection con, + AppIdentifier appIdentifier, + String email) throws StorageQueryException, SQLException { String QUERY = "SELECT DISTINCT all_users.primary_or_recipe_user_id AS user_id " + "FROM " + getConfig(start).getPasswordlessUsersTable() + " AS pless" + @@ -874,7 +878,8 @@ public static String getPrimaryUserByPhoneNumber(Start start, TenantIdentifier t }); } - public static List listUserIdsByPhoneNumber_Transaction(Start start, Connection con, AppIdentifier appIdentifier, + public static List listUserIdsByPhoneNumber_Transaction(Start start, Connection con, + AppIdentifier appIdentifier, @Nonnull String phoneNumber) throws StorageQueryException, SQLException { String QUERY = "SELECT DISTINCT all_users.primary_or_recipe_user_id AS user_id " @@ -905,11 +910,14 @@ public static boolean addUserIdToTenant_Transaction(Start start, Connection sqlC throw new UnknownUserIdException(); } - GeneralQueries.AccountLinkingInfo accountLinkingInfo = GeneralQueries.getAccountLinkingInfo_Transaction(start, sqlCon, tenantIdentifier.toAppIdentifier(), userId); + GeneralQueries.AccountLinkingInfo accountLinkingInfo = GeneralQueries.getAccountLinkingInfo_Transaction(start, + sqlCon, tenantIdentifier.toAppIdentifier(), userId); { // all_auth_recipe_users String QUERY = "INSERT INTO " + getConfig(start).getUsersTable() - + "(app_id, tenant_id, user_id, primary_or_recipe_user_id, is_linked_or_is_a_primary_user, recipe_id, time_joined, primary_or_recipe_user_time_joined)" + + + "(app_id, tenant_id, user_id, primary_or_recipe_user_id, is_linked_or_is_a_primary_user, " + + "recipe_id, time_joined, primary_or_recipe_user_time_joined)" + " VALUES(?, ?, ?, ?, ?, ?, ?, ?)" + " ON CONFLICT DO NOTHING"; update(sqlCon, QUERY, pst -> { pst.setString(1, tenantIdentifier.getAppId()); @@ -922,7 +930,8 @@ public static boolean addUserIdToTenant_Transaction(Start start, Connection sqlC pst.setLong(8, userInfo.timeJoined); }); - GeneralQueries.updateTimeJoinedForPrimaryUser_Transaction(start, sqlCon, tenantIdentifier.toAppIdentifier(), accountLinkingInfo.primaryUserId); + GeneralQueries.updateTimeJoinedForPrimaryUser_Transaction(start, sqlCon, tenantIdentifier.toAppIdentifier(), + accountLinkingInfo.primaryUserId); } { // passwordless_user_to_tenant @@ -971,9 +980,9 @@ private static UserInfoPartial fillUserInfoWithVerified_transaction(Start start, } private static List fillUserInfoWithVerified_transaction(Start start, - Connection sqlCon, - AppIdentifier appIdentifier, - List userInfos) + Connection sqlCon, + AppIdentifier appIdentifier, + List userInfos) throws SQLException, StorageQueryException { List userIdsAndEmails = new ArrayList<>(); for (UserInfoPartial userInfo : userInfos) { diff --git a/src/main/java/io/supertokens/inmemorydb/queries/TOTPQueries.java b/src/main/java/io/supertokens/inmemorydb/queries/TOTPQueries.java index de5afc661..c7e4fd745 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/TOTPQueries.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/TOTPQueries.java @@ -83,10 +83,13 @@ private static int insertUser_Transaction(Start start, Connection con, AppIdenti }); } - private static int insertDevice_Transaction(Start start, Connection con, AppIdentifier appIdentifier, TOTPDevice device) + private static int insertDevice_Transaction(Start start, Connection con, AppIdentifier appIdentifier, + TOTPDevice device) throws SQLException, StorageQueryException { String QUERY = "INSERT INTO " + Config.getConfig(start).getTotpUserDevicesTable() - + " (app_id, user_id, device_name, secret_key, period, skew, verified, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; + + + " (app_id, user_id, device_name, secret_key, period, skew, verified, created_at) VALUES (?, ?, ?, ?, " + + "?, ?, ?, ?)"; return update(con, QUERY, pst -> { pst.setString(1, appIdentifier.getAppId()); @@ -100,17 +103,20 @@ private static int insertDevice_Transaction(Start start, Connection con, AppIden }); } - public static void createDevice_Transaction(Start start, Connection sqlCon, AppIdentifier appIdentifier, TOTPDevice device) + public static void createDevice_Transaction(Start start, Connection sqlCon, AppIdentifier appIdentifier, + TOTPDevice device) throws StorageQueryException, SQLException { insertUser_Transaction(start, sqlCon, appIdentifier, device.userId); insertDevice_Transaction(start, sqlCon, appIdentifier, device); } - public static TOTPDevice getDeviceByName_Transaction(Start start, Connection sqlCon, AppIdentifier appIdentifier, String userId, String deviceName) + public static TOTPDevice getDeviceByName_Transaction(Start start, Connection sqlCon, AppIdentifier appIdentifier, + String userId, String deviceName) throws SQLException, StorageQueryException { ((ConnectionWithLocks) sqlCon).lock( - appIdentifier.getAppId() + "~" + userId + "~" + deviceName + Config.getConfig(start).getTotpUserDevicesTable()); + appIdentifier.getAppId() + "~" + userId + "~" + deviceName + + Config.getConfig(start).getTotpUserDevicesTable()); String QUERY = "SELECT * FROM " + Config.getConfig(start).getTotpUserDevicesTable() + " WHERE app_id = ? AND user_id = ? AND device_name = ?;"; @@ -138,7 +144,8 @@ public static int markDeviceAsVerified(Start start, AppIdentifier appIdentifier, }); } - public static int deleteDevice_Transaction(Start start, Connection con, AppIdentifier appIdentifier, String userId, String deviceName) + public static int deleteDevice_Transaction(Start start, Connection con, AppIdentifier appIdentifier, String userId, + String deviceName) throws SQLException, StorageQueryException { String QUERY = "DELETE FROM " + Config.getConfig(start).getTotpUserDevicesTable() + " WHERE app_id = ? AND user_id = ? AND device_name = ?;"; @@ -175,7 +182,8 @@ public static boolean removeUser(Start start, TenantIdentifier tenantIdentifier, return removedUsersCount > 0; } - public static int updateDeviceName(Start start, AppIdentifier appIdentifier, String userId, String oldDeviceName, String newDeviceName) + public static int updateDeviceName(Start start, AppIdentifier appIdentifier, String userId, String oldDeviceName, + String newDeviceName) throws StorageQueryException, SQLException { String QUERY = "UPDATE " + Config.getConfig(start).getTotpUserDevicesTable() + " SET device_name = ? WHERE app_id = ? AND user_id = ? AND device_name = ?;"; @@ -206,10 +214,12 @@ public static TOTPDevice[] getDevices(Start start, AppIdentifier appIdentifier, }); } - public static TOTPDevice[] getDevices_Transaction(Start start, Connection con, AppIdentifier appIdentifier, String userId) + public static TOTPDevice[] getDevices_Transaction(Start start, Connection con, AppIdentifier appIdentifier, + String userId) throws StorageQueryException, SQLException { - ((ConnectionWithLocks) con).lock(appIdentifier.getAppId() + "~" + userId + Config.getConfig(start).getTotpUserDevicesTable()); + ((ConnectionWithLocks) con).lock( + appIdentifier.getAppId() + "~" + userId + Config.getConfig(start).getTotpUserDevicesTable()); String QUERY = "SELECT * FROM " + Config.getConfig(start).getTotpUserDevicesTable() + " WHERE app_id = ? AND user_id = ?;"; @@ -228,10 +238,13 @@ public static TOTPDevice[] getDevices_Transaction(Start start, Connection con, A } - public static int insertUsedCode_Transaction(Start start, Connection con, TenantIdentifier tenantIdentifier, TOTPUsedCode code) + public static int insertUsedCode_Transaction(Start start, Connection con, TenantIdentifier tenantIdentifier, + TOTPUsedCode code) throws SQLException, StorageQueryException { String QUERY = "INSERT INTO " + Config.getConfig(start).getTotpUsedCodesTable() - + " (app_id, tenant_id, user_id, code, is_valid, expiry_time_ms, created_time_ms) VALUES (?, ?, ?, ?, ?, ?, ?);"; + + + " (app_id, tenant_id, user_id, code, is_valid, expiry_time_ms, created_time_ms) VALUES (?, ?, ?, ?, " + + "?, ?, ?);"; return update(con, QUERY, pst -> { pst.setString(1, tenantIdentifier.getAppId()); @@ -252,7 +265,9 @@ public static TOTPUsedCode[] getAllUsedCodesDescOrder_Transaction(Start start, C TenantIdentifier tenantIdentifier, String userId) throws SQLException, StorageQueryException { // Take a lock based on the user id: - ((ConnectionWithLocks) con).lock(tenantIdentifier.getAppId() + "~" + tenantIdentifier.getTenantId() + "~" + userId + Config.getConfig(start).getTotpUsedCodesTable()); + ((ConnectionWithLocks) con).lock( + tenantIdentifier.getAppId() + "~" + tenantIdentifier.getTenantId() + "~" + userId + + Config.getConfig(start).getTotpUsedCodesTable()); String QUERY = "SELECT * FROM " + Config.getConfig(start).getTotpUsedCodesTable() diff --git a/src/main/java/io/supertokens/inmemorydb/queries/ThirdPartyQueries.java b/src/main/java/io/supertokens/inmemorydb/queries/ThirdPartyQueries.java index 1569ee173..1be4b762f 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/ThirdPartyQueries.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/ThirdPartyQueries.java @@ -104,7 +104,9 @@ public static AuthRecipeUserInfo signUp(Start start, TenantIdentifier tenantIden { // all_auth_recipe_users String QUERY = "INSERT INTO " + getConfig(start).getUsersTable() - + "(app_id, tenant_id, user_id, primary_or_recipe_user_id, recipe_id, time_joined, primary_or_recipe_user_time_joined)" + + + + "(app_id, tenant_id, user_id, primary_or_recipe_user_id, recipe_id, time_joined, " + + "primary_or_recipe_user_time_joined)" + " VALUES(?, ?, ?, ?, ?, ?, ?)"; update(sqlCon, QUERY, pst -> { pst.setString(1, tenantIdentifier.getAppId()); @@ -189,8 +191,8 @@ public static void deleteUser_Transaction(Connection sqlCon, Start start, AppIde } public static List lockEmail_Transaction(Start start, Connection con, - AppIdentifier appIdentifier, - String email) throws SQLException, StorageQueryException { + AppIdentifier appIdentifier, + String email) throws SQLException, StorageQueryException { // normally the query below will use a for update, but sqlite doesn't support it. ((ConnectionWithLocks) con).lock( appIdentifier.getAppId() + "~" + email + @@ -272,7 +274,7 @@ public static List getUsersInfoUsingIdList(Start start, Set } public static List getUsersInfoUsingIdList_Transaction(Start start, Connection con, Set ids, - AppIdentifier appIdentifier) + AppIdentifier appIdentifier) throws SQLException, StorageQueryException { if (ids.size() > 0) { String QUERY = "SELECT user_id, third_party_id, third_party_user_id, email, time_joined " @@ -325,7 +327,8 @@ public static List listUserIdsByThirdPartyInfo(Start start, AppIdentifie }); } - public static List listUserIdsByThirdPartyInfo_Transaction(Start start, Connection con, AppIdentifier appIdentifier, + public static List listUserIdsByThirdPartyInfo_Transaction(Start start, Connection con, + AppIdentifier appIdentifier, String thirdPartyId, String thirdPartyUserId) throws SQLException, StorageQueryException { @@ -349,7 +352,7 @@ public static List listUserIdsByThirdPartyInfo_Transaction(Start start, } public static String getUserIdByThirdPartyInfo(Start start, TenantIdentifier tenantIdentifier, - String thirdPartyId, String thirdPartyUserId) + String thirdPartyId, String thirdPartyUserId) throws SQLException, StorageQueryException { String QUERY = "SELECT DISTINCT all_users.primary_or_recipe_user_id AS user_id " @@ -386,7 +389,7 @@ public static void updateUserEmail_Transaction(Start start, Connection con, AppI } private static UserInfoPartial getUserInfoUsingUserId_Transaction(Start start, Connection con, - AppIdentifier appIdentifier, String userId) + AppIdentifier appIdentifier, String userId) throws SQLException, StorageQueryException { // we don't need a LOCK here because this is already part of a transaction, and locked on app_id_to_user_id @@ -430,7 +433,7 @@ public static List getPrimaryUserIdUsingEmail(Start start, } public static List getPrimaryUserIdUsingEmail_Transaction(Start start, Connection con, - AppIdentifier appIdentifier, String email) + AppIdentifier appIdentifier, String email) throws StorageQueryException, SQLException { String QUERY = "SELECT DISTINCT all_users.primary_or_recipe_user_id AS user_id " + "FROM " + getConfig(start).getThirdPartyUsersTable() + " AS tp" + @@ -460,11 +463,14 @@ public static boolean addUserIdToTenant_Transaction(Start start, Connection sqlC throw new UnknownUserIdException(); } - GeneralQueries.AccountLinkingInfo accountLinkingInfo = GeneralQueries.getAccountLinkingInfo_Transaction(start, sqlCon, tenantIdentifier.toAppIdentifier(), userId); + GeneralQueries.AccountLinkingInfo accountLinkingInfo = GeneralQueries.getAccountLinkingInfo_Transaction(start, + sqlCon, tenantIdentifier.toAppIdentifier(), userId); { // all_auth_recipe_users String QUERY = "INSERT INTO " + getConfig(start).getUsersTable() - + "(app_id, tenant_id, user_id, primary_or_recipe_user_id, is_linked_or_is_a_primary_user, recipe_id, time_joined, primary_or_recipe_user_time_joined)" + + + "(app_id, tenant_id, user_id, primary_or_recipe_user_id, is_linked_or_is_a_primary_user, " + + "recipe_id, time_joined, primary_or_recipe_user_time_joined)" + " VALUES(?, ?, ?, ?, ?, ?, ?, ?)" + " ON CONFLICT DO NOTHING"; update(sqlCon, QUERY, pst -> { pst.setString(1, tenantIdentifier.getAppId()); @@ -477,7 +483,8 @@ public static boolean addUserIdToTenant_Transaction(Start start, Connection sqlC pst.setLong(8, userInfo.timeJoined); }); - GeneralQueries.updateTimeJoinedForPrimaryUser_Transaction(start, sqlCon, tenantIdentifier.toAppIdentifier(), accountLinkingInfo.primaryUserId); + GeneralQueries.updateTimeJoinedForPrimaryUser_Transaction(start, sqlCon, tenantIdentifier.toAppIdentifier(), + accountLinkingInfo.primaryUserId); } { // thirdparty_user_to_tenant diff --git a/src/main/java/io/supertokens/inmemorydb/queries/UserIdMappingQueries.java b/src/main/java/io/supertokens/inmemorydb/queries/UserIdMappingQueries.java index 212ab44be..a60beeffc 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/UserIdMappingQueries.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/UserIdMappingQueries.java @@ -48,13 +48,15 @@ public static String getQueryToCreateUserIdMappingTable(Start start) { + "UNIQUE (app_id, supertokens_user_id)," + "UNIQUE (app_id, external_user_id)," + "PRIMARY KEY(app_id, supertokens_user_id, external_user_id)," - + "FOREIGN KEY(app_id, supertokens_user_id) REFERENCES " + Config.getConfig(start).getAppIdToUserIdTable() + + "FOREIGN KEY(app_id, supertokens_user_id) REFERENCES " + + Config.getConfig(start).getAppIdToUserIdTable() + " (app_id, user_id) ON DELETE CASCADE" + ");"; // @formatter:on } - public static void createUserIdMapping(Start start, AppIdentifier appIdentifier, String superTokensUserId, String externalUserId, + public static void createUserIdMapping(Start start, AppIdentifier appIdentifier, String superTokensUserId, + String externalUserId, String externalUserIdInfo) throws SQLException, StorageQueryException { String QUERY = "INSERT INTO " + Config.getConfig(start).getUserIdMappingTable() + " (app_id, supertokens_user_id, external_user_id, external_user_id_info)" + " VALUES(?, ?, ?, ?)"; @@ -67,7 +69,8 @@ public static void createUserIdMapping(Start start, AppIdentifier appIdentifier, }); } - public static UserIdMapping getuseraIdMappingWithSuperTokensUserId(Start start, AppIdentifier appIdentifier, String userId) + public static UserIdMapping getuseraIdMappingWithSuperTokensUserId(Start start, AppIdentifier appIdentifier, + String userId) throws SQLException, StorageQueryException { String QUERY = "SELECT * FROM " + Config.getConfig(start).getUserIdMappingTable() + " WHERE app_id = ? AND supertokens_user_id = ?"; @@ -82,7 +85,8 @@ public static UserIdMapping getuseraIdMappingWithSuperTokensUserId(Start start, }); } - public static UserIdMapping getUserIdMappingWithExternalUserId(Start start, AppIdentifier appIdentifier, String userId) + public static UserIdMapping getUserIdMappingWithExternalUserId(Start start, AppIdentifier appIdentifier, + String userId) throws SQLException, StorageQueryException { String QUERY = "SELECT * FROM " + Config.getConfig(start).getUserIdMappingTable() + " WHERE app_id = ? AND external_user_id = ?"; @@ -99,7 +103,9 @@ public static UserIdMapping getUserIdMappingWithExternalUserId(Start start, AppI } public static UserIdMapping[] getUserIdMappingWithEitherSuperTokensUserIdOrExternalUserId(Start start, - AppIdentifier appIdentifier, String userId) throws SQLException, StorageQueryException { + AppIdentifier appIdentifier, + String userId) + throws SQLException, StorageQueryException { String QUERY = "SELECT * FROM " + Config.getConfig(start).getUserIdMappingTable() + " WHERE app_id = ? AND (supertokens_user_id = ? OR external_user_id = ?)"; @@ -117,8 +123,11 @@ public static UserIdMapping[] getUserIdMappingWithEitherSuperTokensUserIdOrExter } - public static UserIdMapping[] getUserIdMappingWithEitherSuperTokensUserIdOrExternalUserId_Transaction(Start start, Connection sqlCon, - AppIdentifier appIdentifier, String userId) throws SQLException, StorageQueryException { + public static UserIdMapping[] getUserIdMappingWithEitherSuperTokensUserIdOrExternalUserId_Transaction(Start start, + Connection sqlCon, + AppIdentifier appIdentifier, + String userId) + throws SQLException, StorageQueryException { String QUERY = "SELECT * FROM " + Config.getConfig(start).getUserIdMappingTable() + " WHERE app_id = ? AND (supertokens_user_id = ? OR external_user_id = ?)"; @@ -209,7 +218,8 @@ public static HashMap getUserIdMappingWithUserIds_Transaction(St }); } - public static boolean deleteUserIdMappingWithSuperTokensUserId(Start start, AppIdentifier appIdentifier, String userId) + public static boolean deleteUserIdMappingWithSuperTokensUserId(Start start, AppIdentifier appIdentifier, + String userId) throws SQLException, StorageQueryException { String QUERY = "DELETE FROM " + Config.getConfig(start).getUserIdMappingTable() + " WHERE app_id = ? AND supertokens_user_id = ?"; @@ -225,7 +235,8 @@ public static boolean deleteUserIdMappingWithSuperTokensUserId(Start start, AppI public static boolean deleteUserIdMappingWithExternalUserId(Start start, AppIdentifier appIdentifier, String userId) throws SQLException, StorageQueryException { - String QUERY = "DELETE FROM " + Config.getConfig(start).getUserIdMappingTable() + " WHERE app_id = ? AND external_user_id = ?"; + String QUERY = "DELETE FROM " + Config.getConfig(start).getUserIdMappingTable() + + " WHERE app_id = ? AND external_user_id = ?"; // store the number of rows updated int rowUpdatedCount = update(start, QUERY, pst -> { @@ -237,8 +248,10 @@ public static boolean deleteUserIdMappingWithExternalUserId(Start start, AppIden } public static boolean updateOrDeleteExternalUserIdInfoWithSuperTokensUserId(Start start, - AppIdentifier appIdentifier, String userId, - @Nullable String externalUserIdInfo) throws SQLException, StorageQueryException { + AppIdentifier appIdentifier, + String userId, + @Nullable String externalUserIdInfo) + throws SQLException, StorageQueryException { String QUERY = "UPDATE " + Config.getConfig(start).getUserIdMappingTable() + " SET external_user_id_info = ? WHERE app_id = ? AND supertokens_user_id = ?"; @@ -253,7 +266,8 @@ public static boolean updateOrDeleteExternalUserIdInfoWithSuperTokensUserId(Star public static boolean updateOrDeleteExternalUserIdInfoWithExternalUserId(Start start, AppIdentifier appIdentifier, String userId, - @Nullable String externalUserIdInfo) throws SQLException, StorageQueryException { + @Nullable String externalUserIdInfo) + throws SQLException, StorageQueryException { String QUERY = "UPDATE " + Config.getConfig(start).getUserIdMappingTable() + " SET external_user_id_info = ? WHERE app_id = ? AND external_user_id = ?"; @@ -266,7 +280,9 @@ public static boolean updateOrDeleteExternalUserIdInfoWithExternalUserId(Start s return rowUpdated > 0; } - public static UserIdMapping getuseraIdMappingWithSuperTokensUserId_Transaction(Start start, Connection sqlCon, AppIdentifier appIdentifier, String userId) + public static UserIdMapping getuseraIdMappingWithSuperTokensUserId_Transaction(Start start, Connection sqlCon, + AppIdentifier appIdentifier, + String userId) throws SQLException, StorageQueryException { String QUERY = "SELECT * FROM " + Config.getConfig(start).getUserIdMappingTable() + " WHERE app_id = ? AND supertokens_user_id = ?"; @@ -281,7 +297,9 @@ public static UserIdMapping getuseraIdMappingWithSuperTokensUserId_Transaction(S }); } - public static UserIdMapping getUserIdMappingWithExternalUserId_Transaction(Start start, Connection sqlCon, AppIdentifier appIdentifier, String userId) + public static UserIdMapping getUserIdMappingWithExternalUserId_Transaction(Start start, Connection sqlCon, + AppIdentifier appIdentifier, + String userId) throws SQLException, StorageQueryException { String QUERY = "SELECT * FROM " + Config.getConfig(start).getUserIdMappingTable() + " WHERE app_id = ? AND external_user_id = ?"; diff --git a/src/main/java/io/supertokens/inmemorydb/queries/UserMetadataQueries.java b/src/main/java/io/supertokens/inmemorydb/queries/UserMetadataQueries.java index bbdb4d9c3..b8267febb 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/UserMetadataQueries.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/UserMetadataQueries.java @@ -89,7 +89,8 @@ public static int setUserMetadata_Transaction(Start start, Connection con, AppId public static JsonObject getUserMetadata_Transaction(Start start, Connection con, AppIdentifier appIdentifier, String userId) throws SQLException, StorageQueryException { - ((ConnectionWithLocks) con).lock(appIdentifier.getAppId() + "~" + userId + Config.getConfig(start).getUserMetadataTable()); + ((ConnectionWithLocks) con).lock( + appIdentifier.getAppId() + "~" + userId + Config.getConfig(start).getUserMetadataTable()); String QUERY = "SELECT user_metadata FROM " + getConfig(start).getUserMetadataTable() + " WHERE app_id = ? AND user_id = ?"; diff --git a/src/main/java/io/supertokens/inmemorydb/queries/UserRolesQueries.java b/src/main/java/io/supertokens/inmemorydb/queries/UserRolesQueries.java index 5c954ad46..a382361cf 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/UserRolesQueries.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/UserRolesQueries.java @@ -41,7 +41,8 @@ public static String getQueryToCreateRolesTable(Start start) { + "app_id VARCHAR(64) DEFAULT 'public'," + "role VARCHAR(255) NOT NULL," + "PRIMARY KEY(app_id, role)," - + "CONSTRAINT " + tableName + "_app_id_fkey FOREIGN KEY (app_id) REFERENCES " + Config.getConfig(start).getAppsTable() + + "CONSTRAINT " + tableName + "_app_id_fkey FOREIGN KEY (app_id) REFERENCES " + + Config.getConfig(start).getAppsTable() + " (app_id) ON DELETE CASCADE" + ");"; // @formatter:on @@ -112,13 +113,14 @@ public static void addPermissionToRoleOrDoNothingIfExists_Transaction(Start star } public static boolean deleteRole(Start start, AppIdentifier appIdentifier, - String role) throws SQLException, StorageQueryException { + String role) throws SQLException, StorageQueryException { try { return start.startTransaction(con -> { // Row lock must be taken to delete the role, otherwise the table may be locked for delete Connection sqlCon = (Connection) con.getConnection(); - ((ConnectionWithLocks) sqlCon).lock(appIdentifier.getAppId() + "~" + role + Config.getConfig(start).getRolesTable()); + ((ConnectionWithLocks) sqlCon).lock( + appIdentifier.getAppId() + "~" + role + Config.getConfig(start).getRolesTable()); String QUERY = "DELETE FROM " + getConfig(start).getRolesTable() + " WHERE app_id = ? AND role = ? ;"; @@ -241,7 +243,8 @@ public static boolean deleteRoleForUser_Transaction(Start start, Connection con, public static boolean doesRoleExist_transaction(Start start, Connection con, AppIdentifier appIdentifier, String role) throws SQLException, StorageQueryException { - ((ConnectionWithLocks) con).lock(appIdentifier.getAppId() + "~" + role + Config.getConfig(start).getRolesTable()); + ((ConnectionWithLocks) con).lock( + appIdentifier.getAppId() + "~" + role + Config.getConfig(start).getRolesTable()); String QUERY = "SELECT 1 FROM " + getConfig(start).getRolesTable() + " WHERE app_id = ? AND role = ?"; diff --git a/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/MfaSqlHelper.java b/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/MfaSqlHelper.java index c1a65585f..1c94e92e2 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/MfaSqlHelper.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/MfaSqlHelper.java @@ -33,11 +33,13 @@ public static HashMap selectAllFirstFactors(Start st throws SQLException, StorageQueryException { String QUERY = "SELECT connection_uri_domain, app_id, tenant_id, factor_id FROM " + Config.getConfig(start).getTenantFirstFactorsTable() + ";"; - return execute(start, QUERY, pst -> {}, result -> { + return execute(start, QUERY, pst -> { + }, result -> { HashMap> firstFactors = new HashMap<>(); while (result.next()) { - TenantIdentifier tenantIdentifier = new TenantIdentifier(result.getString("connection_uri_domain"), result.getString("app_id"), result.getString("tenant_id")); + TenantIdentifier tenantIdentifier = new TenantIdentifier(result.getString("connection_uri_domain"), + result.getString("app_id"), result.getString("tenant_id")); if (!firstFactors.containsKey(tenantIdentifier)) { firstFactors.put(tenantIdentifier, new ArrayList<>()); } @@ -58,7 +60,8 @@ public static HashMap selectAllRequiredSecondaryFact throws SQLException, StorageQueryException { String QUERY = "SELECT connection_uri_domain, app_id, tenant_id, factor_id FROM " + Config.getConfig(start).getTenantRequiredSecondaryFactorsTable() + ";"; - return execute(start, QUERY, pst -> {}, result -> { + return execute(start, QUERY, pst -> { + }, result -> { HashMap> defaultRequiredFactors = new HashMap<>(); while (result.next()) { @@ -80,13 +83,15 @@ public static HashMap selectAllRequiredSecondaryFact }); } - public static void createFirstFactors(Start start, Connection sqlCon, TenantIdentifier tenantIdentifier, String[] firstFactors) + public static void createFirstFactors(Start start, Connection sqlCon, TenantIdentifier tenantIdentifier, + String[] firstFactors) throws SQLException, StorageQueryException { if (firstFactors == null || firstFactors.length == 0) { return; } - String QUERY = "INSERT INTO " + Config.getConfig(start).getTenantFirstFactorsTable() + "(connection_uri_domain, app_id, tenant_id, factor_id) VALUES (?, ?, ?, ?);"; + String QUERY = "INSERT INTO " + Config.getConfig(start).getTenantFirstFactorsTable() + + "(connection_uri_domain, app_id, tenant_id, factor_id) VALUES (?, ?, ?, ?);"; for (String factorId : new HashSet<>(Arrays.asList(firstFactors))) { update(sqlCon, QUERY, pst -> { pst.setString(1, tenantIdentifier.getConnectionUriDomain()); @@ -97,13 +102,15 @@ public static void createFirstFactors(Start start, Connection sqlCon, TenantIden } } - public static void createRequiredSecondaryFactors(Start start, Connection sqlCon, TenantIdentifier tenantIdentifier, String[] requiredSecondaryFactors) + public static void createRequiredSecondaryFactors(Start start, Connection sqlCon, TenantIdentifier tenantIdentifier, + String[] requiredSecondaryFactors) throws SQLException, StorageQueryException { if (requiredSecondaryFactors == null || requiredSecondaryFactors.length == 0) { return; } - String QUERY = "INSERT INTO " + Config.getConfig(start).getTenantRequiredSecondaryFactorsTable() + "(connection_uri_domain, app_id, tenant_id, factor_id) VALUES (?, ?, ?, ?);"; + String QUERY = "INSERT INTO " + Config.getConfig(start).getTenantRequiredSecondaryFactorsTable() + + "(connection_uri_domain, app_id, tenant_id, factor_id) VALUES (?, ?, ?, ?);"; for (String factorId : requiredSecondaryFactors) { update(sqlCon, QUERY, pst -> { pst.setString(1, tenantIdentifier.getConnectionUriDomain()); diff --git a/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/TenantConfigSQLHelper.java b/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/TenantConfigSQLHelper.java index e46a36215..fb797f30b 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/TenantConfigSQLHelper.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/TenantConfigSQLHelper.java @@ -39,13 +39,15 @@ public static class TenantConfigRowMapper implements RowMapper> providerMap, HashMap firstFactorsMap, HashMap requiredSecondaryFactorsMap) + public static TenantConfig[] selectAll(Start start, + HashMap> providerMap, + HashMap firstFactorsMap, + HashMap requiredSecondaryFactorsMap) throws SQLException, StorageQueryException { String QUERY = "SELECT connection_uri_domain, app_id, tenant_id, core_config, " + " email_password_enabled, passwordless_enabled, third_party_enabled, " + " is_first_factors_null FROM " + Config.getConfig(start).getTenantConfigsTable() + ";"; - TenantConfig[] tenantConfigs = execute(start, QUERY, pst -> {}, result -> { + TenantConfig[] tenantConfigs = execute(start, QUERY, pst -> { + }, result -> { List temp = new ArrayList<>(); while (result.next()) { - TenantIdentifier tenantIdentifier = new TenantIdentifier(result.getString("connection_uri_domain"), result.getString("app_id"), result.getString("tenant_id")); + TenantIdentifier tenantIdentifier = new TenantIdentifier(result.getString("connection_uri_domain"), + result.getString("app_id"), result.getString("tenant_id")); ThirdPartyConfig.Provider[] providers; if (providerMap.containsKey(tenantIdentifier)) { providers = providerMap.get(tenantIdentifier).values().toArray(new ThirdPartyConfig.Provider[0]); } else { providers = new ThirdPartyConfig.Provider[0]; } - String[] firstFactors = firstFactorsMap.containsKey(tenantIdentifier) ? firstFactorsMap.get(tenantIdentifier) : new String[0]; + String[] firstFactors = + firstFactorsMap.containsKey(tenantIdentifier) ? firstFactorsMap.get(tenantIdentifier) : + new String[0]; - String[] requiredSecondaryFactors = requiredSecondaryFactorsMap.containsKey(tenantIdentifier) ? requiredSecondaryFactorsMap.get(tenantIdentifier) : new String[0]; + String[] requiredSecondaryFactors = requiredSecondaryFactorsMap.containsKey(tenantIdentifier) ? + requiredSecondaryFactorsMap.get(tenantIdentifier) : new String[0]; - temp.add(TenantConfigRowMapper.getInstance(providers, firstFactors, requiredSecondaryFactors).mapOrThrow(result)); + temp.add(TenantConfigRowMapper.getInstance(providers, firstFactors, requiredSecondaryFactors) + .mapOrThrow(result)); } TenantConfig[] finalResult = new TenantConfig[temp.size()]; for (int i = 0; i < temp.size(); i++) { diff --git a/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/ThirdPartyProviderClientSQLHelper.java b/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/ThirdPartyProviderClientSQLHelper.java index 948d6be0c..0441a5e79 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/ThirdPartyProviderClientSQLHelper.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/ThirdPartyProviderClientSQLHelper.java @@ -38,7 +38,8 @@ public class ThirdPartyProviderClientSQLHelper { public static class TenantThirdPartyProviderClientRowMapper implements RowMapper { - public static final TenantThirdPartyProviderClientRowMapper INSTANCE = new TenantThirdPartyProviderClientRowMapper(); + public static final TenantThirdPartyProviderClientRowMapper INSTANCE = + new TenantThirdPartyProviderClientRowMapper(); private TenantThirdPartyProviderClientRowMapper() { } @@ -57,7 +58,7 @@ public ThirdPartyConfig.ProviderClient map(ResultSet result) throws StorageQuery } else { JsonArray scopeArray = new Gson().fromJson(scopeArrayStr, JsonArray.class); scopeStringArray = new String[scopeArray.size()]; - for (int i=0; i < scopeArray.size(); i++) { + for (int i = 0; i < scopeArray.size(); i++) { scopeStringArray[i] = scopeArray.get(i).getAsString(); } } @@ -83,37 +84,47 @@ public ThirdPartyConfig.ProviderClient map(ResultSet result) throws StorageQuery } } - public static HashMap>> selectAll(Start start) + public static HashMap>> selectAll( + Start start) throws SQLException, StorageQueryException { HashMap>> providerClientsMap = new HashMap<>(); - String QUERY = "SELECT connection_uri_domain, app_id, tenant_id, third_party_id, client_type, client_id, client_secret, scope, force_pkce, additional_config FROM " - + Config.getConfig(start).getTenantThirdPartyProviderClientsTable() + ";"; + String QUERY = + "SELECT connection_uri_domain, app_id, tenant_id, third_party_id, client_type, client_id, " + + "client_secret, scope, force_pkce, additional_config FROM " + + Config.getConfig(start).getTenantThirdPartyProviderClientsTable() + ";"; - execute(start, QUERY, pst -> {}, result -> { + execute(start, QUERY, pst -> { + }, result -> { while (result.next()) { - TenantIdentifier tenantIdentifier = new TenantIdentifier(result.getString("connection_uri_domain"), result.getString("app_id"), result.getString("tenant_id")); - ThirdPartyConfig.ProviderClient providerClient = TenantThirdPartyProviderClientRowMapper.getInstance().mapOrThrow(result); + TenantIdentifier tenantIdentifier = new TenantIdentifier(result.getString("connection_uri_domain"), + result.getString("app_id"), result.getString("tenant_id")); + ThirdPartyConfig.ProviderClient providerClient = TenantThirdPartyProviderClientRowMapper.getInstance() + .mapOrThrow(result); if (!providerClientsMap.containsKey(tenantIdentifier)) { providerClientsMap.put(tenantIdentifier, new HashMap<>()); } - if(!providerClientsMap.get(tenantIdentifier).containsKey(result.getString("third_party_id"))) { + if (!providerClientsMap.get(tenantIdentifier).containsKey(result.getString("third_party_id"))) { providerClientsMap.get(tenantIdentifier).put(result.getString("third_party_id"), new HashMap<>()); } - providerClientsMap.get(tenantIdentifier).get(result.getString("third_party_id")).put(providerClient.clientType, providerClient); + providerClientsMap.get(tenantIdentifier).get(result.getString("third_party_id")) + .put(providerClient.clientType, providerClient); } return null; }); return providerClientsMap; } - public static void create(Start start, Connection sqlCon, TenantConfig tenantConfig, ThirdPartyConfig.Provider provider, ThirdPartyConfig.ProviderClient providerClient) + public static void create(Start start, Connection sqlCon, TenantConfig tenantConfig, + ThirdPartyConfig.Provider provider, ThirdPartyConfig.ProviderClient providerClient) throws SQLException, StorageQueryException { String QUERY = "INSERT INTO " + Config.getConfig(start).getTenantThirdPartyProviderClientsTable() - + "(connection_uri_domain, app_id, tenant_id, third_party_id, client_type, client_id, client_secret, scope, force_pkce, additional_config)" + + + "(connection_uri_domain, app_id, tenant_id, third_party_id, client_type, client_id, client_secret, " + + "scope, force_pkce, additional_config)" + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; String scopeArrayStr; diff --git a/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/ThirdPartyProviderSQLHelper.java b/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/ThirdPartyProviderSQLHelper.java index e80f62627..5b13d6350 100644 --- a/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/ThirdPartyProviderSQLHelper.java +++ b/src/main/java/io/supertokens/inmemorydb/queries/multitenancy/ThirdPartyProviderSQLHelper.java @@ -85,21 +85,35 @@ public ThirdPartyConfig.Provider map(ResultSet result) throws StorageQueryExcept } } - public static HashMap> selectAll(Start start, HashMap>> providerClientsMap) + public static HashMap> selectAll(Start start, + HashMap>> providerClientsMap) throws SQLException, StorageQueryException { HashMap> providerMap = new HashMap<>(); - String QUERY = "SELECT connection_uri_domain, app_id, tenant_id, third_party_id, name, authorization_endpoint, authorization_endpoint_query_params, token_endpoint, token_endpoint_body_params, user_info_endpoint, user_info_endpoint_query_params, user_info_endpoint_headers, jwks_uri, oidc_discovery_endpoint, require_email, user_info_map_from_id_token_payload_user_id, user_info_map_from_id_token_payload_email, user_info_map_from_id_token_payload_email_verified, user_info_map_from_user_info_endpoint_user_id, user_info_map_from_user_info_endpoint_email, user_info_map_from_user_info_endpoint_email_verified FROM " - + Config.getConfig(start).getTenantThirdPartyProvidersTable() + ";"; + String QUERY = + "SELECT connection_uri_domain, app_id, tenant_id, third_party_id, name, authorization_endpoint, " + + "authorization_endpoint_query_params, token_endpoint, token_endpoint_body_params, " + + "user_info_endpoint, user_info_endpoint_query_params, user_info_endpoint_headers, jwks_uri, " + + "oidc_discovery_endpoint, require_email, user_info_map_from_id_token_payload_user_id, " + + "user_info_map_from_id_token_payload_email, " + + "user_info_map_from_id_token_payload_email_verified, " + + "user_info_map_from_user_info_endpoint_user_id, user_info_map_from_user_info_endpoint_email, " + + "user_info_map_from_user_info_endpoint_email_verified FROM " + + Config.getConfig(start).getTenantThirdPartyProvidersTable() + ";"; - execute(start, QUERY, pst -> {}, result -> { + execute(start, QUERY, pst -> { + }, result -> { while (result.next()) { - TenantIdentifier tenantIdentifier = new TenantIdentifier(result.getString("connection_uri_domain"), result.getString("app_id"), result.getString("tenant_id")); + TenantIdentifier tenantIdentifier = new TenantIdentifier(result.getString("connection_uri_domain"), + result.getString("app_id"), result.getString("tenant_id")); ThirdPartyConfig.ProviderClient[] clients = null; - if (providerClientsMap.containsKey(tenantIdentifier) && providerClientsMap.get(tenantIdentifier).containsKey(result.getString("third_party_id"))) { - clients = providerClientsMap.get(tenantIdentifier).get(result.getString("third_party_id")).values().toArray(new ThirdPartyConfig.ProviderClient[0]); + if (providerClientsMap.containsKey(tenantIdentifier) && + providerClientsMap.get(tenantIdentifier).containsKey(result.getString("third_party_id"))) { + clients = providerClientsMap.get(tenantIdentifier).get(result.getString("third_party_id")).values() + .toArray(new ThirdPartyConfig.ProviderClient[0]); } - ThirdPartyConfig.Provider provider = TenantThirdPartyProviderRowMapper.getInstance(clients).mapOrThrow(result); + ThirdPartyConfig.Provider provider = TenantThirdPartyProviderRowMapper.getInstance(clients) + .mapOrThrow(result); if (!providerMap.containsKey(tenantIdentifier)) { providerMap.put(tenantIdentifier, new HashMap<>()); @@ -111,10 +125,19 @@ public static HashMap { pst.setString(1, tenantConfig.tenantIdentifier.getConnectionUriDomain()); diff --git a/src/main/java/io/supertokens/jwt/JWTSigningFunctions.java b/src/main/java/io/supertokens/jwt/JWTSigningFunctions.java index d4e5a813a..8ba7714e9 100644 --- a/src/main/java/io/supertokens/jwt/JWTSigningFunctions.java +++ b/src/main/java/io/supertokens/jwt/JWTSigningFunctions.java @@ -127,7 +127,7 @@ public static String createJWTToken(JWTSigningKey.SupportedAlgorithms supportedA headerClaims.put("kid", keyToUse.keyId); // Add relevant claims to the payload, note we only add/override ones that we absolutely need to. - if (jwksDomain != null && !payload.has("iss")){ + if (jwksDomain != null && !payload.has("iss")) { payload.addProperty("iss", jwksDomain); } diff --git a/src/main/java/io/supertokens/multitenancy/Multitenancy.java b/src/main/java/io/supertokens/multitenancy/Multitenancy.java index 1de5eb3f1..ee4a2580e 100644 --- a/src/main/java/io/supertokens/multitenancy/Multitenancy.java +++ b/src/main/java/io/supertokens/multitenancy/Multitenancy.java @@ -407,7 +407,8 @@ public static boolean addUserIdToTenant(Main main, TenantIdentifier tenantIdenti try { return authRecipeStorage.startTransaction(con -> { String tenantId = tenantIdentifier.getTenantId(); - AuthRecipeUserInfo userToAssociate = authRecipeStorage.getPrimaryUserById_Transaction(tenantIdentifier.toAppIdentifier(), con, userId); + AuthRecipeUserInfo userToAssociate = authRecipeStorage.getPrimaryUserById_Transaction( + tenantIdentifier.toAppIdentifier(), con, userId); if (userToAssociate != null && userToAssociate.isPrimaryUser) { Set emails = new HashSet<>(); @@ -428,65 +429,89 @@ public static boolean addUserIdToTenant(Main main, TenantIdentifier tenantIdenti } for (String email : emails) { - AuthRecipeUserInfo[] usersWithSameEmail = authRecipeStorage.listPrimaryUsersByEmail_Transaction(tenantIdentifier.toAppIdentifier(), con, email); + AuthRecipeUserInfo[] usersWithSameEmail = authRecipeStorage.listPrimaryUsersByEmail_Transaction( + tenantIdentifier.toAppIdentifier(), con, email); for (AuthRecipeUserInfo userWithSameEmail : usersWithSameEmail) { - if (userWithSameEmail.getSupertokensUserId().equals(userToAssociate.getSupertokensUserId())) { + if (userWithSameEmail.getSupertokensUserId() + .equals(userToAssociate.getSupertokensUserId())) { continue; // it's the same user, no need to check anything } - if (userWithSameEmail.isPrimaryUser && userWithSameEmail.tenantIds.contains(tenantId) && !userWithSameEmail.getSupertokensUserId().equals(userId)) { + if (userWithSameEmail.isPrimaryUser && userWithSameEmail.tenantIds.contains(tenantId) && + !userWithSameEmail.getSupertokensUserId().equals(userId)) { for (LoginMethod lm1 : userWithSameEmail.loginMethods) { if (lm1.tenantIds.contains(tenantId)) { for (LoginMethod lm2 : userToAssociate.loginMethods) { - if (lm1.recipeId.equals(lm2.recipeId) && email.equals(lm1.email) && lm1.email.equals(lm2.email)) { - throw new StorageTransactionLogicException(new DuplicateEmailException()); + if (lm1.recipeId.equals(lm2.recipeId) && email.equals(lm1.email) && + lm1.email.equals(lm2.email)) { + throw new StorageTransactionLogicException( + new DuplicateEmailException()); } } } } - throw new StorageTransactionLogicException(new AnotherPrimaryUserWithEmailAlreadyExistsException(userWithSameEmail.getSupertokensUserId())); + throw new StorageTransactionLogicException( + new AnotherPrimaryUserWithEmailAlreadyExistsException( + userWithSameEmail.getSupertokensUserId())); } } } for (String phoneNumber : phoneNumbers) { - AuthRecipeUserInfo[] usersWithSamePhoneNumber = authRecipeStorage.listPrimaryUsersByPhoneNumber_Transaction(tenantIdentifier.toAppIdentifier(), con, phoneNumber); + AuthRecipeUserInfo[] usersWithSamePhoneNumber = + authRecipeStorage.listPrimaryUsersByPhoneNumber_Transaction( + tenantIdentifier.toAppIdentifier(), con, phoneNumber); for (AuthRecipeUserInfo userWithSamePhoneNumber : usersWithSamePhoneNumber) { - if (userWithSamePhoneNumber.getSupertokensUserId().equals(userToAssociate.getSupertokensUserId())) { + if (userWithSamePhoneNumber.getSupertokensUserId() + .equals(userToAssociate.getSupertokensUserId())) { continue; // it's the same user, no need to check anything } - if (userWithSamePhoneNumber.tenantIds.contains(tenantId) && !userWithSamePhoneNumber.getSupertokensUserId().equals(userId)) { + if (userWithSamePhoneNumber.tenantIds.contains(tenantId) && + !userWithSamePhoneNumber.getSupertokensUserId().equals(userId)) { for (LoginMethod lm1 : userWithSamePhoneNumber.loginMethods) { if (lm1.tenantIds.contains(tenantId)) { for (LoginMethod lm2 : userToAssociate.loginMethods) { - if (lm1.recipeId.equals(lm2.recipeId) && phoneNumber.equals(lm1.phoneNumber) && lm1.phoneNumber.equals(lm2.phoneNumber)) { - throw new StorageTransactionLogicException(new DuplicatePhoneNumberException()); + if (lm1.recipeId.equals(lm2.recipeId) && + phoneNumber.equals(lm1.phoneNumber) && + lm1.phoneNumber.equals(lm2.phoneNumber)) { + throw new StorageTransactionLogicException( + new DuplicatePhoneNumberException()); } } } } - throw new StorageTransactionLogicException(new AnotherPrimaryUserWithPhoneNumberAlreadyExistsException(userWithSamePhoneNumber.getSupertokensUserId())); + throw new StorageTransactionLogicException( + new AnotherPrimaryUserWithPhoneNumberAlreadyExistsException( + userWithSamePhoneNumber.getSupertokensUserId())); } } } for (LoginMethod.ThirdParty tp : thirdParties) { - AuthRecipeUserInfo[] usersWithSameThirdPartyInfo = authRecipeStorage.listPrimaryUsersByThirdPartyInfo_Transaction(tenantIdentifier.toAppIdentifier(), con, tp.id, tp.userId); + AuthRecipeUserInfo[] usersWithSameThirdPartyInfo = + authRecipeStorage.listPrimaryUsersByThirdPartyInfo_Transaction( + tenantIdentifier.toAppIdentifier(), con, tp.id, tp.userId); for (AuthRecipeUserInfo userWithSameThirdPartyInfo : usersWithSameThirdPartyInfo) { - if (userWithSameThirdPartyInfo.getSupertokensUserId().equals(userToAssociate.getSupertokensUserId())) { + if (userWithSameThirdPartyInfo.getSupertokensUserId() + .equals(userToAssociate.getSupertokensUserId())) { continue; // it's the same user, no need to check anything } - if (userWithSameThirdPartyInfo.tenantIds.contains(tenantId) && !userWithSameThirdPartyInfo.getSupertokensUserId().equals(userId)) { + if (userWithSameThirdPartyInfo.tenantIds.contains(tenantId) && + !userWithSameThirdPartyInfo.getSupertokensUserId().equals(userId)) { for (LoginMethod lm1 : userWithSameThirdPartyInfo.loginMethods) { if (lm1.tenantIds.contains(tenantId)) { for (LoginMethod lm2 : userToAssociate.loginMethods) { - if (lm1.recipeId.equals(lm2.recipeId) && tp.equals(lm1.thirdParty) && lm1.thirdParty.equals(lm2.thirdParty)) { - throw new StorageTransactionLogicException(new DuplicateThirdPartyUserException()); + if (lm1.recipeId.equals(lm2.recipeId) && tp.equals(lm1.thirdParty) && + lm1.thirdParty.equals(lm2.thirdParty)) { + throw new StorageTransactionLogicException( + new DuplicateThirdPartyUserException()); } } } } - throw new StorageTransactionLogicException(new AnotherPrimaryUserWithThirdPartyInfoAlreadyExistsException(userWithSameThirdPartyInfo.getSupertokensUserId())); + throw new StorageTransactionLogicException( + new AnotherPrimaryUserWithThirdPartyInfoAlreadyExistsException( + userWithSameThirdPartyInfo.getSupertokensUserId())); } } } @@ -496,7 +521,8 @@ public static boolean addUserIdToTenant(Main main, TenantIdentifier tenantIdenti // associate it. This happens only in CDI 3.0 where we allow disassociation from all tenants // This will not happen in CDI >= 4.0 because we will not allow disassociation from all tenants try { - boolean result = ((MultitenancySQLStorage) storage).addUserIdToTenant_Transaction(tenantIdentifier, con, userId); + boolean result = ((MultitenancySQLStorage) storage).addUserIdToTenant_Transaction(tenantIdentifier, + con, userId); authRecipeStorage.commitTransaction(con); return result; } catch (TenantOrAppNotFoundException | UnknownUserIdException | DuplicatePhoneNumberException | @@ -606,7 +632,8 @@ public static TenantConfig[] getAllTenants(Main main) { return MultitenancyHelper.getInstance(main).getAllTenants(); } - public static void saveWebsiteAndAPIDomainForApp(Storage storage, AppIdentifier appIdentifier, String websiteDomain, String apiDomain) + public static void saveWebsiteAndAPIDomainForApp(Storage storage, AppIdentifier appIdentifier, String websiteDomain, + String apiDomain) throws StorageQueryException, TenantOrAppNotFoundException { if (websiteDomain != null) { storage.setKeyValue(appIdentifier.getAsPublicTenantIdentifier(), "websiteDomain", diff --git a/src/main/java/io/supertokens/multitenancy/MultitenancyHelper.java b/src/main/java/io/supertokens/multitenancy/MultitenancyHelper.java index 6d542c0b9..ee9ec977e 100644 --- a/src/main/java/io/supertokens/multitenancy/MultitenancyHelper.java +++ b/src/main/java/io/supertokens/multitenancy/MultitenancyHelper.java @@ -126,11 +126,11 @@ public List refreshTenantsInCoreBasedOnChangesInCoreConfigOrIf Map normalizedTenantsFromDb = Config.getNormalisedConfigsForAllTenants( - filteredTenantsFromDb, Config.getBaseConfigAsJsonObject(main)); + filteredTenantsFromDb, Config.getBaseConfigAsJsonObject(main)); Map normalizedTenantsFromMemory = Config.getNormalisedConfigsForAllTenants( - this.tenantConfigs, Config.getBaseConfigAsJsonObject(main)); + this.tenantConfigs, Config.getBaseConfigAsJsonObject(main)); List tenantsThatChanged = new ArrayList<>(); @@ -268,7 +268,8 @@ private TenantConfig[] getFilteredTenantConfigs(TenantConfig[] inputTenantConfig return Arrays.stream(inputTenantConfigs) .filter(tenantConfig -> tenantConfig.tenantIdentifier.getConnectionUriDomain().equals(loadOnlyCUD) - || tenantConfig.tenantIdentifier.getConnectionUriDomain().equals(TenantIdentifier.DEFAULT_CONNECTION_URI)) + || tenantConfig.tenantIdentifier.getConnectionUriDomain() + .equals(TenantIdentifier.DEFAULT_CONNECTION_URI)) .toArray(TenantConfig[]::new); } diff --git a/src/main/java/io/supertokens/output/Logging.java b/src/main/java/io/supertokens/output/Logging.java index d3c89f1fb..0443cc002 100644 --- a/src/main/java/io/supertokens/output/Logging.java +++ b/src/main/java/io/supertokens/output/Logging.java @@ -235,7 +235,8 @@ public static void stopLogging(Main main) { private Logger createLoggerForFile(Main main, String file, String name) { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - LayoutWrappingEncoder ple = new LayoutWrappingEncoder(main.getProcessId(), Version.getVersion(main).getCoreVersion()); + LayoutWrappingEncoder ple = new LayoutWrappingEncoder(main.getProcessId(), + Version.getVersion(main).getCoreVersion()); ple.setContext(lc); ple.start(); FileAppender fileAppender = new FileAppender<>(); @@ -253,7 +254,8 @@ private Logger createLoggerForFile(Main main, String file, String name) { private Logger createLoggerForConsole(Main main, String name, LOG_LEVEL logLevel) { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); - LayoutWrappingEncoder ple = new LayoutWrappingEncoder(main.getProcessId(), Version.getVersion(main).getCoreVersion()); + LayoutWrappingEncoder ple = new LayoutWrappingEncoder(main.getProcessId(), + Version.getVersion(main).getCoreVersion()); ple.setContext(lc); ple.start(); ConsoleAppender logConsoleAppender = new ConsoleAppender<>(); diff --git a/src/main/java/io/supertokens/passwordless/Passwordless.java b/src/main/java/io/supertokens/passwordless/Passwordless.java index 5e026c706..9b5753c4c 100644 --- a/src/main/java/io/supertokens/passwordless/Passwordless.java +++ b/src/main/java/io/supertokens/passwordless/Passwordless.java @@ -285,7 +285,8 @@ public static ConsumeCodeResponse consumeCode(TenantIdentifier tenantIdentifier, false); } - public static PasswordlessDevice checkCodeAndReturnDevice(TenantIdentifier tenantIdentifier, Storage storage, Main main, + public static PasswordlessDevice checkCodeAndReturnDevice(TenantIdentifier tenantIdentifier, Storage storage, + Main main, String deviceId, String deviceIdHashFromUser, String userInputCode, String linkCode, boolean deleteCodeOnSuccess) @@ -418,7 +419,8 @@ public static ConsumeCodeResponse consumeCode(TenantIdentifier tenantIdentifier, PasswordlessSQLStorage passwordlessStorage = StorageUtils.getPasswordlessStorage(storage); - PasswordlessDevice consumedDevice = checkCodeAndReturnDevice(tenantIdentifier, storage, main, deviceId, deviceIdHashFromUser, + PasswordlessDevice consumedDevice = checkCodeAndReturnDevice(tenantIdentifier, storage, main, deviceId, + deviceIdHashFromUser, userInputCode, linkCode, true); // Getting here means that we successfully consumed the code @@ -429,7 +431,9 @@ public static ConsumeCodeResponse consumeCode(TenantIdentifier tenantIdentifier, consumedDevice.email); for (AuthRecipeUserInfo currUser : users) { for (LoginMethod currLM : currUser.loginMethods) { - if (currLM.recipeId == RECIPE_ID.PASSWORDLESS && currLM.email != null && currLM.email.equals(consumedDevice.email) && currLM.tenantIds.contains(tenantIdentifier.getTenantId())) { + if (currLM.recipeId == RECIPE_ID.PASSWORDLESS && currLM.email != null && + currLM.email.equals(consumedDevice.email) && + currLM.tenantIds.contains(tenantIdentifier.getTenantId())) { user = currUser; loginMethod = currLM; break; @@ -442,7 +446,8 @@ public static ConsumeCodeResponse consumeCode(TenantIdentifier tenantIdentifier, for (AuthRecipeUserInfo currUser : users) { for (LoginMethod currLM : currUser.loginMethods) { if (currLM.recipeId == RECIPE_ID.PASSWORDLESS && - currLM.phoneNumber != null && currLM.phoneNumber.equals(consumedDevice.phoneNumber) && currLM.tenantIds.contains(tenantIdentifier.getTenantId())) { + currLM.phoneNumber != null && currLM.phoneNumber.equals(consumedDevice.phoneNumber) && + currLM.tenantIds.contains(tenantIdentifier.getTenantId())) { user = currUser; loginMethod = currLM; break; @@ -468,7 +473,7 @@ public static ConsumeCodeResponse consumeCode(TenantIdentifier tenantIdentifier, evStorage.startTransaction(con -> { try { evStorage.updateIsEmailVerified_Transaction(tenantIdentifier.toAppIdentifier(), con, - finalUser.getSupertokensUserId(), consumedDevice.email, true); + finalUser.getSupertokensUserId(), consumedDevice.email, true); evStorage.commitTransaction(con); return null; @@ -485,7 +490,8 @@ public static ConsumeCodeResponse consumeCode(TenantIdentifier tenantIdentifier, } } - return new ConsumeCodeResponse(true, user, consumedDevice.email, consumedDevice.phoneNumber, consumedDevice); + return new ConsumeCodeResponse(true, user, consumedDevice.email, consumedDevice.phoneNumber, + consumedDevice); } catch (DuplicateEmailException | DuplicatePhoneNumberException e) { // Getting these would mean that between getting the user and trying creating it: // 1. the user managed to do a full create+consume flow @@ -733,7 +739,8 @@ public static void updateUser(AppIdentifier appIdentifier, Storage storage, Stri } LoginMethod lM = Arrays.stream(user.loginMethods) - .filter(currlM -> currlM.getSupertokensUserId().equals(recipeUserId) && currlM.recipeId == RECIPE_ID.PASSWORDLESS) + .filter(currlM -> currlM.getSupertokensUserId().equals(recipeUserId) && + currlM.recipeId == RECIPE_ID.PASSWORDLESS) .findFirst().orElse(null); if (lM == null) { @@ -761,7 +768,8 @@ public static void updateUser(AppIdentifier appIdentifier, Storage storage, Stri if (!userWithSameEmail.tenantIds.contains(tenantId)) { continue; } - if (userWithSameEmail.isPrimaryUser && !userWithSameEmail.getSupertokensUserId().equals(user.getSupertokensUserId())) { + if (userWithSameEmail.isPrimaryUser && + !userWithSameEmail.getSupertokensUserId().equals(user.getSupertokensUserId())) { throw new StorageTransactionLogicException( new EmailChangeNotAllowedException()); } @@ -795,7 +803,9 @@ public static void updateUser(AppIdentifier appIdentifier, Storage storage, Stri if (!userWithSamePhoneNumber.tenantIds.contains(tenantId)) { continue; } - if (userWithSamePhoneNumber.isPrimaryUser && !userWithSamePhoneNumber.getSupertokensUserId().equals(user.getSupertokensUserId())) { + if (userWithSamePhoneNumber.isPrimaryUser && + !userWithSamePhoneNumber.getSupertokensUserId() + .equals(user.getSupertokensUserId())) { throw new StorageTransactionLogicException( new PhoneNumberChangeNotAllowedException()); } @@ -894,7 +904,8 @@ public static class ConsumeCodeResponse { public PasswordlessDevice consumedDevice; - public ConsumeCodeResponse(boolean createdNewUser, @Nullable AuthRecipeUserInfo user, String email, String phoneNumber, PasswordlessDevice consumedDevice) { + public ConsumeCodeResponse(boolean createdNewUser, @Nullable AuthRecipeUserInfo user, String email, + String phoneNumber, PasswordlessDevice consumedDevice) { this.createdNewUser = createdNewUser; this.user = user; this.email = email; diff --git a/src/main/java/io/supertokens/session/Session.java b/src/main/java/io/supertokens/session/Session.java index c716ea094..980502228 100644 --- a/src/main/java/io/supertokens/session/Session.java +++ b/src/main/java/io/supertokens/session/Session.java @@ -459,7 +459,8 @@ public static SessionInformationHolder getSession(AppIdentifier appIdentifier, M while (true) { try { - io.supertokens.pluginInterface.session.noSqlStorage.SessionInfoWithLastUpdated sessionInfo = sessionStorage + io.supertokens.pluginInterface.session.noSqlStorage.SessionInfoWithLastUpdated sessionInfo = + sessionStorage .getSessionInfo_Transaction(accessToken.sessionHandle); if (sessionInfo == null) { @@ -539,7 +540,8 @@ public static SessionInformationHolder refreshSession(Main main, @Nonnull String public static SessionInformationHolder refreshSession(AppIdentifier appIdentifier, Main main, @Nonnull String refreshToken, @Nullable String antiCsrfToken, boolean enableAntiCsrf, - AccessToken.VERSION accessTokenVersion, Boolean shouldUseStaticKey) + AccessToken.VERSION accessTokenVersion, + Boolean shouldUseStaticKey) throws StorageTransactionLogicException, UnauthorisedException, StorageQueryException, TokenTheftDetectedException, UnsupportedJWTSigningAlgorithmException, AccessTokenPayloadError, TenantOrAppNotFoundException { @@ -556,7 +558,8 @@ public static SessionInformationHolder refreshSession(AppIdentifier appIdentifie TenantIdentifier tenantIdentifier = refreshTokenInfo.tenantIdentifier; Storage storage = StorageLayer.getStorage(refreshTokenInfo.tenantIdentifier, main); return refreshSessionHelper( - tenantIdentifier, storage, main, refreshToken, refreshTokenInfo, enableAntiCsrf, accessTokenVersion, shouldUseStaticKey); + tenantIdentifier, storage, main, refreshToken, refreshTokenInfo, enableAntiCsrf, accessTokenVersion, + shouldUseStaticKey); } private static SessionInformationHolder refreshSessionHelper( @@ -587,7 +590,8 @@ private static SessionInformationHolder refreshSessionHelper( sessionStorage.commitTransaction(con); throw new UnauthorisedException("Session missing in db or has expired"); } - boolean useStaticKey = shouldUseStaticKey != null ? shouldUseStaticKey : sessionInfo.useStaticKey; + boolean useStaticKey = + shouldUseStaticKey != null ? shouldUseStaticKey : sessionInfo.useStaticKey; if (sessionInfo.refreshTokenHash2.equals(Utils.hashSHA256(Utils.hashSHA256(refreshToken)))) { if (useStaticKey != sessionInfo.useStaticKey) { @@ -631,7 +635,8 @@ private static SessionInformationHolder refreshSessionHelper( .equals(sessionInfo.refreshTokenHash2))) { sessionStorage.updateSessionInfo_Transaction(tenantIdentifier, con, sessionHandle, Utils.hashSHA256(Utils.hashSHA256(refreshToken)), - System.currentTimeMillis() + config.getRefreshTokenValidityInMillis(), useStaticKey); + System.currentTimeMillis() + config.getRefreshTokenValidityInMillis(), + useStaticKey); sessionStorage.commitTransaction(con); @@ -679,7 +684,8 @@ private static SessionInformationHolder refreshSessionHelper( while (true) { try { String sessionHandle = refreshTokenInfo.sessionHandle; - io.supertokens.pluginInterface.session.noSqlStorage.SessionInfoWithLastUpdated sessionInfo = sessionStorage + io.supertokens.pluginInterface.session.noSqlStorage.SessionInfoWithLastUpdated sessionInfo = + sessionStorage .getSessionInfo_Transaction(sessionHandle); if (sessionInfo == null || sessionInfo.expiry < System.currentTimeMillis()) { diff --git a/src/main/java/io/supertokens/session/info/SessionInformationHolder.java b/src/main/java/io/supertokens/session/info/SessionInformationHolder.java index d380e326a..30f9c6b08 100644 --- a/src/main/java/io/supertokens/session/info/SessionInformationHolder.java +++ b/src/main/java/io/supertokens/session/info/SessionInformationHolder.java @@ -42,7 +42,8 @@ public class SessionInformationHolder { public final String antiCsrfToken; public SessionInformationHolder(@Nonnull SessionInfo session, @Nullable TokenInfo accessToken, - @Nullable TokenInfo refreshToken, @Nullable TokenInfo idRefreshToken, @Nullable String antiCsrfToken) { + @Nullable TokenInfo refreshToken, @Nullable TokenInfo idRefreshToken, + @Nullable String antiCsrfToken) { this.session = session; this.accessToken = accessToken; this.refreshToken = refreshToken; diff --git a/src/main/java/io/supertokens/session/refreshToken/RefreshTokenKey.java b/src/main/java/io/supertokens/session/refreshToken/RefreshTokenKey.java index fb4fcc53f..0da1106b3 100644 --- a/src/main/java/io/supertokens/session/refreshToken/RefreshTokenKey.java +++ b/src/main/java/io/supertokens/session/refreshToken/RefreshTokenKey.java @@ -54,7 +54,8 @@ private RefreshTokenKey(AppIdentifier appIdentifier, Main main) throws try { this.getKey(); } catch (StorageQueryException | StorageTransactionLogicException e) { - Logging.error(main, appIdentifier.getAsPublicTenantIdentifier(), "Error while fetching refresh token key", false, e); + Logging.error(main, appIdentifier.getAsPublicTenantIdentifier(), "Error while fetching refresh token key", + false, e); } } @@ -73,7 +74,8 @@ public static RefreshTokenKey getInstance(Main main) { } } - public static void loadForAllTenants(Main main, List apps, List tenantsThatChanged) { + public static void loadForAllTenants(Main main, List apps, + List tenantsThatChanged) { try { main.getResourceDistributor().withResourceDistributorLock(() -> { Map existingResources = @@ -114,7 +116,8 @@ public String getKey() throws StorageQueryException, StorageTransactionLogicExce private String maybeGenerateNewKeyAndUpdateInDb() throws StorageQueryException, StorageTransactionLogicException, TenantOrAppNotFoundException { - SessionStorage storage = (SessionStorage) StorageLayer.getStorage(this.appIdentifier.getAsPublicTenantIdentifier(), main); + SessionStorage storage = (SessionStorage) StorageLayer.getStorage( + this.appIdentifier.getAsPublicTenantIdentifier(), main); if (storage.getType() == STORAGE_TYPE.SQL) { diff --git a/src/main/java/io/supertokens/signingkeys/AccessTokenSigningKey.java b/src/main/java/io/supertokens/signingkeys/AccessTokenSigningKey.java index 36f79ade7..8be44d17a 100644 --- a/src/main/java/io/supertokens/signingkeys/AccessTokenSigningKey.java +++ b/src/main/java/io/supertokens/signingkeys/AccessTokenSigningKey.java @@ -71,7 +71,8 @@ private AccessTokenSigningKey(AppIdentifier appIdentifier, Main main) this.transferLegacyKeyToNewTable(); this.getOrCreateAndGetSigningKeys(); } catch (StorageQueryException | StorageTransactionLogicException e) { - Logging.error(main, appIdentifier.getAsPublicTenantIdentifier(), "Error while fetching access token signing key", false, e); + Logging.error(main, appIdentifier.getAsPublicTenantIdentifier(), + "Error while fetching access token signing key", false, e); } } @@ -90,7 +91,8 @@ public static AccessTokenSigningKey getInstance(Main main) { } } - public static void loadForAllTenants(Main main, List apps, List tenantsThatChanged) { + public static void loadForAllTenants(Main main, List apps, + List tenantsThatChanged) { try { main.getResourceDistributor().withResourceDistributorLock(() -> { Map existingResources = diff --git a/src/main/java/io/supertokens/signingkeys/SigningKeys.java b/src/main/java/io/supertokens/signingkeys/SigningKeys.java index 658a76c44..e993b9b91 100644 --- a/src/main/java/io/supertokens/signingkeys/SigningKeys.java +++ b/src/main/java/io/supertokens/signingkeys/SigningKeys.java @@ -68,7 +68,8 @@ public static SigningKeys getInstance(Main main) { } } - public static void loadForAllTenants(Main main, List apps, List tenantsThatChanged) { + public static void loadForAllTenants(Main main, List apps, + List tenantsThatChanged) { try { main.getResourceDistributor().withResourceDistributorLock(() -> { Map existingResources = @@ -185,7 +186,8 @@ public KeyInfo getLatestIssuedDynamicKey() AccessTokenSigningKey.getInstance(appIdentifier, main).getDynamicSigningKeyOverlapMS() > System.currentTimeMillis() && // the latest isn't old enough System.currentTimeMillis() < dynamicKeys.get(1).createdAtTime + - config.getAccessTokenDynamicSigningKeyUpdateIntervalInMillis() // the one before can still be used to + config.getAccessTokenDynamicSigningKeyUpdateIntervalInMillis() // the one before can still be + // used to // sign ) { return dynamicKeys.get(1); @@ -358,7 +360,7 @@ public int hashCode() { * @param bigInt The big integer to be converted. Must not be * {@code null}. * @return A byte array representation of the big integer, without the - * sign bit. + * sign bit. */ private static byte[] toBytesUnsigned(final BigInteger bigInt) { diff --git a/src/main/java/io/supertokens/storageLayer/StorageLayer.java b/src/main/java/io/supertokens/storageLayer/StorageLayer.java index e87e114d0..4e03fadd4 100644 --- a/src/main/java/io/supertokens/storageLayer/StorageLayer.java +++ b/src/main/java/io/supertokens/storageLayer/StorageLayer.java @@ -55,7 +55,8 @@ public Storage getUnderlyingStorage() { return storage; } - public static Storage getNewStorageInstance(Main main, JsonObject config, TenantIdentifier tenantIdentifier, boolean doNotLog) throws InvalidConfigException { + public static Storage getNewStorageInstance(Main main, JsonObject config, TenantIdentifier tenantIdentifier, + boolean doNotLog) throws InvalidConfigException { Storage result; if (StorageLayer.ucl == null) { result = new Start(main); @@ -208,7 +209,8 @@ public static void loadAllTenantStorage(Main main, TenantConfig[] tenants) Map idToStorageMap = new HashMap<>(); for (ResourceDistributor.KeyClass key : normalisedConfigs.keySet()) { // setting doNotLog to true so that plugin loading is not logged here - Storage storage = StorageLayer.getNewStorageInstance(main, normalisedConfigs.get(key), key.getTenantIdentifier(), true); + Storage storage = StorageLayer.getNewStorageInstance(main, normalisedConfigs.get(key), + key.getTenantIdentifier(), true); String userPoolId = storage.getUserPoolId(); String connectionPoolId = storage.getConnectionPoolId(); String uniqueId = userPoolId + "~" + connectionPoolId; @@ -290,14 +292,16 @@ public static void loadAllTenantStorage(Main main, TenantConfig[] tenants) if (storageToTenantIdentifiersMap.get(((StorageLayer) resources.get(key)).storage) == null) { storageToTenantIdentifiersMap.put(((StorageLayer) resources.get(key)).storage, new HashSet<>()); } - storageToTenantIdentifiersMap.get(((StorageLayer) resources.get(key)).storage).add(key.getTenantIdentifier()); + storageToTenantIdentifiersMap.get(((StorageLayer) resources.get(key)).storage) + .add(key.getTenantIdentifier()); } for (ResourceDistributor.KeyClass key : resources.keySet()) { ResourceDistributor.SingletonResource resource = resources.get(key); try { - ((StorageLayer) resource).storage.initStorage(false, new ArrayList<>(storageToTenantIdentifiersMap.get(((StorageLayer) resource).storage))); + ((StorageLayer) resource).storage.initStorage(false, + new ArrayList<>(storageToTenantIdentifiersMap.get(((StorageLayer) resource).storage))); ((StorageLayer) resource).storage.initFileLogging( Config.getBaseConfig(main).getInfoLogPath(main), Config.getBaseConfig(main).getErrorLogPath(main)); diff --git a/src/main/java/io/supertokens/thirdparty/ThirdParty.java b/src/main/java/io/supertokens/thirdparty/ThirdParty.java index 27a7df36f..9a1f3f889 100644 --- a/src/main/java/io/supertokens/thirdparty/ThirdParty.java +++ b/src/main/java/io/supertokens/thirdparty/ThirdParty.java @@ -84,7 +84,8 @@ public static SignInUpResponse signInUp2_7(TenantIdentifier tenantIdentifier, St // account linking was not available. So loginMethod length will always be 1. assert (finalResponse.user.loginMethods.length == 1); evStorage.updateIsEmailVerified_Transaction(tenantIdentifier.toAppIdentifier(), con, - finalResponse.user.getSupertokensUserId(), finalResponse.user.loginMethods[0].email, true); + finalResponse.user.getSupertokensUserId(), finalResponse.user.loginMethods[0].email, + true); evStorage.commitTransaction(con); return null; } catch (TenantOrAppNotFoundException e) { @@ -130,7 +131,8 @@ public static SignInUpResponse signInUp(Main main, String thirdPartyId, String t } @TestOnly - public static SignInUpResponse signInUp(Main main, String thirdPartyId, String thirdPartyUserId, String email, boolean isEmailVerified) + public static SignInUpResponse signInUp(Main main, String thirdPartyId, String thirdPartyUserId, String email, + boolean isEmailVerified) throws StorageQueryException, EmailChangeNotAllowedException { try { Storage storage = StorageLayer.getStorage(main); @@ -167,13 +169,14 @@ public static SignInUpResponse signInUp(TenantIdentifier tenantIdentifier, Stora if (isEmailVerified) { for (LoginMethod lM : response.user.loginMethods) { - if (lM.thirdParty != null && lM.thirdParty.id.equals(thirdPartyId) && lM.thirdParty.userId.equals(thirdPartyUserId)) { + if (lM.thirdParty != null && lM.thirdParty.id.equals(thirdPartyId) && + lM.thirdParty.userId.equals(thirdPartyUserId)) { try { EmailVerificationSQLStorage evStorage = StorageUtils.getEmailVerificationStorage(storage); evStorage.startTransaction(con -> { try { evStorage.updateIsEmailVerified_Transaction(tenantIdentifier.toAppIdentifier(), con, - lM.getSupertokensUserId(), lM.email, true); + lM.getSupertokensUserId(), lM.email, true); evStorage.commitTransaction(con); return null; @@ -266,7 +269,8 @@ private static SignInUpResponse signInUpHelper(TenantIdentifier tenantIdentifier tpStorage.startTransaction(con -> { AuthRecipeUserInfo userFromDb1 = null; - AuthRecipeUserInfo[] usersFromDb1 = authRecipeStorage.listPrimaryUsersByThirdPartyInfo_Transaction( + AuthRecipeUserInfo[] usersFromDb1 = + authRecipeStorage.listPrimaryUsersByThirdPartyInfo_Transaction( appIdentifier, con, thirdPartyId, thirdPartyUserId); @@ -311,7 +315,8 @@ private static SignInUpResponse signInUpHelper(TenantIdentifier tenantIdentifier continue; } if (userWithSameEmail.isPrimaryUser && - !userWithSameEmail.getSupertokensUserId().equals(userFromDb1.getSupertokensUserId())) { + !userWithSameEmail.getSupertokensUserId() + .equals(userFromDb1.getSupertokensUserId())) { throw new StorageTransactionLogicException( new EmailChangeNotAllowedException()); } @@ -405,7 +410,8 @@ public static void verifyThirdPartyProvidersArray(ThirdPartyConfig.Provider[] pr if (providers != null) { for (ThirdPartyConfig.Provider provider : providers) { if (thirdPartyIds.contains(provider.thirdPartyId)) { - throw new InvalidProviderConfigException("Duplicate ThirdPartyId was specified in the providers list."); + throw new InvalidProviderConfigException( + "Duplicate ThirdPartyId was specified in the providers list."); } thirdPartyIds.add(provider.thirdPartyId); diff --git a/src/main/java/io/supertokens/totp/Totp.java b/src/main/java/io/supertokens/totp/Totp.java index 91ab3f667..d2afce084 100644 --- a/src/main/java/io/supertokens/totp/Totp.java +++ b/src/main/java/io/supertokens/totp/Totp.java @@ -72,7 +72,7 @@ private static boolean checkCode(TOTPDevice device, String code) { @TestOnly public static TOTPDevice registerDevice(Main main, String userId, - String deviceName, int skew, int period) + String deviceName, int skew, int period) throws StorageQueryException, DeviceAlreadyExistsException, NoSuchAlgorithmException, FeatureNotEnabledException { try { @@ -137,14 +137,14 @@ public static TOTPDevice createDevice(Main main, AppIdentifier appIdentifier, St verified, createdAt ); - } catch (DeviceAlreadyExistsException e){ + } catch (DeviceAlreadyExistsException e) { } verifiedDevicesCount++; } } public static TOTPDevice registerDevice(AppIdentifier appIdentifier, Storage storage, Main main, String userId, - String deviceName, int skew, int period) + String deviceName, int skew, int period) throws StorageQueryException, DeviceAlreadyExistsException, NoSuchAlgorithmException, FeatureNotEnabledException, TenantOrAppNotFoundException { @@ -155,8 +155,8 @@ public static TOTPDevice registerDevice(AppIdentifier appIdentifier, Storage sto } private static void checkAndStoreCode(TenantIdentifier tenantIdentifier, Storage storage, Main main, - String userId, TOTPDevice[] devices, - String code) + String userId, TOTPDevice[] devices, + String code) throws InvalidTotpException, UnknownTotpUserIdException, LimitReachedException, StorageQueryException, StorageTransactionLogicException, TenantOrAppNotFoundException { @@ -217,8 +217,9 @@ private static void checkAndStoreCode(TenantIdentifier tenantIdentifier, Storage long invalidOutOfN = 0; if (invalidUsedCodes.length > 0) { invalidOutOfN = Arrays.stream(invalidUsedCodes).limit(N).takeWhile( - usedCode -> usedCode.createdTime > invalidUsedCodes[0].createdTime - rateLimitResetTimeInMs - ).count(); + usedCode -> usedCode.createdTime > + invalidUsedCodes[0].createdTime - rateLimitResetTimeInMs + ).count(); } // Check if the user has been rate limited: @@ -231,7 +232,8 @@ private static void checkAndStoreCode(TenantIdentifier tenantIdentifier, Storage // Less than rateLimitResetTimeInMs (default = 15 mins) time has elasped since // the last invalid code: long timeLeftMs = (rateLimitResetTimeInMs - (now - latestInvalidCodeCreatedTime)); - throw new StorageTransactionLogicException(new LimitReachedException(timeLeftMs, (int)invalidOutOfN, N)); + throw new StorageTransactionLogicException( + new LimitReachedException(timeLeftMs, (int) invalidOutOfN, N)); // If we insert the used code here, then it will further delay the user from // being able to login. So not inserting it here. @@ -242,7 +244,8 @@ private static void checkAndStoreCode(TenantIdentifier tenantIdentifier, Storage } if (code.length() > 8) { - throw new StorageTransactionLogicException(new InvalidTotpException((int)invalidOutOfN+1, N)); + throw new StorageTransactionLogicException( + new InvalidTotpException((int) invalidOutOfN + 1, N)); } // Check if the code is valid for any device: @@ -303,7 +306,8 @@ private static void checkAndStoreCode(TenantIdentifier tenantIdentifier, Storage if (!isValid) { // transaction has been committed, so we can directly throw the exception: - throw new StorageTransactionLogicException(new InvalidTotpException((int)invalidOutOfN+1, N)); + throw new StorageTransactionLogicException( + new InvalidTotpException((int) invalidOutOfN + 1, N)); } return null; @@ -330,7 +334,7 @@ private static void checkAndStoreCode(TenantIdentifier tenantIdentifier, Storage @TestOnly public static boolean verifyDevice(Main main, - String userId, String deviceName, String code) + String userId, String deviceName, String code) throws UnknownDeviceException, InvalidTotpException, LimitReachedException, StorageQueryException, StorageTransactionLogicException { try { @@ -342,7 +346,7 @@ public static boolean verifyDevice(Main main, } public static boolean verifyDevice(TenantIdentifier tenantIdentifier, Storage storage, Main main, - String userId, String deviceName, String code) + String userId, String deviceName, String code) throws UnknownDeviceException, InvalidTotpException, LimitReachedException, StorageQueryException, StorageTransactionLogicException, TenantOrAppNotFoundException { @@ -385,7 +389,7 @@ public static boolean verifyDevice(TenantIdentifier tenantIdentifier, Storage st // gets a UnknownDevceException. // This behaviour is okay so we can ignore it. try { - checkAndStoreCode(tenantIdentifier, storage, main, userId, new TOTPDevice[] { matchingDevice }, code); + checkAndStoreCode(tenantIdentifier, storage, main, userId, new TOTPDevice[]{matchingDevice}, code); } catch (UnknownTotpUserIdException e) { // User must have deleted the device in parallel. throw new UnknownDeviceException(); @@ -407,7 +411,8 @@ public static void verifyCode(Main main, String userId, String code) } } - public static void verifyCode(TenantIdentifier tenantIdentifier, Storage storage, Main main, String userId, String code) + public static void verifyCode(TenantIdentifier tenantIdentifier, Storage storage, Main main, String userId, + String code) throws InvalidTotpException, UnknownTotpUserIdException, LimitReachedException, StorageQueryException, StorageTransactionLogicException, FeatureNotEnabledException, TenantOrAppNotFoundException { @@ -439,7 +444,7 @@ public static void verifyCode(TenantIdentifier tenantIdentifier, Storage storage @TestOnly public static void removeDevice(Main main, String userId, - String deviceName) + String deviceName) throws StorageQueryException, UnknownDeviceException, StorageTransactionLogicException { try { @@ -454,7 +459,7 @@ public static void removeDevice(Main main, String userId, * Delete device and also delete the user if deleting the last device */ public static void removeDevice(AppIdentifier appIdentifier, Storage storage, String userId, - String deviceName) + String deviceName) throws StorageQueryException, UnknownDeviceException, StorageTransactionLogicException, TenantOrAppNotFoundException { TOTPSQLStorage totpStorage = StorageUtils.getTOTPStorage(storage); @@ -489,7 +494,7 @@ public static void removeDevice(AppIdentifier appIdentifier, Storage storage, St @TestOnly public static void updateDeviceName(Main main, String userId, - String oldDeviceName, String newDeviceName) + String oldDeviceName, String newDeviceName) throws StorageQueryException, DeviceAlreadyExistsException, UnknownDeviceException { try { updateDeviceName(new AppIdentifier(null, null), StorageLayer.getStorage(main), @@ -500,7 +505,7 @@ public static void updateDeviceName(Main main, String userId, } public static void updateDeviceName(AppIdentifier appIdentifier, Storage storage, String userId, - String oldDeviceName, String newDeviceName) + String oldDeviceName, String newDeviceName) throws StorageQueryException, DeviceAlreadyExistsException, UnknownDeviceException, TenantOrAppNotFoundException { TOTPSQLStorage totpStorage = StorageUtils.getTOTPStorage(storage); diff --git a/src/main/java/io/supertokens/useridmapping/UserIdMapping.java b/src/main/java/io/supertokens/useridmapping/UserIdMapping.java index 5f6482b20..36cd1b1bc 100644 --- a/src/main/java/io/supertokens/useridmapping/UserIdMapping.java +++ b/src/main/java/io/supertokens/useridmapping/UserIdMapping.java @@ -59,7 +59,9 @@ public static void createUserIdMapping(AppIdentifier appIdentifier, Storage[] st } @TestOnly - public static void createUserIdMapping(Main main, AppIdentifier appIdentifier, Storage storage, String supertokensUserId, String externalUserId, String externalUserIdInfo, boolean force) + public static void createUserIdMapping(Main main, AppIdentifier appIdentifier, Storage storage, + String supertokensUserId, String externalUserId, String externalUserIdInfo, + boolean force) throws ServletException, UnknownSuperTokensUserIdException, UserIdMappingAlreadyExistsException, StorageQueryException, TenantOrAppNotFoundException { createUserIdMapping( @@ -70,7 +72,8 @@ public static void createUserIdMapping(Main main, AppIdentifier appIdentifier, S public static void createUserIdMapping(AppIdentifier appIdentifier, Storage[] storages, String superTokensUserId, String externalUserId, - String externalUserIdInfo, boolean force, boolean makeExceptionForEmailVerification) + String externalUserIdInfo, boolean force, + boolean makeExceptionForEmailVerification) throws UnknownSuperTokensUserIdException, UserIdMappingAlreadyExistsException, StorageQueryException, ServletException, TenantOrAppNotFoundException { @@ -127,16 +130,22 @@ public static void createUserIdMapping(AppIdentifier appIdentifier, Storage[] st // check that none of the non-auth recipes are using the superTokensUserId List storageClasses = findNonAuthStoragesWhereUserIdIsUsedOrAssertIfUsed(appIdentifier, userStorage, superTokensUserId, false); - if (storageClasses.size() == 1 && storageClasses.get(0).equals(EmailVerificationStorage.class.getName())) { - // if the userId is used in email verification, then we do an exception and update the isEmailVerified - // to the externalUserId. We do this because we automatically set the isEmailVerified to true for passwordless - // and third party sign in up when the user info from provider says the email is verified and If we don't make - // an exception, then the creation of userIdMapping for the user will be blocked. And, to overcome that the - // email will have to be unverified first, then the userIdMapping should be created and then the email must be + if (storageClasses.size() == 1 && + storageClasses.get(0).equals(EmailVerificationStorage.class.getName())) { + // if the userId is used in email verification, then we do an exception and update the + // isEmailVerified + // to the externalUserId. We do this because we automatically set the isEmailVerified to true for + // passwordless + // and third party sign in up when the user info from provider says the email is verified and If + // we don't make + // an exception, then the creation of userIdMapping for the user will be blocked. And, to + // overcome that the + // email will have to be unverified first, then the userIdMapping should be created and then the + // email must be // verified again on the externalUserId, which is not a good user experience. StorageUtils.getEmailVerificationStorage(userStorage).updateIsEmailVerifiedToExternalUserId( appIdentifier, superTokensUserId, externalUserId); - } else if (storageClasses.size() > 0) { + } else if (storageClasses.size() > 0) { String recipeName = storageClasses.get(0); String[] parts = recipeName.split("[.]"); recipeName = parts[parts.length - 1]; @@ -166,7 +175,8 @@ public static void createUserIdMapping(Main main, @TestOnly public static void createUserIdMapping(Main main, String superTokensUserId, String externalUserId, - String externalUserIdInfo, boolean force, boolean makeExceptionForEmailVerification) + String externalUserIdInfo, boolean force, + boolean makeExceptionForEmailVerification) throws UnknownSuperTokensUserIdException, UserIdMappingAlreadyExistsException, StorageQueryException, ServletException, UnknownUserIdException { try { @@ -214,7 +224,8 @@ public static io.supertokens.pluginInterface.useridmapping.UserIdMapping getUser return uidMappingStorage.getUserIdMapping_Transaction(con, appIdentifier, userId, false); } - io.supertokens.pluginInterface.useridmapping.UserIdMapping[] userIdMappings = uidMappingStorage.getUserIdMapping_Transaction( + io.supertokens.pluginInterface.useridmapping.UserIdMapping[] userIdMappings = + uidMappingStorage.getUserIdMapping_Transaction( con, appIdentifier, userId); if (userIdMappings.length == 0) { @@ -400,7 +411,8 @@ public static List findNonAuthStoragesWhereUserIdIsUsedOrAssertIfUsed( result.add(EmailVerificationStorage.class.getName()); if (assertIfUsed) { throw new ServletException( - new WebserverAPI.BadRequestException("UserId is already in use in EmailVerification recipe")); + new WebserverAPI.BadRequestException( + "UserId is already in use in EmailVerification recipe")); } } } diff --git a/src/main/java/io/supertokens/userroles/UserRoles.java b/src/main/java/io/supertokens/userroles/UserRoles.java index 5b1f85553..21b132aa1 100644 --- a/src/main/java/io/supertokens/userroles/UserRoles.java +++ b/src/main/java/io/supertokens/userroles/UserRoles.java @@ -102,7 +102,7 @@ public static boolean createNewRoleOrModifyItsPermissions(AppIdentifier appIdent return wasANewRoleCreated; }); } catch (StorageTransactionLogicException e) { - if (e.actualException instanceof TenantOrAppNotFoundException) { + if (e.actualException instanceof TenantOrAppNotFoundException) { throw (TenantOrAppNotFoundException) e.actualException; } throw e; diff --git a/src/main/java/io/supertokens/utils/RateLimiter.java b/src/main/java/io/supertokens/utils/RateLimiter.java index 79439beae..9033e8e66 100644 --- a/src/main/java/io/supertokens/utils/RateLimiter.java +++ b/src/main/java/io/supertokens/utils/RateLimiter.java @@ -33,7 +33,8 @@ public class RateLimiter extends ResourceDistributor.SingletonResource { private long tokenBucketSize = 5; private long tokensAvailable = tokenBucketSize; - public static RateLimiter getInstance(AppIdentifier appIdentifier, Main main, long timeIntervalIfCreatingNewRateLimiter) { + public static RateLimiter getInstance(AppIdentifier appIdentifier, Main main, + long timeIntervalIfCreatingNewRateLimiter) { try { return (RateLimiter) main.getResourceDistributor().getResource(appIdentifier, RESOURCE_KEY); } catch (TenantOrAppNotFoundException e) { diff --git a/src/main/java/io/supertokens/webserver/InputParser.java b/src/main/java/io/supertokens/webserver/InputParser.java index ebf1e86ee..b10028746 100644 --- a/src/main/java/io/supertokens/webserver/InputParser.java +++ b/src/main/java/io/supertokens/webserver/InputParser.java @@ -56,7 +56,8 @@ public static String getQueryParamOrThrowError(HttpServletRequest request, Strin } public static String[] getCommaSeparatedStringArrayQueryParamOrThrowError(HttpServletRequest request, - String fieldName, boolean nullable) throws ServletException { + String fieldName, boolean nullable) + throws ServletException { String[] value = null; // expect val1,val2,val3 and so on... String queryParamValue = getQueryParamOrThrowError(request, fieldName, nullable); @@ -145,7 +146,7 @@ public static String parseStringOrThrowError(JsonObject element, String fieldNam } public static String parseStringFromElementOrThrowError(JsonElement element, String parentFieldName, - boolean nullable) throws ServletException { + boolean nullable) throws ServletException { try { if (nullable && element == null) { return null; diff --git a/src/main/java/io/supertokens/webserver/PathRouter.java b/src/main/java/io/supertokens/webserver/PathRouter.java index 2f124ec3e..5e01d3d52 100644 --- a/src/main/java/io/supertokens/webserver/PathRouter.java +++ b/src/main/java/io/supertokens/webserver/PathRouter.java @@ -83,7 +83,8 @@ private WebserverAPI getAPIThatMatchesPath(HttpServletRequest req) { } String tenantIdStopWords = String.join("|", Utils.INVALID_WORDS_FOR_TENANTID); - if (requestPath.matches("^(/appid-[a-z0-9-]*)?(/(?!" + tenantIdStopWords + ")[a-z0-9-]+)?" + apiPath + "/?$")) { + if (requestPath.matches( + "^(/appid-[a-z0-9-]*)?(/(?!" + tenantIdStopWords + ")[a-z0-9-]+)?" + apiPath + "/?$")) { return api; } } diff --git a/src/main/java/io/supertokens/webserver/RequestStats.java b/src/main/java/io/supertokens/webserver/RequestStats.java index 56851cd74..164ae5a75 100644 --- a/src/main/java/io/supertokens/webserver/RequestStats.java +++ b/src/main/java/io/supertokens/webserver/RequestStats.java @@ -31,7 +31,8 @@ public class RequestStats extends ResourceDistributor.SingletonResource { private final int MAX_MINUTES = 24 * 60; private long currentMinute; // current minute since epoch - private final int[] currentMinuteRequestCounts; // array of 60 items representing number of requests at each second in the current minute + private final int[] currentMinuteRequestCounts; // array of 60 items representing number of requests at each + // second in the current minute // The 2 arrays below contains stats for a day for every minute // the array is stored in such a way that array[currentMinute % MAX_MINUTES] contains the stats for a day ago @@ -117,7 +118,9 @@ public void updateRequestStats() { synchronized private void updateRequestStats(boolean updateCounts) { long now = System.currentTimeMillis() / 1000; this.checkAndUpdateMinute(now); - if (updateCounts) { this.updateCounts(now); } + if (updateCounts) { + this.updateCounts(now); + } } public JsonObject getStats() { diff --git a/src/main/java/io/supertokens/webserver/Utils.java b/src/main/java/io/supertokens/webserver/Utils.java index e59672246..f730bc3b9 100644 --- a/src/main/java/io/supertokens/webserver/Utils.java +++ b/src/main/java/io/supertokens/webserver/Utils.java @@ -39,16 +39,20 @@ public static String normalizeAndValidateConnectionUriDomain(String connectionUr return normalizeAndValidateConnectionUriDomain(connectionUriDomain, true); } - public static String normalizeAndValidateConnectionUriDomain(String connectionUriDomain, boolean throwExceptionIfInvalid) throws ServletException { + public static String normalizeAndValidateConnectionUriDomain(String connectionUriDomain, + boolean throwExceptionIfInvalid) + throws ServletException { connectionUriDomain = connectionUriDomain.trim(); connectionUriDomain = connectionUriDomain.toLowerCase(); if (connectionUriDomain.length() == 0) { - throw new ServletException(new WebserverAPI.BadRequestException("connectionUriDomain should not be an empty String")); + throw new ServletException( + new WebserverAPI.BadRequestException("connectionUriDomain should not be an empty String")); } String hostnameRegex = "^[a-z0-9-]+(\\.[a-z0-9-]+)*(:[0-9]+)?$"; - String ipRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(:[0-9]+)?$"; + String ipRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}" + + "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(:[0-9]+)?$"; if (!connectionUriDomain.matches(hostnameRegex) && !connectionUriDomain.matches(ipRegex)) { if (throwExceptionIfInvalid) { @@ -86,7 +90,8 @@ public static String normalizeAndValidateAppId(String appId) throws ServletExcep } if (!appId.matches("^[a-z0-9-]+$")) { - throw new ServletException(new WebserverAPI.BadRequestException("appId can only contain letters, numbers and hyphens")); + throw new ServletException( + new WebserverAPI.BadRequestException("appId can only contain letters, numbers and hyphens")); } return appId; @@ -101,7 +106,8 @@ public static String normalizeAndValidateTenantId(String tenantId) throws Servle } if (INVALID_WORDS_FOR_TENANTID.contains(tenantId)) { - throw new ServletException(new WebserverAPI.BadRequestException("Cannot use '" + tenantId + "'" + " as a tenantId")); + throw new ServletException( + new WebserverAPI.BadRequestException("Cannot use '" + tenantId + "'" + " as a tenantId")); } if (tenantId.startsWith("appid-")) { @@ -109,7 +115,8 @@ public static String normalizeAndValidateTenantId(String tenantId) throws Servle } if (!tenantId.matches("^[a-z0-9-]+$")) { - throw new ServletException(new WebserverAPI.BadRequestException("tenantId can only contain letters, numbers and hyphens")); + throw new ServletException( + new WebserverAPI.BadRequestException("tenantId can only contain letters, numbers and hyphens")); } return tenantId; diff --git a/src/main/java/io/supertokens/webserver/api/core/ApiVersionAPI.java b/src/main/java/io/supertokens/webserver/api/core/ApiVersionAPI.java index 76087978b..62103e587 100644 --- a/src/main/java/io/supertokens/webserver/api/core/ApiVersionAPI.java +++ b/src/main/java/io/supertokens/webserver/api/core/ApiVersionAPI.java @@ -33,6 +33,7 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import java.io.IOException; public class ApiVersionAPI extends WebserverAPI { @@ -76,7 +77,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO try { Multitenancy.saveWebsiteAndAPIDomainForApp(storage, appIdentifier, websiteDomain, apiDomain); } catch (Exception e) { - Logging.warn(main, appIdentifier.getAsPublicTenantIdentifier(), "Error while saving website/API domain: " + e.toString()); + Logging.warn(main, appIdentifier.getAsPublicTenantIdentifier(), + "Error while saving website/API domain: " + e.toString()); } } catch (TenantOrAppNotFoundException | BadPermissionException e) { throw new ServletException(e); diff --git a/src/main/java/io/supertokens/webserver/api/core/ConfigAPI.java b/src/main/java/io/supertokens/webserver/api/core/ConfigAPI.java index 6c9abfe14..6b419da14 100644 --- a/src/main/java/io/supertokens/webserver/api/core/ConfigAPI.java +++ b/src/main/java/io/supertokens/webserver/api/core/ConfigAPI.java @@ -28,6 +28,7 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; + import java.io.File; import java.io.IOException; @@ -59,7 +60,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO throw new ServletException(e); } if (!tenantIdentifier.equals(new TenantIdentifier(null, null, null))) { - throw new ServletException(new BadPermissionException("you can call this only from the base connection uri domain, public app and tenant")); + throw new ServletException(new BadPermissionException( + "you can call this only from the base connection uri domain, public app and tenant")); } if ((ProcessHandle.current().pid() + "").equals(pid)) { diff --git a/src/main/java/io/supertokens/webserver/api/core/HelloAPI.java b/src/main/java/io/supertokens/webserver/api/core/HelloAPI.java index a4c219bce..c0691863a 100644 --- a/src/main/java/io/supertokens/webserver/api/core/HelloAPI.java +++ b/src/main/java/io/supertokens/webserver/api/core/HelloAPI.java @@ -80,7 +80,8 @@ private void handleRequest(HttpServletRequest req, HttpServletResponse resp) thr try { AppIdentifier appIdentifier = getAppIdentifier(req); - Storage[] storages = StorageLayer.getStoragesForApp(main, appIdentifier); // throws tenantOrAppNotFoundException + Storage[] storages = StorageLayer.getStoragesForApp(main, + appIdentifier); // throws tenantOrAppNotFoundException RateLimiter rateLimiter = RateLimiter.getInstance(appIdentifier, super.main, 200); if (!rateLimiter.checkRequest()) { diff --git a/src/main/java/io/supertokens/webserver/api/core/JWKSPublicAPI.java b/src/main/java/io/supertokens/webserver/api/core/JWKSPublicAPI.java index 922f1876d..54f517e4b 100644 --- a/src/main/java/io/supertokens/webserver/api/core/JWKSPublicAPI.java +++ b/src/main/java/io/supertokens/webserver/api/core/JWKSPublicAPI.java @@ -69,7 +69,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO resp.setHeader("Cache-Control", "max-age=" + signingKeys.getCacheDurationInSeconds() + ", must-revalidate"); super.sendJsonResponse(200, reply, resp); } catch (StorageQueryException | StorageTransactionLogicException | NoSuchAlgorithmException - | InvalidKeySpecException | TenantOrAppNotFoundException | UnsupportedJWTSigningAlgorithmException e) { + | InvalidKeySpecException | TenantOrAppNotFoundException | UnsupportedJWTSigningAlgorithmException e) { throw new ServletException(e); } } diff --git a/src/main/java/io/supertokens/webserver/api/core/LicenseKeyAPI.java b/src/main/java/io/supertokens/webserver/api/core/LicenseKeyAPI.java index 1d11d07f5..54fe69d05 100644 --- a/src/main/java/io/supertokens/webserver/api/core/LicenseKeyAPI.java +++ b/src/main/java/io/supertokens/webserver/api/core/LicenseKeyAPI.java @@ -64,7 +64,8 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO JsonObject result = new JsonObject(); result.addProperty("status", success ? "OK" : "MISSING_EE_FOLDER_ERROR"); super.sendJsonResponse(200, result, resp); - } catch (StorageQueryException | HttpResponseException | TenantOrAppNotFoundException | BadPermissionException e) { + } catch (StorageQueryException | HttpResponseException | TenantOrAppNotFoundException | + BadPermissionException e) { throw new ServletException(e); } catch (InvalidLicenseKeyException e) { JsonObject result = new JsonObject(); @@ -83,7 +84,8 @@ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws JsonObject result = new JsonObject(); result.addProperty("status", "OK"); super.sendJsonResponse(200, result, resp); - } catch (StorageQueryException | HttpResponseException | TenantOrAppNotFoundException | BadPermissionException e) { + } catch (StorageQueryException | HttpResponseException | TenantOrAppNotFoundException | + BadPermissionException e) { throw new ServletException(e); } } diff --git a/src/main/java/io/supertokens/webserver/api/core/NotFoundOrHelloAPI.java b/src/main/java/io/supertokens/webserver/api/core/NotFoundOrHelloAPI.java index ab86ac62c..ce9acc90b 100644 --- a/src/main/java/io/supertokens/webserver/api/core/NotFoundOrHelloAPI.java +++ b/src/main/java/io/supertokens/webserver/api/core/NotFoundOrHelloAPI.java @@ -110,7 +110,8 @@ protected void handleRequest(HttpServletRequest req, HttpServletResponse resp) t } else { super.sendTextResponse(404, "Not found", resp); - Logging.error(main, appIdentifier.getAsPublicTenantIdentifier(), "Unknown API called: " + req.getRequestURL(), + Logging.error(main, appIdentifier.getAsPublicTenantIdentifier(), + "Unknown API called: " + req.getRequestURL(), false); } } diff --git a/src/main/java/io/supertokens/webserver/api/core/SearchTagsAPI.java b/src/main/java/io/supertokens/webserver/api/core/SearchTagsAPI.java index ce5af71e4..6aac94e9f 100644 --- a/src/main/java/io/supertokens/webserver/api/core/SearchTagsAPI.java +++ b/src/main/java/io/supertokens/webserver/api/core/SearchTagsAPI.java @@ -31,7 +31,7 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -public class SearchTagsAPI extends WebserverAPI{ +public class SearchTagsAPI extends WebserverAPI { public SearchTagsAPI(Main main) { super(main, ""); @@ -41,10 +41,10 @@ public SearchTagsAPI(Main main) { public String getPath() { return "/user/search/tags"; } - + @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { - + JsonObject response = new JsonObject(); response.addProperty("status", "OK"); JsonArray tags = new JsonArray(); diff --git a/src/main/java/io/supertokens/webserver/api/dashboard/DashboardUserAPI.java b/src/main/java/io/supertokens/webserver/api/dashboard/DashboardUserAPI.java index 722fb4245..c66444b74 100644 --- a/src/main/java/io/supertokens/webserver/api/dashboard/DashboardUserAPI.java +++ b/src/main/java/io/supertokens/webserver/api/dashboard/DashboardUserAPI.java @@ -200,7 +200,8 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO response.addProperty("status", "UNKNOWN_USER_ERROR"); super.sendJsonResponse(200, response, resp); return; - } catch (StorageQueryException | StorageTransactionLogicException | TenantOrAppNotFoundException | BadPermissionException e) { + } catch (StorageQueryException | StorageTransactionLogicException | TenantOrAppNotFoundException | + BadPermissionException e) { throw new ServletException(e); } // Both email and userId are null diff --git a/src/main/java/io/supertokens/webserver/api/dashboard/GetTenantCoreConfigForDashboardAPI.java b/src/main/java/io/supertokens/webserver/api/dashboard/GetTenantCoreConfigForDashboardAPI.java index 4c0214dcb..8ab2d68e8 100644 --- a/src/main/java/io/supertokens/webserver/api/dashboard/GetTenantCoreConfigForDashboardAPI.java +++ b/src/main/java/io/supertokens/webserver/api/dashboard/GetTenantCoreConfigForDashboardAPI.java @@ -54,7 +54,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO ArrayList config = new ArrayList<>(); List coreConfigFields = CoreConfig.getConfigFieldsInfoForDashboard(main, getTenantIdentifier(req)); - List storageFields = StorageUtils.getDashboardStorage(getTenantStorage(req)).getPluginConfigFieldsInfo(); + List storageFields = StorageUtils.getDashboardStorage(getTenantStorage(req)) + .getPluginConfigFieldsInfo(); config.addAll(coreConfigFields); config.addAll(storageFields); @@ -73,7 +74,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO .getProtectedConfigsFromSuperTokensSaaSUsers(); for (JsonElement field : configJson) { String fieldName = field.getAsJsonObject().get("key").getAsString(); - if (!Arrays.asList(protectedPluginFields).contains(fieldName) && !Arrays.asList(CoreConfig.PROTECTED_CONFIGS).contains(fieldName)) { + if (!Arrays.asList(protectedPluginFields).contains(fieldName) && + !Arrays.asList(CoreConfig.PROTECTED_CONFIGS).contains(fieldName)) { configWithoutProtectedFields.add(field); } } diff --git a/src/main/java/io/supertokens/webserver/api/emailpassword/GeneratePasswordResetTokenAPI.java b/src/main/java/io/supertokens/webserver/api/emailpassword/GeneratePasswordResetTokenAPI.java index e568c9aae..8cc8464b4 100644 --- a/src/main/java/io/supertokens/webserver/api/emailpassword/GeneratePasswordResetTokenAPI.java +++ b/src/main/java/io/supertokens/webserver/api/emailpassword/GeneratePasswordResetTokenAPI.java @@ -60,7 +60,7 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I String userId = InputParser.parseStringOrThrowError(input, "userId", false); // logic according to https://github.com/supertokens/supertokens-core/issues/106 - TenantIdentifier tenantIdentifier; + TenantIdentifier tenantIdentifier; try { tenantIdentifier = getTenantIdentifier(req); } catch (TenantOrAppNotFoundException e) { @@ -68,7 +68,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I } try { - io.supertokens.webserver.api.emailpassword.Utils.assertIfEmailPasswordIsEnabledForTenant(main, tenantIdentifier, getVersionFromRequest(req)); + io.supertokens.webserver.api.emailpassword.Utils.assertIfEmailPasswordIsEnabledForTenant(main, + tenantIdentifier, getVersionFromRequest(req)); StorageAndUserIdMapping storageAndUserIdMapping = getStorageAndUserIdMappingForTenantSpecificApi(req, userId, UserIdType.ANY); diff --git a/src/main/java/io/supertokens/webserver/api/emailpassword/ImportUserWithPasswordHashAPI.java b/src/main/java/io/supertokens/webserver/api/emailpassword/ImportUserWithPasswordHashAPI.java index 4794d7a45..10dcb8a7c 100644 --- a/src/main/java/io/supertokens/webserver/api/emailpassword/ImportUserWithPasswordHashAPI.java +++ b/src/main/java/io/supertokens/webserver/api/emailpassword/ImportUserWithPasswordHashAPI.java @@ -98,7 +98,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I TenantIdentifier tenantIdentifier = getTenantIdentifier(req); Storage storage = getTenantStorage(req); - io.supertokens.webserver.api.emailpassword.Utils.assertIfEmailPasswordIsEnabledForTenant(main, tenantIdentifier, getVersionFromRequest(req)); + io.supertokens.webserver.api.emailpassword.Utils.assertIfEmailPasswordIsEnabledForTenant(main, + tenantIdentifier, getVersionFromRequest(req)); EmailPassword.ImportUserResponse importUserResponse = EmailPassword.importUserWithPasswordHash( tenantIdentifier, storage, main, email, diff --git a/src/main/java/io/supertokens/webserver/api/emailpassword/SignInAPI.java b/src/main/java/io/supertokens/webserver/api/emailpassword/SignInAPI.java index c05e4ccb8..9daaec81b 100644 --- a/src/main/java/io/supertokens/webserver/api/emailpassword/SignInAPI.java +++ b/src/main/java/io/supertokens/webserver/api/emailpassword/SignInAPI.java @@ -76,7 +76,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I } try { - io.supertokens.webserver.api.emailpassword.Utils.assertIfEmailPasswordIsEnabledForTenant(main, tenantIdentifier, getVersionFromRequest(req)); + io.supertokens.webserver.api.emailpassword.Utils.assertIfEmailPasswordIsEnabledForTenant(main, + tenantIdentifier, getVersionFromRequest(req)); AuthRecipeUserInfo user = EmailPassword.signIn(tenantIdentifier, storage, super.main, normalisedEmail, password); @@ -96,7 +97,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I result.add("user", userJson); if (getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v4_0)) { for (LoginMethod loginMethod : user.loginMethods) { - if (loginMethod.recipeId.equals(RECIPE_ID.EMAIL_PASSWORD) && normalisedEmail.equals(loginMethod.email)) { + if (loginMethod.recipeId.equals(RECIPE_ID.EMAIL_PASSWORD) && + normalisedEmail.equals(loginMethod.email)) { result.addProperty("recipeUserId", loginMethod.getSupertokensOrExternalUserId()); break; } diff --git a/src/main/java/io/supertokens/webserver/api/emailpassword/SignUpAPI.java b/src/main/java/io/supertokens/webserver/api/emailpassword/SignUpAPI.java index 6722f956a..ff24536ed 100644 --- a/src/main/java/io/supertokens/webserver/api/emailpassword/SignUpAPI.java +++ b/src/main/java/io/supertokens/webserver/api/emailpassword/SignUpAPI.java @@ -79,7 +79,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I } try { - io.supertokens.webserver.api.emailpassword.Utils.assertIfEmailPasswordIsEnabledForTenant(main, tenantIdentifier, getVersionFromRequest(req)); + io.supertokens.webserver.api.emailpassword.Utils.assertIfEmailPasswordIsEnabledForTenant(main, + tenantIdentifier, getVersionFromRequest(req)); AuthRecipeUserInfo user = EmailPassword.signUp(tenantIdentifier, storage, super.main, normalisedEmail, password); diff --git a/src/main/java/io/supertokens/webserver/api/emailpassword/UserAPI.java b/src/main/java/io/supertokens/webserver/api/emailpassword/UserAPI.java index 6f1c56ae9..08d4570d2 100644 --- a/src/main/java/io/supertokens/webserver/api/emailpassword/UserAPI.java +++ b/src/main/java/io/supertokens/webserver/api/emailpassword/UserAPI.java @@ -94,11 +94,11 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO user = EmailPassword.getUserUsingId( appIdentifier, storageAndUserIdMapping.storage, userId); - if (user != null) { - UserIdMapping.populateExternalUserIdForUsers(appIdentifier, - storageAndUserIdMapping.storage, - new AuthRecipeUserInfo[]{user}); - } + if (user != null) { + UserIdMapping.populateExternalUserIdForUsers(appIdentifier, + storageAndUserIdMapping.storage, + new AuthRecipeUserInfo[]{user}); + } } else { // API is tenant specific for get by Email diff --git a/src/main/java/io/supertokens/webserver/api/emailverification/GenerateEmailVerificationTokenAPI.java b/src/main/java/io/supertokens/webserver/api/emailverification/GenerateEmailVerificationTokenAPI.java index e2256f99a..12f461393 100644 --- a/src/main/java/io/supertokens/webserver/api/emailverification/GenerateEmailVerificationTokenAPI.java +++ b/src/main/java/io/supertokens/webserver/api/emailverification/GenerateEmailVerificationTokenAPI.java @@ -85,7 +85,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I JsonObject result = new JsonObject(); result.addProperty("status", "EMAIL_ALREADY_VERIFIED_ERROR"); super.sendJsonResponse(200, result, resp); - } catch (StorageQueryException | NoSuchAlgorithmException | InvalidKeySpecException | TenantOrAppNotFoundException e) { + } catch (StorageQueryException | NoSuchAlgorithmException | InvalidKeySpecException | + TenantOrAppNotFoundException e) { throw new ServletException(e); } diff --git a/src/main/java/io/supertokens/webserver/api/emailverification/UnverifyEmailAPI.java b/src/main/java/io/supertokens/webserver/api/emailverification/UnverifyEmailAPI.java index 826805856..0e6d85567 100644 --- a/src/main/java/io/supertokens/webserver/api/emailverification/UnverifyEmailAPI.java +++ b/src/main/java/io/supertokens/webserver/api/emailverification/UnverifyEmailAPI.java @@ -61,7 +61,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I AppIdentifier appIdentifier = getAppIdentifier(req); Storage storage; try { - StorageAndUserIdMapping storageAndUidMapping = enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( + StorageAndUserIdMapping storageAndUidMapping = + enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( req, userId, UserIdType.ANY, false); storage = storageAndUidMapping.storage; } catch (UnknownUserIdException e) { diff --git a/src/main/java/io/supertokens/webserver/api/emailverification/VerifyEmailAPI.java b/src/main/java/io/supertokens/webserver/api/emailverification/VerifyEmailAPI.java index a7ba01f29..cb758a6a2 100644 --- a/src/main/java/io/supertokens/webserver/api/emailverification/VerifyEmailAPI.java +++ b/src/main/java/io/supertokens/webserver/api/emailverification/VerifyEmailAPI.java @@ -94,7 +94,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I JsonObject result = new JsonObject(); result.addProperty("status", "EMAIL_VERIFICATION_INVALID_TOKEN_ERROR"); super.sendJsonResponse(200, result, resp); - } catch (StorageQueryException | NoSuchAlgorithmException | StorageTransactionLogicException | TenantOrAppNotFoundException e) { + } catch (StorageQueryException | NoSuchAlgorithmException | StorageTransactionLogicException | + TenantOrAppNotFoundException e) { throw new ServletException(e); } @@ -112,7 +113,8 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws Servl AppIdentifier appIdentifier = getAppIdentifier(req); Storage storage; try { - StorageAndUserIdMapping storageAndUserIdMapping = enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( + StorageAndUserIdMapping storageAndUserIdMapping = + enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( req, userId, UserIdType.ANY, false); storage = storageAndUserIdMapping.storage; } catch (UnknownUserIdException e) { diff --git a/src/main/java/io/supertokens/webserver/api/multitenancy/AssociateUserToTenantAPI.java b/src/main/java/io/supertokens/webserver/api/multitenancy/AssociateUserToTenantAPI.java index 0fbaac29a..1f9d45718 100644 --- a/src/main/java/io/supertokens/webserver/api/multitenancy/AssociateUserToTenantAPI.java +++ b/src/main/java/io/supertokens/webserver/api/multitenancy/AssociateUserToTenantAPI.java @@ -113,7 +113,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I result.addProperty("status", "THIRD_PARTY_USER_ALREADY_EXISTS_ERROR"); super.sendJsonResponse(200, result, resp); - } catch (AnotherPrimaryUserWithEmailAlreadyExistsException | AnotherPrimaryUserWithPhoneNumberAlreadyExistsException | + } catch (AnotherPrimaryUserWithEmailAlreadyExistsException | + AnotherPrimaryUserWithPhoneNumberAlreadyExistsException | AnotherPrimaryUserWithThirdPartyInfoAlreadyExistsException e) { JsonObject result = new JsonObject(); result.addProperty("status", "ASSOCIATION_NOT_ALLOWED_ERROR"); diff --git a/src/main/java/io/supertokens/webserver/api/multitenancy/BaseCreateOrUpdate.java b/src/main/java/io/supertokens/webserver/api/multitenancy/BaseCreateOrUpdate.java index 0029bf45b..2ee4aeb46 100644 --- a/src/main/java/io/supertokens/webserver/api/multitenancy/BaseCreateOrUpdate.java +++ b/src/main/java/io/supertokens/webserver/api/multitenancy/BaseCreateOrUpdate.java @@ -234,15 +234,18 @@ private static TenantConfig applyTenantUpdates( return tenantConfig; } - private static TenantConfig applyTenantUpdates_3_0(TenantConfig tenantConfig, JsonObject input) throws ServletException { + private static TenantConfig applyTenantUpdates_3_0(TenantConfig tenantConfig, JsonObject input) + throws ServletException { Boolean emailPasswordEnabled = InputParser.parseBooleanOrThrowError(input, "emailPasswordEnabled", true); Boolean thirdPartyEnabled = InputParser.parseBooleanOrThrowError(input, "thirdPartyEnabled", true); Boolean passwordlessEnabled = InputParser.parseBooleanOrThrowError(input, "passwordlessEnabled", true); - Set firstFactors = tenantConfig.firstFactors == null ? null : new HashSet<>(Set.of(tenantConfig.firstFactors)); + Set firstFactors = + tenantConfig.firstFactors == null ? null : new HashSet<>(Set.of(tenantConfig.firstFactors)); // Enabling recipes - if (Boolean.TRUE.equals(emailPasswordEnabled) && !tenantConfig.emailPasswordConfig.isEnabledInLesserThanOrEqualTo4_0(tenantConfig.firstFactors)) { + if (Boolean.TRUE.equals(emailPasswordEnabled) && + !tenantConfig.emailPasswordConfig.isEnabledInLesserThanOrEqualTo4_0(tenantConfig.firstFactors)) { tenantConfig = new TenantConfig( tenantConfig.tenantIdentifier, new EmailPasswordConfig(true), @@ -257,7 +260,8 @@ private static TenantConfig applyTenantUpdates_3_0(TenantConfig tenantConfig, Js firstFactors.add("emailpassword"); } } - if (Boolean.TRUE.equals(thirdPartyEnabled) && !tenantConfig.thirdPartyConfig.isEnabledInLesserThanOrEqualTo4_0(tenantConfig.firstFactors)) { + if (Boolean.TRUE.equals(thirdPartyEnabled) && + !tenantConfig.thirdPartyConfig.isEnabledInLesserThanOrEqualTo4_0(tenantConfig.firstFactors)) { tenantConfig = new TenantConfig( tenantConfig.tenantIdentifier, tenantConfig.emailPasswordConfig, @@ -272,7 +276,8 @@ private static TenantConfig applyTenantUpdates_3_0(TenantConfig tenantConfig, Js firstFactors.add("thirdparty"); } } - if (Boolean.TRUE.equals(passwordlessEnabled) && !tenantConfig.passwordlessConfig.isEnabledInLesserThanOrEqualTo4_0(tenantConfig.firstFactors)) { + if (Boolean.TRUE.equals(passwordlessEnabled) && + !tenantConfig.passwordlessConfig.isEnabledInLesserThanOrEqualTo4_0(tenantConfig.firstFactors)) { tenantConfig = new TenantConfig( tenantConfig.tenantIdentifier, tenantConfig.emailPasswordConfig, @@ -294,15 +299,16 @@ private static TenantConfig applyTenantUpdates_3_0(TenantConfig tenantConfig, Js // Disabling recipes if (firstFactors == null && ( tenantConfig.emailPasswordConfig.enabled == false || - tenantConfig.thirdPartyConfig.enabled == false || - tenantConfig.passwordlessConfig.enabled == false || - Boolean.FALSE.equals(emailPasswordEnabled) || - Boolean.FALSE.equals(thirdPartyEnabled) || - Boolean.FALSE.equals(passwordlessEnabled) + tenantConfig.thirdPartyConfig.enabled == false || + tenantConfig.passwordlessConfig.enabled == false || + Boolean.FALSE.equals(emailPasswordEnabled) || + Boolean.FALSE.equals(thirdPartyEnabled) || + Boolean.FALSE.equals(passwordlessEnabled) )) { // since the boolean states corresponds to the first factors // setting it to all factors now, and later we will remove the disabled ones - firstFactors = new HashSet<>(Set.of("emailpassword", "thirdparty", "otp-phone", "otp-email", "link-phone", "link-email")); + firstFactors = new HashSet<>( + Set.of("emailpassword", "thirdparty", "otp-phone", "otp-email", "link-phone", "link-email")); } if (tenantConfig.emailPasswordConfig.enabled == false || Boolean.FALSE.equals(emailPasswordEnabled)) { @@ -323,7 +329,8 @@ private static TenantConfig applyTenantUpdates_3_0(TenantConfig tenantConfig, Js // tenantConfig = new TenantConfig( // tenantConfig.tenantIdentifier, // tenantConfig.emailPasswordConfig, -// new ThirdPartyConfig(tenantConfig.thirdPartyConfig.enabled, tenantConfig.thirdPartyConfig.providers), +// new ThirdPartyConfig(tenantConfig.thirdPartyConfig.enabled, tenantConfig.thirdPartyConfig +// .providers), // tenantConfig.passwordlessConfig, // tenantConfig.firstFactors, // tenantConfig.requiredSecondaryFactors, @@ -412,52 +419,80 @@ private static TenantConfig applyTenantUpdates_5_0(TenantConfig tenantConfig, Js if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && requiredSecondaryFactors.length == 0) { throw new ServletException(new BadRequestException( - "requiredSecondaryFactors cannot be empty. Set null instead to remove all required secondary factors.")); + "requiredSecondaryFactors cannot be empty. Set null instead to remove all required secondary " + + "factors.")); } // check for conflicting updates if (Boolean.FALSE.equals(emailPasswordEnabled)) { if (hasFirstFactors && firstFactors != null && List.of(firstFactors).contains("emailpassword")) { - throw new InvalidConfigException("firstFactors should not contain 'emailpassword' because emailPassword is disabled for the tenant."); + throw new InvalidConfigException( + "firstFactors should not contain 'emailpassword' because emailPassword is disabled for the " + + "tenant."); } - if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && List.of(requiredSecondaryFactors).contains("emailpassword")) { - throw new InvalidConfigException("requiredSecondaryFactors should not contain 'emailpassword' because emailPassword is disabled for the tenant."); + if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && + List.of(requiredSecondaryFactors).contains("emailpassword")) { + throw new InvalidConfigException( + "requiredSecondaryFactors should not contain 'emailpassword' because emailPassword is " + + "disabled for the tenant."); } } if (Boolean.FALSE.equals(thirdPartyEnabled)) { if (hasFirstFactors && firstFactors != null && List.of(firstFactors).contains("thirdparty")) { - throw new InvalidConfigException("firstFactors should not contain 'thirdparty' because thirdParty is disabled for the tenant."); + throw new InvalidConfigException( + "firstFactors should not contain 'thirdparty' because thirdParty is disabled for the tenant."); } - if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && List.of(requiredSecondaryFactors).contains("thirdparty")) { - throw new InvalidConfigException("requiredSecondaryFactors should not contain 'thirdparty' because thirdParty is disabled for the tenant."); + if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && + List.of(requiredSecondaryFactors).contains("thirdparty")) { + throw new InvalidConfigException( + "requiredSecondaryFactors should not contain 'thirdparty' because thirdParty is disabled for " + + "the tenant."); } } if (Boolean.FALSE.equals(passwordlessEnabled)) { if (hasFirstFactors && firstFactors != null && List.of(firstFactors).contains("otp-phone")) { - throw new InvalidConfigException("firstFactors should not contain 'otp-phone' because passwordless is disabled for the tenant."); + throw new InvalidConfigException( + "firstFactors should not contain 'otp-phone' because passwordless is disabled for the tenant."); } if (hasFirstFactors && firstFactors != null && List.of(firstFactors).contains("otp-email")) { - throw new InvalidConfigException("firstFactors should not contain 'otp-email' because passwordless is disabled for the tenant."); + throw new InvalidConfigException( + "firstFactors should not contain 'otp-email' because passwordless is disabled for the tenant."); } if (hasFirstFactors && firstFactors != null && List.of(firstFactors).contains("link-phone")) { - throw new InvalidConfigException("firstFactors should not contain 'link-phone' because passwordless is disabled for the tenant."); + throw new InvalidConfigException( + "firstFactors should not contain 'link-phone' because passwordless is disabled for the tenant" + + "."); } if (hasFirstFactors && firstFactors != null && List.of(firstFactors).contains("link-email")) { - throw new InvalidConfigException("firstFactors should not contain 'link-email' because passwordless is disabled for the tenant."); + throw new InvalidConfigException( + "firstFactors should not contain 'link-email' because passwordless is disabled for the tenant" + + "."); } - if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && List.of(requiredSecondaryFactors).contains("otp-phone")) { - throw new InvalidConfigException("requiredSecondaryFactors should not contain 'otp-phone' because passwordless is disabled for the tenant."); + if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && + List.of(requiredSecondaryFactors).contains("otp-phone")) { + throw new InvalidConfigException( + "requiredSecondaryFactors should not contain 'otp-phone' because passwordless is disabled for" + + " the tenant."); } - if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && List.of(requiredSecondaryFactors).contains("otp-email")) { - throw new InvalidConfigException("requiredSecondaryFactors should not contain 'otp-email' because passwordless is disabled for the tenant."); + if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && + List.of(requiredSecondaryFactors).contains("otp-email")) { + throw new InvalidConfigException( + "requiredSecondaryFactors should not contain 'otp-email' because passwordless is disabled for" + + " the tenant."); } - if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && List.of(requiredSecondaryFactors).contains("link-phone")) { - throw new InvalidConfigException("requiredSecondaryFactors should not contain 'link-phone' because passwordless is disabled for the tenant."); + if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && + List.of(requiredSecondaryFactors).contains("link-phone")) { + throw new InvalidConfigException( + "requiredSecondaryFactors should not contain 'link-phone' because passwordless is disabled " + + "for the tenant."); } - if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && List.of(requiredSecondaryFactors).contains("link-email")) { - throw new InvalidConfigException("requiredSecondaryFactors should not contain 'link-email' because passwordless is disabled for the tenant."); + if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && + List.of(requiredSecondaryFactors).contains("link-email")) { + throw new InvalidConfigException( + "requiredSecondaryFactors should not contain 'link-email' because passwordless is disabled " + + "for the tenant."); } } @@ -466,12 +501,14 @@ private static TenantConfig applyTenantUpdates_5_0(TenantConfig tenantConfig, Js if (Boolean.FALSE.equals(emailPasswordEnabled)) { if (hasFirstFactors && firstFactors != null && List.of(firstFactors).contains("emailpassword")) { throw new InvalidConfigException( - "firstFactors should not contain 'emailpassword' because emailPassword is disabled for the tenant."); + "firstFactors should not contain 'emailpassword' because emailPassword is disabled for the " + + "tenant."); } if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && List.of(requiredSecondaryFactors).contains("emailpassword")) { throw new InvalidConfigException( - "requiredSecondaryFactors should not contain 'emailpassword' because emailPassword is disabled for the tenant."); + "requiredSecondaryFactors should not contain 'emailpassword' because emailPassword is " + + "disabled for the tenant."); } } @@ -483,7 +520,8 @@ private static TenantConfig applyTenantUpdates_5_0(TenantConfig tenantConfig, Js if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && List.of(requiredSecondaryFactors).contains("thirdparty")) { throw new InvalidConfigException( - "requiredSecondaryFactors should not contain 'thirdparty' because thirdParty is disabled for the tenant."); + "requiredSecondaryFactors should not contain 'thirdparty' because thirdParty is disabled for " + + "the tenant."); } } @@ -498,40 +536,49 @@ private static TenantConfig applyTenantUpdates_5_0(TenantConfig tenantConfig, Js } if (hasFirstFactors && firstFactors != null && List.of(firstFactors).contains("link-phone")) { throw new InvalidConfigException( - "firstFactors should not contain 'link-phone' because passwordless is disabled for the tenant."); + "firstFactors should not contain 'link-phone' because passwordless is disabled for the tenant" + + "."); } if (hasFirstFactors && firstFactors != null && List.of(firstFactors).contains("link-email")) { throw new InvalidConfigException( - "firstFactors should not contain 'link-email' because passwordless is disabled for the tenant."); + "firstFactors should not contain 'link-email' because passwordless is disabled for the tenant" + + "."); } if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && List.of(requiredSecondaryFactors).contains("otp-phone")) { throw new InvalidConfigException( - "requiredSecondaryFactors should not contain 'otp-phone' because passwordless is disabled for the tenant."); + "requiredSecondaryFactors should not contain 'otp-phone' because passwordless is disabled for" + + " the tenant."); } if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && List.of(requiredSecondaryFactors).contains("otp-email")) { throw new InvalidConfigException( - "requiredSecondaryFactors should not contain 'otp-email' because passwordless is disabled for the tenant."); + "requiredSecondaryFactors should not contain 'otp-email' because passwordless is disabled for" + + " the tenant."); } if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && List.of(requiredSecondaryFactors).contains("link-phone")) { throw new InvalidConfigException( - "requiredSecondaryFactors should not contain 'link-phone' because passwordless is disabled for the tenant."); + "requiredSecondaryFactors should not contain 'link-phone' because passwordless is disabled " + + "for the tenant."); } if (hasRequiredSecondaryFactors && requiredSecondaryFactors != null && List.of(requiredSecondaryFactors).contains("link-email")) { throw new InvalidConfigException( - "requiredSecondaryFactors should not contain 'link-email' because passwordless is disabled for the tenant."); + "requiredSecondaryFactors should not contain 'link-email' because passwordless is disabled " + + "for the tenant."); } } List updateKeys = new ArrayList<>(); List updateValues = new ArrayList<>(); - if ((Boolean.TRUE.equals(emailPasswordEnabled) && !tenantConfig.emailPasswordConfig.isEnabledIn5_0(tenantConfig.firstFactors)) || - (Boolean.TRUE.equals(thirdPartyEnabled) && !tenantConfig.thirdPartyConfig.isEnabledIn5_0(tenantConfig.firstFactors)) || - (Boolean.TRUE.equals(passwordlessEnabled) && !tenantConfig.passwordlessConfig.isEnabledIn5_0(tenantConfig.firstFactors)) + if ((Boolean.TRUE.equals(emailPasswordEnabled) && + !tenantConfig.emailPasswordConfig.isEnabledIn5_0(tenantConfig.firstFactors)) || + (Boolean.TRUE.equals(thirdPartyEnabled) && + !tenantConfig.thirdPartyConfig.isEnabledIn5_0(tenantConfig.firstFactors)) || + (Boolean.TRUE.equals(passwordlessEnabled) && + !tenantConfig.passwordlessConfig.isEnabledIn5_0(tenantConfig.firstFactors)) ) { if (tenantConfig.firstFactors != null && tenantConfig.firstFactors.length == 0) { tenantConfig = new TenantConfig( @@ -576,7 +623,8 @@ private static TenantConfig applyTenantUpdates_5_0(TenantConfig tenantConfig, Js updateValues.add(false); } - if (Boolean.FALSE.equals(emailPasswordEnabled) || Boolean.FALSE.equals(thirdPartyEnabled) || Boolean.FALSE.equals(passwordlessEnabled)) { + if (Boolean.FALSE.equals(emailPasswordEnabled) || Boolean.FALSE.equals(thirdPartyEnabled) || + Boolean.FALSE.equals(passwordlessEnabled)) { if (tenantConfig.firstFactors != null && !hasFirstFactors) { Set firstFactorsSet = new HashSet<>(Set.of(tenantConfig.firstFactors)); @@ -635,15 +683,18 @@ private static TenantConfig applyTenantUpdates_5_0(TenantConfig tenantConfig, Js updateValues.add(firstFactors); for (String factor : firstFactors) { - if (factor.equals("emailpassword") && !tenantConfig.emailPasswordConfig.isEnabledIn5_0(tenantConfig.firstFactors)) { + if (factor.equals("emailpassword") && + !tenantConfig.emailPasswordConfig.isEnabledIn5_0(tenantConfig.firstFactors)) { updateKeys.add("emailPasswordEnabled"); updateValues.add(true); } - if (factor.equals("thirdparty") && !tenantConfig.thirdPartyConfig.isEnabledIn5_0(tenantConfig.firstFactors)) { + if (factor.equals("thirdparty") && + !tenantConfig.thirdPartyConfig.isEnabledIn5_0(tenantConfig.firstFactors)) { updateKeys.add("thirdPartyEnabled"); updateValues.add(true); } - if ((factor.equals("otp-phone") || factor.equals("otp-email") || factor.equals("link-phone") || factor.equals("link-email")) && + if ((factor.equals("otp-phone") || factor.equals("otp-email") || factor.equals("link-phone") || + factor.equals("link-email")) && !tenantConfig.passwordlessConfig.isEnabledIn5_0(tenantConfig.firstFactors)) { updateKeys.add("passwordlessEnabled"); updateValues.add(true); @@ -662,21 +713,24 @@ private static TenantConfig applyTenantUpdates_5_0(TenantConfig tenantConfig, Js for (String factor : requiredSecondaryFactors) { boolean enablingSomeRecipe = false; - if (factor.equals("emailpassword") && !tenantConfig.emailPasswordConfig.isEnabledIn5_0(tenantConfig.firstFactors)) { + if (factor.equals("emailpassword") && + !tenantConfig.emailPasswordConfig.isEnabledIn5_0(tenantConfig.firstFactors)) { updateKeys.add("emailPasswordEnabled"); updateValues.add(true); if (!Boolean.TRUE.equals(emailPasswordEnabled)) { enablingSomeRecipe = true; } } - if (factor.equals("thirdparty") && !tenantConfig.thirdPartyConfig.isEnabledIn5_0(tenantConfig.firstFactors)) { + if (factor.equals("thirdparty") && + !tenantConfig.thirdPartyConfig.isEnabledIn5_0(tenantConfig.firstFactors)) { updateKeys.add("thirdPartyEnabled"); updateValues.add(true); if (!Boolean.TRUE.equals(thirdPartyEnabled)) { enablingSomeRecipe = true; } } - if ((factor.equals("otp-phone") || factor.equals("otp-email") || factor.equals("link-phone") || factor.equals("link-email")) && + if ((factor.equals("otp-phone") || factor.equals("otp-email") || factor.equals("link-phone") || + factor.equals("link-email")) && !tenantConfig.passwordlessConfig.isEnabledIn5_0(tenantConfig.firstFactors)) { updateKeys.add("passwordlessEnabled"); updateValues.add(true); @@ -688,13 +742,16 @@ private static TenantConfig applyTenantUpdates_5_0(TenantConfig tenantConfig, Js if (!hasFirstFactors && enablingSomeRecipe == true && tenantConfig.firstFactors == null) { Set firstFactorsSet = new HashSet<>(); - if ((tenantConfig.emailPasswordConfig.enabled || Boolean.TRUE.equals(emailPasswordEnabled)) && !Boolean.FALSE.equals(emailPasswordEnabled)) { + if ((tenantConfig.emailPasswordConfig.enabled || Boolean.TRUE.equals(emailPasswordEnabled)) && + !Boolean.FALSE.equals(emailPasswordEnabled)) { firstFactorsSet.add("emailpassword"); } - if ((tenantConfig.thirdPartyConfig.enabled || Boolean.TRUE.equals(thirdPartyEnabled)) && !Boolean.FALSE.equals(thirdPartyEnabled)) { + if ((tenantConfig.thirdPartyConfig.enabled || Boolean.TRUE.equals(thirdPartyEnabled)) && + !Boolean.FALSE.equals(thirdPartyEnabled)) { firstFactorsSet.add("thirdparty"); } - if ((tenantConfig.passwordlessConfig.enabled || Boolean.TRUE.equals(passwordlessEnabled)) && !Boolean.FALSE.equals(passwordlessEnabled)) { + if ((tenantConfig.passwordlessConfig.enabled || Boolean.TRUE.equals(passwordlessEnabled)) && + !Boolean.FALSE.equals(passwordlessEnabled)) { firstFactorsSet.add("otp-phone"); firstFactorsSet.add("otp-email"); firstFactorsSet.add("link-phone"); @@ -802,7 +859,7 @@ private static TenantConfig applyTenantUpdates_5_0(TenantConfig tenantConfig, Js // if firstFactors or requiredSecondaryFactors are set, make sure // appropriate recipes are enabled if (tenantConfig.firstFactors != null) { - for (String factor: tenantConfig.firstFactors) { + for (String factor : tenantConfig.firstFactors) { if (factor.equals("emailpassword")) { tenantConfig = new TenantConfig( tenantConfig.tenantIdentifier, @@ -825,7 +882,8 @@ private static TenantConfig applyTenantUpdates_5_0(TenantConfig tenantConfig, Js tenantConfig.coreConfig ); } - if (factor.equals("otp-phone") || factor.equals("otp-email") || factor.equals("link-phone") || factor.equals("link-email")) { + if (factor.equals("otp-phone") || factor.equals("otp-email") || factor.equals("link-phone") || + factor.equals("link-email")) { tenantConfig = new TenantConfig( tenantConfig.tenantIdentifier, tenantConfig.emailPasswordConfig, @@ -839,7 +897,7 @@ private static TenantConfig applyTenantUpdates_5_0(TenantConfig tenantConfig, Js } } if (tenantConfig.requiredSecondaryFactors != null) { - for (String factor: tenantConfig.requiredSecondaryFactors) { + for (String factor : tenantConfig.requiredSecondaryFactors) { if (factor.equals("emailpassword")) { tenantConfig = new TenantConfig( tenantConfig.tenantIdentifier, @@ -862,7 +920,8 @@ private static TenantConfig applyTenantUpdates_5_0(TenantConfig tenantConfig, Js tenantConfig.coreConfig ); } - if (factor.equals("otp-phone") || factor.equals("otp-email") || factor.equals("link-phone") || factor.equals("link-email")) { + if (factor.equals("otp-phone") || factor.equals("otp-email") || factor.equals("link-phone") || + factor.equals("link-email")) { tenantConfig = new TenantConfig( tenantConfig.tenantIdentifier, tenantConfig.emailPasswordConfig, @@ -879,9 +938,11 @@ private static TenantConfig applyTenantUpdates_5_0(TenantConfig tenantConfig, Js return tenantConfig; } - private static TenantConfig applyV2TenantUpdates_5_1(TenantConfig tenantConfig, JsonObject input) throws ServletException { + private static TenantConfig applyV2TenantUpdates_5_1(TenantConfig tenantConfig, JsonObject input) + throws ServletException { if (input.has("emailPasswordEnabled")) { - throw new ServletException(new BadRequestException("emailPasswordEnabled is not a valid input for this API")); + throw new ServletException( + new BadRequestException("emailPasswordEnabled is not a valid input for this API")); } if (input.has("thirdPartyEnabled")) { throw new ServletException(new BadRequestException("thirdParty is not a valid input for this API")); @@ -898,10 +959,12 @@ private static TenantConfig applyV2TenantUpdates_5_1(TenantConfig tenantConfig, JsonArray firstFactorsArr = InputParser.parseArrayOrThrowError(input, "firstFactors", true); firstFactors = new String[firstFactorsArr.size()]; for (int i = 0; i < firstFactors.length; i++) { - firstFactors[i] = InputParser.parseStringFromElementOrThrowError(firstFactorsArr.get(i), "firstFactors", false); + firstFactors[i] = InputParser.parseStringFromElementOrThrowError(firstFactorsArr.get(i), "firstFactors", + false); } if (firstFactors.length != new HashSet<>(Arrays.asList(firstFactors)).size()) { - throw new ServletException(new BadRequestException("firstFactors input should not contain duplicate values")); + throw new ServletException( + new BadRequestException("firstFactors input should not contain duplicate values")); } } @@ -910,13 +973,16 @@ private static TenantConfig applyV2TenantUpdates_5_1(TenantConfig tenantConfig, boolean hasRequiredSecondaryFactors; hasRequiredSecondaryFactors = input.has("requiredSecondaryFactors"); if (hasRequiredSecondaryFactors && !input.get("requiredSecondaryFactors").isJsonNull()) { - JsonArray requiredSecondaryFactorsArr = InputParser.parseArrayOrThrowError(input, "requiredSecondaryFactors", true); + JsonArray requiredSecondaryFactorsArr = InputParser.parseArrayOrThrowError(input, + "requiredSecondaryFactors", true); requiredSecondaryFactors = new String[requiredSecondaryFactorsArr.size()]; for (int i = 0; i < requiredSecondaryFactors.length; i++) { - requiredSecondaryFactors[i] = InputParser.parseStringFromElementOrThrowError(requiredSecondaryFactorsArr.get(i), "requiredSecondaryFactors", false); + requiredSecondaryFactors[i] = InputParser.parseStringFromElementOrThrowError( + requiredSecondaryFactorsArr.get(i), "requiredSecondaryFactors", false); } if (requiredSecondaryFactors.length != new HashSet<>(Arrays.asList(requiredSecondaryFactors)).size()) { - throw new ServletException(new BadRequestException("requiredSecondaryFactors input should not contain duplicate values")); + throw new ServletException( + new BadRequestException("requiredSecondaryFactors input should not contain duplicate values")); } } diff --git a/src/main/java/io/supertokens/webserver/api/multitenancy/CreateOrUpdateTenantOrGetTenantAPI.java b/src/main/java/io/supertokens/webserver/api/multitenancy/CreateOrUpdateTenantOrGetTenantAPI.java index 46c5179f2..7ca8a242a 100644 --- a/src/main/java/io/supertokens/webserver/api/multitenancy/CreateOrUpdateTenantOrGetTenantAPI.java +++ b/src/main/java/io/supertokens/webserver/api/multitenancy/CreateOrUpdateTenantOrGetTenantAPI.java @@ -63,7 +63,8 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO super.handle( req, resp, sourceTenantIdentifier, - new TenantIdentifier(sourceTenantIdentifier.getConnectionUriDomain(), sourceTenantIdentifier.getAppId(), tenantId), + new TenantIdentifier(sourceTenantIdentifier.getConnectionUriDomain(), sourceTenantIdentifier.getAppId(), + tenantId), input, false); } @@ -78,7 +79,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO boolean shouldProtect = shouldProtectProtectedConfig(req); JsonObject result; if (getVersionFromRequest(req).lesserThan(SemVer.v5_0)) { - result = config.toJsonLesserThanOrEqualTo4_0(shouldProtect, getTenantStorage(req), CoreConfig.PROTECTED_CONFIGS); + result = config.toJsonLesserThanOrEqualTo4_0(shouldProtect, getTenantStorage(req), + CoreConfig.PROTECTED_CONFIGS); } else { result = config.toJson5_0(shouldProtect, getTenantStorage(req), CoreConfig.PROTECTED_CONFIGS); } diff --git a/src/main/java/io/supertokens/webserver/api/multitenancy/CreateOrUpdateTenantOrGetTenantV2API.java b/src/main/java/io/supertokens/webserver/api/multitenancy/CreateOrUpdateTenantOrGetTenantV2API.java index 7447372c9..6e84f46e8 100644 --- a/src/main/java/io/supertokens/webserver/api/multitenancy/CreateOrUpdateTenantOrGetTenantV2API.java +++ b/src/main/java/io/supertokens/webserver/api/multitenancy/CreateOrUpdateTenantOrGetTenantV2API.java @@ -62,7 +62,8 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO super.handle( req, resp, sourceTenantIdentifier, - new TenantIdentifier(sourceTenantIdentifier.getConnectionUriDomain(), sourceTenantIdentifier.getAppId(), tenantId), + new TenantIdentifier(sourceTenantIdentifier.getConnectionUriDomain(), sourceTenantIdentifier.getAppId(), + tenantId), input, true); } @@ -75,7 +76,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO throw new TenantOrAppNotFoundException(tenantIdentifier); } boolean shouldProtect = shouldProtectProtectedConfig(req); - JsonObject result = config.toJson_v2_5_1(shouldProtect, getTenantStorage(req), CoreConfig.PROTECTED_CONFIGS); + JsonObject result = config.toJson_v2_5_1(shouldProtect, getTenantStorage(req), + CoreConfig.PROTECTED_CONFIGS); result.addProperty("status", "OK"); diff --git a/src/main/java/io/supertokens/webserver/api/multitenancy/ListAppsAPI.java b/src/main/java/io/supertokens/webserver/api/multitenancy/ListAppsAPI.java index b2360fc56..a3c4a9ecc 100644 --- a/src/main/java/io/supertokens/webserver/api/multitenancy/ListAppsAPI.java +++ b/src/main/java/io/supertokens/webserver/api/multitenancy/ListAppsAPI.java @@ -78,15 +78,16 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO boolean shouldProtect = shouldProtectProtectedConfig(req); JsonArray appsArray = new JsonArray(); for (Map.Entry> entry : appsToTenants.entrySet()) { - String appId = entry.getKey(); - JsonObject appObject = new JsonObject(); - appObject.addProperty("appId", appId); + String appId = entry.getKey(); + JsonObject appObject = new JsonObject(); + appObject.addProperty("appId", appId); JsonArray tenantsArray = new JsonArray(); for (TenantConfig tenantConfig : entry.getValue()) { JsonObject tenantConfigJson; if (getVersionFromRequest(req).lesserThan(SemVer.v5_0)) { - tenantConfigJson = tenantConfig.toJsonLesserThanOrEqualTo4_0(shouldProtect, storage, CoreConfig.PROTECTED_CONFIGS); + tenantConfigJson = tenantConfig.toJsonLesserThanOrEqualTo4_0(shouldProtect, storage, + CoreConfig.PROTECTED_CONFIGS); } else { tenantConfigJson = tenantConfig.toJson5_0(shouldProtect, storage, CoreConfig.PROTECTED_CONFIGS); } diff --git a/src/main/java/io/supertokens/webserver/api/multitenancy/ListAppsV2API.java b/src/main/java/io/supertokens/webserver/api/multitenancy/ListAppsV2API.java index fde531d37..7ea91d365 100644 --- a/src/main/java/io/supertokens/webserver/api/multitenancy/ListAppsV2API.java +++ b/src/main/java/io/supertokens/webserver/api/multitenancy/ListAppsV2API.java @@ -76,9 +76,9 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO boolean shouldProtect = shouldProtectProtectedConfig(req); JsonArray appsArray = new JsonArray(); for (Map.Entry> entry : appsToTenants.entrySet()) { - String appId = entry.getKey(); - JsonObject appObject = new JsonObject(); - appObject.addProperty("appId", appId); + String appId = entry.getKey(); + JsonObject appObject = new JsonObject(); + appObject.addProperty("appId", appId); JsonArray tenantsArray = new JsonArray(); for (TenantConfig tenantConfig : entry.getValue()) { JsonObject tenantConfigJson = tenantConfig.toJson_v2_5_1(shouldProtect, storage, diff --git a/src/main/java/io/supertokens/webserver/api/multitenancy/ListConnectionUriDomainsAPI.java b/src/main/java/io/supertokens/webserver/api/multitenancy/ListConnectionUriDomainsAPI.java index b563d3b81..1b3608eb2 100644 --- a/src/main/java/io/supertokens/webserver/api/multitenancy/ListConnectionUriDomainsAPI.java +++ b/src/main/java/io/supertokens/webserver/api/multitenancy/ListConnectionUriDomainsAPI.java @@ -60,7 +60,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO if (!tenantIdentifier.equals(new TenantIdentifier(null, null, null))) { throw new BadPermissionException( - "Only the public tenantId, public appId and default connectionUriDomain is allowed to list all " + + "Only the public tenantId, public appId and default connectionUriDomain is allowed to list " + + "all " + "connectionUriDomains and appIds associated with this " + "core"); } @@ -99,9 +100,11 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO JsonObject tenantConfigJson; if (getVersionFromRequest(req).lesserThan(SemVer.v5_0)) { - tenantConfigJson = tenantConfig.toJsonLesserThanOrEqualTo4_0(shouldProtect, storage, CoreConfig.PROTECTED_CONFIGS); + tenantConfigJson = tenantConfig.toJsonLesserThanOrEqualTo4_0(shouldProtect, storage, + CoreConfig.PROTECTED_CONFIGS); } else { - tenantConfigJson = tenantConfig.toJson5_0(shouldProtect, storage, CoreConfig.PROTECTED_CONFIGS); + tenantConfigJson = tenantConfig.toJson5_0(shouldProtect, storage, + CoreConfig.PROTECTED_CONFIGS); } tenantsArray.add(tenantConfigJson); diff --git a/src/main/java/io/supertokens/webserver/api/multitenancy/ListConnectionUriDomainsV2API.java b/src/main/java/io/supertokens/webserver/api/multitenancy/ListConnectionUriDomainsV2API.java index 0ca7e72db..315dd9a44 100644 --- a/src/main/java/io/supertokens/webserver/api/multitenancy/ListConnectionUriDomainsV2API.java +++ b/src/main/java/io/supertokens/webserver/api/multitenancy/ListConnectionUriDomainsV2API.java @@ -58,7 +58,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO if (!tenantIdentifier.equals(new TenantIdentifier(null, null, null))) { throw new BadPermissionException( - "Only the public tenantId, public appId and default connectionUriDomain is allowed to list all " + + "Only the public tenantId, public appId and default connectionUriDomain is allowed to list " + + "all " + "connectionUriDomains and appIds associated with this " + "core"); } diff --git a/src/main/java/io/supertokens/webserver/api/multitenancy/ListTenantsAPI.java b/src/main/java/io/supertokens/webserver/api/multitenancy/ListTenantsAPI.java index b0dde10cc..755c85f82 100644 --- a/src/main/java/io/supertokens/webserver/api/multitenancy/ListTenantsAPI.java +++ b/src/main/java/io/supertokens/webserver/api/multitenancy/ListTenantsAPI.java @@ -68,7 +68,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO JsonObject tenantConfigJson; if (getVersionFromRequest(req).lesserThan(SemVer.v5_0)) { - tenantConfigJson = tenantConfig.toJsonLesserThanOrEqualTo4_0(shouldProtect, storage, CoreConfig.PROTECTED_CONFIGS); + tenantConfigJson = tenantConfig.toJsonLesserThanOrEqualTo4_0(shouldProtect, storage, + CoreConfig.PROTECTED_CONFIGS); } else { tenantConfigJson = tenantConfig.toJson5_0(shouldProtect, storage, CoreConfig.PROTECTED_CONFIGS); } diff --git a/src/main/java/io/supertokens/webserver/api/multitenancy/RemoveAppAPI.java b/src/main/java/io/supertokens/webserver/api/multitenancy/RemoveAppAPI.java index 4219c5c79..5f8ee47f7 100644 --- a/src/main/java/io/supertokens/webserver/api/multitenancy/RemoveAppAPI.java +++ b/src/main/java/io/supertokens/webserver/api/multitenancy/RemoveAppAPI.java @@ -55,16 +55,19 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I appId = Utils.normalizeAndValidateAppId(appId); if (appId.equals(TenantIdentifier.DEFAULT_APP_ID)) { - throw new ServletException(new BadPermissionException("Cannot delete the public app, use remove connection uri domain API instead")); + throw new ServletException(new BadPermissionException( + "Cannot delete the public app, use remove connection uri domain API instead")); } try { TenantIdentifier sourceTenantIdentifier = this.getTenantIdentifier(req); if (!sourceTenantIdentifier.getTenantId().equals(TenantIdentifier.DEFAULT_TENANT_ID) || !sourceTenantIdentifier.getAppId().equals(TenantIdentifier.DEFAULT_APP_ID)) { - throw new BadPermissionException("Only the public tenantId and public appId is allowed to delete an app"); + throw new BadPermissionException( + "Only the public tenantId and public appId is allowed to delete an app"); } - boolean didExist = Multitenancy.deleteApp(new AppIdentifier(sourceTenantIdentifier.getConnectionUriDomain(), appId), main); + boolean didExist = Multitenancy.deleteApp( + new AppIdentifier(sourceTenantIdentifier.getConnectionUriDomain(), appId), main); JsonObject result = new JsonObject(); result.addProperty("status", "OK"); result.addProperty("didExist", didExist); diff --git a/src/main/java/io/supertokens/webserver/api/multitenancy/RemoveConnectionUriDomainAPI.java b/src/main/java/io/supertokens/webserver/api/multitenancy/RemoveConnectionUriDomainAPI.java index fa4ca3a68..69ffb82d1 100644 --- a/src/main/java/io/supertokens/webserver/api/multitenancy/RemoveConnectionUriDomainAPI.java +++ b/src/main/java/io/supertokens/webserver/api/multitenancy/RemoveConnectionUriDomainAPI.java @@ -61,7 +61,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I TenantIdentifier sourceTenantIdentifier = this.getTenantIdentifier(req); if (!sourceTenantIdentifier.equals(new TenantIdentifier(null, null, null))) { throw new BadPermissionException( - "Only the public tenantId, public appId and default connectionUriDomain is allowed to delete a connectionUriDomain"); + "Only the public tenantId, public appId and default connectionUriDomain is allowed to delete " + + "a connectionUriDomain"); } boolean didExist = Multitenancy.deleteConnectionUriDomain(connectionUriDomain, main); diff --git a/src/main/java/io/supertokens/webserver/api/multitenancy/RemoveTenantAPI.java b/src/main/java/io/supertokens/webserver/api/multitenancy/RemoveTenantAPI.java index b4faa4cd3..294ad3825 100644 --- a/src/main/java/io/supertokens/webserver/api/multitenancy/RemoveTenantAPI.java +++ b/src/main/java/io/supertokens/webserver/api/multitenancy/RemoveTenantAPI.java @@ -54,7 +54,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I tenantId = Utils.normalizeAndValidateTenantId(tenantId); if (tenantId.equals(TenantIdentifier.DEFAULT_TENANT_ID)) { - throw new ServletException(new BadPermissionException("Cannot delete public tenant, use remove app API instead")); + throw new ServletException( + new BadPermissionException("Cannot delete public tenant, use remove app API instead")); } try { @@ -64,7 +65,9 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I throw new BadPermissionException("Only the public tenantId is allowed to delete a tenant"); } - boolean didExist = Multitenancy.deleteTenant(new TenantIdentifier(sourceTenantIdentifier.getConnectionUriDomain(), sourceTenantIdentifier.getAppId(), tenantId), main); + boolean didExist = Multitenancy.deleteTenant( + new TenantIdentifier(sourceTenantIdentifier.getConnectionUriDomain(), + sourceTenantIdentifier.getAppId(), tenantId), main); JsonObject result = new JsonObject(); result.addProperty("status", "OK"); diff --git a/src/main/java/io/supertokens/webserver/api/multitenancy/thirdparty/CreateOrUpdateThirdPartyConfigAPI.java b/src/main/java/io/supertokens/webserver/api/multitenancy/thirdparty/CreateOrUpdateThirdPartyConfigAPI.java index c7da916fa..5c73ca886 100644 --- a/src/main/java/io/supertokens/webserver/api/multitenancy/thirdparty/CreateOrUpdateThirdPartyConfigAPI.java +++ b/src/main/java/io/supertokens/webserver/api/multitenancy/thirdparty/CreateOrUpdateThirdPartyConfigAPI.java @@ -92,10 +92,12 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO // Loop through all the existing thirdParty providers in the db if (!provider.thirdPartyId.equals(thirdPartyId)) { - // if the thirdPartyId is not the same as the one we are trying to update, add it to the new list + // if the thirdPartyId is not the same as the one we are trying to update, add it to the new + // list newProviders.add(provider); } else { - // if the thirdPartyId is the same as the one we are trying to update, add the one from json input + // if the thirdPartyId is the same as the one we are trying to update, add the one from json + // input // to the new list ThirdPartyConfig.Provider newProvider = new Gson().fromJson(config, ThirdPartyConfig.Provider.class); diff --git a/src/main/java/io/supertokens/webserver/api/passwordless/ConsumeCodeAPI.java b/src/main/java/io/supertokens/webserver/api/passwordless/ConsumeCodeAPI.java index da5691ce3..2eb524614 100644 --- a/src/main/java/io/supertokens/webserver/api/passwordless/ConsumeCodeAPI.java +++ b/src/main/java/io/supertokens/webserver/api/passwordless/ConsumeCodeAPI.java @@ -116,8 +116,10 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I if (getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v4_0)) { for (LoginMethod loginMethod : consumeCodeResponse.user.loginMethods) { if (loginMethod.recipeId.equals(RECIPE_ID.PASSWORDLESS) - && (consumeCodeResponse.email == null || Objects.equals(loginMethod.email, consumeCodeResponse.email)) - && (consumeCodeResponse.phoneNumber == null || Objects.equals(loginMethod.phoneNumber, consumeCodeResponse.phoneNumber))) { + && (consumeCodeResponse.email == null || + Objects.equals(loginMethod.email, consumeCodeResponse.email)) + && (consumeCodeResponse.phoneNumber == null || + Objects.equals(loginMethod.phoneNumber, consumeCodeResponse.phoneNumber))) { result.addProperty("recipeUserId", loginMethod.getSupertokensOrExternalUserId()); break; } @@ -127,7 +129,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I if (getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v5_0)) { JsonObject jsonDevice = new JsonObject(); jsonDevice.addProperty("preAuthSessionId", consumeCodeResponse.consumedDevice.deviceIdHash); - jsonDevice.addProperty("failedCodeInputAttemptCount", consumeCodeResponse.consumedDevice.failedAttempts); + jsonDevice.addProperty("failedCodeInputAttemptCount", + consumeCodeResponse.consumedDevice.failedAttempts); if (consumeCodeResponse.consumedDevice.email != null) { jsonDevice.addProperty("email", consumeCodeResponse.consumedDevice.email); diff --git a/src/main/java/io/supertokens/webserver/api/passwordless/GetCodesAPI.java b/src/main/java/io/supertokens/webserver/api/passwordless/GetCodesAPI.java index 48ff84fa0..9ba338db1 100644 --- a/src/main/java/io/supertokens/webserver/api/passwordless/GetCodesAPI.java +++ b/src/main/java/io/supertokens/webserver/api/passwordless/GetCodesAPI.java @@ -62,7 +62,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO // logic based on: https://app.code2flow.com/Odo88u7TNKIk String email = InputParser.getQueryParamOrThrowError(req, "email", true); - String phoneNumber = Utils.normalizeIfPhoneNumber(InputParser.getQueryParamOrThrowError(req, "phoneNumber", true)); + String phoneNumber = Utils.normalizeIfPhoneNumber( + InputParser.getQueryParamOrThrowError(req, "phoneNumber", true)); String deviceId = InputParser.getQueryParamOrThrowError(req, "deviceId", true); String deviceIdHash = InputParser.getQueryParamOrThrowError(req, "preAuthSessionId", true); @@ -135,7 +136,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } catch (Base64EncodingException ex) { throw new ServletException(new BadRequestException("Input encoding error in " + ex.source)); } catch (NoSuchAlgorithmException | StorageQueryException - | TenantOrAppNotFoundException e) { + | TenantOrAppNotFoundException e) { throw new ServletException(e); } } diff --git a/src/main/java/io/supertokens/webserver/api/passwordless/UserAPI.java b/src/main/java/io/supertokens/webserver/api/passwordless/UserAPI.java index 05f4d4786..de4add9a3 100644 --- a/src/main/java/io/supertokens/webserver/api/passwordless/UserAPI.java +++ b/src/main/java/io/supertokens/webserver/api/passwordless/UserAPI.java @@ -69,7 +69,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO // logic based on: https://app.code2flow.com/flowcharts/617a9aafdc97ee415448db74 String userId = InputParser.getQueryParamOrThrowError(req, "userId", true); String email = InputParser.getQueryParamOrThrowError(req, "email", true); - String phoneNumber = Utils.normalizeIfPhoneNumber(InputParser.getQueryParamOrThrowError(req, "phoneNumber", true)); + String phoneNumber = Utils.normalizeIfPhoneNumber( + InputParser.getQueryParamOrThrowError(req, "phoneNumber", true)); if (Stream.of(userId, email, phoneNumber).filter(Objects::nonNull).count() != 1) { throw new ServletException( diff --git a/src/main/java/io/supertokens/webserver/api/session/HandshakeAPI.java b/src/main/java/io/supertokens/webserver/api/session/HandshakeAPI.java index 637249b17..fd7c8a514 100644 --- a/src/main/java/io/supertokens/webserver/api/session/HandshakeAPI.java +++ b/src/main/java/io/supertokens/webserver/api/session/HandshakeAPI.java @@ -72,7 +72,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I Config.getConfig(tenantIdentifier, main) .getRefreshTokenValidityInMillis()); super.sendJsonResponse(200, result, resp); - } catch (StorageQueryException | StorageTransactionLogicException | TenantOrAppNotFoundException | UnsupportedJWTSigningAlgorithmException e) { + } catch (StorageQueryException | StorageTransactionLogicException | TenantOrAppNotFoundException | + UnsupportedJWTSigningAlgorithmException e) { throw new ServletException(e); } } diff --git a/src/main/java/io/supertokens/webserver/api/session/JWTDataAPI.java b/src/main/java/io/supertokens/webserver/api/session/JWTDataAPI.java index c87c1eeb5..8d3b5c373 100644 --- a/src/main/java/io/supertokens/webserver/api/session/JWTDataAPI.java +++ b/src/main/java/io/supertokens/webserver/api/session/JWTDataAPI.java @@ -68,7 +68,8 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO Storage storage; try { AppIdentifier appIdentifier = getAppIdentifier(req); - tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), Session.getTenantIdFromSessionHandle(sessionHandle)); + tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), + Session.getTenantIdFromSessionHandle(sessionHandle)); storage = StorageLayer.getStorage(tenantIdentifier, main); } catch (TenantOrAppNotFoundException e) { throw new ServletException(e); @@ -113,7 +114,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO Storage storage; try { AppIdentifier appIdentifier = getAppIdentifier(req); - tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), Session.getTenantIdFromSessionHandle(sessionHandle)); + tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), + Session.getTenantIdFromSessionHandle(sessionHandle)); storage = StorageLayer.getStorage(tenantIdentifier, main); } catch (TenantOrAppNotFoundException e) { throw new ServletException(e); diff --git a/src/main/java/io/supertokens/webserver/api/session/SessionDataAPI.java b/src/main/java/io/supertokens/webserver/api/session/SessionDataAPI.java index 12d512227..cb675140f 100644 --- a/src/main/java/io/supertokens/webserver/api/session/SessionDataAPI.java +++ b/src/main/java/io/supertokens/webserver/api/session/SessionDataAPI.java @@ -63,7 +63,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO Storage storage; try { AppIdentifier appIdentifier = getAppIdentifier(req); - tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), Session.getTenantIdFromSessionHandle(sessionHandle)); + tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), + Session.getTenantIdFromSessionHandle(sessionHandle)); storage = StorageLayer.getStorage(tenantIdentifier, main); } catch (TenantOrAppNotFoundException e) { throw new ServletException(e); @@ -101,7 +102,8 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO Storage storage; try { AppIdentifier appIdentifier = getAppIdentifier(req); - tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), Session.getTenantIdFromSessionHandle(sessionHandle)); + tenantIdentifier = new TenantIdentifier(appIdentifier.getConnectionUriDomain(), appIdentifier.getAppId(), + Session.getTenantIdFromSessionHandle(sessionHandle)); storage = StorageLayer.getStorage(tenantIdentifier, main); } catch (TenantOrAppNotFoundException e) { throw new ServletException(e); diff --git a/src/main/java/io/supertokens/webserver/api/session/SessionUserAPI.java b/src/main/java/io/supertokens/webserver/api/session/SessionUserAPI.java index 5f17f18f0..dbe6058fb 100644 --- a/src/main/java/io/supertokens/webserver/api/session/SessionUserAPI.java +++ b/src/main/java/io/supertokens/webserver/api/session/SessionUserAPI.java @@ -82,7 +82,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO try { StorageAndUserIdMapping storageAndUserIdMapping = enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( - req, userId, UserIdType.ANY, false); + req, userId, UserIdType.ANY, false); storage = storageAndUserIdMapping.storage; } catch (UnknownUserIdException e) { throw new IllegalStateException("should never happen"); diff --git a/src/main/java/io/supertokens/webserver/api/totp/CreateOrUpdateTotpDeviceAPI.java b/src/main/java/io/supertokens/webserver/api/totp/CreateOrUpdateTotpDeviceAPI.java index 1243bec42..5898fb375 100644 --- a/src/main/java/io/supertokens/webserver/api/totp/CreateOrUpdateTotpDeviceAPI.java +++ b/src/main/java/io/supertokens/webserver/api/totp/CreateOrUpdateTotpDeviceAPI.java @@ -74,7 +74,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I // While sending the usage stats we do a join, so totp tables also must use internal user id. // Try to find the appIdentifier with right storage based on the userId - StorageAndUserIdMapping storageAndUserIdMapping = enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( + StorageAndUserIdMapping storageAndUserIdMapping = + enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( req, userId, UserIdType.ANY, false); storage = storageAndUserIdMapping.storage; } catch (UnknownUserIdException e) { @@ -127,7 +128,7 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO // Try to find the appIdentifier with right storage based on the userId StorageAndUserIdMapping storageAndUserIdMapping = enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( - req, userId, UserIdType.ANY, false); + req, userId, UserIdType.ANY, false); storage = storageAndUserIdMapping.storage; } catch (UnknownUserIdException e) { diff --git a/src/main/java/io/supertokens/webserver/api/totp/GetTotpDevicesAPI.java b/src/main/java/io/supertokens/webserver/api/totp/GetTotpDevicesAPI.java index 0f7c86d59..bb1631abd 100644 --- a/src/main/java/io/supertokens/webserver/api/totp/GetTotpDevicesAPI.java +++ b/src/main/java/io/supertokens/webserver/api/totp/GetTotpDevicesAPI.java @@ -53,7 +53,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO // While sending the usage stats we do a join, so totp tables also must use internal user id. // Try to find the appIdentifier with right storage based on the userId - StorageAndUserIdMapping storageAndUserIdMapping = enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( + StorageAndUserIdMapping storageAndUserIdMapping = + enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( req, userId, UserIdType.ANY, false); storage = storageAndUserIdMapping.storage; } catch (UnknownUserIdException e) { diff --git a/src/main/java/io/supertokens/webserver/api/totp/ImportTotpDeviceAPI.java b/src/main/java/io/supertokens/webserver/api/totp/ImportTotpDeviceAPI.java index 22ea7118b..17971c571 100644 --- a/src/main/java/io/supertokens/webserver/api/totp/ImportTotpDeviceAPI.java +++ b/src/main/java/io/supertokens/webserver/api/totp/ImportTotpDeviceAPI.java @@ -76,7 +76,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I // Try to find the appIdentifier with right storage based on the userId try { - StorageAndUserIdMapping mappingAndStorage = enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( + StorageAndUserIdMapping mappingAndStorage = + enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( req, userId, UserIdType.ANY, false); storage = mappingAndStorage.storage; } catch (UnknownUserIdException e) { @@ -93,7 +94,7 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I result.addProperty("status", "DEVICE_ALREADY_EXISTS_ERROR"); super.sendJsonResponse(200, result, resp); } catch (StorageQueryException | FeatureNotEnabledException | - TenantOrAppNotFoundException | BadPermissionException e) { + TenantOrAppNotFoundException | BadPermissionException e) { throw new ServletException(e); } } diff --git a/src/main/java/io/supertokens/webserver/api/totp/RemoveTotpDeviceAPI.java b/src/main/java/io/supertokens/webserver/api/totp/RemoveTotpDeviceAPI.java index 0501d5dfe..3f5943f97 100644 --- a/src/main/java/io/supertokens/webserver/api/totp/RemoveTotpDeviceAPI.java +++ b/src/main/java/io/supertokens/webserver/api/totp/RemoveTotpDeviceAPI.java @@ -59,7 +59,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I // While sending the usage stats we do a join, so totp tables also must use internal user id. // Try to find the appIdentifier with right storage based on the userId - StorageAndUserIdMapping storageAndUserIdMapping = enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( + StorageAndUserIdMapping storageAndUserIdMapping = + enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( req, userId, UserIdType.ANY, false); storage = storageAndUserIdMapping.storage; } catch (UnknownUserIdException e) { diff --git a/src/main/java/io/supertokens/webserver/api/totp/VerifyTotpDeviceAPI.java b/src/main/java/io/supertokens/webserver/api/totp/VerifyTotpDeviceAPI.java index e50c22f2e..3d61bd09f 100644 --- a/src/main/java/io/supertokens/webserver/api/totp/VerifyTotpDeviceAPI.java +++ b/src/main/java/io/supertokens/webserver/api/totp/VerifyTotpDeviceAPI.java @@ -55,7 +55,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I try { TenantIdentifier tenantIdentifier = getTenantIdentifier(req); - Storage storage = getTenantStorage(req);; + Storage storage = getTenantStorage(req); + ; boolean isNewlyVerified = Totp.verifyDevice(tenantIdentifier, storage, main, userId, deviceName, totp); result.addProperty("status", "OK"); diff --git a/src/main/java/io/supertokens/webserver/api/useridmapping/UserIdMappingAPI.java b/src/main/java/io/supertokens/webserver/api/useridmapping/UserIdMappingAPI.java index 475e30f93..86872a8bf 100644 --- a/src/main/java/io/supertokens/webserver/api/useridmapping/UserIdMappingAPI.java +++ b/src/main/java/io/supertokens/webserver/api/useridmapping/UserIdMappingAPI.java @@ -97,7 +97,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I try { UserIdMapping.createUserIdMapping( getAppIdentifier(req), enforcePublicTenantAndGetAllStoragesForApp(req), - superTokensUserId, externalUserId, externalUserIdInfo, force, getVersionFromRequest(req).greaterThanOrEqualTo( + superTokensUserId, externalUserId, externalUserIdInfo, force, + getVersionFromRequest(req).greaterThanOrEqualTo( SemVer.v4_0)); JsonObject response = new JsonObject(); @@ -163,7 +164,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO // Request from (app1, tenant3) may result in either user1 or user2 StorageAndUserIdMapping storageAndUserIdMapping = - this.enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi(req, userId, userIdType, true); + this.enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi(req, userId, userIdType, + true); if (storageAndUserIdMapping.userIdMapping == null) { JsonObject response = new JsonObject(); diff --git a/src/main/java/io/supertokens/webserver/api/usermetadata/UserMetadataAPI.java b/src/main/java/io/supertokens/webserver/api/usermetadata/UserMetadataAPI.java index 6326fb160..6417a2152 100644 --- a/src/main/java/io/supertokens/webserver/api/usermetadata/UserMetadataAPI.java +++ b/src/main/java/io/supertokens/webserver/api/usermetadata/UserMetadataAPI.java @@ -57,7 +57,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO AppIdentifier appIdentifier = getAppIdentifier(req); JsonObject metadata; try { - StorageAndUserIdMapping storageAndUserIdMapping = this.enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( + StorageAndUserIdMapping storageAndUserIdMapping = + this.enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( req, userId, UserIdType.ANY, false); metadata = UserMetadata.getUserMetadata(appIdentifier, storageAndUserIdMapping.storage, userId); } catch (UnknownUserIdException e) { @@ -85,7 +86,8 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO JsonObject metadata; try { - StorageAndUserIdMapping storageAndUserIdMapping = this.enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( + StorageAndUserIdMapping storageAndUserIdMapping = + this.enforcePublicTenantAndGetStorageAndUserIdMappingForAppSpecificApi( req, userId, UserIdType.ANY, false); metadata = UserMetadata.updateUserMetadata(appIdentifier, storageAndUserIdMapping.storage, userId, update); @@ -97,7 +99,8 @@ protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IO response.add("metadata", metadata); response.addProperty("status", "OK"); super.sendJsonResponse(200, response, resp); - } catch (StorageQueryException | StorageTransactionLogicException | TenantOrAppNotFoundException | BadPermissionException e) { + } catch (StorageQueryException | StorageTransactionLogicException | TenantOrAppNotFoundException | + BadPermissionException e) { throw new ServletException(e); } } diff --git a/src/test/java/io/supertokens/test/APIKeysTest.java b/src/test/java/io/supertokens/test/APIKeysTest.java index c0164ad5c..828ad9e7e 100644 --- a/src/test/java/io/supertokens/test/APIKeysTest.java +++ b/src/test/java/io/supertokens/test/APIKeysTest.java @@ -494,8 +494,8 @@ private static boolean isJsonValid(String jsonInString) { } private static T sendJsonRequest(Main main, String url, JsonElement requestBody, - int connectionTimeoutMS, int readTimeoutMS, String method, - Map headers) throws IOException, + int connectionTimeoutMS, int readTimeoutMS, String method, + Map headers) throws IOException, io.supertokens.test.httpRequest.HttpResponseException { URL obj = getURL(main, "", url); InputStream inputStream = null; diff --git a/src/test/java/io/supertokens/test/APITestsWithTrailingSlash.java b/src/test/java/io/supertokens/test/APITestsWithTrailingSlash.java index 00ca46400..548924d32 100644 --- a/src/test/java/io/supertokens/test/APITestsWithTrailingSlash.java +++ b/src/test/java/io/supertokens/test/APITestsWithTrailingSlash.java @@ -16,12 +16,12 @@ package io.supertokens.test; +import com.google.gson.JsonObject; import io.supertokens.ProcessState; import io.supertokens.pluginInterface.STORAGE_TYPE; import io.supertokens.storageLayer.StorageLayer; import io.supertokens.test.httpRequest.HttpRequestForTesting; import io.supertokens.test.httpRequest.HttpResponseException; - import io.supertokens.utils.SemVer; import org.junit.AfterClass; import org.junit.Before; @@ -29,8 +29,6 @@ import org.junit.Test; import org.junit.rules.TestRule; -import com.google.gson.JsonObject; - import static org.junit.Assert.*; public class APITestsWithTrailingSlash { @@ -49,7 +47,7 @@ public void beforeEach() { @Test public void testTrailingSlashesWorks() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -109,7 +107,7 @@ public void testTrailingSlashesWorks() throws Exception { @Test public void testThatAPISWorkWithTrailingSlashes() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/ApiVersionAPITest.java b/src/test/java/io/supertokens/test/ApiVersionAPITest.java index 7b915238c..2bb28f136 100644 --- a/src/test/java/io/supertokens/test/ApiVersionAPITest.java +++ b/src/test/java/io/supertokens/test/ApiVersionAPITest.java @@ -61,7 +61,7 @@ public void beforeEach() { // * being returned by this API. @Test public void testThatCoreDriverInterfaceSupportedVersionsAreBeingReturnedByTheAPI() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -94,7 +94,7 @@ public void testThatCoreDriverInterfaceSupportedVersionsAreBeingReturnedByTheAPI // - no version needed for this API. @Test public void testThatNoVersionIsNeededForThisAPI() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -107,7 +107,8 @@ public void testThatNoVersionIsNeededForThisAPI() throws Exception { // with setting cdi-version header apiVersionResponse = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/apiversion", null, 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), ""); + "http://localhost:3567/apiversion", null, 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), + ""); assertNotNull(apiVersionResponse.getAsJsonArray("versions")); assertTrue(apiVersionResponse.getAsJsonArray("versions").size() >= 1); @@ -119,7 +120,7 @@ public void testThatNoVersionIsNeededForThisAPI() throws Exception { // - test that all returned versions are correct based on WebserverAPI's supportedVersions set @Test public void testThatApiVersionsAreBasedOnWebserverAPIsSupportedVersions() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -142,7 +143,7 @@ public void testThatApiVersionsAreBasedOnWebserverAPIsSupportedVersions() throws // - check that all returned versions have X.Y format @Test public void testThatAllReturnedVersionsHaveXYFormat() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -160,32 +161,34 @@ public void testThatAllReturnedVersionsHaveXYFormat() throws Exception { @Test public void testThatWebsiteAndAPIDomainAreSaved() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); { - Map params = new HashMap<>(); + Map params = new HashMap<>(); params.put("websiteDomain", "https://example.com"); HttpRequestForTesting.sendGETRequest(process.getProcess(), "", "http://localhost:3567/apiversion", params, 1000, 1000, null, null, ""); - assertEquals("https://example.com", Multitenancy.getWebsiteDomain(StorageLayer.getBaseStorage(process.getProcess()), - new AppIdentifier(null, - null))); + assertEquals("https://example.com", + Multitenancy.getWebsiteDomain(StorageLayer.getBaseStorage(process.getProcess()), + new AppIdentifier(null, + null))); } { - Map params = new HashMap<>(); + Map params = new HashMap<>(); params.put("apiDomain", "https://api.example.com"); HttpRequestForTesting.sendGETRequest(process.getProcess(), "", "http://localhost:3567/apiversion", params, 1000, 1000, null, null, ""); - assertEquals("https://api.example.com", Multitenancy.getAPIDomain(StorageLayer.getBaseStorage(process.getProcess()), - new AppIdentifier(null, - null))); + assertEquals("https://api.example.com", + Multitenancy.getAPIDomain(StorageLayer.getBaseStorage(process.getProcess()), + new AppIdentifier(null, + null))); } process.kill(); @@ -194,7 +197,7 @@ public void testThatWebsiteAndAPIDomainAreSaved() throws Exception { @Test public void testAPIVersionWorksEvenIfThereIsAnException() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); FeatureFlagTestContent.getInstance(process.getProcess()) @@ -225,9 +228,10 @@ public void testAPIVersionWorksEvenIfThereIsAnException() throws Exception { null, null, tenantConfigJson); StorageLayer.getMultitenancyStorage(process.getProcess()).createTenant(tenantConfig); - MultitenancyHelper.getInstance(process.getProcess()).refreshTenantsInCoreBasedOnChangesInCoreConfigOrIfTenantListChanged(true); + MultitenancyHelper.getInstance(process.getProcess()) + .refreshTenantsInCoreBasedOnChangesInCoreConfigOrIfTenantListChanged(true); - Map params = new HashMap<>(); + Map params = new HashMap<>(); params.put("websiteDomain", "https://example.com"); params.put("apiDomain", "https://api.example.com"); diff --git a/src/test/java/io/supertokens/test/AuthRecipeAPITest2_10.java b/src/test/java/io/supertokens/test/AuthRecipeAPITest2_10.java index e8209e53d..d8806711a 100644 --- a/src/test/java/io/supertokens/test/AuthRecipeAPITest2_10.java +++ b/src/test/java/io/supertokens/test/AuthRecipeAPITest2_10.java @@ -25,7 +25,10 @@ import io.supertokens.test.httpRequest.HttpRequestForTesting; import io.supertokens.test.httpRequest.HttpResponseException; import io.supertokens.utils.SemVer; -import org.junit.*; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; import org.junit.rules.TestRule; import static junit.framework.TestCase.assertEquals; @@ -47,7 +50,7 @@ public void beforeEach() { @Test public void deleteUser() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -88,7 +91,7 @@ public void deleteUser() throws Exception { @Test public void deleteUserBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/AuthRecipeAPITest2_8.java b/src/test/java/io/supertokens/test/AuthRecipeAPITest2_8.java index c259f0fdf..5d17b3eb5 100644 --- a/src/test/java/io/supertokens/test/AuthRecipeAPITest2_8.java +++ b/src/test/java/io/supertokens/test/AuthRecipeAPITest2_8.java @@ -48,7 +48,7 @@ public void beforeEach() { @Test public void getUsersCountArrayFormat() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -133,7 +133,7 @@ public void getUsersCountArrayFormat() throws Exception { @Test public void getUsersCountBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -158,7 +158,7 @@ public void getUsersCountBadInput() throws Exception { @Test public void paginationtBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -214,7 +214,7 @@ public void paginationtBadInput() throws Exception { @Test public void testGoodInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/AuthRecipeTest.java b/src/test/java/io/supertokens/test/AuthRecipeTest.java index 11bbbb65a..5af5d82ae 100644 --- a/src/test/java/io/supertokens/test/AuthRecipeTest.java +++ b/src/test/java/io/supertokens/test/AuthRecipeTest.java @@ -525,7 +525,8 @@ public void randomPaginationTest() throws Exception { AuthRecipeUserInfo expected = usersCreated.get(indexIntoUsers); AuthRecipeUserInfo actualUser = uc; - assert (actualUser.equals(expected) && uc.loginMethods[0].recipeId.toString().equals(expected.loginMethods[0].recipeId.toString())); + assert (actualUser.equals(expected) && uc.loginMethods[0].recipeId.toString() + .equals(expected.loginMethods[0].recipeId.toString())); indexIntoUsers++; } @@ -564,7 +565,8 @@ public void randomPaginationTest() throws Exception { AuthRecipeUserInfo expected = usersCreated.get(indexIntoUsers); AuthRecipeUserInfo actualUser = uc; - assert (actualUser.equals(expected) && uc.loginMethods[0].recipeId.toString().equals(expected.loginMethods[0].recipeId.toString())); + assert (actualUser.equals(expected) && uc.loginMethods[0].recipeId.toString() + .equals(expected.loginMethods[0].recipeId.toString())); indexIntoUsers--; } @@ -605,28 +607,38 @@ public void deleteUserTest() throws Exception { JsonObject testMetadata = new JsonObject(); testMetadata.addProperty("test", "test"); UserMetadata.updateUserMetadata(process.getProcess(), user1.getSupertokensUserId(), testMetadata); - Session.createNewSession(process.getProcess(), user1.getSupertokensUserId(), new JsonObject(), new JsonObject()); + Session.createNewSession(process.getProcess(), user1.getSupertokensUserId(), new JsonObject(), + new JsonObject()); String emailVerificationToken = EmailVerification.generateEmailVerificationToken(process.getProcess(), user1.getSupertokensUserId(), "email"); EmailVerification.verifyEmail(process.getProcess(), emailVerificationToken); AuthRecipeUserInfo user2 = signUpMap.get(userType).apply(null); - Session.createNewSession(process.getProcess(), user2.getSupertokensUserId(), new JsonObject(), new JsonObject()); + Session.createNewSession(process.getProcess(), user2.getSupertokensUserId(), new JsonObject(), + new JsonObject()); String emailVerificationToken2 = EmailVerification.generateEmailVerificationToken(process.getProcess(), user2.getSupertokensUserId(), "email"); - assertEquals(2, AuthRecipe.getUsersCount(process.getProcess(), new RECIPE_ID[]{user1.loginMethods[0].recipeId})); + assertEquals(2, + AuthRecipe.getUsersCount(process.getProcess(), new RECIPE_ID[]{user1.loginMethods[0].recipeId})); AuthRecipe.deleteUser(process.getProcess(), user1.getSupertokensUserId()); - assertEquals(1, AuthRecipe.getUsersCount(process.getProcess(), new RECIPE_ID[]{user1.loginMethods[0].recipeId})); - assertEquals(0, Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user1.getSupertokensUserId()).length); - assertEquals(1, Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user2.getSupertokensUserId()).length); + assertEquals(1, + AuthRecipe.getUsersCount(process.getProcess(), new RECIPE_ID[]{user1.loginMethods[0].recipeId})); + assertEquals(0, Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), + user1.getSupertokensUserId()).length); + assertEquals(1, Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), + user2.getSupertokensUserId()).length); assertFalse(EmailVerification.isEmailVerified(process.getProcess(), user1.getSupertokensUserId(), "email")); - assertEquals(0, UserMetadata.getUserMetadata(process.getProcess(), user1.getSupertokensUserId()).entrySet().size()); + assertEquals(0, + UserMetadata.getUserMetadata(process.getProcess(), user1.getSupertokensUserId()).entrySet().size()); AuthRecipe.deleteUser(process.getProcess(), user2.getSupertokensUserId()); - assertEquals(0, AuthRecipe.getUsersCount(process.getProcess(), new RECIPE_ID[]{user1.loginMethods[0].recipeId})); - assertEquals(0, Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user2.getSupertokensUserId()).length); - assertEquals(0, UserMetadata.getUserMetadata(process.getProcess(), user2.getSupertokensUserId()).entrySet().size()); + assertEquals(0, + AuthRecipe.getUsersCount(process.getProcess(), new RECIPE_ID[]{user1.loginMethods[0].recipeId})); + assertEquals(0, Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), + user2.getSupertokensUserId()).length); + assertEquals(0, + UserMetadata.getUserMetadata(process.getProcess(), user2.getSupertokensUserId()).entrySet().size()); Exception error = null; try { diff --git a/src/test/java/io/supertokens/test/AuthRecipesParallelTest.java b/src/test/java/io/supertokens/test/AuthRecipesParallelTest.java index dfd7c78ef..e78ea330c 100644 --- a/src/test/java/io/supertokens/test/AuthRecipesParallelTest.java +++ b/src/test/java/io/supertokens/test/AuthRecipesParallelTest.java @@ -20,15 +20,9 @@ import io.supertokens.emailpassword.EmailPassword; import io.supertokens.emailpassword.exceptions.EmailChangeNotAllowedException; import io.supertokens.emailpassword.exceptions.WrongCredentialsException; -import io.supertokens.featureflag.EE_FEATURES; -import io.supertokens.featureflag.FeatureFlagTestContent; import io.supertokens.pluginInterface.STORAGE_TYPE; -import io.supertokens.pluginInterface.authRecipe.AuthRecipeUserInfo; -import io.supertokens.pluginInterface.emailpassword.exceptions.DuplicateEmailException; import io.supertokens.pluginInterface.exceptions.StorageQueryException; import io.supertokens.storageLayer.StorageLayer; -import io.supertokens.test.TestingProcessManager; -import io.supertokens.test.Utils; import io.supertokens.thirdparty.ThirdParty; import org.junit.AfterClass; import org.junit.Before; @@ -79,7 +73,7 @@ public void timeTakenFor500SignInParallel() throws Exception { long st = System.currentTimeMillis(); for (int i = 0; i < numberOfThreads; i++) { ex.execute(() -> { - while(true) { + while (true) { try { EmailPassword.signIn(process.getProcess(), "test@example.com", "password"); counter.incrementAndGet(); @@ -97,7 +91,9 @@ public void timeTakenFor500SignInParallel() throws Exception { ex.shutdown(); ex.awaitTermination(2, TimeUnit.MINUTES); - System.out.println("Time taken for " + numberOfThreads + " sign in parallel: " + (System.currentTimeMillis() - st) + "ms"); + System.out.println( + "Time taken for " + numberOfThreads + " sign in parallel: " + (System.currentTimeMillis() - st) + + "ms"); System.out.println("Retry counter: " + retryCounter.get()); assertEquals(counter.get(), numberOfThreads); @@ -143,7 +139,7 @@ public void timeTakenFor500SignInUpParallel() throws Exception { long st = System.currentTimeMillis(); for (int i = 0; i < numberOfThreads; i++) { ex.execute(() -> { - while(true) { + while (true) { try { ThirdParty.signInUp(process.getProcess(), "google", "google-user", "test@example.com"); counter.incrementAndGet(); @@ -161,9 +157,10 @@ public void timeTakenFor500SignInUpParallel() throws Exception { ex.shutdown(); ex.awaitTermination(2, TimeUnit.MINUTES); - System.out.println("Time taken for " + numberOfThreads + " sign in parallel: " + (System.currentTimeMillis() - st) + "ms"); + System.out.println( + "Time taken for " + numberOfThreads + " sign in parallel: " + (System.currentTimeMillis() - st) + "ms"); System.out.println("Retry counter: " + retryCounter.get()); - assertEquals (counter.get(), numberOfThreads); + assertEquals(counter.get(), numberOfThreads); assertEquals(0, retryCounter.get()); process.kill(); diff --git a/src/test/java/io/supertokens/test/CDIVersionTest.java b/src/test/java/io/supertokens/test/CDIVersionTest.java index 6387c1522..3f2295997 100644 --- a/src/test/java/io/supertokens/test/CDIVersionTest.java +++ b/src/test/java/io/supertokens/test/CDIVersionTest.java @@ -313,7 +313,8 @@ public void testJWKSEndpointWorksInAllCases() throws Exception { { // check regular output - JsonObject response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/.well-known/jwks.json", null, + JsonObject response = HttpRequest.sendGETRequest(process.getProcess(), "", + "http://localhost:3567/.well-known/jwks.json", null, 1000, 1000, null); assertEquals(response.entrySet().size(), 1); @@ -325,7 +326,8 @@ public void testJWKSEndpointWorksInAllCases() throws Exception { { JsonObject oldResponse = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/recipe/jwt/jwks", null, 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), + "http://localhost:3567/recipe/jwt/jwks", null, 1000, 1000, null, + Utils.getCdiVersionStringLatestForTests(), "jwt"); JsonArray oldKeys = oldResponse.getAsJsonArray("keys"); @@ -346,7 +348,8 @@ public void testJWKSEndpointWorksInAllCases() throws Exception { { // check regular output - JsonObject response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/.well-known/jwks.json", null, + JsonObject response = HttpRequest.sendGETRequest(process.getProcess(), "", + "http://localhost:3567/.well-known/jwks.json", null, 1000, 1000, null); assertEquals(response.entrySet().size(), 1); @@ -369,7 +372,7 @@ public void testJWKSEndpointWorksInAllCases() throws Exception { assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } } - + @Test public void testInvalidSemanticVersion() throws Exception { String[] args = {"../"}; @@ -381,7 +384,8 @@ public void testInvalidSemanticVersion() throws Exception { ProcessState.EventAndException state = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(state); - assertEquals("supertokens_max_cdi_version is not a valid semantic version", state.exception.getCause().getMessage()); + assertEquals("supertokens_max_cdi_version is not a valid semantic version", + state.exception.getCause().getMessage()); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @@ -425,7 +429,7 @@ public void testThatGreatedThanMaxCDIVersionIsNotAllowed() throws Exception { "jwt"); fail(); } catch (HttpResponseException e) { - assert(e.getMessage().contains("cdi-version 2.21 not supported")); + assert (e.getMessage().contains("cdi-version 2.21 not supported")); } try { @@ -434,7 +438,7 @@ public void testThatGreatedThanMaxCDIVersionIsNotAllowed() throws Exception { "jwt"); fail(); } catch (HttpResponseException e) { - assert(e.getMessage().contains("cdi-version 3.0 not supported")); + assert (e.getMessage().contains("cdi-version 3.0 not supported")); } process.kill(); diff --git a/src/test/java/io/supertokens/test/CLIOptionsTest.java b/src/test/java/io/supertokens/test/CLIOptionsTest.java index 8a2564109..d783c63be 100644 --- a/src/test/java/io/supertokens/test/CLIOptionsTest.java +++ b/src/test/java/io/supertokens/test/CLIOptionsTest.java @@ -65,7 +65,7 @@ public void cli0ArgsTest() throws TestingProcessManagerException, InterruptedExc @Test public void cli1ArgsTest() throws TestingProcessManagerException, InterruptedException { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcess process = TestingProcessManager.start(args); EventAndException e = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); assertNotNull(e); @@ -75,7 +75,7 @@ public void cli1ArgsTest() throws TestingProcessManagerException, InterruptedExc @Test public void cli2ArgsTest() throws Exception { // testing that when badInput is given to second cli argument, default values for host and port are used - String[] args = { "../", "random" }; + String[] args = {"../", "random"}; TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -87,7 +87,7 @@ public void cli2ArgsTest() throws Exception { assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STOPPED)); // custom host and port - args = new String[] { "../", "host=127.0.0.1", "port=8081" }; + args = new String[]{"../", "host=127.0.0.1", "port=8081"}; process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -102,7 +102,7 @@ public void cli2ArgsTest() throws Exception { @Test public void testMultipleInstancesAtTheSameTime() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; try { // Create 2 custom config files @@ -119,14 +119,14 @@ public void testMultipleInstancesAtTheSameTime() throws Exception { TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - args = new String[] { "../", "port=8081", - "configFile=" + new File("../temp/new1Config.yaml").getAbsolutePath() }; + args = new String[]{"../", "port=8081", + "configFile=" + new File("../temp/new1Config.yaml").getAbsolutePath()}; TestingProcess process1 = TestingProcessManager.start(args); assertNotNull(process1.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - args = new String[] { "../", "port=8082", - "configFile=" + new File("../temp/new2Config.yaml").getAbsolutePath() }; + args = new String[]{"../", "port=8082", + "configFile=" + new File("../temp/new2Config.yaml").getAbsolutePath()}; TestingProcess process2 = TestingProcessManager.start(args); assertNotNull(process2.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -154,12 +154,14 @@ public void testMultipleInstancesAtTheSameTime() throws Exception { // clear log files { - FileWriter f = new FileWriter(Config.getConfig(process.getProcess()).getInfoLogPath(process.getProcess())); + FileWriter f = new FileWriter( + Config.getConfig(process.getProcess()).getInfoLogPath(process.getProcess())); f.flush(); f.close(); } { - FileWriter f = new FileWriter(Config.getConfig(process.getProcess()).getErrorLogPath(process.getProcess())); + FileWriter f = new FileWriter( + Config.getConfig(process.getProcess()).getErrorLogPath(process.getProcess())); f.flush(); f.close(); } diff --git a/src/test/java/io/supertokens/test/ConfigAPITest2_7.java b/src/test/java/io/supertokens/test/ConfigAPITest2_7.java index b30baa16f..4eb06ff43 100644 --- a/src/test/java/io/supertokens/test/ConfigAPITest2_7.java +++ b/src/test/java/io/supertokens/test/ConfigAPITest2_7.java @@ -52,7 +52,7 @@ public void beforeEach() { @Test public void inputErrorConfigAPITest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -87,7 +87,7 @@ public void inputErrorConfigAPITest() throws Exception { @Test public void testVersion2InputErrorConfigAPITest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -124,7 +124,7 @@ public void testVersion2InputErrorConfigAPITest() throws Exception { @Test public void testCustomConfigPath() throws Exception { String path = new File("../temp/config.yaml").getAbsolutePath(); - String[] args = { "../", "configFile=" + path }; + String[] args = {"../", "configFile=" + path}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -148,7 +148,7 @@ public void testCustomConfigPath() throws Exception { @Test public void testVersion2TestCustomConfigPath() throws Exception { String path = new File("../temp/config.yaml").getAbsolutePath(); - String[] args = { "../", "configFile=" + path }; + String[] args = {"../", "configFile=" + path}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -171,7 +171,7 @@ public void testVersion2TestCustomConfigPath() throws Exception { @Test public void outputPossibilitiesConfigAPITest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -211,7 +211,7 @@ public void outputPossibilitiesConfigAPITest() throws Exception { @Test public void testVersion2OutputPossibilitiesConfigAPITest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/ConfigMapperTest.java b/src/test/java/io/supertokens/test/ConfigMapperTest.java index 1b048020b..2f071e379 100644 --- a/src/test/java/io/supertokens/test/ConfigMapperTest.java +++ b/src/test/java/io/supertokens/test/ConfigMapperTest.java @@ -276,8 +276,7 @@ public void testInvalidConversions() throws Exception { JsonObject config = new JsonObject(); if (values[i] == null) { config.add(properties[i], null); - } - else if (values[i] instanceof String) { + } else if (values[i] instanceof String) { config.addProperty(properties[i], (String) values[i]); } else if (values[i] instanceof Boolean) { config.addProperty(properties[i], (Boolean) values[i]); diff --git a/src/test/java/io/supertokens/test/ConfigTest2_21.java b/src/test/java/io/supertokens/test/ConfigTest2_21.java index b1dddf8dc..ea583ed84 100644 --- a/src/test/java/io/supertokens/test/ConfigTest2_21.java +++ b/src/test/java/io/supertokens/test/ConfigTest2_21.java @@ -46,7 +46,7 @@ public void beforeEach() { public void testThatDeprecatedConfigStillWorks() throws Exception { Utils.setValueInConfig("access_token_signing_key_update_interval", "2"); - String[] args = { "../" }; + String[] args = {"../"}; TestingProcess process = TestingProcessManager.start(args); @@ -68,7 +68,7 @@ public void testThatDeprecatedConfigStillWorks() throws Exception { public void testThatNewConfigWorks() throws Exception { Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "2"); - String[] args = { "../" }; + String[] args = {"../"}; TestingProcess process = TestingProcessManager.start(args); @@ -90,14 +90,17 @@ public void testThatNewConfigWorks() throws Exception { public void testCoreConfigTypeValidationInConfigYaml() throws Exception { Utils.setValueInConfig("access_token_validity", "abcd"); - String[] args = { "../" }; + String[] args = {"../"}; TestingProcess process = TestingProcessManager.start(args); EventAndException startEvent = process.checkOrWaitForEvent(PROCESS_STATE.INIT_FAILURE); assertNotNull(startEvent); - assertEquals("io.supertokens.pluginInterface.exceptions.InvalidConfigException: 'access_token_validity' must be of type long", startEvent.exception.getMessage()); + assertEquals( + "io.supertokens.pluginInterface.exceptions.InvalidConfigException: 'access_token_validity' must be of" + + " type long", + startEvent.exception.getMessage()); process.kill(); EventAndException stopEvent = process.checkOrWaitForEvent(PROCESS_STATE.STOPPED); diff --git a/src/test/java/io/supertokens/test/CronjobTest.java b/src/test/java/io/supertokens/test/CronjobTest.java index 41eb8960b..6d72addb8 100644 --- a/src/test/java/io/supertokens/test/CronjobTest.java +++ b/src/test/java/io/supertokens/test/CronjobTest.java @@ -216,10 +216,12 @@ private PerTenantCronjob(Main main, List> tenantsInfo) { public static PerTenantCronjob getInstance(Main main, List> tenantsInfo) { try { - return (PerTenantCronjob) main.getResourceDistributor().getResource(new TenantIdentifier(null, null, null), RESOURCE_ID); + return (PerTenantCronjob) main.getResourceDistributor() + .getResource(new TenantIdentifier(null, null, null), RESOURCE_ID); } catch (TenantOrAppNotFoundException e) { return (PerTenantCronjob) main.getResourceDistributor() - .setResource(new TenantIdentifier(null, null, null), RESOURCE_ID, new PerTenantCronjob(main, tenantsInfo)); + .setResource(new TenantIdentifier(null, null, null), RESOURCE_ID, + new PerTenantCronjob(main, tenantsInfo)); } } @@ -251,10 +253,12 @@ private PerAppCronjob(Main main, List> tenantsInfo) { public static PerAppCronjob getInstance(Main main, List> tenantsInfo) { try { - return (PerAppCronjob) main.getResourceDistributor().getResource(new TenantIdentifier(null, null, null), RESOURCE_ID); + return (PerAppCronjob) main.getResourceDistributor() + .getResource(new TenantIdentifier(null, null, null), RESOURCE_ID); } catch (TenantOrAppNotFoundException e) { return (PerAppCronjob) main.getResourceDistributor() - .setResource(new TenantIdentifier(null, null, null), RESOURCE_ID, new PerAppCronjob(main, tenantsInfo)); + .setResource(new TenantIdentifier(null, null, null), RESOURCE_ID, + new PerAppCronjob(main, tenantsInfo)); } } @@ -285,10 +289,12 @@ private PerUserPoolCronjob(Main main, List> tenantsInfo) public static PerUserPoolCronjob getInstance(Main main, List> tenantsInfo) { try { - return (PerUserPoolCronjob) main.getResourceDistributor().getResource(new TenantIdentifier(null, null, null), RESOURCE_ID); + return (PerUserPoolCronjob) main.getResourceDistributor() + .getResource(new TenantIdentifier(null, null, null), RESOURCE_ID); } catch (TenantOrAppNotFoundException e) { return (PerUserPoolCronjob) main.getResourceDistributor() - .setResource(new TenantIdentifier(null, null, null), RESOURCE_ID, new PerUserPoolCronjob(main, tenantsInfo)); + .setResource(new TenantIdentifier(null, null, null), RESOURCE_ID, + new PerUserPoolCronjob(main, tenantsInfo)); } } @@ -582,10 +588,12 @@ public void testTargetTenantCronTask() throws Exception { new JsonObject() ), false); - Cronjobs.addCronjob(process.getProcess(), TargetTenantCronjob.getInstance(process.getProcess(), new TenantIdentifier(null, "a1", "t1"))); + Cronjobs.addCronjob(process.getProcess(), + TargetTenantCronjob.getInstance(process.getProcess(), new TenantIdentifier(null, "a1", "t1"))); Thread.sleep(1100); - assertTrue(TargetTenantCronjob.getInstance(process.getProcess(), new TenantIdentifier(null, "a1", "t1")).wasCalled); + assertTrue(TargetTenantCronjob.getInstance(process.getProcess(), + new TenantIdentifier(null, "a1", "t1")).wasCalled); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -638,11 +646,14 @@ public void testPerTenantCronTask() throws Exception { new JsonObject() ), false); - List> uniqueUserPoolIdsTenants = StorageLayer.getTenantsWithUniqueUserPoolId(process.getProcess()); - Cronjobs.addCronjob(process.getProcess(), PerTenantCronjob.getInstance(process.getProcess(), uniqueUserPoolIdsTenants)); + List> uniqueUserPoolIdsTenants = StorageLayer.getTenantsWithUniqueUserPoolId( + process.getProcess()); + Cronjobs.addCronjob(process.getProcess(), + PerTenantCronjob.getInstance(process.getProcess(), uniqueUserPoolIdsTenants)); Thread.sleep(1100); - assertEquals(5, PerTenantCronjob.getInstance(process.getProcess(), uniqueUserPoolIdsTenants).tenantIdentifiers.size()); + assertEquals(5, + PerTenantCronjob.getInstance(process.getProcess(), uniqueUserPoolIdsTenants).tenantIdentifiers.size()); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -695,11 +706,14 @@ public void testPerAppCronTask() throws Exception { new JsonObject() ), false); - List> uniqueUserPoolIdsTenants = StorageLayer.getTenantsWithUniqueUserPoolId(process.getProcess()); - Cronjobs.addCronjob(process.getProcess(), PerAppCronjob.getInstance(process.getProcess(), uniqueUserPoolIdsTenants)); + List> uniqueUserPoolIdsTenants = StorageLayer.getTenantsWithUniqueUserPoolId( + process.getProcess()); + Cronjobs.addCronjob(process.getProcess(), + PerAppCronjob.getInstance(process.getProcess(), uniqueUserPoolIdsTenants)); Thread.sleep(1100); - assertEquals(3, PerAppCronjob.getInstance(process.getProcess(), uniqueUserPoolIdsTenants).appIdentifiers.size()); + assertEquals(3, + PerAppCronjob.getInstance(process.getProcess(), uniqueUserPoolIdsTenants).appIdentifiers.size()); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -759,8 +773,10 @@ public void testPerUserPoolCronTask() throws Exception { config ), false); - List> uniqueUserPoolIdsTenants = StorageLayer.getTenantsWithUniqueUserPoolId(process.getProcess()); - Cronjobs.addCronjob(process.getProcess(), PerUserPoolCronjob.getInstance(process.getProcess(), uniqueUserPoolIdsTenants)); + List> uniqueUserPoolIdsTenants = StorageLayer.getTenantsWithUniqueUserPoolId( + process.getProcess()); + Cronjobs.addCronjob(process.getProcess(), + PerUserPoolCronjob.getInstance(process.getProcess(), uniqueUserPoolIdsTenants)); Thread.sleep(1100); assertEquals(2, PerUserPoolCronjob.getInstance(process.getProcess(), uniqueUserPoolIdsTenants).storages.size()); @@ -856,13 +872,14 @@ public void testThatReAddingSameCronTaskDoesNotScheduleMoreExecutors() throws Ex TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); - for (int i=0; i<10; i++) { + for (int i = 0; i < 10; i++) { Cronjobs.addCronjob(process.getProcess(), CounterCronJob.getInstance(process.getProcess())); Thread.sleep(50); } Thread.sleep(5000); - assertTrue(CounterCronJob.getInstance(process.getProcess()).getCount() > 3 && CounterCronJob.getInstance(process.getProcess()).getCount() < 8); + assertTrue(CounterCronJob.getInstance(process.getProcess()).getCount() > 3 && + CounterCronJob.getInstance(process.getProcess()).getCount() < 8); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -946,7 +963,8 @@ public void testThatCronJobsHaveTenantsInfoAfterRestart() throws Exception { ), false, false, true); { - List>> tenantsInfos = Cronjobs.getInstance(process.getProcess()).getTenantInfos(); + List>> tenantsInfos = Cronjobs.getInstance(process.getProcess()) + .getTenantInfos(); assertEquals(10, tenantsInfos.size()); int count = 0; for (List> tenantsInfo : tenantsInfos) { @@ -972,7 +990,8 @@ public void testThatCronJobsHaveTenantsInfoAfterRestart() throws Exception { // we expect the state of the tenantsInfo to be same after core restart { - List>> tenantsInfos = Cronjobs.getInstance(process.getProcess()).getTenantInfos(); + List>> tenantsInfos = Cronjobs.getInstance(process.getProcess()) + .getTenantInfos(); assertEquals(10, tenantsInfos.size()); int count = 0; for (List> tenantsInfo : tenantsInfos) { @@ -1018,25 +1037,32 @@ public void testThatThereAreTasksOfAllCronTaskClassesAndHaveCorrectIntervals() t intervals.put("io.supertokens.ee.cronjobs.EELicenseCheck", 86400); intervals.put("io.supertokens.cronjobs.syncCoreConfigWithDb.SyncCoreConfigWithDb", 60); intervals.put("io.supertokens.cronjobs.deleteExpiredSessions.DeleteExpiredSessions", 43200); - intervals.put("io.supertokens.cronjobs.deleteExpiredPasswordResetTokens.DeleteExpiredPasswordResetTokens", 3600); - intervals.put("io.supertokens.cronjobs.deleteExpiredEmailVerificationTokens.DeleteExpiredEmailVerificationTokens", 43200); - intervals.put("io.supertokens.cronjobs.deleteExpiredPasswordlessDevices.DeleteExpiredPasswordlessDevices", 3600); + intervals.put("io.supertokens.cronjobs.deleteExpiredPasswordResetTokens.DeleteExpiredPasswordResetTokens", + 3600); + intervals.put( + "io.supertokens.cronjobs.deleteExpiredEmailVerificationTokens.DeleteExpiredEmailVerificationTokens", + 43200); + intervals.put("io.supertokens.cronjobs.deleteExpiredPasswordlessDevices.DeleteExpiredPasswordlessDevices", + 3600); intervals.put("io.supertokens.cronjobs.deleteExpiredTotpTokens.DeleteExpiredTotpTokens", 3600); intervals.put("io.supertokens.cronjobs.deleteExpiredDashboardSessions.DeleteExpiredDashboardSessions", 43200); intervals.put("io.supertokens.cronjobs.telemetry.Telemetry", 86400); - intervals.put("io.supertokens.cronjobs.deleteExpiredAccessTokenSigningKeys.DeleteExpiredAccessTokenSigningKeys", 86400); + intervals.put("io.supertokens.cronjobs.deleteExpiredAccessTokenSigningKeys.DeleteExpiredAccessTokenSigningKeys", + 86400); Map delays = new HashMap<>(); delays.put("io.supertokens.ee.cronjobs.EELicenseCheck", 86400); delays.put("io.supertokens.cronjobs.syncCoreConfigWithDb.SyncCoreConfigWithDb", 0); delays.put("io.supertokens.cronjobs.deleteExpiredSessions.DeleteExpiredSessions", 0); delays.put("io.supertokens.cronjobs.deleteExpiredPasswordResetTokens.DeleteExpiredPasswordResetTokens", 0); - delays.put("io.supertokens.cronjobs.deleteExpiredEmailVerificationTokens.DeleteExpiredEmailVerificationTokens", 0); + delays.put("io.supertokens.cronjobs.deleteExpiredEmailVerificationTokens.DeleteExpiredEmailVerificationTokens", + 0); delays.put("io.supertokens.cronjobs.deleteExpiredPasswordlessDevices.DeleteExpiredPasswordlessDevices", 0); delays.put("io.supertokens.cronjobs.deleteExpiredTotpTokens.DeleteExpiredTotpTokens", 0); delays.put("io.supertokens.cronjobs.deleteExpiredDashboardSessions.DeleteExpiredDashboardSessions", 0); delays.put("io.supertokens.cronjobs.telemetry.Telemetry", 0); - delays.put("io.supertokens.cronjobs.deleteExpiredAccessTokenSigningKeys.DeleteExpiredAccessTokenSigningKeys", 0); + delays.put("io.supertokens.cronjobs.deleteExpiredAccessTokenSigningKeys.DeleteExpiredAccessTokenSigningKeys", + 0); List allTasks = Cronjobs.getInstance(process.getProcess()).getTasks(); assertEquals(10, allTasks.size()); diff --git a/src/test/java/io/supertokens/test/DotStartedFileTest.java b/src/test/java/io/supertokens/test/DotStartedFileTest.java index dfe19a33b..b812863b1 100644 --- a/src/test/java/io/supertokens/test/DotStartedFileTest.java +++ b/src/test/java/io/supertokens/test/DotStartedFileTest.java @@ -24,7 +24,7 @@ import org.junit.Test; import org.junit.rules.TestRule; -import java.io.*; +import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; @@ -46,7 +46,7 @@ public void beforeEach() { @Test public void fiveProcessInParallelDotStartedFileTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process1 = TestingProcessManager.start(args); assertNotNull(process1.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -119,7 +119,7 @@ public void fiveProcessInParallelDotStartedFileTest() throws Exception { @Test public void dotStartedFileNameAndContentTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; String host = "localhost"; String port = "8081"; String hostPortNameCheck = host + "-" + port; @@ -171,7 +171,7 @@ public void dotStartedFileNameAndContentTest() throws Exception { @Test public void processFailToStartDotStartedFileTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; String installDir = "../"; Utils.setValueInConfig("access_token_validity", "-1"); diff --git a/src/test/java/io/supertokens/test/FeatureFlagTest.java b/src/test/java/io/supertokens/test/FeatureFlagTest.java index e29579884..ac09c01f1 100644 --- a/src/test/java/io/supertokens/test/FeatureFlagTest.java +++ b/src/test/java/io/supertokens/test/FeatureFlagTest.java @@ -272,8 +272,10 @@ public void testThatCallingGetFeatureFlagAPIReturnsMfaStats() throws Exception { JsonObject user2 = Utils.signUpRequest_2_5(process, "test2@gmail.com", "validPass123"); assert signUpResponse2.get("status").getAsString().equals("OK"); - AuthRecipe.createPrimaryUser(process.getProcess(), user1.get("user").getAsJsonObject().get("id").getAsString()); - AuthRecipe.linkAccounts(process.getProcess(), user2.get("user").getAsJsonObject().get("id").getAsString(), user1.get("user").getAsJsonObject().get("id").getAsString()); + AuthRecipe.createPrimaryUser(process.getProcess(), + user1.get("user").getAsJsonObject().get("id").getAsString()); + AuthRecipe.linkAccounts(process.getProcess(), user2.get("user").getAsJsonObject().get("id").getAsString(), + user1.get("user").getAsJsonObject().get("id").getAsString()); JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", "http://localhost:3567/ee/featureflag", @@ -364,7 +366,7 @@ public void testThatCallingGetFeatureFlagAPIReturnsMfaStats() throws Exception { process.getProcess(), new TenantIdentifier(null, null, "t1"), (StorageLayer.getStorage(process.getProcess())), signUpResponse.get("user").getAsJsonObject().get("id").getAsString() - ); + ); JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", "http://localhost:3567/ee/featureflag", null, 1000, 1000, null, WebserverAPI.getLatestCDIVersion().get(), ""); @@ -391,7 +393,9 @@ public void testThatCallingGetFeatureFlagAPIReturnsMfaStats() throws Exception { Assert.assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } - private final static String OPAQUE_KEY_WITH_MFA_FEATURE = "Qk8olVa=v-9PU=snnUFMF4ihMCx4zVBOO6Jd7Nrg6Cg5YyFliEj252ADgpwEpDLfFowA0U5OyVo3XL=U4FMft2HDHCDGg9hWD4iwQQiyjMRi6Mu03CVbAxIkNGaXtJ53"; + private final static String OPAQUE_KEY_WITH_MFA_FEATURE = "Qk8olVa=v-9PU" + + "=snnUFMF4ihMCx4zVBOO6Jd7Nrg6Cg5YyFliEj252ADgpwEpDLfFowA0U5OyVo3XL" + + "=U4FMft2HDHCDGg9hWD4iwQQiyjMRi6Mu03CVbAxIkNGaXtJ53"; private final String OPAQUE_KEY_WITH_MULTITENANCY_FEATURE = "ijaleljUd2kU9XXWLiqFYv5br8nutTxbyBqWypQdv2N-" + @@ -943,7 +947,8 @@ public void testPaidStatsContainsAllEnabledFeatures() throws Exception { process = TestingProcessManager.start(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); - ProcessState.EventAndException event = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.LICENSE_KEY_CHECK_NETWORK_CALL); + ProcessState.EventAndException event = process.checkOrWaitForEvent( + ProcessState.PROCESS_STATE.LICENSE_KEY_CHECK_NETWORK_CALL); assertNotNull(event); assertNotNull(event.data); diff --git a/src/test/java/io/supertokens/test/HelloAPITest.java b/src/test/java/io/supertokens/test/HelloAPITest.java index f11f9d1b2..0944b4d3a 100644 --- a/src/test/java/io/supertokens/test/HelloAPITest.java +++ b/src/test/java/io/supertokens/test/HelloAPITest.java @@ -144,13 +144,14 @@ public void testHelloAPIWithBasePath3() throws Exception { "http://localhost:3567/hello", // baseUrl + / "http://localhost:3567/hello/", // baseUrl + / "http://localhost:3567/hello/hello", // baseUrl + /hello - "http://localhost:3567/hello/hello/", // baseUrl + (hello tenant) + / : works because the hello api doesn't check if that tenant exists + "http://localhost:3567/hello/hello/", + // baseUrl + (hello tenant) + / : works because the hello api doesn't check if that tenant exists "http://localhost:3567/hello/appid-hello/hello", // baseUrl + app + /hello "http://localhost:3567/hello/appid-hello/hello/", // baseUrl + app + /hello "http://localhost:3567/hello/appid-hello/test/hello", // baseUrl + app + tenant + /hello }; - for (String helloUrl: HELLO_ROUTES) { + for (String helloUrl : HELLO_ROUTES) { System.out.println(helloUrl); String res = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", helloUrl, null, 1000, 1000, @@ -230,13 +231,14 @@ public void testWithBasePathThatHelloAPIDoesNotRequireAPIKeys() throws Exception "http://localhost:3567/hello", // baseUrl + / "http://localhost:3567/hello/", // baseUrl + / "http://localhost:3567/hello/hello", // baseUrl + /hello - "http://localhost:3567/hello/hello/", // baseUrl + (hello tenant) + / : works because the hello api doesn't check if that tenant exists + "http://localhost:3567/hello/hello/", + // baseUrl + (hello tenant) + / : works because the hello api doesn't check if that tenant exists "http://localhost:3567/hello/appid-hello/hello", // baseUrl + app + /hello "http://localhost:3567/hello/appid-hello/hello/", // baseUrl + app + /hello "http://localhost:3567/hello/appid-hello/test/hello", // baseUrl + app + tenant + /hello }; - for (String helloUrl: HELLO_ROUTES) { + for (String helloUrl : HELLO_ROUTES) { System.out.println(helloUrl); String res = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", helloUrl, null, 1000, 1000, @@ -317,13 +319,14 @@ public void testThatHelloAPIDoesNotRequireAPIKeys() throws Exception { "http://localhost:3567", // / "http://localhost:3567/", // / "http://localhost:3567/hello", // /hello - "http://localhost:3567/hello/", // (hello tenant) + / : works because the hello api doesn't check if that tenant exists + "http://localhost:3567/hello/", + // (hello tenant) + / : works because the hello api doesn't check if that tenant exists "http://localhost:3567/appid-hello/hello", // app + /hello "http://localhost:3567/appid-hello/hello/", // app + /hello "http://localhost:3567/appid-hello/test/hello", // app + tenant + /hello }; - for (String helloUrl: HELLO_ROUTES) { + for (String helloUrl : HELLO_ROUTES) { System.out.println(helloUrl); String res = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", helloUrl, null, 1000, 1000, diff --git a/src/test/java/io/supertokens/test/HttpRequestTest.java b/src/test/java/io/supertokens/test/HttpRequestTest.java index ab6de577c..973d37818 100644 --- a/src/test/java/io/supertokens/test/HttpRequestTest.java +++ b/src/test/java/io/supertokens/test/HttpRequestTest.java @@ -55,7 +55,7 @@ public void beforeEach() { @Test public void jsonResponseTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -130,7 +130,7 @@ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws @Test public void nonJsonResponseTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -199,7 +199,7 @@ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws @Test public void errorRequestTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -284,7 +284,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IO @Test public void withAndWithoutBodyTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -483,7 +483,7 @@ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws @Test public void withAndWithoutVersionTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -660,7 +660,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IO @Test public void getRequestTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/InMemoryDBStorageTest.java b/src/test/java/io/supertokens/test/InMemoryDBStorageTest.java index 6c6913a6d..081e7ec7c 100644 --- a/src/test/java/io/supertokens/test/InMemoryDBStorageTest.java +++ b/src/test/java/io/supertokens/test/InMemoryDBStorageTest.java @@ -307,7 +307,7 @@ public void transactionThrowRunTimeErrorAndExpectRollbackTest() @Test public void multipleParallelTransactionTest() throws InterruptedException, IOException { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "0.00005"); TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); process.getProcess().setForceInMemoryDB(); diff --git a/src/test/java/io/supertokens/test/InMemoryDBTest.java b/src/test/java/io/supertokens/test/InMemoryDBTest.java index e9198ccc2..485fbbbc5 100644 --- a/src/test/java/io/supertokens/test/InMemoryDBTest.java +++ b/src/test/java/io/supertokens/test/InMemoryDBTest.java @@ -604,7 +604,8 @@ public void refreshSessionTestWithAntiCsrf() throws Exception { } SessionInformationHolder refreshedSession2 = Session.refreshSession(process.getProcess(), - refreshedSession.refreshToken.token, refreshedSession.antiCsrfToken, true, AccessToken.getLatestVersion()); + refreshedSession.refreshToken.token, refreshedSession.antiCsrfToken, true, + AccessToken.getLatestVersion()); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())).getNumberOfSessions( new TenantIdentifier(null, null, null)), 1); @@ -691,7 +692,8 @@ public void refreshSessionTestWithNoAntiCsrf() throws Exception { } SessionInformationHolder refreshedSession2 = Session.refreshSession(process.getProcess(), - refreshedSession.refreshToken.token, refreshedSession.antiCsrfToken, false, AccessToken.getLatestVersion()); + refreshedSession.refreshToken.token, refreshedSession.antiCsrfToken, false, + AccessToken.getLatestVersion()); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); @@ -810,7 +812,8 @@ public void refreshTokenExpiresAfterShortTime() throws Exception { Thread.sleep(500); SessionInformationHolder newRefreshedSession2 = Session.refreshSession(main, - newRefreshedSession.refreshToken.token, newRefreshedSession.antiCsrfToken, false, AccessToken.getLatestVersion()); + newRefreshedSession.refreshToken.token, newRefreshedSession.antiCsrfToken, false, + AccessToken.getLatestVersion()); assert newRefreshedSession2.refreshToken != null; assert newRefreshedSession2.accessToken != null; assertNotEquals(newRefreshedSession.accessToken.token, newRefreshedSession2.accessToken.token); @@ -821,7 +824,8 @@ public void refreshTokenExpiresAfterShortTime() throws Exception { Thread.sleep(500); SessionInformationHolder newRefreshedSession3 = Session.refreshSession(main, - newRefreshedSession2.refreshToken.token, newRefreshedSession2.antiCsrfToken, false, AccessToken.getLatestVersion()); + newRefreshedSession2.refreshToken.token, newRefreshedSession2.antiCsrfToken, false, + AccessToken.getLatestVersion()); assert newRefreshedSession3.refreshToken != null; assert newRefreshedSession3.accessToken != null; assertNotEquals(newRefreshedSession3.accessToken.token, newRefreshedSession2.accessToken.token); diff --git a/src/test/java/io/supertokens/test/InputParserTest.java b/src/test/java/io/supertokens/test/InputParserTest.java index 40ea78c7c..2f4c0325f 100644 --- a/src/test/java/io/supertokens/test/InputParserTest.java +++ b/src/test/java/io/supertokens/test/InputParserTest.java @@ -47,7 +47,7 @@ public void beforeEach() { @Test public void testParseStringOrJSONNullOrThrowError() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/IpAllowDenyRegexTest.java b/src/test/java/io/supertokens/test/IpAllowDenyRegexTest.java index f17e50d2f..b281663be 100644 --- a/src/test/java/io/supertokens/test/IpAllowDenyRegexTest.java +++ b/src/test/java/io/supertokens/test/IpAllowDenyRegexTest.java @@ -114,7 +114,8 @@ public void InvalidRegexErrorForIpAllow() throws InterruptedException, IOExcepti TestingProcess process = TestingProcessManager.start(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); - assertTrue(e.exception.getMessage().contains("Provided regular expression is invalid for ip_allow_regex config")); + assertTrue(e.exception.getMessage() + .contains("Provided regular expression is invalid for ip_allow_regex config")); process.kill(); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STOPPED)); @@ -129,7 +130,8 @@ public void InvalidRegexErrorForIpDeny() throws InterruptedException, IOExceptio TestingProcess process = TestingProcessManager.start(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); - assertTrue(e.exception.getMessage().contains("Provided regular expression is invalid for ip_deny_regex config")); + assertTrue(e.exception.getMessage() + .contains("Provided regular expression is invalid for ip_deny_regex config")); process.kill(); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/JWKSPublicAPITest.java b/src/test/java/io/supertokens/test/JWKSPublicAPITest.java index 8c4b90ea0..fd9cc53d4 100644 --- a/src/test/java/io/supertokens/test/JWKSPublicAPITest.java +++ b/src/test/java/io/supertokens/test/JWKSPublicAPITest.java @@ -17,21 +17,15 @@ package io.supertokens.test; import com.google.gson.JsonArray; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import io.supertokens.Main; import io.supertokens.ProcessState; -import io.supertokens.cliOptions.CLIOptions; import io.supertokens.httpRequest.HttpRequest; -import io.supertokens.httpRequest.HttpResponseException; -import io.supertokens.test.httpRequest.HttpRequestForTesting; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; -import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; @@ -55,13 +49,14 @@ public void beforeEach() { @Test public void testSuccessOutput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); // check regular output - JsonObject response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/.well-known/jwks.json", null, + JsonObject response = HttpRequest.sendGETRequest(process.getProcess(), "", + "http://localhost:3567/.well-known/jwks.json", null, 1000, 1000, null); assertEquals(response.entrySet().size(), 1); @@ -76,7 +71,7 @@ public void testSuccessOutput() throws Exception { @Test public void testCacheControlValue() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "1"); @@ -85,7 +80,8 @@ public void testCacheControlValue() throws Exception { // check regular output Map responseHeaders = new HashMap<>(); - JsonObject response = HttpRequest.sendGETRequestWithResponseHeaders(process.getProcess(), "", "http://localhost:3567/.well-known/jwks.json", null, + JsonObject response = HttpRequest.sendGETRequestWithResponseHeaders(process.getProcess(), "", + "http://localhost:3567/.well-known/jwks.json", null, 1000, 1000, null, responseHeaders); assertEquals(response.entrySet().size(), 1); @@ -99,7 +95,8 @@ public void testCacheControlValue() throws Exception { Thread.sleep(2000); - response = HttpRequest.sendGETRequestWithResponseHeaders(process.getProcess(), "", "http://localhost:3567/.well-known/jwks.json", null, + response = HttpRequest.sendGETRequestWithResponseHeaders(process.getProcess(), "", + "http://localhost:3567/.well-known/jwks.json", null, 1000, 1000, null, responseHeaders); assertEquals(response.entrySet().size(), 1); diff --git a/src/test/java/io/supertokens/test/RequestStatsTest.java b/src/test/java/io/supertokens/test/RequestStatsTest.java index 553dbc4bd..7140a119e 100644 --- a/src/test/java/io/supertokens/test/RequestStatsTest.java +++ b/src/test/java/io/supertokens/test/RequestStatsTest.java @@ -77,7 +77,8 @@ public void testLastMinuteStats() throws Exception { int finalI = i; ex.execute(() -> { try { - TestMultitenancyAPIHelper.epSignUp(TenantIdentifier.BASE_TENANT, "test" + finalI + "@example.com", "password", process.getProcess()); + TestMultitenancyAPIHelper.epSignUp(TenantIdentifier.BASE_TENANT, "test" + finalI + "@example.com", + "password", process.getProcess()); } catch (Exception e) { throw new RuntimeException(e); } @@ -159,13 +160,15 @@ public void testLastMinuteStatsPerApp() throws Exception { int finalI = i; ex.execute(() -> { try { - TestMultitenancyAPIHelper.epSignUp(TenantIdentifier.BASE_TENANT, "test" + finalI + "@example.com", "password", process.getProcess()); + TestMultitenancyAPIHelper.epSignUp(TenantIdentifier.BASE_TENANT, "test" + finalI + "@example.com", + "password", process.getProcess()); } catch (Exception e) { // ignore } if (finalI < 400) { try { - TestMultitenancyAPIHelper.epSignUp(new TenantIdentifier(null, "a1", null), "test" + finalI + "@example.com", "password", process.getProcess()); + TestMultitenancyAPIHelper.epSignUp(new TenantIdentifier(null, "a1", null), + "test" + finalI + "@example.com", "password", process.getProcess()); } catch (Exception e) { // ignore } @@ -215,7 +218,8 @@ public void testLastMinuteStatsPerApp() throws Exception { { JsonObject stats = HttpRequestForTesting - .sendGETRequest(process.getProcess(), "", "http://localhost:3567/appid-a1/requests/stats", null, 1000, + .sendGETRequest(process.getProcess(), "", "http://localhost:3567/appid-a1/requests/stats", null, + 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), null); JsonArray avgRps = stats.get("averageRequestsPerSecond").getAsJsonArray(); @@ -275,12 +279,16 @@ public void testWithNonExistantApp() throws Exception { try { JsonObject stats = HttpRequestForTesting - .sendGETRequest(process.getProcess(), "", "http://localhost:3567/appid-a1/requests/stats", null, 1000, + .sendGETRequest(process.getProcess(), "", "http://localhost:3567/appid-a1/requests/stats", null, + 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), null); fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: AppId or tenantId not found => Tenant with the following connectionURIDomain, appId and tenantId combination not found: (, a1, public)", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: AppId or tenantId not found => Tenant with the following " + + "connectionURIDomain, appId and tenantId combination not found: (, a1, public)", + e.getMessage()); } process.kill(); diff --git a/src/test/java/io/supertokens/test/ResourceDistributorTest.java b/src/test/java/io/supertokens/test/ResourceDistributorTest.java index 6fa860a3a..091f75683 100644 --- a/src/test/java/io/supertokens/test/ResourceDistributorTest.java +++ b/src/test/java/io/supertokens/test/ResourceDistributorTest.java @@ -79,8 +79,10 @@ public void testClearAllResourcesWithKeyWorksCorrectly() throws Exception { process.getProcess().getResourceDistributor().setResource(a1, ResourceB.RESOURCE_ID, new ResourceB()); process.getProcess().getResourceDistributor().setResource(t1, ResourceB.RESOURCE_ID, new ResourceB()); - assertTrue(process.getProcess().getResourceDistributor().getResource(a1, ResourceA.RESOURCE_ID) instanceof ResourceA); - assertTrue(process.getProcess().getResourceDistributor().getResource(t1, ResourceA.RESOURCE_ID) instanceof ResourceA); + assertTrue(process.getProcess().getResourceDistributor() + .getResource(a1, ResourceA.RESOURCE_ID) instanceof ResourceA); + assertTrue(process.getProcess().getResourceDistributor() + .getResource(t1, ResourceA.RESOURCE_ID) instanceof ResourceA); process.getProcess().getResourceDistributor().clearAllResourcesWithResourceKey(ResourceA.RESOURCE_ID); @@ -97,8 +99,10 @@ public void testClearAllResourcesWithKeyWorksCorrectly() throws Exception { // ignored } - assertTrue(process.getProcess().getResourceDistributor().getResource(a1, ResourceB.RESOURCE_ID) instanceof ResourceB); - assertTrue(process.getProcess().getResourceDistributor().getResource(t1, ResourceB.RESOURCE_ID) instanceof ResourceB); + assertTrue(process.getProcess().getResourceDistributor() + .getResource(a1, ResourceB.RESOURCE_ID) instanceof ResourceB); + assertTrue(process.getProcess().getResourceDistributor() + .getResource(t1, ResourceB.RESOURCE_ID) instanceof ResourceB); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/SemVerTest.java b/src/test/java/io/supertokens/test/SemVerTest.java index 213992dec..7a1f1168d 100644 --- a/src/test/java/io/supertokens/test/SemVerTest.java +++ b/src/test/java/io/supertokens/test/SemVerTest.java @@ -39,24 +39,24 @@ public void beforeEach() { @Test public void betweenInclusive() { - assert(!SemVer.v2_7.betweenInclusive(SemVer.v2_8, SemVer.v2_10)); - assert(SemVer.v2_8.betweenInclusive(SemVer.v2_8, SemVer.v2_10)); - assert(SemVer.v2_9.betweenInclusive(SemVer.v2_8, SemVer.v2_10)); - assert(SemVer.v2_10.betweenInclusive(SemVer.v2_8, SemVer.v2_10)); - assert(!SemVer.v2_11.betweenInclusive(SemVer.v2_8, SemVer.v2_10)); + assert (!SemVer.v2_7.betweenInclusive(SemVer.v2_8, SemVer.v2_10)); + assert (SemVer.v2_8.betweenInclusive(SemVer.v2_8, SemVer.v2_10)); + assert (SemVer.v2_9.betweenInclusive(SemVer.v2_8, SemVer.v2_10)); + assert (SemVer.v2_10.betweenInclusive(SemVer.v2_8, SemVer.v2_10)); + assert (!SemVer.v2_11.betweenInclusive(SemVer.v2_8, SemVer.v2_10)); } @Test public void greaterThanOrEqualTo() { - assert(!SemVer.v2_7.greaterThanOrEqualTo(SemVer.v2_8)); - assert(SemVer.v2_8.greaterThanOrEqualTo(SemVer.v2_8)); - assert(SemVer.v2_9.greaterThanOrEqualTo(SemVer.v2_8)); + assert (!SemVer.v2_7.greaterThanOrEqualTo(SemVer.v2_8)); + assert (SemVer.v2_8.greaterThanOrEqualTo(SemVer.v2_8)); + assert (SemVer.v2_9.greaterThanOrEqualTo(SemVer.v2_8)); } @Test public void lesserThan() { - assert(SemVer.v2_7.lesserThan(SemVer.v2_8)); - assert(!SemVer.v2_8.lesserThan(SemVer.v2_8)); - assert(!SemVer.v2_9.lesserThan(SemVer.v2_8)); + assert (SemVer.v2_7.lesserThan(SemVer.v2_8)); + assert (!SemVer.v2_8.lesserThan(SemVer.v2_8)); + assert (!SemVer.v2_9.lesserThan(SemVer.v2_8)); } } diff --git a/src/test/java/io/supertokens/test/ShutdownTest.java b/src/test/java/io/supertokens/test/ShutdownTest.java index 53f97840e..d2c5bc072 100644 --- a/src/test/java/io/supertokens/test/ShutdownTest.java +++ b/src/test/java/io/supertokens/test/ShutdownTest.java @@ -45,7 +45,7 @@ public void beforeEach() { @Test public void shutdownSignalTest() throws TestingProcessManagerException, InterruptedException { // TODO: make sure all processes like cron jobs and tomcat etc are shutdown - to do later... - String[] args = { "../" }; + String[] args = {"../"}; TestingProcess process = TestingProcessManager.start(args); EventAndException e = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); assertNotNull(e); diff --git a/src/test/java/io/supertokens/test/StorageTest.java b/src/test/java/io/supertokens/test/StorageTest.java index 19065d377..e242b7656 100644 --- a/src/test/java/io/supertokens/test/StorageTest.java +++ b/src/test/java/io/supertokens/test/StorageTest.java @@ -228,7 +228,8 @@ public void transactionIsolationWithAnInitialRowTesting() if (info.value.equals("Value")) { try { - sqlStorage.setKeyValue_Transaction(new TenantIdentifier(null, null, null), con, "Key", + sqlStorage.setKeyValue_Transaction(new TenantIdentifier(null, null, null), con, + "Key", new KeyValueInfo("Value1")); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -255,7 +256,8 @@ public void transactionIsolationWithAnInitialRowTesting() if (info.value.equals("Value")) { try { - sqlStorage.setKeyValue_Transaction(new TenantIdentifier(null, null, null), con, "Key", + sqlStorage.setKeyValue_Transaction(new TenantIdentifier(null, null, null), con, + "Key", new KeyValueInfo("Value2")); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -744,7 +746,8 @@ public void storageDeadAndAlive() throws InterruptedException, IOException, Http storage.setStorageLayerEnabled(true); JsonObject sessionCreated = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", - "http://localhost:3567/recipe/session", request, 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), + "http://localhost:3567/recipe/session", request, 1000, 1000, null, + Utils.getCdiVersionStringLatestForTests(), "session"); JsonObject jsonBody = new JsonObject(); @@ -777,7 +780,7 @@ public void storageDeadAndAlive() throws InterruptedException, IOException, Http @Test public void multipleParallelTransactionTest() throws InterruptedException, IOException { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "0.00005"); TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/SuperTokensSaaSSecretTest.java b/src/test/java/io/supertokens/test/SuperTokensSaaSSecretTest.java index aa31aded6..d35aa0436 100644 --- a/src/test/java/io/supertokens/test/SuperTokensSaaSSecretTest.java +++ b/src/test/java/io/supertokens/test/SuperTokensSaaSSecretTest.java @@ -429,7 +429,8 @@ public static void checkSessionResponse(JsonObject response, TestingProcessManag } private static final String[] PROTECTED_CORE_CONFIG = new String[]{"ip_allow_regex", "ip_deny_regex"}; - private static final Object[] PROTECTED_CORE_CONFIG_VALUES = new String[]{"127\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+|::1|0:0:0:0:0:0:0:1", "192.0.0.1"}; + private static final Object[] PROTECTED_CORE_CONFIG_VALUES = new String[]{ + "127\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+|::1|0:0:0:0:0:0:0:1", "192.0.0.1"}; @Test public void testThatTenantCannotSetProtectedConfigIfSuperTokensSaaSSecretIsSet() @@ -460,10 +461,11 @@ public void testThatTenantCannotSetProtectedConfigIfSuperTokensSaaSSecretIsSet() try { JsonObject j = new JsonObject(); j.addProperty(PROTECTED_CORE_CONFIG[i], ""); - Multitenancy.addNewOrUpdateAppOrTenant(process.main, new TenantConfig(new TenantIdentifier(null, null, "t1"), new EmailPasswordConfig(false), - new ThirdPartyConfig(false, new ThirdPartyConfig.Provider[0]), - new PasswordlessConfig(false), - null, null, j), true); + Multitenancy.addNewOrUpdateAppOrTenant(process.main, + new TenantConfig(new TenantIdentifier(null, null, "t1"), new EmailPasswordConfig(false), + new ThirdPartyConfig(false, new ThirdPartyConfig.Provider[0]), + new PasswordlessConfig(false), + null, null, j), true); fail(); } catch (BadPermissionException e) { assertEquals(e.getMessage(), "Not allowed to modify protected configs."); @@ -553,7 +555,8 @@ public void testThatTenantCannotGetProtectedConfigIfSuperTokensSaaSSecretIsSet() { JsonObject response = HttpRequestForTesting.sendJsonRequest(process.getProcess(), "", - HttpRequestForTesting.getMultitenantUrl(TenantIdentifier.BASE_TENANT, "/recipe/multitenancy/tenant/list"), + HttpRequestForTesting.getMultitenantUrl(TenantIdentifier.BASE_TENANT, + "/recipe/multitenancy/tenant/list"), null, 1000, 1000, null, SemVer.v3_0.get(), "GET", apiKey, "multitenancy"); @@ -574,7 +577,8 @@ public void testThatTenantCannotGetProtectedConfigIfSuperTokensSaaSSecretIsSet() { JsonObject response = HttpRequestForTesting.sendJsonRequest(process.getProcess(), "", - HttpRequestForTesting.getMultitenantUrl(TenantIdentifier.BASE_TENANT, "/recipe/multitenancy/tenant/list"), + HttpRequestForTesting.getMultitenantUrl(TenantIdentifier.BASE_TENANT, + "/recipe/multitenancy/tenant/list"), null, 1000, 1000, null, SemVer.v3_0.get(), "GET", saasSecret, "multitenancy"); @@ -666,7 +670,7 @@ public void testLogContainsCorrectCud() throws Exception { @Test public void testThatAllProtectedPropsAreTested() throws Exception { - for (String protectedConfig: CoreConfig.PROTECTED_CONFIGS) { + for (String protectedConfig : CoreConfig.PROTECTED_CONFIGS) { assertTrue(Arrays.asList(PROTECTED_CORE_CONFIG).contains(protectedConfig)); } } diff --git a/src/test/java/io/supertokens/test/TelemetryAPITest2_7.java b/src/test/java/io/supertokens/test/TelemetryAPITest2_7.java index 4e0492e74..863cc3a92 100644 --- a/src/test/java/io/supertokens/test/TelemetryAPITest2_7.java +++ b/src/test/java/io/supertokens/test/TelemetryAPITest2_7.java @@ -51,7 +51,7 @@ public void beforeEach() { @Test public void testTelemetryDisabledInMemDb() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -71,7 +71,7 @@ public void testTelemetryDisabledInMemDb() throws Exception { @Test public void testDefaultTelemetry() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -93,7 +93,7 @@ public void testDefaultTelemetry() throws Exception { @Test public void testDisableTelemetry() throws Exception { Utils.setValueInConfig("disable_telemetry", "true"); - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -114,7 +114,7 @@ public void testDisableTelemetry() throws Exception { @Test public void testEnableTelemetry() throws Exception { Utils.setValueInConfig("disable_telemetry", "false"); - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/TelemetryTest.java b/src/test/java/io/supertokens/test/TelemetryTest.java index b1da7d5d9..73af36fac 100644 --- a/src/test/java/io/supertokens/test/TelemetryTest.java +++ b/src/test/java/io/supertokens/test/TelemetryTest.java @@ -61,7 +61,7 @@ public void beforeEach() { @Test public void testThatDisablingTelemetryDoesNotSendOne() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("disable_telemetry", "true"); @@ -76,7 +76,7 @@ public void testThatDisablingTelemetryDoesNotSendOne() throws Exception { @Test public void testThatTelemetryDoesNotSendOneIfInMemDb() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -93,7 +93,7 @@ public void testThatTelemetryDoesNotSendOneIfInMemDb() throws Exception { @Test public void testThatTelemetryDoesNotSendOneIfInMemDbButActualDBThere() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcess process = TestingProcessManager.start(args, false); process.getProcess().setForceInMemoryDB(); @@ -113,7 +113,7 @@ public void testThatTelemetryDoesNotSendOneIfInMemDbButActualDBThere() throws Ex @Test public void testThatTelemetryWorks() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcess process = TestingProcessManager.start(args, false); process.startProcess(); @@ -176,7 +176,8 @@ protected URLConnection openConnection(URL u) { if (StorageLayer.getBaseStorage(process.getProcess()).getType() == STORAGE_TYPE.SQL) { assertEquals(1, telemetryData.get("dashboardUserEmails").getAsJsonArray().size()); - assertEquals("test@example.com", telemetryData.get("dashboardUserEmails").getAsJsonArray().get(0).getAsString()); + assertEquals("test@example.com", + telemetryData.get("dashboardUserEmails").getAsJsonArray().get(0).getAsString()); assertEquals(31, telemetryData.get("maus").getAsJsonArray().size()); assertEquals(0, telemetryData.get("usersCount").getAsInt()); } else { @@ -191,7 +192,7 @@ protected URLConnection openConnection(URL u) { @Test public void testThatTelemetryWorksWithApiDomainAndWebsiteDomainSet() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcess process = TestingProcessManager.start(args, false); process.startProcess(); @@ -259,7 +260,8 @@ protected URLConnection openConnection(URL u) { if (StorageLayer.getBaseStorage(process.getProcess()).getType() == STORAGE_TYPE.SQL) { assertEquals(1, telemetryData.get("dashboardUserEmails").getAsJsonArray().size()); - assertEquals("test@example.com", telemetryData.get("dashboardUserEmails").getAsJsonArray().get(0).getAsString()); + assertEquals("test@example.com", + telemetryData.get("dashboardUserEmails").getAsJsonArray().get(0).getAsString()); assertEquals(31, telemetryData.get("maus").getAsJsonArray().size()); assertEquals(0, telemetryData.get("usersCount").getAsInt()); } else { @@ -276,7 +278,7 @@ protected URLConnection openConnection(URL u) { public void testThatTelemetryIdDoesNotChange() throws Exception { String telemetryId = null; { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcess process = TestingProcessManager.start(args, false); @@ -325,7 +327,7 @@ protected URLConnection openConnection(URL u) { } { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcess process = TestingProcessManager.start(args, false); @@ -380,7 +382,7 @@ protected URLConnection openConnection(URL u) { @Test public void testThatTelemetryWillNotGoIfTestingAndNoMockRequest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/TestHelloAPIRateLimiting.java b/src/test/java/io/supertokens/test/TestHelloAPIRateLimiting.java index f58fe93fe..9c91a76d8 100644 --- a/src/test/java/io/supertokens/test/TestHelloAPIRateLimiting.java +++ b/src/test/java/io/supertokens/test/TestHelloAPIRateLimiting.java @@ -163,7 +163,7 @@ public void testThatTheHelloAPIisRateLimited() throws Exception { createApps(process); // Call 5 requests rapidly - for (int i=0; i < 5; i++) { + for (int i = 0; i < 5; i++) { assertTrue(callHello(new TenantIdentifier(null, "a1", null), process.getProcess())); } @@ -195,7 +195,7 @@ public void testThatTheHelloAPIisRateLimitedPerApp() throws Exception { createApps(process); // Call 5 requests rapidly - for (int i=0; i < 5; i++) { + for (int i = 0; i < 5; i++) { assertTrue(callHello(new TenantIdentifier(null, "a1", null), process.getProcess())); } @@ -203,7 +203,7 @@ public void testThatTheHelloAPIisRateLimitedPerApp() throws Exception { assertFalse(callHello(new TenantIdentifier(null, "a1", null), process.getProcess())); // But it should work for a different app - for (int i=0; i < 5; i++) { + for (int i = 0; i < 5; i++) { assertTrue(callHello(new TenantIdentifier(null, "a2", null), process.getProcess())); assertTrue(callHello(new TenantIdentifier(null, "a3", null), process.getProcess())); } @@ -239,7 +239,7 @@ public void testThatTheHelloAPIisRateLimited2() throws Exception { createApps(process); // Call 5 requests rapidly - for (int i=0; i < 5; i++) { + for (int i = 0; i < 5; i++) { assertTrue(callHello2(new TenantIdentifier(null, null, null), process.getProcess())); } diff --git a/src/test/java/io/supertokens/test/VersionTest.java b/src/test/java/io/supertokens/test/VersionTest.java index c5eb45fd4..95b6b303f 100644 --- a/src/test/java/io/supertokens/test/VersionTest.java +++ b/src/test/java/io/supertokens/test/VersionTest.java @@ -49,7 +49,7 @@ public void beforeEach() { @Test public void simpleLoadingOfVersionTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -85,7 +85,7 @@ public void versionFileMissingTest() throws Exception { process1 = pb.start(); process1.waitFor(); - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); diff --git a/src/test/java/io/supertokens/test/accountlinking/CreatePrimaryUserTest.java b/src/test/java/io/supertokens/test/accountlinking/CreatePrimaryUserTest.java index 4417f756f..22b3598d9 100644 --- a/src/test/java/io/supertokens/test/accountlinking/CreatePrimaryUserTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/CreatePrimaryUserTest.java @@ -167,7 +167,8 @@ public void makeEmailPasswordPrimaryUserSuccess() throws Exception { AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); assert (result.user.isPrimaryUser); assert (result.user.loginMethods.length == 1); @@ -320,7 +321,8 @@ public void alreadyPrimaryUsertest() throws Exception { AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); @@ -360,7 +362,8 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", @@ -398,7 +401,8 @@ public void makePrimarySucceedsEvenIfAnotherAccountWithSameEmailButIsNotAPrimary ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", "test@example.com"); - AuthRecipe.CreatePrimaryUserResult r = AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult r = AuthRecipe.createPrimaryUser(process.main, + signInUpResponse.user.getSupertokensUserId()); assert (!r.wasAlreadyAPrimaryUser); process.kill(); @@ -431,7 +435,8 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", @@ -479,13 +484,15 @@ public void makePrimarySucceedsEvenIfAnotherAccountWithSameEmailButInADifferentT "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", "test@example.com"); - AuthRecipe.CreatePrimaryUserResult r = AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult r = AuthRecipe.createPrimaryUser(process.main, + signInUpResponse.user.getSupertokensUserId()); assert !r.wasAlreadyAPrimaryUser; process.kill(); @@ -536,7 +543,8 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccount() throws Ex "pass1234"); AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + emailPasswordUser1.getSupertokensUserId()); try { AuthRecipe.createPrimaryUser(process.main, emailPasswordUser2.getSupertokensUserId()); diff --git a/src/test/java/io/supertokens/test/accountlinking/DeleteUserTest.java b/src/test/java/io/supertokens/test/accountlinking/DeleteUserTest.java index edc07511d..cb1c6bb79 100644 --- a/src/test/java/io/supertokens/test/accountlinking/DeleteUserTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/DeleteUserTest.java @@ -73,7 +73,8 @@ public void deleteLinkedUserWithoutRemovingAllUsers() throws Exception { AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + r2.getSupertokensUserId()).wasAlreadyLinked); AuthRecipe.deleteUser(process.main, r1.getSupertokensUserId(), false); @@ -110,7 +111,8 @@ public void deleteLinkedPrimaryUserWithoutRemovingAllUsers() throws Exception { AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + r2.getSupertokensUserId()).wasAlreadyLinked); AuthRecipe.deleteUser(process.main, r2.getSupertokensUserId(), false); @@ -148,7 +150,8 @@ public void deleteLinkedPrimaryUserRemovingAllUsers() throws Exception { AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + r2.getSupertokensUserId()).wasAlreadyLinked); AuthRecipe.deleteUser(process.main, r2.getSupertokensUserId()); @@ -183,7 +186,8 @@ public void deleteLinkedPrimaryUserRemovingAllUsers2() throws Exception { AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + r2.getSupertokensUserId()).wasAlreadyLinked); AuthRecipe.deleteUser(process.main, r1.getSupertokensUserId()); @@ -228,7 +232,8 @@ public void deleteUserTestWithUserIdMapping1() throws Exception { AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + r2.getSupertokensUserId()).wasAlreadyLinked); AuthRecipe.deleteUser(process.main, r1.getSupertokensUserId(), false); @@ -242,8 +247,10 @@ public void deleteUserTestWithUserIdMapping1() throws Exception { assertEquals(UserMetadata.getUserMetadata(process.main, r1.getSupertokensUserId()), new JsonObject()); assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), metadata); assertEquals(UserMetadata.getUserMetadata(process.main, r2.getSupertokensUserId()), new JsonObject()); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); + assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + null); + assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); process.kill(); @@ -280,7 +287,8 @@ public void deleteUserTestWithUserIdMapping2() throws Exception { AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + r2.getSupertokensUserId()).wasAlreadyLinked); AuthRecipe.deleteUser(process.main, r1.getSupertokensUserId()); @@ -294,8 +302,10 @@ public void deleteUserTestWithUserIdMapping2() throws Exception { assertEquals(UserMetadata.getUserMetadata(process.main, r1.getSupertokensUserId()), new JsonObject()); assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), new JsonObject()); assertEquals(UserMetadata.getUserMetadata(process.main, r2.getSupertokensUserId()), new JsonObject()); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); + assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); + assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); process.kill(); @@ -338,8 +348,10 @@ public void deleteUserTestWithUserIdMapping3() throws Exception { AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - assert (!AuthRecipe.linkAccounts(process.main, r3.getSupertokensUserId(), r1.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + r2.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r3.getSupertokensUserId(), + r1.getSupertokensUserId()).wasAlreadyLinked); AuthRecipe.deleteUser(process.main, r1.getSupertokensUserId(), false); @@ -355,9 +367,12 @@ public void deleteUserTestWithUserIdMapping3() throws Exception { assert (userR2.loginMethods.length == 2); assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), metadata); assertEquals(UserMetadata.getUserMetadata(process.main, "e3"), metadata); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); + assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + null); + assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + null); + assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); } AuthRecipe.deleteUser(process.main, r2.getSupertokensUserId(), false); @@ -369,9 +384,12 @@ public void deleteUserTestWithUserIdMapping3() throws Exception { assert (userR2.loginMethods.length == 1); assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), metadata); assertEquals(UserMetadata.getUserMetadata(process.main, "e3"), metadata); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); + assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + null); + assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + null); + assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); } AuthRecipe.deleteUser(process.main, r3.getSupertokensUserId(), false); @@ -382,9 +400,12 @@ public void deleteUserTestWithUserIdMapping3() throws Exception { assert (userR2 == null && userR3 == null); assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), new JsonObject()); assertEquals(UserMetadata.getUserMetadata(process.main, "e3"), new JsonObject()); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); - assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); + assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); + assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); + assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); } process.kill(); diff --git a/src/test/java/io/supertokens/test/accountlinking/EmailPasswordTests.java b/src/test/java/io/supertokens/test/accountlinking/EmailPasswordTests.java index 094fc4bf8..fea54dee7 100644 --- a/src/test/java/io/supertokens/test/accountlinking/EmailPasswordTests.java +++ b/src/test/java/io/supertokens/test/accountlinking/EmailPasswordTests.java @@ -68,7 +68,8 @@ public void testUpdatePasswordWithDifferentValidUserId() throws Exception { } AuthRecipeUserInfo user1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "password"); - AuthRecipeUserInfo user2 = ThirdParty.signInUp(process.getProcess(), "google", "googleid", "test@example.com").user; + AuthRecipeUserInfo user2 = ThirdParty.signInUp(process.getProcess(), "google", "googleid", + "test@example.com").user; AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user1.getSupertokensUserId(), user2.getSupertokensUserId()); @@ -102,14 +103,16 @@ public void testPasswordlessUserWithSameEmail() throws Exception { AuthRecipeUserInfo user1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "password"); Passwordless.CreateCodeResponse code = Passwordless.createCode(process.getProcess(), null, "+919876543210", null, null); - AuthRecipeUserInfo user2 = Passwordless.consumeCode(process.getProcess(), code.deviceId, code.deviceIdHash, code.userInputCode, null).user; + AuthRecipeUserInfo user2 = Passwordless.consumeCode(process.getProcess(), code.deviceId, code.deviceIdHash, + code.userInputCode, null).user; AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user1.getSupertokensUserId()); Passwordless.CreateCodeResponse code1 = Passwordless.createCode(process.getProcess(), "test@example.com", null, null, null); - AuthRecipeUserInfo user3 = Passwordless.consumeCode(process.getProcess(), code1.deviceId, code1.deviceIdHash, code1.userInputCode, null).user; + AuthRecipeUserInfo user3 = Passwordless.consumeCode(process.getProcess(), code1.deviceId, code1.deviceIdHash, + code1.userInputCode, null).user; process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -131,20 +134,23 @@ public void testPasswordlessUsersLinked() throws Exception { Passwordless.CreateCodeResponse code1 = Passwordless.createCode(process.getProcess(), "test@example.com", null, null, null); - AuthRecipeUserInfo user1 = Passwordless.consumeCode(process.getProcess(), code1.deviceId, code1.deviceIdHash, code1.userInputCode, null).user; + AuthRecipeUserInfo user1 = Passwordless.consumeCode(process.getProcess(), code1.deviceId, code1.deviceIdHash, + code1.userInputCode, null).user; Thread.sleep(50); Passwordless.CreateCodeResponse code2 = Passwordless.createCode(process.getProcess(), null, "+919876543210", null, null); - AuthRecipeUserInfo user2 = Passwordless.consumeCode(process.getProcess(), code2.deviceId, code2.deviceIdHash, code2.userInputCode, null).user; + AuthRecipeUserInfo user2 = Passwordless.consumeCode(process.getProcess(), code2.deviceId, code2.deviceIdHash, + code2.userInputCode, null).user; AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user1.getSupertokensUserId()); Passwordless.CreateCodeResponse code3 = Passwordless.createCode(process.getProcess(), null, "+919876543210", null, null); - AuthRecipeUserInfo user3 = Passwordless.consumeCode(process.getProcess(), code3.deviceId, code3.deviceIdHash, code3.userInputCode, null).user; + AuthRecipeUserInfo user3 = Passwordless.consumeCode(process.getProcess(), code3.deviceId, code3.deviceIdHash, + code3.userInputCode, null).user; process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/accountlinking/GetUserByAccountInfoTest.java b/src/test/java/io/supertokens/test/accountlinking/GetUserByAccountInfoTest.java index e920629b2..dede68e37 100644 --- a/src/test/java/io/supertokens/test/accountlinking/GetUserByAccountInfoTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/GetUserByAccountInfoTest.java @@ -126,7 +126,7 @@ public void testListUsersByAccountInfoForUnlinkedAccounts() throws Exception { assertEquals(RECIPE_ID.EMAIL_PASSWORD, userToTest.loginMethods[0].recipeId); assertEquals(user1.getSupertokensUserId(), userToTest.loginMethods[0].getSupertokensUserId()); assertFalse(userToTest.loginMethods[0].verified); - assert(userToTest.loginMethods[0].timeJoined > 0); + assert (userToTest.loginMethods[0].timeJoined > 0); // test for result assertEquals(user1, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage @@ -256,9 +256,11 @@ public void testListUserByAccountInfoWhenAccountsAreLinked1() throws Exception { AuthRecipeUserInfo user1 = EmailPassword.signUp(process.getProcess(), "test1@example.com", "password1"); Thread.sleep(50); - AuthRecipeUserInfo user2 = ThirdParty.signInUp(process.getProcess(), "google", "userid1", "test2@example.com").user; + AuthRecipeUserInfo user2 = ThirdParty.signInUp(process.getProcess(), "google", "userid1", + "test2@example.com").user; - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); Storage storage = ( @@ -304,7 +306,8 @@ public void testListUserByAccountInfoWhenAccountsAreLinked2() throws Exception { Thread.sleep(50); AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "password2"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); Storage storage = ( @@ -341,7 +344,8 @@ public void testListUserByAccountInfoWhenAccountsAreLinked3() throws Exception { Thread.sleep(50); AuthRecipeUserInfo user2 = createPasswordlessUserWithEmail(process.getProcess(), "test2@example.com"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); Storage storage = ( @@ -378,7 +382,8 @@ public void testListUserByAccountInfoWhenAccountsAreLinked4() throws Exception { Thread.sleep(50); AuthRecipeUserInfo user2 = createPasswordlessUserWithPhone(process.getProcess(), "+919876543210"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); Storage storage = ( @@ -418,7 +423,8 @@ public void testListUserByAccountInfoWhenAccountsAreLinked5() throws Exception { Thread.sleep(50); AuthRecipeUserInfo user2 = createThirdPartyUser(process.getProcess(), "google", "userid1", "test2@example.com"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); Storage storage = ( @@ -466,10 +472,12 @@ public void testForEmptyResults() throws Exception { Thread.sleep(50); Passwordless.CreateCodeResponse code = Passwordless.createCode(process.getProcess(), null, "+919876543210", null, null); - AuthRecipeUserInfo user3 = Passwordless.consumeCode(process.getProcess(), code.deviceId, code.deviceIdHash, code.userInputCode, null).user; + AuthRecipeUserInfo user3 = Passwordless.consumeCode(process.getProcess(), code.deviceId, code.deviceIdHash, + code.userInputCode, null).user; - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), primaryUser.getSupertokensUserId()); @@ -519,7 +527,8 @@ public void testGetUserByAccountInfoOrdersUserBasedOnTimeJoined() throws Excepti Thread.sleep(50); Passwordless.CreateCodeResponse code = Passwordless.createCode(process.getProcess(), null, "+919876543210", null, null); - AuthRecipeUserInfo user3 = Passwordless.consumeCode(process.getProcess(), code.deviceId, code.deviceIdHash, code.userInputCode, null).user; + AuthRecipeUserInfo user3 = Passwordless.consumeCode(process.getProcess(), code.deviceId, code.deviceIdHash, + code.userInputCode, null).user; Thread.sleep(50); AuthRecipeUserInfo user4 = createEmailPasswordUser(process.getProcess(), "test2@example.com", "password1"); Thread.sleep(50); diff --git a/src/test/java/io/supertokens/test/accountlinking/GetUserByIdTest.java b/src/test/java/io/supertokens/test/accountlinking/GetUserByIdTest.java index 48bf9ee9a..3df98a762 100644 --- a/src/test/java/io/supertokens/test/accountlinking/GetUserByIdTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/GetUserByIdTest.java @@ -129,19 +129,21 @@ public void testAllLoginMethods() throws Exception { assertEquals(RECIPE_ID.EMAIL_PASSWORD, userToTest.loginMethods[0].recipeId); assertEquals(user1.getSupertokensUserId(), userToTest.loginMethods[0].getSupertokensUserId()); assertFalse(userToTest.loginMethods[0].verified); - assert(userToTest.loginMethods[0].timeJoined > 0); + assert (userToTest.loginMethods[0].timeJoined > 0); assertEquals(user1, AuthRecipe.getUserById(process.getProcess(), user1.getSupertokensUserId())); assertEquals(user2, AuthRecipe.getUserById(process.getProcess(), user2.getSupertokensUserId())); assertEquals(user3, AuthRecipe.getUserById(process.getProcess(), user3.getSupertokensUserId())); assertEquals(user4, AuthRecipe.getUserById(process.getProcess(), user4.getSupertokensUserId())); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user4.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user4.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), primaryUser.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user1.getSupertokensUserId(), primaryUser.getSupertokensUserId()); - for (String userId : new String[]{user1.getSupertokensUserId(), user2.getSupertokensUserId(), user3.getSupertokensUserId(), user4.getSupertokensUserId()}) { + for (String userId : new String[]{user1.getSupertokensUserId(), user2.getSupertokensUserId(), + user3.getSupertokensUserId(), user4.getSupertokensUserId()}) { AuthRecipeUserInfo result = AuthRecipe.getUserById(process.getProcess(), userId); assertTrue(result.isPrimaryUser); @@ -196,14 +198,16 @@ public void testLoginMethodsAreSortedByTime() throws Exception { // Create users AuthRecipeUserInfo user4 = createPasswordlessUserWithPhone(process.getProcess(), "+919876543210"); Thread.sleep(50); - AuthRecipeUserInfo user2 = createThirdPartyUser(process.getProcess(), "google", "userid1", "test@example.com"); + AuthRecipeUserInfo user2 = createThirdPartyUser(process.getProcess(), "google", "userid1", + "test@example.com"); Thread.sleep(50); AuthRecipeUserInfo user3 = createPasswordlessUserWithEmail(process.getProcess(), "test@example.com"); Thread.sleep(50); AuthRecipeUserInfo user1 = createEmailPasswordUser(process.getProcess(), "test@example.com", "password1"); // Link accounts randomly - String[] userIds = new String[]{user1.getSupertokensUserId(), user2.getSupertokensUserId(), user3.getSupertokensUserId(), user4.getSupertokensUserId()}; + String[] userIds = new String[]{user1.getSupertokensUserId(), user2.getSupertokensUserId(), + user3.getSupertokensUserId(), user4.getSupertokensUserId()}; Collections.shuffle(Arrays.asList(userIds)); AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), userIds[0]).user; AuthRecipe.linkAccounts(process.getProcess(), userIds[1], primaryUser.getSupertokensUserId()); @@ -215,9 +219,9 @@ public void testLoginMethodsAreSortedByTime() throws Exception { assertTrue(result.isPrimaryUser); assertEquals(4, result.loginMethods.length); - assert(result.loginMethods[0].timeJoined <= result.loginMethods[1].timeJoined); - assert(result.loginMethods[1].timeJoined <= result.loginMethods[2].timeJoined); - assert(result.loginMethods[2].timeJoined <= result.loginMethods[3].timeJoined); + assert (result.loginMethods[0].timeJoined <= result.loginMethods[1].timeJoined); + assert (result.loginMethods[1].timeJoined <= result.loginMethods[2].timeJoined); + assert (result.loginMethods[2].timeJoined <= result.loginMethods[3].timeJoined); } process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/accountlinking/LinkAccountsTest.java b/src/test/java/io/supertokens/test/accountlinking/LinkAccountsTest.java index 71406feab..00c95536b 100644 --- a/src/test/java/io/supertokens/test/accountlinking/LinkAccountsTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/LinkAccountsTest.java @@ -93,7 +93,8 @@ public void linkAccountSuccess() throws Exception { String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user2.getSupertokensUserId()); assert (sessions.length == 1); - boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; + boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + user.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.main, user2.getSupertokensUserId()); @@ -145,7 +146,8 @@ public void linkAccountSuccessWithSameEmail() throws Exception { String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user2.getSupertokensUserId()); assert (sessions.length == 1); - boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; + boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + user.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.main, user2.getSupertokensUserId()); @@ -213,13 +215,15 @@ public void linkAccountSuccessEvenIfUsingRecipeUserIdThatIsLinkedToPrimaryUser() AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); - boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; + boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + user.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); AuthRecipeUserInfo user3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "password"); assert (!user3.isPrimaryUser); - wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user3.getSupertokensUserId(), user2.getSupertokensUserId()).wasAlreadyLinked; + wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user3.getSupertokensUserId(), + user2.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.main, user.getSupertokensUserId()); @@ -265,14 +269,16 @@ public void alreadyLinkAccountLinkAgain() throws Exception { AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); - boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; + boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + user.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); Session.createNewSession(process.main, user2.getSupertokensUserId(), new JsonObject(), new JsonObject()); String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user2.getSupertokensUserId()); assert (sessions.length == 1); - wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; + wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + user.getSupertokensUserId()).wasAlreadyLinked; assert (wasAlreadyLinked); // cause linkAccounts revokes sessions for the recipe user ID @@ -310,7 +316,8 @@ public void linkAccountFailureCauseRecipeUserIdLinkedWithAnotherPrimaryUser() th AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); - boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; + boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + user.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); AuthRecipeUserInfo user3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "password"); @@ -442,7 +449,8 @@ public void linkAccountFailureCauseAccountInfoAssociatedWithAPrimaryUser() throw AuthRecipe.createPrimaryUser(process.main, otherPrimaryUser.getSupertokensUserId()); try { - AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), otherPrimaryUser.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + otherPrimaryUser.getSupertokensUserId()); assert (false); } catch (AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException e) { assert (e.primaryUserId.equals(user.getSupertokensUserId())); @@ -476,8 +484,8 @@ public void linkAccountFailureCauseAccountInfoAssociatedWithAPrimaryUserEvenIfIn AuthRecipeUserInfo user = EmailPassword.signUp(new TenantIdentifier(null, null, "t1"), storage, - process.getProcess(), - "test@example.com", "password"); + process.getProcess(), + "test@example.com", "password"); assert (!user.isPrimaryUser); AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); @@ -497,7 +505,8 @@ public void linkAccountFailureCauseAccountInfoAssociatedWithAPrimaryUserEvenIfIn AuthRecipe.createPrimaryUser(process.main, otherPrimaryUser.getSupertokensUserId()); try { - AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), otherPrimaryUser.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + otherPrimaryUser.getSupertokensUserId()); assert (false); } catch (AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException e) { assert (e.primaryUserId.equals(user.getSupertokensUserId())); @@ -544,7 +553,8 @@ public void linkAccountSuccessAcrossTenants() throws Exception { AuthRecipeUserInfo user2 = signInUpResponse.user; assert (!user2.isPrimaryUser); - boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; + boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + user.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); AuthRecipeUserInfo refetchedUser1 = AuthRecipe.getUserById(process.main, user.getSupertokensUserId()); @@ -556,8 +566,10 @@ public void linkAccountSuccessAcrossTenants() throws Exception { assert refetchedUser1.tenantIds.contains("public"); assert refetchedUser1.getSupertokensUserId().equals(user.getSupertokensUserId()); assert refetchedUser1.isPrimaryUser; - assert refetchedUser1.loginMethods[0].getSupertokensUserId().equals(user.loginMethods[0].getSupertokensUserId()); - assert refetchedUser1.loginMethods[1].getSupertokensUserId().equals(user2.loginMethods[0].getSupertokensUserId()); + assert refetchedUser1.loginMethods[0].getSupertokensUserId() + .equals(user.loginMethods[0].getSupertokensUserId()); + assert refetchedUser1.loginMethods[1].getSupertokensUserId() + .equals(user2.loginMethods[0].getSupertokensUserId()); process.kill(); @@ -595,7 +607,8 @@ public void linkAccountSuccessWithPasswordlessEmailAndPhoneNumber() throws Excep Passwordless.updateUser(process.main, user2.getSupertokensUserId(), null, new Passwordless.FieldUpdate("1234")); user2 = AuthRecipe.getUserById(process.main, user2.getSupertokensUserId()); - boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; + boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + user.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.main, user2.getSupertokensUserId()); @@ -657,7 +670,8 @@ public void linkAccountMergesLastActiveTimes() throws Exception { assertEquals(ActiveUsers.countUsersActiveSince(process.main, 0), 1); assertEquals(ActiveUsers.countUsersActiveSince(process.main, secondUserTime), 1); - assertEquals(ActiveUsers.countUsersActiveSince(process.main, createPrimaryTime), 1); // 1 since we update user last active while linking + assertEquals(ActiveUsers.countUsersActiveSince(process.main, createPrimaryTime), + 1); // 1 since we update user last active while linking process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -708,7 +722,8 @@ public void linkAccountMergesLastActiveTimes_PrimaryFirst() throws Exception { assertEquals(ActiveUsers.countUsersActiveSince(process.main, 0), 1); assertEquals(ActiveUsers.countUsersActiveSince(process.main, secondUserTime), 1); - assertEquals(ActiveUsers.countUsersActiveSince(process.main, createPrimaryTime), 1); // 1 since we update user last active while linking + assertEquals(ActiveUsers.countUsersActiveSince(process.main, createPrimaryTime), + 1); // 1 since we update user last active while linking process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/accountlinking/MultitenantTest.java b/src/test/java/io/supertokens/test/accountlinking/MultitenantTest.java index 54241e317..3c42ed9ca 100644 --- a/src/test/java/io/supertokens/test/accountlinking/MultitenantTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/MultitenantTest.java @@ -416,7 +416,8 @@ public void testVariousCases() throws Exception { new LinkAccounts(t1, 0, 1), new CreateEmailPasswordUser(t3, "test1@example.com"), new MakePrimaryUser(t3, 2), - new AssociateUserToTenant(t2, 2).expect(new AnotherPrimaryUserWithEmailAlreadyExistsException("")), + new AssociateUserToTenant(t2, 2).expect( + new AnotherPrimaryUserWithEmailAlreadyExistsException("")), }), new TestCase(new TestCaseStep[]{ @@ -426,7 +427,8 @@ public void testVariousCases() throws Exception { new LinkAccounts(t1, 0, 1), new CreateEmailPasswordUser(t3, "test1@example.com"), new AssociateUserToTenant(t2, 2), - new MakePrimaryUser(t3, 2).expect(new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException("", "")), + new MakePrimaryUser(t3, 2).expect( + new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException("", "")), }), new TestCase(new TestCaseStep[]{ @@ -446,7 +448,8 @@ public void testVariousCases() throws Exception { new LinkAccounts(t1, 0, 1), new CreateEmailPasswordUser(t3, "test1@example.com"), new MakePrimaryUser(t3, 2), - new AssociateUserToTenant(t2, 2).expect(new AnotherPrimaryUserWithEmailAlreadyExistsException("")), + new AssociateUserToTenant(t2, 2).expect( + new AnotherPrimaryUserWithEmailAlreadyExistsException("")), }), new TestCase(new TestCaseStep[]{ @@ -456,7 +459,8 @@ public void testVariousCases() throws Exception { new LinkAccounts(t1, 0, 1), new CreateEmailPasswordUser(t3, "test1@example.com"), new AssociateUserToTenant(t2, 2), - new MakePrimaryUser(t3, 2).expect(new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException("", "")), + new MakePrimaryUser(t3, 2).expect( + new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException("", "")), }), new TestCase(new TestCaseStep[]{ @@ -476,7 +480,8 @@ public void testVariousCases() throws Exception { new LinkAccounts(t1, 0, 1), new CreateEmailPasswordUser(t3, "test1@example.com"), new MakePrimaryUser(t3, 2), - new AssociateUserToTenant(t2, 2).expect(new AnotherPrimaryUserWithEmailAlreadyExistsException("")), + new AssociateUserToTenant(t2, 2).expect( + new AnotherPrimaryUserWithEmailAlreadyExistsException("")), }), new TestCase(new TestCaseStep[]{ @@ -486,7 +491,8 @@ public void testVariousCases() throws Exception { new LinkAccounts(t1, 0, 1), new CreateEmailPasswordUser(t3, "test1@example.com"), new AssociateUserToTenant(t2, 2), - new MakePrimaryUser(t3, 2).expect(new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException("", "")), + new MakePrimaryUser(t3, 2).expect( + new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException("", "")), }), new TestCase(new TestCaseStep[]{ @@ -505,7 +511,8 @@ public void testVariousCases() throws Exception { new MakePrimaryUser(t1, 0), new LinkAccounts(t1, 0, 2), new MakePrimaryUser(t2, 1), - new UpdatePlessUserEmail(t1, 0, "test3@example.com").expect(new EmailChangeNotAllowedException()), + new UpdatePlessUserEmail(t1, 0, "test3@example.com").expect( + new EmailChangeNotAllowedException()), }), new TestCase(new TestCaseStep[]{ @@ -515,7 +522,8 @@ public void testVariousCases() throws Exception { new MakePrimaryUser(t1, 0), new LinkAccounts(t1, 0, 2), new MakePrimaryUser(t2, 1), - new UpdatePlessUserEmail(t1, 1, "test1@example.com").expect(new EmailChangeNotAllowedException()), + new UpdatePlessUserEmail(t1, 1, "test1@example.com").expect( + new EmailChangeNotAllowedException()), }), new TestCase(new TestCaseStep[]{ @@ -545,7 +553,8 @@ public void testVariousCases() throws Exception { new MakePrimaryUser(t1, 0), new LinkAccounts(t1, 0, 2), new MakePrimaryUser(t2, 1), - new UpdateEmailPasswordUserEmail(t1, 0, "test3@example.com").expect(new EmailChangeNotAllowedException()), + new UpdateEmailPasswordUserEmail(t1, 0, "test3@example.com").expect( + new EmailChangeNotAllowedException()), }), new TestCase(new TestCaseStep[]{ @@ -555,7 +564,8 @@ public void testVariousCases() throws Exception { new MakePrimaryUser(t1, 0), new LinkAccounts(t1, 0, 2), new MakePrimaryUser(t2, 1), - new UpdateEmailPasswordUserEmail(t1, 1, "test1@example.com").expect(new EmailChangeNotAllowedException()), + new UpdateEmailPasswordUserEmail(t1, 1, "test1@example.com").expect( + new EmailChangeNotAllowedException()), }), new TestCase(new TestCaseStep[]{ @@ -575,7 +585,8 @@ public void testVariousCases() throws Exception { new LinkAccounts(t1, 0, 1), new CreateEmailPasswordUser(t3, "test1@example.com"), new MakePrimaryUser(t3, 2), - new AssociateUserToTenant(t2, 2).expect(new AnotherPrimaryUserWithEmailAlreadyExistsException("")), + new AssociateUserToTenant(t2, 2).expect( + new AnotherPrimaryUserWithEmailAlreadyExistsException("")), }), new TestCase(new TestCaseStep[]{ @@ -585,7 +596,8 @@ public void testVariousCases() throws Exception { new LinkAccounts(t1, 0, 1), new CreateEmailPasswordUser(t3, "test1@example.com"), new AssociateUserToTenant(t2, 2), - new MakePrimaryUser(t3, 2).expect(new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException("", "")), + new MakePrimaryUser(t3, 2).expect( + new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException("", "")), }), new TestCase(new TestCaseStep[]{ @@ -605,7 +617,8 @@ public void testVariousCases() throws Exception { new LinkAccounts(t1, 0, 1), new CreateEmailPasswordUser(t3, "test1@example.com"), new MakePrimaryUser(t3, 2), - new AssociateUserToTenant(t2, 2).expect(new AnotherPrimaryUserWithEmailAlreadyExistsException("")), + new AssociateUserToTenant(t2, 2).expect( + new AnotherPrimaryUserWithEmailAlreadyExistsException("")), }), new TestCase(new TestCaseStep[]{ @@ -615,7 +628,8 @@ public void testVariousCases() throws Exception { new LinkAccounts(t1, 0, 1), new CreateEmailPasswordUser(t3, "test1@example.com"), new AssociateUserToTenant(t2, 2), - new MakePrimaryUser(t3, 2).expect(new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException("", "")), + new MakePrimaryUser(t3, 2).expect( + new AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException("", "")), }), new TestCase(new TestCaseStep[]{ @@ -634,7 +648,8 @@ public void testVariousCases() throws Exception { new MakePrimaryUser(t1, 0), new LinkAccounts(t1, 0, 2), new MakePrimaryUser(t2, 1), - new CreateThirdPartyUser(t1, "google", "googleid1", "test3@example.com").expect(new EmailChangeNotAllowedException()), + new CreateThirdPartyUser(t1, "google", "googleid1", "test3@example.com").expect( + new EmailChangeNotAllowedException()), }), new TestCase(new TestCaseStep[]{ @@ -644,7 +659,8 @@ public void testVariousCases() throws Exception { new MakePrimaryUser(t1, 0), new LinkAccounts(t1, 0, 2), new MakePrimaryUser(t2, 1), - new CreateThirdPartyUser(t1, "google", "googleid3", "test1@example.com").expect(new EmailChangeNotAllowedException()), + new CreateThirdPartyUser(t1, "google", "googleid3", "test1@example.com").expect( + new EmailChangeNotAllowedException()), }), new TestCase(new TestCaseStep[]{ @@ -655,7 +671,8 @@ public void testVariousCases() throws Exception { new LinkAccounts(t1, 0, 1), new MakePrimaryUser(t3, 2), new AssociateUserToTenant(t1, 2).expect(new DuplicatePhoneNumberException()), - new AssociateUserToTenant(t2, 2).expect(new AnotherPrimaryUserWithPhoneNumberAlreadyExistsException("")), + new AssociateUserToTenant(t2, 2).expect( + new AnotherPrimaryUserWithPhoneNumberAlreadyExistsException("")), }), new TestCase(new TestCaseStep[]{ @@ -666,7 +683,8 @@ public void testVariousCases() throws Exception { new LinkAccounts(t1, 0, 1), new MakePrimaryUser(t3, 2), new AssociateUserToTenant(t1, 2).expect(new DuplicateThirdPartyUserException()), - new AssociateUserToTenant(t2, 2).expect(new AnotherPrimaryUserWithThirdPartyInfoAlreadyExistsException("")), + new AssociateUserToTenant(t2, 2).expect( + new AnotherPrimaryUserWithThirdPartyInfoAlreadyExistsException("")), }), new TestCase(new TestCaseStep[]{ new CreateThirdPartyUser(t1, "google", "googleid1", "test1@example.com"), @@ -675,16 +693,18 @@ public void testVariousCases() throws Exception { new MakePrimaryUser(t1, 0), new LinkAccounts(t1, 0, 1), new MakePrimaryUser(t1, 2), - new CreateThirdPartyUser(t1, "google", "googleid1", "test3@example.com").expect(new EmailChangeNotAllowedException()), - new CreateThirdPartyUser(t1, "google", "googleid3", "test1@example.com").expect(new EmailChangeNotAllowedException()), + new CreateThirdPartyUser(t1, "google", "googleid1", "test3@example.com").expect( + new EmailChangeNotAllowedException()), + new CreateThirdPartyUser(t1, "google", "googleid3", "test1@example.com").expect( + new EmailChangeNotAllowedException()), }), new TestCase(new TestCaseStep[]{ - new CreateEmailPasswordUser(t1, "test@example.com"), - new CreateEmailPasswordUser(t1, "test2@example.com"), - new MakePrimaryUser(t1, 0), - new LinkAccounts(t1, 0, 1), - new UnlinkAccount(t1, 0), - new AssociateUserToTenant(t2, 0).expect(new UnknownUserIdException()), + new CreateEmailPasswordUser(t1, "test@example.com"), + new CreateEmailPasswordUser(t1, "test2@example.com"), + new MakePrimaryUser(t1, 0), + new LinkAccounts(t1, 0, 1), + new UnlinkAccount(t1, 0), + new AssociateUserToTenant(t2, 0).expect(new UnknownUserIdException()), }), new TestCase(new TestCaseStep[]{ @@ -733,7 +753,8 @@ public void execute(Main main) throws Exception { new MakePrimaryUser(t1, 1), new AssociateUserToTenant(t1, 0), new AssociateUserToTenant(t1, 1).expect(new DuplicateEmailException()), - new LinkAccounts(t1, 0, 1).expect(new RecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException(null, "")), + new LinkAccounts(t1, 0, 1).expect( + new RecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException(null, "")), }), new TestCase(new TestCaseStep[]{ @@ -803,14 +824,16 @@ public void execute(Main main) throws Exception { new CreatePlessUserWithEmail(t1, "test2@example.com"), new MakePrimaryUser(t1, 0), new MakePrimaryUser(t1, 1), - new UpdatePlessUserEmail(t1, 1, "test1@example.com").expect(new EmailChangeNotAllowedException()), + new UpdatePlessUserEmail(t1, 1, "test1@example.com").expect( + new EmailChangeNotAllowedException()), }), new TestCase(new TestCaseStep[]{ new CreatePlessUserWithEmail(t1, "test1@example.com"), new CreateEmailPasswordUser(t1, "test2@example.com"), new MakePrimaryUser(t1, 0), new MakePrimaryUser(t1, 1), - new UpdateEmailPasswordUserEmail(t1, 1, "test1@example.com").expect(new EmailChangeNotAllowedException()), + new UpdateEmailPasswordUserEmail(t1, 1, "test1@example.com").expect( + new EmailChangeNotAllowedException()), }), new TestCase(new TestCaseStep[]{ @@ -830,7 +853,8 @@ public void execute(Main main) throws Exception { new CreateThirdPartyUser(t1, "google", "googleid", "test2@example.com"), new MakePrimaryUser(t1, 0), new MakePrimaryUser(t1, 1), - new CreateThirdPartyUser(t1, "google", "googleid", "test1@example.com").expect(new EmailChangeNotAllowedException()), + new CreateThirdPartyUser(t1, "google", "googleid", "test1@example.com").expect( + new EmailChangeNotAllowedException()), }), new TestCase(new TestCaseStep[]{ new CreateEmailPasswordUser(t1, "test1@example.com"), @@ -839,7 +863,8 @@ public void execute(Main main) throws Exception { new LinkAccounts(t1, 0, 1), new CreateThirdPartyUser(t2, "google", "googleid", "test2@example.com"), new MakePrimaryUser(t2, 2), - new CreateThirdPartyUser(t2, "google", "googleid", "test1@example.com").expect(new EmailChangeNotAllowedException()), + new CreateThirdPartyUser(t2, "google", "googleid", "test1@example.com").expect( + new EmailChangeNotAllowedException()), }), }; @@ -985,7 +1010,8 @@ private static class CreateThirdPartyUser extends TestCaseStep { String thirdPartyUserId; String email; - public CreateThirdPartyUser(TenantIdentifier tenantIdentifier, String thirdPartyId, String thirdPartyUserId, String email) { + public CreateThirdPartyUser(TenantIdentifier tenantIdentifier, String thirdPartyId, String thirdPartyUserId, + String email) { this.tenantIdentifier = tenantIdentifier; this.thirdPartyId = thirdPartyId; this.thirdPartyUserId = thirdPartyUserId; @@ -1034,7 +1060,8 @@ public LinkAccounts(TenantIdentifier tenantIdentifier, int primaryUserIndex, int public void execute(Main main) throws Exception { Storage storage = (StorageLayer.getStorage(tenantIdentifier, main)); AuthRecipe.linkAccounts(main, tenantIdentifier.toAppIdentifier(), storage, - TestCase.users.get(recipeUserIndex).getSupertokensUserId(), TestCase.users.get(primaryUserIndex).getSupertokensUserId()); + TestCase.users.get(recipeUserIndex).getSupertokensUserId(), + TestCase.users.get(primaryUserIndex).getSupertokensUserId()); } } @@ -1108,7 +1135,8 @@ public UpdatePlessUserPhone(TenantIdentifier tenantIdentifier, int userIndex, St public void execute(Main main) throws Exception { Storage storage = (StorageLayer.getStorage(tenantIdentifier, main)); Passwordless.updateUser(tenantIdentifier.toAppIdentifier(), storage, - TestCase.users.get(userIndex).getSupertokensUserId(), null, new Passwordless.FieldUpdate(phoneNumber)); + TestCase.users.get(userIndex).getSupertokensUserId(), null, + new Passwordless.FieldUpdate(phoneNumber)); } } diff --git a/src/test/java/io/supertokens/test/accountlinking/SessionTests.java b/src/test/java/io/supertokens/test/accountlinking/SessionTests.java index dd78ceef1..ac12a8c9a 100644 --- a/src/test/java/io/supertokens/test/accountlinking/SessionTests.java +++ b/src/test/java/io/supertokens/test/accountlinking/SessionTests.java @@ -160,7 +160,7 @@ private void createTenants(Main main) t3 = new TenantIdentifier(null, "a1", "t2"); t4 = new TenantIdentifier(null, "a1", "t3"); } - + @Test public void testCreateSessionWithRecipeUserIdReturnsSessionWithPrimaryUserId() throws Exception { String[] args = {"../"}; @@ -212,7 +212,8 @@ public void testSessionIsRemovedWhileLinking() throws Exception { SessionInformationHolder session1 = Session.createNewSession(process.getProcess(), user1.getSupertokensUserId(), new JsonObject(), new JsonObject()); - SessionInformationHolder session2 = Session.createNewSession(process.getProcess(), "extid2", new JsonObject(), new JsonObject()); + SessionInformationHolder session2 = Session.createNewSession(process.getProcess(), "extid2", new JsonObject(), + new JsonObject()); AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user1.getSupertokensUserId()); @@ -288,7 +289,7 @@ public void testSessionBehaviourWhenUserBelongsTo2TenantsAndThenLinkedToSomeOthe AuthRecipeUserInfo user1 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test@example.com", "password"); - AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test1@example.com", + AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test1@example.com", "password"); AuthRecipe.createPrimaryUser(process.getProcess(), t1.toAppIdentifier(), @@ -332,9 +333,9 @@ public void testSessionBehaviourWhenUserBelongsTo2TenantsAndThenLinkedToSomeOthe Storage t1Storage = (StorageLayer.getStorage(t1, process.getProcess())); Storage t2Storage = (StorageLayer.getStorage(t2, process.getProcess())); - AuthRecipeUserInfo user1 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test@example.com", + AuthRecipeUserInfo user1 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test@example.com", "password"); - AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test1@example.com", + AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test1@example.com", "password"); AuthRecipe.createPrimaryUser(process.getProcess(), t1.toAppIdentifier(), @@ -378,9 +379,9 @@ public void testSessionBehaviourWhenUserBelongsTo2TenantsAndThenLinkedToSomeOthe Storage t1Storage = (StorageLayer.getStorage(t1, process.getProcess())); Storage t2Storage = (StorageLayer.getStorage(t2, process.getProcess())); - AuthRecipeUserInfo user1 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test@example.com", + AuthRecipeUserInfo user1 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test@example.com", "password"); - AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test1@example.com", + AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test1@example.com", "password"); AuthRecipe.createPrimaryUser(process.getProcess(), t1.toAppIdentifier(), t1Storage, @@ -421,7 +422,7 @@ public void testCreateSessionUsesPrimaryUserIdEvenWhenTheUserIsNotInThatTenant() AuthRecipeUserInfo user1 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test@example.com", "password"); - AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test1@example.com", + AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test1@example.com", "password"); AuthRecipe.createPrimaryUser(process.getProcess(), t1.toAppIdentifier(), t1Storage, @@ -483,12 +484,14 @@ public void testGetSessionForUserWithAndWithoutIncludingAllLinkedAccounts() thro } { - String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(TenantIdentifier.BASE_TENANT, baseTenant, user1.getSupertokensUserId(), + String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(TenantIdentifier.BASE_TENANT, baseTenant, + user1.getSupertokensUserId(), true); assertEquals(2, sessions.length); } { - String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(TenantIdentifier.BASE_TENANT, baseTenant, user2.getSupertokensUserId(), + String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(TenantIdentifier.BASE_TENANT, baseTenant, + user2.getSupertokensUserId(), true); assertEquals(2, sessions.length); } @@ -528,7 +531,8 @@ public void testRevokeSessionsForUserWithAndWithoutIncludingAllLinkedAccounts() Storage baseTenant = ( StorageLayer.getBaseStorage(process.getProcess())); - Session.revokeAllSessionsForUser(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, user1.getSupertokensUserId(), true); + Session.revokeAllSessionsForUser(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + user1.getSupertokensUserId(), true); try { Session.getSession(process.getProcess(), session1.session.handle); @@ -554,7 +558,8 @@ public void testRevokeSessionsForUserWithAndWithoutIncludingAllLinkedAccounts() Storage baseTenant = ( StorageLayer.getBaseStorage(process.getProcess())); - Session.revokeAllSessionsForUser(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, user2.getSupertokensUserId(), true); + Session.revokeAllSessionsForUser(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + user2.getSupertokensUserId(), true); try { Session.getSession(process.getProcess(), session1.session.handle); @@ -580,7 +585,8 @@ public void testRevokeSessionsForUserWithAndWithoutIncludingAllLinkedAccounts() Storage baseTenant = ( StorageLayer.getBaseStorage(process.getProcess())); - Session.revokeAllSessionsForUser(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, user1.getSupertokensUserId(), false); + Session.revokeAllSessionsForUser(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + user1.getSupertokensUserId(), false); try { Session.getSession(process.getProcess(), session1.session.handle); @@ -602,7 +608,8 @@ public void testRevokeSessionsForUserWithAndWithoutIncludingAllLinkedAccounts() Storage baseTenant = ( StorageLayer.getBaseStorage(process.getProcess())); - Session.revokeAllSessionsForUser(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, user2.getSupertokensUserId(), false); + Session.revokeAllSessionsForUser(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + user2.getSupertokensUserId(), false); Session.getSession(process.getProcess(), session1.session.handle); @@ -640,10 +647,14 @@ public void testCreateSessionWithUserIdMappedForRecipeUser() throws Exception { UserIdMapping.createUserIdMapping(process.getProcess(), user1.getSupertokensUserId(), "extid1", null, false); UserIdMapping.createUserIdMapping(process.getProcess(), user2.getSupertokensUserId(), "extid2", null, false); - SessionInformationHolder session1 = Session.createNewSession(process.getProcess(), user1.getSupertokensUserId(), new JsonObject(), new JsonObject()); - SessionInformationHolder session2 = Session.createNewSession(process.getProcess(), user2.getSupertokensUserId(), new JsonObject(), new JsonObject()); - SessionInformationHolder session3 = Session.createNewSession(process.getProcess(), "extid1", new JsonObject(), new JsonObject()); - SessionInformationHolder session4 = Session.createNewSession(process.getProcess(), "extid2", new JsonObject(), new JsonObject()); + SessionInformationHolder session1 = Session.createNewSession(process.getProcess(), user1.getSupertokensUserId(), + new JsonObject(), new JsonObject()); + SessionInformationHolder session2 = Session.createNewSession(process.getProcess(), user2.getSupertokensUserId(), + new JsonObject(), new JsonObject()); + SessionInformationHolder session3 = Session.createNewSession(process.getProcess(), "extid1", new JsonObject(), + new JsonObject()); + SessionInformationHolder session4 = Session.createNewSession(process.getProcess(), "extid2", new JsonObject(), + new JsonObject()); assertEquals("extid1", session1.session.userId); assertEquals("extid1", session1.session.recipeUserId); diff --git a/src/test/java/io/supertokens/test/accountlinking/TestGetUserSpeed.java b/src/test/java/io/supertokens/test/accountlinking/TestGetUserSpeed.java index 237e26ac1..071535742 100644 --- a/src/test/java/io/supertokens/test/accountlinking/TestGetUserSpeed.java +++ b/src/test/java/io/supertokens/test/accountlinking/TestGetUserSpeed.java @@ -60,7 +60,8 @@ public void beforeEach() { } public void testUserCreationLinkingAndGetByIdSpeedsCommon(TestingProcessManager.TestingProcess process, - long createTime, long linkingTime, long getTime) throws Exception { + long createTime, long linkingTime, long getTime) + throws Exception { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; diff --git a/src/test/java/io/supertokens/test/accountlinking/UpdateUserTest.java b/src/test/java/io/supertokens/test/accountlinking/UpdateUserTest.java index 899ca6a6a..cc66157b6 100644 --- a/src/test/java/io/supertokens/test/accountlinking/UpdateUserTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/UpdateUserTest.java @@ -65,13 +65,15 @@ public void testThatUpdateEmailFailsWhenPassedWithNonEmailPasswordRecipeUserId() } AuthRecipeUserInfo user1 = EmailPassword.signUp(process.getProcess(), "test1@example.com", "password"); - AuthRecipeUserInfo user2 = ThirdParty.signInUp(process.getProcess(), "google", "googleid1", "test2@example.com").user; + AuthRecipeUserInfo user2 = ThirdParty.signInUp(process.getProcess(), "google", "googleid1", + "test2@example.com").user; AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user1.getSupertokensUserId()); try { - EmailPassword.updateUsersEmailOrPassword(process.getProcess(), user2.getSupertokensUserId(), "test3@example.com", null); + EmailPassword.updateUsersEmailOrPassword(process.getProcess(), user2.getSupertokensUserId(), + "test3@example.com", null); fail(); } catch (UnknownUserIdException e) { // ignore diff --git a/src/test/java/io/supertokens/test/accountlinking/UserIdMappingTest.java b/src/test/java/io/supertokens/test/accountlinking/UserIdMappingTest.java index d846e0728..78f4c79ac 100644 --- a/src/test/java/io/supertokens/test/accountlinking/UserIdMappingTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/UserIdMappingTest.java @@ -75,7 +75,8 @@ public void testUserIdMappingWithUnlinkedAccountUserid() throws Exception { AuthRecipe.unlinkAccounts(process.getProcess(), user1.getSupertokensUserId()); try { - UserIdMapping.createUserIdMapping(process.getProcess(), user2.getSupertokensUserId(), user1.getSupertokensUserId(), null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user2.getSupertokensUserId(), + user1.getSupertokensUserId(), null, false); fail(); // should not be allowed } catch (ServletException e) { assertTrue(e.getCause() instanceof WebserverAPI.BadRequestException); @@ -105,10 +106,12 @@ public void testUserIdMappingWithDeletedUser() throws Exception { AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user1.getSupertokensUserId()); - AuthRecipe.deleteUser(process.getProcess(), user1.getSupertokensUserId(), false); // should not delete the user from app_id_to_user_id table + AuthRecipe.deleteUser(process.getProcess(), user1.getSupertokensUserId(), + false); // should not delete the user from app_id_to_user_id table try { - UserIdMapping.createUserIdMapping(process.getProcess(), user2.getSupertokensUserId(), user1.getSupertokensUserId(), null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user2.getSupertokensUserId(), + user1.getSupertokensUserId(), null, false); fail(); // should not be allowed } catch (ServletException e) { assertTrue(e.getCause() instanceof WebserverAPI.BadRequestException); diff --git a/src/test/java/io/supertokens/test/accountlinking/UserSearchTest.java b/src/test/java/io/supertokens/test/accountlinking/UserSearchTest.java index be1508ba3..acd06e505 100644 --- a/src/test/java/io/supertokens/test/accountlinking/UserSearchTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/UserSearchTest.java @@ -76,12 +76,15 @@ public void testUserSearch() throws Exception { Passwordless.CreateCodeResponse code1 = Passwordless.createCode(process.getProcess(), "test3@example.com", null, null, null); - AuthRecipeUserInfo user3 = Passwordless.consumeCode(process.getProcess(), code1.deviceId, code1.deviceIdHash, code1.userInputCode, null).user; + AuthRecipeUserInfo user3 = Passwordless.consumeCode(process.getProcess(), code1.deviceId, code1.deviceIdHash, + code1.userInputCode, null).user; Passwordless.CreateCodeResponse code2 = Passwordless.createCode(process.getProcess(), null, "+919876543210", null, null); - AuthRecipeUserInfo user4 = Passwordless.consumeCode(process.getProcess(), code2.deviceId, code2.deviceIdHash, code2.userInputCode, null).user; + AuthRecipeUserInfo user4 = Passwordless.consumeCode(process.getProcess(), code2.deviceId, code2.deviceIdHash, + code2.userInputCode, null).user; - AuthRecipeUserInfo user5 = ThirdParty.signInUp(process.getProcess(), "google", "googleid", "test4@example.com").user; + AuthRecipeUserInfo user5 = ThirdParty.signInUp(process.getProcess(), "google", "googleid", + "test4@example.com").user; AuthRecipe.createPrimaryUser(process.getProcess(), user5.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user1.getSupertokensUserId(), user5.getSupertokensUserId()); diff --git a/src/test/java/io/supertokens/test/accountlinking/api/ActiveUserTest.java b/src/test/java/io/supertokens/test/accountlinking/api/ActiveUserTest.java index 2bc7eb759..122eb8b3e 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/ActiveUserTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/ActiveUserTest.java @@ -113,7 +113,8 @@ public void testActiveUserIsRemovedAfterLinkingAccounts() throws Exception { } AuthRecipeUserInfo user1 = createEmailPasswordUser(process.getProcess(), "test@example.com", "password"); - AuthRecipeUserInfo user2 = createThirdPartyUser(process.getProcess(), "google", "google-user", "test@example.com"); + AuthRecipeUserInfo user2 = createThirdPartyUser(process.getProcess(), "google", "google-user", + "test@example.com"); { // Update active user diff --git a/src/test/java/io/supertokens/test/accountlinking/api/CanCreatePrimaryUserAPITest.java b/src/test/java/io/supertokens/test/accountlinking/api/CanCreatePrimaryUserAPITest.java index bf2d42429..c682cb649 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/CanCreatePrimaryUserAPITest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/CanCreatePrimaryUserAPITest.java @@ -217,7 +217,8 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", @@ -262,7 +263,8 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccount() throws Ex "pass1234"); AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + emailPasswordUser1.getSupertokensUserId()); { Map params = new HashMap<>(); @@ -302,7 +304,8 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU "pass1234"); UserIdMapping.createUserIdMapping(process.main, emailPasswordUser.getSupertokensUserId(), "r1", null, false); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", @@ -348,7 +351,8 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa "pass1234"); AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + emailPasswordUser1.getSupertokensUserId()); { Map params = new HashMap<>(); diff --git a/src/test/java/io/supertokens/test/accountlinking/api/CanLinkAccountsAPITest.java b/src/test/java/io/supertokens/test/accountlinking/api/CanLinkAccountsAPITest.java index ab155e481..957dce5f6 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/CanLinkAccountsAPITest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/CanLinkAccountsAPITest.java @@ -270,7 +270,8 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", @@ -321,18 +322,21 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser "pass1234"); UserIdMapping.createUserIdMapping(process.main, emailPasswordUser.getSupertokensUserId(), "e1", null, false); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", "test2@example.com"); - UserIdMapping.createUserIdMapping(process.main, signInUpResponse.user.getSupertokensUserId(), "e2", null, false); + UserIdMapping.createUserIdMapping(process.main, signInUpResponse.user.getSupertokensUserId(), "e2", null, + false); AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); ThirdParty.SignInUpResponse signInUpResponse2 = ThirdParty.signInUp(process.main, "fb", "user-fb", "test@example.com"); - UserIdMapping.createUserIdMapping(process.main, signInUpResponse2.user.getSupertokensUserId(), "e3", null, false); + UserIdMapping.createUserIdMapping(process.main, signInUpResponse2.user.getSupertokensUserId(), "e3", null, + false); { @@ -375,7 +379,8 @@ public void linkingUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exceptio "pass1234"); AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); @@ -424,7 +429,8 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa UserIdMapping.createUserIdMapping(process.main, emailPasswordUser2.getSupertokensUserId(), "r2", null, false); AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); diff --git a/src/test/java/io/supertokens/test/accountlinking/api/CreatePrimaryUserAPITest.java b/src/test/java/io/supertokens/test/accountlinking/api/CreatePrimaryUserAPITest.java index c1edbf517..8042faf6c 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/CreatePrimaryUserAPITest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/CreatePrimaryUserAPITest.java @@ -273,7 +273,8 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", @@ -318,7 +319,8 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccount() throws Ex "pass1234"); AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + emailPasswordUser1.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -358,7 +360,8 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU "pass1234"); UserIdMapping.createUserIdMapping(process.main, emailPasswordUser.getSupertokensUserId(), "r1", null, false); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", @@ -404,7 +407,8 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa "pass1234"); AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + emailPasswordUser1.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -498,7 +502,7 @@ public void createPrimaryUserInTenantWithAnotherStorage() throws Exception { AuthRecipe.createPrimaryUser(process.main, tenantIdentifier.toAppIdentifier(), (StorageLayer.getStorage(tenantIdentifier, - process.main)), + process.main)), user.getSupertokensUserId()); { diff --git a/src/test/java/io/supertokens/test/accountlinking/api/DeleteUserTest.java b/src/test/java/io/supertokens/test/accountlinking/api/DeleteUserTest.java index d59885a47..1431e241c 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/DeleteUserTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/DeleteUserTest.java @@ -97,7 +97,8 @@ public void deleteLinkedUserWithoutRemovingAllUsers() throws Exception { AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + r2.getSupertokensUserId()).wasAlreadyLinked); deleteUserAPICall(process.main, r1.getSupertokensUserId(), false); @@ -134,7 +135,8 @@ public void deleteLinkedPrimaryUserWithoutRemovingAllUsers() throws Exception { AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + r2.getSupertokensUserId()).wasAlreadyLinked); deleteUserAPICall(process.main, r2.getSupertokensUserId(), false); @@ -172,7 +174,8 @@ public void deleteLinkedPrimaryUserRemovingAllUsers() throws Exception { AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + r2.getSupertokensUserId()).wasAlreadyLinked); deleteUserAPICall(process.main, r2.getSupertokensUserId()); @@ -207,7 +210,8 @@ public void deleteLinkedPrimaryUserRemovingAllUsers2() throws Exception { AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + r2.getSupertokensUserId()).wasAlreadyLinked); deleteUserAPICall(process.main, r1.getSupertokensUserId()); @@ -252,7 +256,8 @@ public void deleteUserTestWithUserIdMapping1() throws Exception { AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + r2.getSupertokensUserId()).wasAlreadyLinked); deleteUserAPICall(process.main, r1.getSupertokensUserId(), false); @@ -266,8 +271,10 @@ public void deleteUserTestWithUserIdMapping1() throws Exception { assertEquals(UserMetadata.getUserMetadata(process.main, r1.getSupertokensUserId()), new JsonObject()); assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), metadata); assertEquals(UserMetadata.getUserMetadata(process.main, r2.getSupertokensUserId()), new JsonObject()); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); + assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + null); + assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); process.kill(); @@ -304,7 +311,8 @@ public void deleteUserTestWithUserIdMapping2() throws Exception { AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + r2.getSupertokensUserId()).wasAlreadyLinked); deleteUserAPICall(process.main, r1.getSupertokensUserId()); @@ -318,8 +326,10 @@ public void deleteUserTestWithUserIdMapping2() throws Exception { assertEquals(UserMetadata.getUserMetadata(process.main, r1.getSupertokensUserId()), new JsonObject()); assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), new JsonObject()); assertEquals(UserMetadata.getUserMetadata(process.main, r2.getSupertokensUserId()), new JsonObject()); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); + assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); + assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); process.kill(); @@ -362,8 +372,10 @@ public void deleteUserTestWithUserIdMapping3() throws Exception { AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - assert (!AuthRecipe.linkAccounts(process.main, r3.getSupertokensUserId(), r1.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + r2.getSupertokensUserId()).wasAlreadyLinked); + assert (!AuthRecipe.linkAccounts(process.main, r3.getSupertokensUserId(), + r1.getSupertokensUserId()).wasAlreadyLinked); deleteUserAPICall(process.main, r1.getSupertokensUserId(), false); @@ -379,9 +391,12 @@ public void deleteUserTestWithUserIdMapping3() throws Exception { assert (userR2.loginMethods.length == 2); assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), metadata); assertEquals(UserMetadata.getUserMetadata(process.main, "e3"), metadata); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); + assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + null); + assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + null); + assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); } deleteUserAPICall(process.main, r2.getSupertokensUserId(), false); @@ -393,9 +408,12 @@ public void deleteUserTestWithUserIdMapping3() throws Exception { assert (userR2.loginMethods.length == 1); assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), metadata); assertEquals(UserMetadata.getUserMetadata(process.main, "e3"), metadata); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); + assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + null); + assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + null); + assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); } deleteUserAPICall(process.main, r3.getSupertokensUserId(), false); @@ -406,9 +424,12 @@ public void deleteUserTestWithUserIdMapping3() throws Exception { assert (userR2 == null && userR3 == null); assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), new JsonObject()); assertEquals(UserMetadata.getUserMetadata(process.main, "e3"), new JsonObject()); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); - assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); + assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); + assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); + assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + null); } process.kill(); diff --git a/src/test/java/io/supertokens/test/accountlinking/api/EmailVerificationTest.java b/src/test/java/io/supertokens/test/accountlinking/api/EmailVerificationTest.java index d3aa7779c..f75ebce76 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/EmailVerificationTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/EmailVerificationTest.java @@ -72,7 +72,8 @@ public void testEmailVerificationWithUserIdMapping() throws Exception { AuthRecipeUserInfo user1 = EmailPassword.signUp(process.getProcess(), "test1@example.com", "password"); UserIdMapping.createUserIdMapping(process.getProcess(), user1.getSupertokensUserId(), "euserid1", null, false); - String token = EmailVerification.generateEmailVerificationToken(process.getProcess(), "euserid1", "test1@example.com"); + String token = EmailVerification.generateEmailVerificationToken(process.getProcess(), "euserid1", + "test1@example.com"); EmailVerification.verifyEmail(process.getProcess(), token); AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "password"); @@ -88,8 +89,10 @@ public void testEmailVerificationWithUserIdMapping() throws Exception { "http://localhost:3567/user/id", params, 1000, 1000, null, WebserverAPI.getLatestCDIVersion().get(), ""); JsonObject user = response.get("user").getAsJsonObject(); - assertTrue(user.get("loginMethods").getAsJsonArray().get(0).getAsJsonObject().get("verified").getAsBoolean()); - assertFalse(user.get("loginMethods").getAsJsonArray().get(1).getAsJsonObject().get("verified").getAsBoolean()); + assertTrue( + user.get("loginMethods").getAsJsonArray().get(0).getAsJsonObject().get("verified").getAsBoolean()); + assertFalse( + user.get("loginMethods").getAsJsonArray().get(1).getAsJsonObject().get("verified").getAsBoolean()); } process.kill(); diff --git a/src/test/java/io/supertokens/test/accountlinking/api/GetUserByAccountInfoTest.java b/src/test/java/io/supertokens/test/accountlinking/api/GetUserByAccountInfoTest.java index e86763772..8bcceca3c 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/GetUserByAccountInfoTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/GetUserByAccountInfoTest.java @@ -107,7 +107,8 @@ private JsonObject getUserById(Main main, String userId) throws Exception { return response.get("user").getAsJsonObject(); } - private JsonArray getUsersByAccountInfo(Main main, boolean doUnionOfAccountInfo, String email, String phoneNumber, String thirdPartyId, String thirdPartyUserId) throws Exception { + private JsonArray getUsersByAccountInfo(Main main, boolean doUnionOfAccountInfo, String email, String phoneNumber, + String thirdPartyId, String thirdPartyUserId) throws Exception { Map params = new HashMap<>(); params.put("doUnionOfAccountInfo", String.valueOf(doUnionOfAccountInfo)); if (email != null) { @@ -153,19 +154,31 @@ public void testListUsersByAccountInfoForUnlinkedAccounts() throws Exception { JsonObject user4json = getUserById(process.getProcess(), user4.getSupertokensUserId()); // test for result - assertEquals(user1json, getUsersByAccountInfo(process.getProcess(), false, "test1@example.com", null, null, null).get(0)); - assertEquals(user2json, getUsersByAccountInfo(process.getProcess(), false, null, null, "google", "userid1").get(0)); - assertEquals(user2json, getUsersByAccountInfo(process.getProcess(), false, "test2@example.com", null, "google", "userid1").get(0)); - assertEquals(user3json, getUsersByAccountInfo(process.getProcess(), false, "test3@example.com", null, null, null).get(0)); - assertEquals(user4json, getUsersByAccountInfo(process.getProcess(), false, null, "+919876543210", null, null).get(0)); + assertEquals(user1json, + getUsersByAccountInfo(process.getProcess(), false, "test1@example.com", null, null, null).get(0)); + assertEquals(user2json, + getUsersByAccountInfo(process.getProcess(), false, null, null, "google", "userid1").get(0)); + assertEquals(user2json, + getUsersByAccountInfo(process.getProcess(), false, "test2@example.com", null, "google", "userid1").get( + 0)); + assertEquals(user3json, + getUsersByAccountInfo(process.getProcess(), false, "test3@example.com", null, null, null).get(0)); + assertEquals(user4json, + getUsersByAccountInfo(process.getProcess(), false, null, "+919876543210", null, null).get(0)); // test for no result - assertEquals(0, getUsersByAccountInfo(process.getProcess(), false, "test1@example.com", "+919876543210", null, null).size()); - assertEquals(0, getUsersByAccountInfo(process.getProcess(), false, "test2@example.com", "+919876543210", null, null).size()); - assertEquals(0, getUsersByAccountInfo(process.getProcess(), false, "test3@example.com", "+919876543210", null, null).size()); - assertEquals(0, getUsersByAccountInfo(process.getProcess(), false, null, "+919876543210", "google", "userid1").size()); - assertEquals(0, getUsersByAccountInfo(process.getProcess(), false, "test1@gmail.com", null, "google", "userid1").size()); - assertEquals(0, getUsersByAccountInfo(process.getProcess(), false, "test3@gmail.com", null, "google", "userid1").size()); + assertEquals(0, getUsersByAccountInfo(process.getProcess(), false, "test1@example.com", "+919876543210", null, + null).size()); + assertEquals(0, getUsersByAccountInfo(process.getProcess(), false, "test2@example.com", "+919876543210", null, + null).size()); + assertEquals(0, getUsersByAccountInfo(process.getProcess(), false, "test3@example.com", "+919876543210", null, + null).size()); + assertEquals(0, + getUsersByAccountInfo(process.getProcess(), false, null, "+919876543210", "google", "userid1").size()); + assertEquals(0, getUsersByAccountInfo(process.getProcess(), false, "test1@gmail.com", null, "google", + "userid1").size()); + assertEquals(0, getUsersByAccountInfo(process.getProcess(), false, "test3@gmail.com", null, "google", + "userid1").size()); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -192,7 +205,8 @@ public void testListUserByAccountInfoByUnnormalisedPhoneNumber() throws Exceptio JsonObject userJSON = getUserById(process.getProcess(), user.getSupertokensUserId()); - assertEquals(userJSON, getUsersByAccountInfo(process.getProcess(), false, null, phoneNumber, null, null).get(0)); + assertEquals(userJSON, + getUsersByAccountInfo(process.getProcess(), false, null, phoneNumber, null, null).get(0)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -223,25 +237,29 @@ public void testListUsersByAccountInfoForUnlinkedAccountsWithUnionOption() throw JsonObject user4json = getUserById(process.getProcess(), user4.getSupertokensUserId()); { - JsonArray users = getUsersByAccountInfo(process.getProcess(), true, "test1@example.com", "+919876543210", null, null); + JsonArray users = getUsersByAccountInfo(process.getProcess(), true, "test1@example.com", "+919876543210", + null, null); assertEquals(2, users.size()); users.contains(user1json); users.contains(user4json); } { - JsonArray users = getUsersByAccountInfo(process.getProcess(), true, "test1@example.com", null, "google", "userid1"); + JsonArray users = getUsersByAccountInfo(process.getProcess(), true, "test1@example.com", null, "google", + "userid1"); assertEquals(2, users.size()); users.contains(user1json); users.contains(user2json); } { - JsonArray users = getUsersByAccountInfo(process.getProcess(), true, null, "+919876543210", "google", "userid1"); + JsonArray users = getUsersByAccountInfo(process.getProcess(), true, null, "+919876543210", "google", + "userid1"); assertEquals(2, users.size()); users.contains(user4json); users.contains(user2json); } { - JsonArray users = getUsersByAccountInfo(process.getProcess(), true, "test1@example.com", "+919876543210", "google", "userid1"); + JsonArray users = getUsersByAccountInfo(process.getProcess(), true, "test1@example.com", "+919876543210", + "google", "userid1"); assertEquals(3, users.size()); users.contains(user1json); users.contains(user2json); @@ -266,9 +284,11 @@ public void testUnknownAccountInfo() throws Exception { return; } - assertEquals(0, getUsersByAccountInfo(process.getProcess(), false, "test1@example.com", null, null, null).size()); + assertEquals(0, + getUsersByAccountInfo(process.getProcess(), false, "test1@example.com", null, null, null).size()); assertEquals(0, getUsersByAccountInfo(process.getProcess(), false, null, null, "google", "userid1").size()); - assertEquals(0, getUsersByAccountInfo(process.getProcess(), false, "test3@example.com", null, null, null).size()); + assertEquals(0, + getUsersByAccountInfo(process.getProcess(), false, "test3@example.com", null, null, null).size()); assertEquals(0, getUsersByAccountInfo(process.getProcess(), false, null, "+919876543210", null, null).size()); process.kill(); @@ -291,9 +311,11 @@ public void testListUserByAccountInfoWhenAccountsAreLinked1() throws Exception { AuthRecipeUserInfo user1 = EmailPassword.signUp(process.getProcess(), "test1@example.com", "password1"); Thread.sleep(50); - AuthRecipeUserInfo user2 = ThirdParty.signInUp(process.getProcess(), "google", "userid1", "test2@example.com").user; + AuthRecipeUserInfo user2 = ThirdParty.signInUp(process.getProcess(), "google", "userid1", + "test2@example.com").user; - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); JsonObject primaryUserJson = getUserById(process.getProcess(), user1.getSupertokensUserId()); @@ -331,7 +353,8 @@ public void testListUserByAccountInfoWhenAccountsAreLinked2() throws Exception { Thread.sleep(50); AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "password2"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); JsonObject primaryUserJson = getUserById(process.getProcess(), user1.getSupertokensUserId()); @@ -363,7 +386,8 @@ public void testListUserByAccountInfoWhenAccountsAreLinked3() throws Exception { Thread.sleep(50); AuthRecipeUserInfo user2 = createPasswordlessUserWithEmail(process.getProcess(), "test2@example.com"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); JsonObject primaryUserJson = getUserById(process.getProcess(), user1.getSupertokensUserId()); @@ -395,7 +419,8 @@ public void testListUserByAccountInfoWhenAccountsAreLinked4() throws Exception { Thread.sleep(50); AuthRecipeUserInfo user2 = createPasswordlessUserWithPhone(process.getProcess(), "+919876543210"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); JsonObject primaryUserJson = getUserById(process.getProcess(), user1.getSupertokensUserId()); @@ -429,7 +454,8 @@ public void testListUserByAccountInfoWhenAccountsAreLinked5() throws Exception { Thread.sleep(50); AuthRecipeUserInfo user2 = createThirdPartyUser(process.getProcess(), "google", "userid1", "test2@example.com"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); JsonObject primaryUserJson = getUserById(process.getProcess(), user1.getSupertokensUserId()); @@ -475,16 +501,23 @@ public void testWithUserIdMapping() throws Exception { UserIdMapping.createUserIdMapping(process.getProcess(), user2.getSupertokensUserId(), "ext2", "", false); UserIdMapping.createUserIdMapping(process.getProcess(), user3.getSupertokensUserId(), "ext3", "", false); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), primaryUser.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user4.getSupertokensUserId(), primaryUser.getSupertokensUserId()); JsonObject primaryUserInfo = getUsersByAccountInfo(process.getProcess(), false, "test@example.com", null, null, null).get(0).getAsJsonObject(); - assertEquals("ext1", primaryUserInfo.get("loginMethods").getAsJsonArray().get(0).getAsJsonObject().get("recipeUserId").getAsString()); - assertEquals("ext2", primaryUserInfo.get("loginMethods").getAsJsonArray().get(1).getAsJsonObject().get("recipeUserId").getAsString()); - assertEquals("ext3", primaryUserInfo.get("loginMethods").getAsJsonArray().get(2).getAsJsonObject().get("recipeUserId").getAsString()); + assertEquals("ext1", + primaryUserInfo.get("loginMethods").getAsJsonArray().get(0).getAsJsonObject().get("recipeUserId") + .getAsString()); + assertEquals("ext2", + primaryUserInfo.get("loginMethods").getAsJsonArray().get(1).getAsJsonObject().get("recipeUserId") + .getAsString()); + assertEquals("ext3", + primaryUserInfo.get("loginMethods").getAsJsonArray().get(2).getAsJsonObject().get("recipeUserId") + .getAsString()); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/accountlinking/api/GetUserByIdTest.java b/src/test/java/io/supertokens/test/accountlinking/api/GetUserByIdTest.java index dc6345086..1b2275486 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/GetUserByIdTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/GetUserByIdTest.java @@ -123,12 +123,14 @@ public void testJsonStructure() throws Exception { Thread.sleep(50); AuthRecipeUserInfo user4 = createPasswordlessUserWithPhone(process.getProcess(), "+919876543210"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), primaryUser.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user4.getSupertokensUserId(), primaryUser.getSupertokensUserId()); - for (String userId : new String[]{user1.getSupertokensUserId(), user2.getSupertokensUserId(), user3.getSupertokensUserId(), user4.getSupertokensUserId()}) { + for (String userId : new String[]{user1.getSupertokensUserId(), user2.getSupertokensUserId(), + user3.getSupertokensUserId(), user4.getSupertokensUserId()}) { Map params = new HashMap<>(); params.put("userId", userId); JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", @@ -185,11 +187,13 @@ public void testThatEmailIsAUnionOfLinkedAccounts1() throws Exception { Thread.sleep(50); AuthRecipeUserInfo user3 = createPasswordlessUserWithEmail(process.getProcess(), "test3@example.com"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), primaryUser.getSupertokensUserId()); - for (String userId : new String[]{user1.getSupertokensUserId(), user2.getSupertokensUserId(), user3.getSupertokensUserId()}) { + for (String userId : new String[]{user1.getSupertokensUserId(), user2.getSupertokensUserId(), + user3.getSupertokensUserId()}) { Map params = new HashMap<>(); params.put("userId", userId); JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", @@ -229,7 +233,8 @@ public void testThatEmailIsAUnionOfLinkedAccounts2() throws Exception { Thread.sleep(50); AuthRecipeUserInfo user2 = createThirdPartyUser(process.getProcess(), "google", "userid1", "test2@example.com"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); for (String userId : new String[]{user1.getSupertokensUserId(), user2.getSupertokensUserId()}) { @@ -271,7 +276,8 @@ public void testThatEmailIsAUnionOfLinkedAccounts3() throws Exception { Thread.sleep(50); AuthRecipeUserInfo user2 = createPasswordlessUserWithEmail(process.getProcess(), "test2@example.com"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); for (String userId : new String[]{user1.getSupertokensUserId(), user2.getSupertokensUserId()}) { @@ -309,11 +315,13 @@ public void testThatEmailIsAUnionOfLinkedAccounts4() throws Exception { return; } - AuthRecipeUserInfo user1 = createThirdPartyUser(process.getProcess(), "google", "googleid", "test1@example.com"); + AuthRecipeUserInfo user1 = createThirdPartyUser(process.getProcess(), "google", "googleid", + "test1@example.com"); Thread.sleep(50); AuthRecipeUserInfo user2 = createPasswordlessUserWithEmail(process.getProcess(), "test2@example.com"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); for (String userId : new String[]{user1.getSupertokensUserId(), user2.getSupertokensUserId()}) { @@ -355,7 +363,8 @@ public void testThatPhoneNumberIsUnionOfLinkedAccounts1() throws Exception { Thread.sleep(50); AuthRecipeUserInfo user2 = createPasswordlessUserWithPhone(process.getProcess(), "+911234567890"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); for (String userId : new String[]{user1.getSupertokensUserId(), user2.getSupertokensUserId()}) { @@ -399,7 +408,8 @@ public void testThatPhoneNumberIsUnionOfLinkedAccounts2() throws Exception { Thread.sleep(50); AuthRecipeUserInfo user3 = createThirdPartyUser(process.getProcess(), "google", "googleid", "test@example.com"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), primaryUser.getSupertokensUserId()); @@ -444,7 +454,8 @@ public void testThatPhoneNumberIsUnionOfLinkedAccounts3() throws Exception { Thread.sleep(50); AuthRecipeUserInfo user3 = createEmailPasswordUser(process.getProcess(), "test@example.com", "password"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), primaryUser.getSupertokensUserId()); @@ -495,12 +506,14 @@ public void testWithUserIdMapping() throws Exception { UserIdMapping.createUserIdMapping(process.getProcess(), user2.getSupertokensUserId(), "ext2", "", false); UserIdMapping.createUserIdMapping(process.getProcess(), user3.getSupertokensUserId(), "ext3", "", false); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), primaryUser.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), primaryUser.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user4.getSupertokensUserId(), primaryUser.getSupertokensUserId()); - for (String userId : new String[]{user1.getSupertokensUserId(), user2.getSupertokensUserId(), user3.getSupertokensUserId(), user4.getSupertokensUserId(), "ext1", "ext2", "ext3"}) { + for (String userId : new String[]{user1.getSupertokensUserId(), user2.getSupertokensUserId(), + user3.getSupertokensUserId(), user4.getSupertokensUserId(), "ext1", "ext2", "ext3"}) { Map params = new HashMap<>(); params.put("userId", userId); JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", @@ -508,9 +521,12 @@ public void testWithUserIdMapping() throws Exception { SemVer.v4_0.get(), ""); JsonObject user = response.get("user").getAsJsonObject(); assertEquals("ext1", user.get("id").getAsString()); - assertEquals("ext1", user.get("loginMethods").getAsJsonArray().get(0).getAsJsonObject().get("recipeUserId").getAsString()); - assertEquals("ext2", user.get("loginMethods").getAsJsonArray().get(1).getAsJsonObject().get("recipeUserId").getAsString()); - assertEquals("ext3", user.get("loginMethods").getAsJsonArray().get(2).getAsJsonObject().get("recipeUserId").getAsString()); + assertEquals("ext1", user.get("loginMethods").getAsJsonArray().get(0).getAsJsonObject().get("recipeUserId") + .getAsString()); + assertEquals("ext2", user.get("loginMethods").getAsJsonArray().get(1).getAsJsonObject().get("recipeUserId") + .getAsString()); + assertEquals("ext3", user.get("loginMethods").getAsJsonArray().get(2).getAsJsonObject().get("recipeUserId") + .getAsString()); } process.kill(); diff --git a/src/test/java/io/supertokens/test/accountlinking/api/LinkAccountsAPITest.java b/src/test/java/io/supertokens/test/accountlinking/api/LinkAccountsAPITest.java index 1adae1ba1..4457280fe 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/LinkAccountsAPITest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/LinkAccountsAPITest.java @@ -275,7 +275,8 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", @@ -326,18 +327,21 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser "pass1234"); UserIdMapping.createUserIdMapping(process.main, emailPasswordUser.getSupertokensUserId(), "e1", null, false); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", "test2@example.com"); - UserIdMapping.createUserIdMapping(process.main, signInUpResponse.user.getSupertokensUserId(), "e2", null, false); + UserIdMapping.createUserIdMapping(process.main, signInUpResponse.user.getSupertokensUserId(), "e2", null, + false); AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); ThirdParty.SignInUpResponse signInUpResponse2 = ThirdParty.signInUp(process.main, "fb", "user-fb", "test@example.com"); - UserIdMapping.createUserIdMapping(process.main, signInUpResponse2.user.getSupertokensUserId(), "e3", null, false); + UserIdMapping.createUserIdMapping(process.main, signInUpResponse2.user.getSupertokensUserId(), "e3", null, + false); { @@ -380,7 +384,8 @@ public void linkingUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exceptio "pass1234"); AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); @@ -431,7 +436,8 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa UserIdMapping.createUserIdMapping(process.main, emailPasswordUser2.getSupertokensUserId(), "r2", null, false); AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); @@ -599,7 +605,8 @@ public void linkingUserFailsCauseAlreadyLinkedToAnotherAccountReturnsUserObject( "pass1234"); AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); diff --git a/src/test/java/io/supertokens/test/accountlinking/api/SessionTests.java b/src/test/java/io/supertokens/test/accountlinking/api/SessionTests.java index ddac8d03e..639317ccf 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/SessionTests.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/SessionTests.java @@ -80,7 +80,7 @@ private String[] getSessionsForUser(Main main, String userId, Boolean includeAll return result; } - + private void revokeSessionsForUser(Main main, String userId, Boolean includeAllLinkedAccounts) throws HttpResponseException, IOException { JsonObject params = new JsonObject(); diff --git a/src/test/java/io/supertokens/test/accountlinking/api/TestRecipeUserIdInSignInUpAPIs.java b/src/test/java/io/supertokens/test/accountlinking/api/TestRecipeUserIdInSignInUpAPIs.java index b09b69976..51711a5d1 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/TestRecipeUserIdInSignInUpAPIs.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/TestRecipeUserIdInSignInUpAPIs.java @@ -162,7 +162,8 @@ public void testEmailPasswordSignIn() throws Exception { AuthRecipeUserInfo user2 = createPasswordlessUserWithEmail(process.getProcess(), "test@example.com"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user2.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user.getSupertokensUserId(), primaryUser.getSupertokensUserId()); { @@ -274,7 +275,8 @@ public void testThirdPartySignInUp() throws Exception { AuthRecipeUserInfo user2 = createEmailPasswordUser(process.getProcess(), "test@example.com", "password"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user2.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), userId, primaryUser.getSupertokensUserId()); { @@ -296,7 +298,8 @@ public void testThirdPartySignInUp() throws Exception { assertEquals(userId, response.get("recipeUserId").getAsString()); } - AuthRecipeUserInfo user3 = createThirdPartyUser(process.getProcess(), "facebook", "fb-user", "test@example.com"); + AuthRecipeUserInfo user3 = createThirdPartyUser(process.getProcess(), "facebook", "fb-user", + "test@example.com"); AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), primaryUser.getSupertokensUserId()); { @@ -356,7 +359,8 @@ public void testPasswordlessConsumeCode() throws Exception { String userId = null; { - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), "test@example.com", null, null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), + "test@example.com", null, null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -372,7 +376,8 @@ public void testPasswordlessConsumeCode() throws Exception { } { // Without account linking - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), "test@example.com", null, null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), + "test@example.com", null, null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -386,13 +391,16 @@ public void testPasswordlessConsumeCode() throws Exception { assertEquals(userId, response.get("recipeUserId").getAsString()); } - AuthRecipeUserInfo user2 = createThirdPartyUser(process.getProcess(), "google", "google-user", "test@example.com"); + AuthRecipeUserInfo user2 = createThirdPartyUser(process.getProcess(), "google", "google-user", + "test@example.com"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user2.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), userId, primaryUser.getSupertokensUserId()); { // after account linking - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), "test@example.com", null, null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), + "test@example.com", null, null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -410,7 +418,8 @@ public void testPasswordlessConsumeCode() throws Exception { AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), primaryUser.getSupertokensUserId()); { // after account linking - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), "test@example.com", null, null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), + "test@example.com", null, null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -424,7 +433,8 @@ public void testPasswordlessConsumeCode() throws Exception { assertEquals(userId, response.get("recipeUserId").getAsString()); } { // after account linking - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), "test2@example.com", null, null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), + "test2@example.com", null, null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -458,7 +468,8 @@ public void testPasswordlessConsumeCodeForPhone() throws Exception { String userId = null; { - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, "+919876543210", null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, + "+919876543210", null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -474,7 +485,8 @@ public void testPasswordlessConsumeCodeForPhone() throws Exception { } { // Without account linking - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, "+919876543210", null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, + "+919876543210", null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -488,13 +500,16 @@ public void testPasswordlessConsumeCodeForPhone() throws Exception { assertEquals(userId, response.get("recipeUserId").getAsString()); } - AuthRecipeUserInfo user2 = createThirdPartyUser(process.getProcess(), "google", "google-user", "test@example.com"); + AuthRecipeUserInfo user2 = createThirdPartyUser(process.getProcess(), "google", "google-user", + "test@example.com"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user2.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), userId, primaryUser.getSupertokensUserId()); { // after account linking - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, "+919876543210", null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, + "+919876543210", null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -512,7 +527,8 @@ public void testPasswordlessConsumeCodeForPhone() throws Exception { AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), primaryUser.getSupertokensUserId()); { // after account linking - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, "+919876543210", null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, + "+919876543210", null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -526,7 +542,8 @@ public void testPasswordlessConsumeCodeForPhone() throws Exception { assertEquals(userId, response.get("recipeUserId").getAsString()); } { // after account linking - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, "+919876543211", null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, + "+919876543211", null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -560,7 +577,8 @@ public void testPasswordlessConsumeCodeForPhoneAndEmail() throws Exception { String userId = null; { - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, "+919876543210", null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, + "+919876543210", null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -578,7 +596,8 @@ public void testPasswordlessConsumeCodeForPhoneAndEmail() throws Exception { Passwordless.updateUser(process.getProcess(), userId, new Passwordless.FieldUpdate("test@example.com"), null); { // Without account linking - phone - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, "+919876543210", null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, + "+919876543210", null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -592,7 +611,8 @@ public void testPasswordlessConsumeCodeForPhoneAndEmail() throws Exception { assertEquals(userId, response.get("recipeUserId").getAsString()); } { // Without account linking - email - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), "test@example.com", null, null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), + "test@example.com", null, null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -606,13 +626,16 @@ public void testPasswordlessConsumeCodeForPhoneAndEmail() throws Exception { assertEquals(userId, response.get("recipeUserId").getAsString()); } - AuthRecipeUserInfo user2 = createThirdPartyUser(process.getProcess(), "google", "google-user", "test@example.com"); + AuthRecipeUserInfo user2 = createThirdPartyUser(process.getProcess(), "google", "google-user", + "test@example.com"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user2.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), userId, primaryUser.getSupertokensUserId()); { // after account linking - phone - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, "+919876543210", null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, + "+919876543210", null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -626,7 +649,8 @@ public void testPasswordlessConsumeCodeForPhoneAndEmail() throws Exception { assertEquals(userId, response.get("recipeUserId").getAsString()); } { // after account linking - email - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), "test@example.com", null, null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), + "test@example.com", null, null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -644,7 +668,8 @@ public void testPasswordlessConsumeCodeForPhoneAndEmail() throws Exception { AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), primaryUser.getSupertokensUserId()); { // after account linking - phone - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, "+919876543210", null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), null, + "+919876543210", null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -658,7 +683,8 @@ public void testPasswordlessConsumeCodeForPhoneAndEmail() throws Exception { assertEquals(userId, response.get("recipeUserId").getAsString()); } { // after account linking - email - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), "test@example.com", null, null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), + "test@example.com", null, null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); @@ -712,7 +738,8 @@ public void testWithEmailPasswordUserWithUserIdMapping() throws Exception { AuthRecipeUserInfo user2 = createPasswordlessUserWithEmail(process.getProcess(), "test@example.com"); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user2.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user.getSupertokensUserId(), primaryUser.getSupertokensUserId()); { diff --git a/src/test/java/io/supertokens/test/accountlinking/api/UserPaginationTest.java b/src/test/java/io/supertokens/test/accountlinking/api/UserPaginationTest.java index bb2bf18be..59b09ecfd 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/UserPaginationTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/UserPaginationTest.java @@ -159,19 +159,26 @@ public void testUserPaginationResultJson() throws Exception { AuthRecipeUserInfo user8 = createThirdPartyUser(process.getProcess(), "google", "test8", "test8@example.com"); { - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()).user; - AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), primaryUser.getSupertokensUserId()); + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user1.getSupertokensUserId()).user; + AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), + primaryUser.getSupertokensUserId()); } { - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()).user; - AuthRecipe.linkAccounts(process.getProcess(), user5.getSupertokensUserId(), primaryUser.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.getProcess(), user7.getSupertokensUserId(), primaryUser.getSupertokensUserId()); + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user2.getSupertokensUserId()).user; + AuthRecipe.linkAccounts(process.getProcess(), user5.getSupertokensUserId(), + primaryUser.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user7.getSupertokensUserId(), + primaryUser.getSupertokensUserId()); } { - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user6.getSupertokensUserId()).user; - AuthRecipe.linkAccounts(process.getProcess(), user8.getSupertokensUserId(), primaryUser.getSupertokensUserId()); + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user6.getSupertokensUserId()).user; + AuthRecipe.linkAccounts(process.getProcess(), user8.getSupertokensUserId(), + primaryUser.getSupertokensUserId()); } @@ -181,7 +188,7 @@ public void testUserPaginationResultJson() throws Exception { SemVer.v4_0.get(), ""); JsonArray users = response.get("users").getAsJsonArray(); - assertEquals(4,users.size()); + assertEquals(4, users.size()); { params = new HashMap<>(); @@ -248,8 +255,9 @@ public void testUserPaginationWithManyUsers() throws Exception { Set thirdPartyUsers = new HashSet<>(); // emailpassword users - for (int i=0; i < 200; i++) { - AuthRecipeUserInfo user = createEmailPasswordUser(process.getProcess(), "epuser" + i + "@gmail.com", "password" + i); + for (int i = 0; i < 200; i++) { + AuthRecipeUserInfo user = createEmailPasswordUser(process.getProcess(), "epuser" + i + "@gmail.com", + "password" + i); userInfoMap.put(user.getSupertokensUserId(), user); userIds.add(user.getSupertokensUserId()); emailPasswordUsers.add(user.getSupertokensUserId()); @@ -257,8 +265,9 @@ public void testUserPaginationWithManyUsers() throws Exception { } // passwordless users with email - for (int i=0; i < 200; i++) { - AuthRecipeUserInfo user = createPasswordlessUserWithEmail(process.getProcess(), "pluser" + i + "@gmail.com"); + for (int i = 0; i < 200; i++) { + AuthRecipeUserInfo user = createPasswordlessUserWithEmail(process.getProcess(), + "pluser" + i + "@gmail.com"); userInfoMap.put(user.getSupertokensUserId(), user); userIds.add(user.getSupertokensUserId()); passwordlessUsers.add(user.getSupertokensUserId()); @@ -266,7 +275,7 @@ public void testUserPaginationWithManyUsers() throws Exception { } // passwordless users with phone - for (int i=0; i < 200; i++) { + for (int i = 0; i < 200; i++) { AuthRecipeUserInfo user = createPasswordlessUserWithPhone(process.getProcess(), "+1234567890" + i); userInfoMap.put(user.getSupertokensUserId(), user); userIds.add(user.getSupertokensUserId()); @@ -275,8 +284,9 @@ public void testUserPaginationWithManyUsers() throws Exception { } // thirdparty users - for (int i=0; i < 200; i++) { - AuthRecipeUserInfo user = createThirdPartyUser(process.getProcess(), "google", "tpuser" + i, "tpuser" + i + "@gmail.com"); + for (int i = 0; i < 200; i++) { + AuthRecipeUserInfo user = createThirdPartyUser(process.getProcess(), "google", "tpuser" + i, + "tpuser" + i + "@gmail.com"); userInfoMap.put(user.getSupertokensUserId(), user); userIds.add(user.getSupertokensUserId()); thirdPartyUsers.add(user.getSupertokensUserId()); @@ -292,7 +302,7 @@ public void testUserPaginationWithManyUsers() throws Exception { int numAccountsToLink = Math.min(rand.nextInt(3) + 1, userIds.size()); List userIdsToLink = new ArrayList<>(); - for (int i=0; i < numAccountsToLink; i++) { + for (int i = 0; i < numAccountsToLink; i++) { String[] userIdsArray = userIds.toArray(new String[0]); String userId = userIdsArray[rand.nextInt(userIds.size())]; userIdsToLink.add(userId); @@ -304,17 +314,19 @@ public void testUserPaginationWithManyUsers() throws Exception { } if (userIdsToLink.size() > 1) { - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), userIdsToLink.get(0)).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + userIdsToLink.get(0)).user; primaryUserIds.add(primaryUser.getSupertokensUserId()); - for (int i=1; i < userIdsToLink.size(); i++) { - AuthRecipe.linkAccounts(process.getProcess(), userIdsToLink.get(i), primaryUser.getSupertokensUserId()); + for (int i = 1; i < userIdsToLink.size(); i++) { + AuthRecipe.linkAccounts(process.getProcess(), userIdsToLink.get(i), + primaryUser.getSupertokensUserId()); } } else { primaryUserIds.add(userIdsToLink.get(0)); } } - + // Pagination tests { JsonArray usersResult = getUsersFromAllPages(process.getProcess(), 10, null); @@ -350,7 +362,8 @@ public void testUserPaginationWithManyUsers() throws Exception { assertEquals(primaryUsers.size(), usersResult.size()); } { - JsonArray usersResult = getUsersFromAllPages(process.getProcess(), 20, new String[]{"emailpassword", "passwordless"}); + JsonArray usersResult = getUsersFromAllPages(process.getProcess(), 20, + new String[]{"emailpassword", "passwordless"}); Set primaryUsers = new HashSet<>(); for (String userId : emailPasswordUsers) { primaryUsers.add(primaryUserIdMap.get(userId)); @@ -362,7 +375,8 @@ public void testUserPaginationWithManyUsers() throws Exception { assertEquals(primaryUsers.size(), usersResult.size()); } { - JsonArray usersResult = getUsersFromAllPages(process.getProcess(), 20, new String[]{"thirdparty", "passwordless"}); + JsonArray usersResult = getUsersFromAllPages(process.getProcess(), 20, + new String[]{"thirdparty", "passwordless"}); Set primaryUsers = new HashSet<>(); for (String userId : thirdPartyUsers) { primaryUsers.add(primaryUserIdMap.get(userId)); @@ -374,7 +388,8 @@ public void testUserPaginationWithManyUsers() throws Exception { assertEquals(primaryUsers.size(), usersResult.size()); } { - JsonArray usersResult = getUsersFromAllPages(process.getProcess(), 20, new String[]{"thirdparty", "passwordless", "emailpassword"}); + JsonArray usersResult = getUsersFromAllPages(process.getProcess(), 20, + new String[]{"thirdparty", "passwordless", "emailpassword"}); assertEquals(primaryUserIds.size(), usersResult.size()); } @@ -403,7 +418,8 @@ public void testUserPaginationFromOldVersion() throws Exception { AuthRecipeUserInfo user3 = createPasswordlessUserWithEmail(process.getProcess(), "test@example.com"); Thread.sleep(50); - AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()).user; + AuthRecipeUserInfo primaryUser = AuthRecipe.createPrimaryUser(process.getProcess(), + user2.getSupertokensUserId()).user; AuthRecipe.linkAccounts(process.getProcess(), user1.getSupertokensUserId(), primaryUser.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), primaryUser.getSupertokensUserId()); diff --git a/src/test/java/io/supertokens/test/authRecipe/DeleteUserAPIWithUserIdMappingTest.java b/src/test/java/io/supertokens/test/authRecipe/DeleteUserAPIWithUserIdMappingTest.java index aa5d0e538..ea19d3d38 100644 --- a/src/test/java/io/supertokens/test/authRecipe/DeleteUserAPIWithUserIdMappingTest.java +++ b/src/test/java/io/supertokens/test/authRecipe/DeleteUserAPIWithUserIdMappingTest.java @@ -54,7 +54,7 @@ public void beforeEach() { @Test public void createAUserMapTheirIdCreateMetadataWithExternalIdAndDelete() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -113,7 +113,7 @@ public void createAUserMapTheirIdCreateMetadataWithExternalIdAndDelete() throws // test intermediate state behavior, deleting superTokensUserId_1 @Test public void testDeleteUserBehaviorInIntermediateStateWithUser_1sUserId() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -134,7 +134,8 @@ public void testDeleteUserBehaviorInIntermediateStateWithUser_1sUserId() throws "test123@example.com"); // force create a mapping between the thirdParty user and EmailPassword user - UserIdMapping.createUserIdMapping(process.main, userInfo_2.user.getSupertokensUserId(), userInfo_1.getSupertokensUserId(), null, true); + UserIdMapping.createUserIdMapping(process.main, userInfo_2.user.getSupertokensUserId(), + userInfo_1.getSupertokensUserId(), null, true); // delete User with EmailPassword userId { @@ -173,7 +174,7 @@ public void testDeleteUserBehaviorInIntermediateStateWithUser_1sUserId() throws // test intermediate state behavior, deleting superTokensUserId_2 @Test public void testDeleteUserBehaviorInIntermediateStateWithUser_2sUserId() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -194,7 +195,8 @@ public void testDeleteUserBehaviorInIntermediateStateWithUser_2sUserId() throws "test123@example.com"); // force create a mapping between the thirdParty user and EmailPassword user - UserIdMapping.createUserIdMapping(process.main, userInfo_2.user.getSupertokensUserId(), userInfo_1.getSupertokensUserId(), null, true); + UserIdMapping.createUserIdMapping(process.main, userInfo_2.user.getSupertokensUserId(), + userInfo_1.getSupertokensUserId(), null, true); // delete User with ThirdParty users id { diff --git a/src/test/java/io/supertokens/test/authRecipe/GetUsersAPIWithUserIdMappingTest.java b/src/test/java/io/supertokens/test/authRecipe/GetUsersAPIWithUserIdMappingTest.java index eca8e44a5..078b4efdb 100644 --- a/src/test/java/io/supertokens/test/authRecipe/GetUsersAPIWithUserIdMappingTest.java +++ b/src/test/java/io/supertokens/test/authRecipe/GetUsersAPIWithUserIdMappingTest.java @@ -70,7 +70,8 @@ public void createMultipleUsersAndMapTheirIdsRetrieveAllUsersAndCheckThatExterna for (int i = 1; i <= 10; i++) { // create User - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test" + i + "@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test" + i + "@example.com", + "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalId" + i; externalUserIdList.add(externalUserId); @@ -110,7 +111,8 @@ public void createMultipleUsersAndMapTheirIdsRetrieveUsersUsingPaginationTokenAn for (int i = 1; i <= 20; i++) { // create User - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test" + i + "@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test" + i + "@example.com", + "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalId" + i; externalUserIdList.add(externalUserId); diff --git a/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsAPITest.java b/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsAPITest.java index 9dabb17d4..a76857cb9 100644 --- a/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsAPITest.java +++ b/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsAPITest.java @@ -60,7 +60,7 @@ public void beforeEach() { @Test public void testSearchingWhenFieldsHaveEmptyInputsWillBehaveLikeRegularPaginationAPI() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -70,10 +70,12 @@ public void testSearchingWhenFieldsHaveEmptyInputsWillBehaveLikeRegularPaginatio // create emailpassword user ArrayList userIds = new ArrayList<>(); - userIds.add(EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); + userIds.add( + EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); // create thirdparty user - userIds.add(ThirdParty.signInUp(process.getProcess(), "testTPID", "test", "test2@example.com").user.getSupertokensUserId()); + userIds.add(ThirdParty.signInUp(process.getProcess(), "testTPID", "test", + "test2@example.com").user.getSupertokensUserId()); // create passwordless user CreateCodeResponse createCodeResponse = Passwordless.createCode(process.getProcess(), "test@example.com", null, @@ -136,7 +138,7 @@ public void testSearchingWhenFieldsHaveEmptyInputsWillBehaveLikeRegularPaginatio @Test public void testSearchingForUsers() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -146,11 +148,14 @@ public void testSearchingForUsers() throws Exception { // create emailpassword user ArrayList userIds = new ArrayList<>(); - userIds.add(EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); - userIds.add(EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123").getSupertokensUserId()); + userIds.add( + EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); + userIds.add( + EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123").getSupertokensUserId()); // create thirdparty user - userIds.add(ThirdParty.signInUp(process.getProcess(), "testTPID", "test", "test2@example.com").user.getSupertokensUserId()); + userIds.add(ThirdParty.signInUp(process.getProcess(), "testTPID", "test", + "test2@example.com").user.getSupertokensUserId()); // create passwordless user CreateCodeResponse createCodeResponse = Passwordless.createCode(process.getProcess(), "test@example.com", null, @@ -180,7 +185,7 @@ public void testSearchingForUsers() throws Exception { @Test public void testSearchingForUsersWithMultipleInputsForEachField() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -190,9 +195,11 @@ public void testSearchingForUsersWithMultipleInputsForEachField() throws Excepti // create emailpassword user ArrayList userIds = new ArrayList<>(); - userIds.add(EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); + userIds.add( + EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); Thread.sleep(50); - userIds.add(EmailPassword.signUp(process.getProcess(), "abc@example.com", "testPass123").getSupertokensUserId()); + userIds.add( + EmailPassword.signUp(process.getProcess(), "abc@example.com", "testPass123").getSupertokensUserId()); Thread.sleep(50); // search with multiple inputs to email @@ -213,9 +220,11 @@ public void testSearchingForUsersWithMultipleInputsForEachField() throws Excepti } // create thirdparty user - userIds.add(ThirdParty.signInUp(process.getProcess(), "testpid", "test", "test@example.com").user.getSupertokensUserId()); + userIds.add(ThirdParty.signInUp(process.getProcess(), "testpid", "test", + "test@example.com").user.getSupertokensUserId()); Thread.sleep(50); - userIds.add(ThirdParty.signInUp(process.getProcess(), "newtestpid", "test123", "test@example.com").user.getSupertokensUserId()); + userIds.add(ThirdParty.signInUp(process.getProcess(), "newtestpid", "test123", + "test@example.com").user.getSupertokensUserId()); Thread.sleep(50); // search with multiple inputs to provider { @@ -275,7 +284,7 @@ public void testSearchingForUsersWithMultipleInputsForEachField() throws Excepti @Test public void testRetrievingUsersWithConflictingTagsReturnsEmptyList() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -285,10 +294,12 @@ public void testRetrievingUsersWithConflictingTagsReturnsEmptyList() throws Exce // create emailpassword user ArrayList userIds = new ArrayList<>(); - userIds.add(EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); + userIds.add( + EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); // create thirdparty user - userIds.add(ThirdParty.signInUp(process.getProcess(), "testTPID", "test", "test@example.com").user.getSupertokensUserId()); + userIds.add(ThirdParty.signInUp(process.getProcess(), "testTPID", "test", + "test@example.com").user.getSupertokensUserId()); // create passwordless user CreateCodeResponse createCodeResponse = Passwordless.createCode(process.getProcess(), "test@example.com", @@ -316,7 +327,7 @@ public void testRetrievingUsersWithConflictingTagsReturnsEmptyList() throws Exce @Test public void testNormalizingSearchInputsWorksCorrectly() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -326,10 +337,12 @@ public void testNormalizingSearchInputsWorksCorrectly() throws Exception { // create emailpassword user ArrayList userIds = new ArrayList<>(); - userIds.add(EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); + userIds.add( + EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); // create thirdparty user - userIds.add(ThirdParty.signInUp(process.getProcess(), "testpid", "test", "test@example.com").user.getSupertokensUserId()); + userIds.add(ThirdParty.signInUp(process.getProcess(), "testpid", "test", + "test@example.com").user.getSupertokensUserId()); { // searching for email with upper and lower case combination @@ -362,7 +375,7 @@ public void testNormalizingSearchInputsWorksCorrectly() throws Exception { @Test public void testMultipleParams() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -390,7 +403,7 @@ public void testMultipleParams() throws Exception { JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", "http://localhost:3567/users", params, 1000, 1000, null, SemVer.v2_18.get(), null); - + assertEquals("OK", response.get("status").getAsString()); assertEquals(0, response.get("users").getAsJsonArray().size()); diff --git a/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsTest.java b/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsTest.java index 4f0246f73..5a7542472 100644 --- a/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsTest.java +++ b/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsTest.java @@ -25,6 +25,7 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; + import static org.junit.Assert.*; import static org.junit.Assert.assertNotNull; @@ -57,7 +58,7 @@ public void beforeEach() { @Test public void retriveUsersUsingSearchTags() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -67,11 +68,14 @@ public void retriveUsersUsingSearchTags() throws Exception { // create emailpassword user ArrayList userIds = new ArrayList<>(); - userIds.add(EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); - userIds.add(EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123").getSupertokensUserId()); + userIds.add( + EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); + userIds.add( + EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123").getSupertokensUserId()); // create thirdparty user - userIds.add(ThirdParty.signInUp(process.getProcess(), "testTPID", "test", "test2@example.com").user.getSupertokensUserId()); + userIds.add(ThirdParty.signInUp(process.getProcess(), "testTPID", "test", + "test2@example.com").user.getSupertokensUserId()); // create passwordless user CreateCodeResponse createCodeResponse = Passwordless.createCode(process.getProcess(), "test@example.com", @@ -130,7 +134,7 @@ public void retriveUsersUsingSearchTags() throws Exception { @Test public void testRetrievingUsersWithConflictingTagsReturnsEmptyList() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -140,11 +144,14 @@ public void testRetrievingUsersWithConflictingTagsReturnsEmptyList() throws Exce // create emailpassword user ArrayList userIds = new ArrayList<>(); - userIds.add(EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); - userIds.add(EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123").getSupertokensUserId()); + userIds.add( + EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); + userIds.add( + EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123").getSupertokensUserId()); // create thirdparty user - userIds.add(ThirdParty.signInUp(process.getProcess(), "testTPID", "test", "test2@example.com").user.getSupertokensUserId()); + userIds.add(ThirdParty.signInUp(process.getProcess(), "testTPID", "test", + "test2@example.com").user.getSupertokensUserId()); // create passwordless user CreateCodeResponse createCodeResponse = Passwordless.createCode(process.getProcess(), "test@example.com", @@ -173,7 +180,7 @@ public void testRetrievingUsersWithConflictingTagsReturnsEmptyList() throws Exce @Test public void testSearchParamRegex() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -183,12 +190,15 @@ public void testSearchParamRegex() throws Exception { // create emailpassword user ArrayList userIds = new ArrayList<>(); - userIds.add(EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); - userIds.add(EmailPassword.signUp(process.getProcess(), "abc@example.com", "testPass123").getSupertokensUserId()); + userIds.add( + EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); + userIds.add( + EmailPassword.signUp(process.getProcess(), "abc@example.com", "testPass123").getSupertokensUserId()); userIds.add(EmailPassword.signUp(process.getProcess(), "user@abc.com", "testPass123").getSupertokensUserId()); // create thirdparty user - userIds.add(ThirdParty.signInUp(process.getProcess(), "testTPID", "test", "test2@example.com").user.getSupertokensUserId()); + userIds.add(ThirdParty.signInUp(process.getProcess(), "testTPID", "test", + "test2@example.com").user.getSupertokensUserId()); // create passwordless user CreateCodeResponse createCodeResponse = Passwordless.createCode(process.getProcess(), "test@example.com", @@ -252,7 +262,7 @@ public void testSearchParamRegex() throws Exception { @Test public void testThatQueryLimitIsCappedAt1000PerTable() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -264,10 +274,11 @@ public void testThatQueryLimitIsCappedAt1000PerTable() throws Exception { ArrayList userIds = new ArrayList<>(); for (int i = 0; i < 1005; i++) { - userIds.add(EmailPassword.signUp(process.getProcess(), "test" + i + "@example.com", "testPass123").getSupertokensUserId()); + userIds.add(EmailPassword.signUp(process.getProcess(), "test" + i + "@example.com", "testPass123") + .getSupertokensUserId()); Thread.sleep(10); } - + // retrieve users ArrayList emailList = new ArrayList<>(); emailList.add("test"); @@ -279,7 +290,7 @@ public void testThatQueryLimitIsCappedAt1000PerTable() throws Exception { assertTrue(userIds.contains(info.users[i].getSupertokensUserId())); } - + process.kill(); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STOPPED)); } diff --git a/src/test/java/io/supertokens/test/authRecipe/UserPaginationTest.java b/src/test/java/io/supertokens/test/authRecipe/UserPaginationTest.java index 9480c7a36..822784428 100644 --- a/src/test/java/io/supertokens/test/authRecipe/UserPaginationTest.java +++ b/src/test/java/io/supertokens/test/authRecipe/UserPaginationTest.java @@ -364,7 +364,8 @@ public void testUserPaginationWithSameTimeJoined() throws Exception { long timeJoined = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { String userId = io.supertokens.utils.Utils.getUUID(); - storage.signUp(TenantIdentifier.BASE_TENANT, userId, "test"+i+"@example.com", new LoginMethod.ThirdParty("google", userId), timeJoined); + storage.signUp(TenantIdentifier.BASE_TENANT, userId, "test" + i + "@example.com", + new LoginMethod.ThirdParty("google", userId), timeJoined); userIds.add(userId); } diff --git a/src/test/java/io/supertokens/test/dashboard/apis/DeleteDashboardUserSessionAPITest.java b/src/test/java/io/supertokens/test/dashboard/apis/DeleteDashboardUserSessionAPITest.java index 312c0858b..c3b22df73 100644 --- a/src/test/java/io/supertokens/test/dashboard/apis/DeleteDashboardUserSessionAPITest.java +++ b/src/test/java/io/supertokens/test/dashboard/apis/DeleteDashboardUserSessionAPITest.java @@ -58,7 +58,7 @@ public void beforeEach() { @Test public void BadInputTests() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -102,7 +102,7 @@ public void BadInputTests() throws Exception { @Test public void testRevokeSessionAPI() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUserSessionsAPITest.java b/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUserSessionsAPITest.java index e634f3930..1660a7a16 100644 --- a/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUserSessionsAPITest.java +++ b/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUserSessionsAPITest.java @@ -59,7 +59,7 @@ public void beforeEach() { @Test public void BadInputTests() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -104,7 +104,7 @@ public void BadInputTests() throws Exception { @Test public void testRetrievingSessionsForUser() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -134,7 +134,7 @@ public void testRetrievingSessionsForUser() throws Exception { assertEquals("OK", response.get("status").getAsString()); JsonArray sessions = response.get("sessions").getAsJsonArray(); - + assertNotNull(sessions); assertEquals(1, sessions.size()); diff --git a/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUsersAPITests.java b/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUsersAPITests.java index 5c544c413..bc69975df 100644 --- a/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUsersAPITests.java +++ b/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUsersAPITests.java @@ -61,7 +61,7 @@ public void beforeEach() { @Test public void testRetrievingDashboardUsers() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -72,7 +72,7 @@ public void testRetrievingDashboardUsers() throws Exception { // enable dashboard feature FeatureFlagTestContent.getInstance(process.getProcess()).setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, - new EE_FEATURES[] { EE_FEATURES.DASHBOARD_LOGIN }); + new EE_FEATURES[]{EE_FEATURES.DASHBOARD_LOGIN}); // create multiple users ArrayList createdUsers = new ArrayList<>(); @@ -107,7 +107,7 @@ public void testRetrievingDashboardUsers() throws Exception { @Test public void testRetrievingDashboardUsersOnlyReturnsUnsuspendedUsers() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -118,7 +118,7 @@ public void testRetrievingDashboardUsersOnlyReturnsUnsuspendedUsers() throws Exc // enable dashboard feature FeatureFlagTestContent.getInstance(process.getProcess()).setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, - new EE_FEATURES[] { EE_FEATURES.DASHBOARD_LOGIN }); + new EE_FEATURES[]{EE_FEATURES.DASHBOARD_LOGIN}); // create multiple users ArrayList createdUsers = new ArrayList<>(); @@ -131,7 +131,7 @@ public void testRetrievingDashboardUsersOnlyReturnsUnsuspendedUsers() throws Exc // remove dashboard feature FeatureFlagTestContent.getInstance(process.getProcess()).setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, - new EE_FEATURES[] {}); + new EE_FEATURES[]{}); // retrieve users and check that there were correctly created @@ -145,9 +145,10 @@ public void testRetrievingDashboardUsersOnlyReturnsUnsuspendedUsers() throws Exc assertEquals(Dashboard.MAX_NUMBER_OF_FREE_DASHBOARD_USERS, retrievedUsers.size()); for (int i = 0; i < Dashboard.MAX_NUMBER_OF_FREE_DASHBOARD_USERS; i++) { - assertEquals(createdUsers.get(i).userId, retrievedUsers.get(i).getAsJsonObject().get("userId").getAsString()); + assertEquals(createdUsers.get(i).userId, + retrievedUsers.get(i).getAsJsonObject().get("userId").getAsString()); } - + process.kill(); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/dashboard/apis/UpdateUserAPITest.java b/src/test/java/io/supertokens/test/dashboard/apis/UpdateUserAPITest.java index 137040b08..c9aaa29a5 100644 --- a/src/test/java/io/supertokens/test/dashboard/apis/UpdateUserAPITest.java +++ b/src/test/java/io/supertokens/test/dashboard/apis/UpdateUserAPITest.java @@ -57,7 +57,7 @@ public void beforeEach() { @Test public void BadInputTests() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -167,7 +167,7 @@ public void BadInputTests() throws Exception { @Test public void testSuccessfullyUpdatingUserDataWithUserId() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/dashboard/apis/VerifySessionAPITest.java b/src/test/java/io/supertokens/test/dashboard/apis/VerifySessionAPITest.java index 9f50f7933..a669bbf72 100644 --- a/src/test/java/io/supertokens/test/dashboard/apis/VerifySessionAPITest.java +++ b/src/test/java/io/supertokens/test/dashboard/apis/VerifySessionAPITest.java @@ -52,7 +52,7 @@ public void beforeEach() { @Test public void testSessionBehavior() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -94,7 +94,7 @@ public void testSessionBehavior() throws Exception { @Test public void testSessionBehaviorForCDI2_22() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/emailpassword/DeleteExpiredPasswordResetTokensCronjobTest.java b/src/test/java/io/supertokens/test/emailpassword/DeleteExpiredPasswordResetTokensCronjobTest.java index 63959abb4..a98e51f68 100644 --- a/src/test/java/io/supertokens/test/emailpassword/DeleteExpiredPasswordResetTokensCronjobTest.java +++ b/src/test/java/io/supertokens/test/emailpassword/DeleteExpiredPasswordResetTokensCronjobTest.java @@ -66,16 +66,21 @@ public void checkingCronJob() throws Exception { AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test1@example.com", "password"); - String tok = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); - String tok2 = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); + String tok = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), + user.getSupertokensUserId()); + String tok2 = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), + user.getSupertokensUserId()); Thread.sleep(2000); - String tok3 = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); - String tok4 = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); + String tok3 = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), + user.getSupertokensUserId()); + String tok4 = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), + user.getSupertokensUserId()); assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), user.getSupertokensUserId()).length == 4); + .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + user.getSupertokensUserId()).length == 4); Thread.sleep(3500); diff --git a/src/test/java/io/supertokens/test/emailpassword/EmailPasswordTest.java b/src/test/java/io/supertokens/test/emailpassword/EmailPasswordTest.java index 235a9c72f..232d03ce2 100644 --- a/src/test/java/io/supertokens/test/emailpassword/EmailPasswordTest.java +++ b/src/test/java/io/supertokens/test/emailpassword/EmailPasswordTest.java @@ -206,7 +206,8 @@ public void testThatAfterResetPasswordGenerateTokenTheTokenIsHashedInTheDatabase AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "random@gmail.com", "validPass123"); - String resetToken = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); + String resetToken = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), + user.getSupertokensUserId()); PasswordResetTokenInfo resetTokenInfo = ((EmailPasswordSQLStorage) StorageLayer.getStorage( process.getProcess())) .getPasswordResetTokenInfo(new AppIdentifier(null, null), @@ -235,7 +236,8 @@ public void testThatAfterResetPasswordIsCompletedThePasswordIsHashedInTheDatabas AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "random@gmail.com", "validPass123"); - String resetToken = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); + String resetToken = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), + user.getSupertokensUserId()); EmailPassword.resetPassword(process.getProcess(), resetToken, "newValidPass123"); @@ -265,10 +267,12 @@ public void passwordResetTokenExpiredCheck() throws Exception { AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test1@example.com", "password"); - String tok = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); + String tok = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), + user.getSupertokensUserId()); assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), user.getSupertokensUserId()).length == 1); + .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + user.getSupertokensUserId()).length == 1); Thread.sleep(20); @@ -280,7 +284,8 @@ public void passwordResetTokenExpiredCheck() throws Exception { } assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), user.getSupertokensUserId()).length == 0); + .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + user.getSupertokensUserId()).length == 0); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -300,7 +305,8 @@ public void multiplePasswordResetTokensPerUserAndThenVerifyWithSignin() throws E AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test1@example.com", "password"); EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); - String tok = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); + String tok = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), + user.getSupertokensUserId()); EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); PasswordResetTokenInfo[] tokens = ((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) @@ -636,13 +642,15 @@ public void testGeneratingResetPasswordTokenForNonEPUserNonPrimary() throws Exce "test@example.com"); try { - EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.main, signInUpResponse.user.getSupertokensUserId()); + EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.main, + signInUpResponse.user.getSupertokensUserId()); assert false; } catch (UnknownUserIdException ignored) { } - String token = EmailPassword.generatePasswordResetToken(process.main, signInUpResponse.user.getSupertokensUserId(), + String token = EmailPassword.generatePasswordResetToken(process.main, + signInUpResponse.user.getSupertokensUserId(), "test@example.com"); EmailPassword.ConsumeResetPasswordTokenResult res = EmailPassword.consumeResetPasswordToken(process.main, @@ -675,7 +683,8 @@ public void testGeneratingResetPasswordTokenForNonEPUserPrimary() throws Excepti AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); - String token = EmailPassword.generatePasswordResetToken(process.main, signInUpResponse.user.getSupertokensUserId(), + String token = EmailPassword.generatePasswordResetToken(process.main, + signInUpResponse.user.getSupertokensUserId(), "test@example.com"); EmailPassword.ConsumeResetPasswordTokenResult res = EmailPassword.consumeResetPasswordToken(process.main, @@ -711,10 +720,12 @@ public void testGeneratingResetPasswordTokenForNonEPUserPrimaryButDeletedWithOth "test2@example.com"); AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, signInUpResponse2.user.getSupertokensUserId(), signInUpResponse.user.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, signInUpResponse2.user.getSupertokensUserId(), + signInUpResponse.user.getSupertokensUserId()); assert (AuthRecipe.unlinkAccounts(process.main, signInUpResponse.user.getSupertokensUserId())); - String token = EmailPassword.generatePasswordResetToken(process.main, signInUpResponse.user.getSupertokensUserId(), + String token = EmailPassword.generatePasswordResetToken(process.main, + signInUpResponse.user.getSupertokensUserId(), "test@example.com"); EmailPassword.ConsumeResetPasswordTokenResult res = EmailPassword.consumeResetPasswordToken(process.main, @@ -746,7 +757,8 @@ public void deletionOfTpUserDeletesPasswordResetToken() throws Exception { "test@example.com"); - String token = EmailPassword.generatePasswordResetToken(process.main, signInUpResponse.user.getSupertokensUserId(), + String token = EmailPassword.generatePasswordResetToken(process.main, + signInUpResponse.user.getSupertokensUserId(), "test@example.com"); token = io.supertokens.utils.Utils.hashSHA256(token); @@ -777,10 +789,12 @@ public void passwordResetTokenExpiredCheckWithConsumeCode() throws Exception { AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test1@example.com", "password"); - String tok = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); + String tok = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), + user.getSupertokensUserId()); assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), user.getSupertokensUserId()).length == 1); + .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + user.getSupertokensUserId()).length == 1); Thread.sleep(20); @@ -792,7 +806,8 @@ public void passwordResetTokenExpiredCheckWithConsumeCode() throws Exception { } assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), user.getSupertokensUserId()).length == 0); + .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + user.getSupertokensUserId()).length == 0); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -812,7 +827,8 @@ public void multiplePasswordResetTokensPerUserAndThenVerifyWithSigninWithConsume AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test1@example.com", "password"); EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); - String tok = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); + String tok = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), + user.getSupertokensUserId()); EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); PasswordResetTokenInfo[] tokens = ((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) @@ -870,9 +886,11 @@ public void consumeCodeCorrectlySetsTheUserEmailForOlderTokens() throws Exceptio user.getSupertokensUserId()); assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), user.getSupertokensUserId()).length == 1); + .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + user.getSupertokensUserId()).length == 1); assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), user.getSupertokensUserId())[0].email == null); + .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + user.getSupertokensUserId())[0].email == null); EmailPassword.ConsumeResetPasswordTokenResult result = EmailPassword.consumeResetPasswordToken( process.getProcess(), tok); @@ -880,7 +898,8 @@ public void consumeCodeCorrectlySetsTheUserEmailForOlderTokens() throws Exceptio assert (result.userId.equals(user.getSupertokensUserId())); assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), user.getSupertokensUserId()).length == 0); + .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + user.getSupertokensUserId()).length == 0); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -908,7 +927,8 @@ public void updateEmailFailsIfEmailUsedByOtherPrimaryUserInSameTenant() throws E AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); try { - EmailPassword.updateUsersEmailOrPassword(process.main, user.getSupertokensUserId(), "someemail1@gmail.com", null); + EmailPassword.updateUsersEmailOrPassword(process.main, user.getSupertokensUserId(), "someemail1@gmail.com", + null); assert (false); } catch (EmailChangeNotAllowedException ignored) { @@ -950,7 +970,8 @@ public void updateEmailSucceedsIfEmailUsedByOtherPrimaryUserInDifferentTenantWhi AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "someemail@gmail.com", "somePass"); AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); - EmailPassword.updateUsersEmailOrPassword(process.main, user.getSupertokensUserId(), "someemail1@gmail.com", null); + EmailPassword.updateUsersEmailOrPassword(process.main, user.getSupertokensUserId(), "someemail1@gmail.com", + null); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -992,7 +1013,8 @@ public void updateEmailFailsIfEmailUsedByOtherPrimaryUserInDifferentTenant() new TenantIdentifier(null, null, "t1"), storage, user.getSupertokensUserId()); try { - EmailPassword.updateUsersEmailOrPassword(process.main, user.getSupertokensUserId(), "someemail1@gmail.com", null); + EmailPassword.updateUsersEmailOrPassword(process.main, user.getSupertokensUserId(), "someemail1@gmail.com", + null); assert (false); } catch (EmailChangeNotAllowedException ignored) { diff --git a/src/test/java/io/supertokens/test/emailpassword/MultitenantEmailPasswordTest.java b/src/test/java/io/supertokens/test/emailpassword/MultitenantEmailPasswordTest.java index 64c96c15c..88ca1efd3 100644 --- a/src/test/java/io/supertokens/test/emailpassword/MultitenantEmailPasswordTest.java +++ b/src/test/java/io/supertokens/test/emailpassword/MultitenantEmailPasswordTest.java @@ -421,7 +421,8 @@ public void testUpdatePasswordWorksCorrectlyAcrossAllTenants() process.getProcess(), user3.getSupertokensUserId(), null, "newpassword3"); { - t1storage = StorageLayer.findStorageAndUserIdMappingForUser(process.getProcess(), t1, user1.getSupertokensUserId(), + t1storage = StorageLayer.findStorageAndUserIdMappingForUser(process.getProcess(), t1, + user1.getSupertokensUserId(), UserIdType.SUPERTOKENS).storage; AuthRecipeUserInfo userInfo = EmailPassword.signIn(t1, t1storage, process.getProcess(), "user@example.com", "newpassword1"); diff --git a/src/test/java/io/supertokens/test/emailpassword/ParsedFirebaseSCryptResponseTest.java b/src/test/java/io/supertokens/test/emailpassword/ParsedFirebaseSCryptResponseTest.java index bcdc88461..cfa9dc3c9 100644 --- a/src/test/java/io/supertokens/test/emailpassword/ParsedFirebaseSCryptResponseTest.java +++ b/src/test/java/io/supertokens/test/emailpassword/ParsedFirebaseSCryptResponseTest.java @@ -48,7 +48,7 @@ public void beforeEach() { @Test public void testGoodInputToParsedFirebaseSCryptResponse() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -100,7 +100,7 @@ public void testGoodInputToParsedFirebaseSCryptResponse() throws Exception { @Test public void testBadInputToParsedFirebaseSCryptResponse() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/emailpassword/PasswordHashingTest.java b/src/test/java/io/supertokens/test/emailpassword/PasswordHashingTest.java index 683d99001..5d2543940 100644 --- a/src/test/java/io/supertokens/test/emailpassword/PasswordHashingTest.java +++ b/src/test/java/io/supertokens/test/emailpassword/PasswordHashingTest.java @@ -529,7 +529,8 @@ public void hashAndVerifyWithBcryptChangeToArgonPasswordWithResetFlow() throws E Config.getConfig(process.getProcess()).setPasswordHashingAlg(CoreConfig.PASSWORD_HASHING_ALG.ARGON2); - String token = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); + String token = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), + user.getSupertokensUserId()); EmailPassword.resetPassword(process.getProcess(), token, "somePass2"); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.PASSWORD_HASH_ARGON)); @@ -560,7 +561,8 @@ public void hashAndVerifyWithArgonChangeToBcryptPasswordWithResetFlow() throws E Config.getConfig(process.getProcess()).setPasswordHashingAlg(CoreConfig.PASSWORD_HASHING_ALG.BCRYPT); - String token = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); + String token = EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), + user.getSupertokensUserId()); EmailPassword.resetPassword(process.getProcess(), token, "somePass2"); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.PASSWORD_HASH_BCRYPT)); diff --git a/src/test/java/io/supertokens/test/emailpassword/UpdateUsersEmailAndPasswordTest.java b/src/test/java/io/supertokens/test/emailpassword/UpdateUsersEmailAndPasswordTest.java index aea6505ee..377dcb36f 100644 --- a/src/test/java/io/supertokens/test/emailpassword/UpdateUsersEmailAndPasswordTest.java +++ b/src/test/java/io/supertokens/test/emailpassword/UpdateUsersEmailAndPasswordTest.java @@ -74,7 +74,8 @@ public void testUpdateEmailOnly() throws Exception { AuthRecipeUserInfo userInfo = EmailPassword.signUp(main, "john.doe@example.com", "password"); // when - EmailPassword.updateUsersEmailOrPassword(main, userInfo.getSupertokensUserId(), "dave.doe@example.com", null); + EmailPassword.updateUsersEmailOrPassword(main, userInfo.getSupertokensUserId(), "dave.doe@example.com", + null); // then AuthRecipeUserInfo changedEmailUserInfo = EmailPassword.signIn(main, "dave.doe@example.com", "password"); @@ -99,7 +100,8 @@ public void testUpdateEmailToAnotherThatAlreadyExists() throws Exception { // when try { - EmailPassword.updateUsersEmailOrPassword(main, userInfo.getSupertokensUserId(), userInfo2.loginMethods[0].email, null); + EmailPassword.updateUsersEmailOrPassword(main, userInfo.getSupertokensUserId(), + userInfo2.loginMethods[0].email, null); Assert.fail(); } catch (DuplicateEmailException ignored) { } @@ -142,7 +144,8 @@ public void testUpdateEmailAndPassword() throws Exception { AuthRecipeUserInfo userInfo = EmailPassword.signUp(main, "john.doe@example.com", "password"); // when - EmailPassword.updateUsersEmailOrPassword(main, userInfo.getSupertokensUserId(), "dave.doe@example.com", "newPassword"); + EmailPassword.updateUsersEmailOrPassword(main, userInfo.getSupertokensUserId(), "dave.doe@example.com", + "newPassword"); // then AuthRecipeUserInfo changedCredentialsUserInfo = EmailPassword.signIn(main, "dave.doe@example.com", diff --git a/src/test/java/io/supertokens/test/emailpassword/api/EmailPasswordGetUserAPITest2_7.java b/src/test/java/io/supertokens/test/emailpassword/api/EmailPasswordGetUserAPITest2_7.java index ee71b3b44..ae617e4b7 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/EmailPasswordGetUserAPITest2_7.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/EmailPasswordGetUserAPITest2_7.java @@ -209,10 +209,12 @@ public void testGetUserForUsersOfOtherRecipeIds() throws Exception { return; } - AuthRecipeUserInfo user1 = ThirdParty.signInUp(process.getProcess(), "google", "googleid", "test@example.com").user; + AuthRecipeUserInfo user1 = ThirdParty.signInUp(process.getProcess(), "google", "googleid", + "test@example.com").user; Passwordless.CreateCodeResponse user2code = Passwordless.createCode(process.getProcess(), "test@example.com", null, null, null); - AuthRecipeUserInfo user2 = Passwordless.consumeCode(process.getProcess(), user2code.deviceId, user2code.deviceIdHash, user2code.userInputCode, null).user; + AuthRecipeUserInfo user2 = Passwordless.consumeCode(process.getProcess(), user2code.deviceId, + user2code.deviceIdHash, user2code.userInputCode, null).user; { HashMap map = new HashMap<>(); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/GenerateEmailVerificationTokenAPITest2_7.java b/src/test/java/io/supertokens/test/emailpassword/api/GenerateEmailVerificationTokenAPITest2_7.java index bc273a237..dd50ce5f7 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/GenerateEmailVerificationTokenAPITest2_7.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/GenerateEmailVerificationTokenAPITest2_7.java @@ -50,7 +50,7 @@ public void beforeEach() { @Test public void testBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -105,7 +105,7 @@ public void testBadInput() throws Exception { // Check good input works @Test public void testGoodInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -138,7 +138,7 @@ public void testGoodInput() throws Exception { // Check for all types of output @Test public void testAllTypesOfOutput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/ImportUserWithPasswordHashAPITest.java b/src/test/java/io/supertokens/test/emailpassword/api/ImportUserWithPasswordHashAPITest.java index 2422599b5..62ae42cd8 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/ImportUserWithPasswordHashAPITest.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/ImportUserWithPasswordHashAPITest.java @@ -536,7 +536,8 @@ public void testUpdatingAUsersPasswordHash() throws Exception { assertTrue(response.get("didUserAlreadyExist").getAsBoolean()); // check that a new user was not created by comparing userIds - assertEquals(initialUserInfo.getSupertokensUserId(), response.get("user").getAsJsonObject().get("id").getAsString()); + assertEquals(initialUserInfo.getSupertokensUserId(), + response.get("user").getAsJsonObject().get("id").getAsString()); // sign in with the new password to check if the password hash got updated AuthRecipeUserInfo updatedUserInfo = EmailPassword.signIn(process.main, email, newPassword); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/MultitenantAPITest.java b/src/test/java/io/supertokens/test/emailpassword/api/MultitenantAPITest.java index 477de20f8..11e484202 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/MultitenantAPITest.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/MultitenantAPITest.java @@ -584,7 +584,8 @@ public void testCrossTenantPasswordResetCombinations() throws Exception { } else { if (StorageLayer.isInMemDb(process.getProcess())) { // For in memory db, the user is in the same user pool and the password reset will succeed - successfulResetPasswordUsingToken(tenant, user.getAsJsonPrimitive("id").getAsString(), token, + successfulResetPasswordUsingToken(tenant, user.getAsJsonPrimitive("id").getAsString(), + token, newPassword); } else { invalidResetPasswordUsingToken(tenant, token, newPassword); @@ -621,7 +622,8 @@ public void testCrossTenantPasswordResetCombinations() throws Exception { } else { if (StorageLayer.isInMemDb(process.getProcess())) { // For in memory db, the user is in the same user pool and the password reset will succeed - successfulResetPasswordUsingToken(tenant, user.getAsJsonPrimitive("id").getAsString(), token, + successfulResetPasswordUsingToken(tenant, user.getAsJsonPrimitive("id").getAsString(), + token, newPassword); } else { invalidResetPasswordUsingToken(tenant, token, newPassword); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_12.java b/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_12.java index b8d701b1c..473d4cdae 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_12.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_12.java @@ -60,7 +60,7 @@ public void beforeEach() { // Check good input works @Test public void testGoodInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_7.java b/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_7.java index a0b2f89ee..164a75901 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_7.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_7.java @@ -59,7 +59,7 @@ public void beforeEach() { // Check for bad input (missing fields) @Test public void testBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -148,7 +148,7 @@ public void testBadInput() throws Exception { // Check good input works @Test public void testGoodInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -216,7 +216,7 @@ public void testGoodInput() throws Exception { // Failure condition: passing a valid password reset token will fail the test @Test public void testALLTypesOfOutPut() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -245,7 +245,7 @@ public void testALLTypesOfOutPut() throws Exception { // Failure condition: passing a valid method will fail the test @Test public void testInvalidMethodThrows400Error() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -276,7 +276,7 @@ public void testInvalidMethodThrows400Error() throws Exception { // Failure condition: submitting a valid password will fail the test @Test public void testEmptyPasswordThrows400Error() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/SignInAPITest2_7.java b/src/test/java/io/supertokens/test/emailpassword/api/SignInAPITest2_7.java index c7b09769e..6f7f7f8b5 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/SignInAPITest2_7.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/SignInAPITest2_7.java @@ -62,7 +62,7 @@ public void beforeEach() { // Check for bad input (missing fields) @Test public void testBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -122,7 +122,7 @@ public void testBadInput() throws Exception { // Check good input works @Test public void testGoodInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -169,7 +169,7 @@ public void testGoodInput() throws Exception { // work @Test public void testThatUnnormalisedEmailShouldAlsoWork() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -210,7 +210,7 @@ public void testThatUnnormalisedEmailShouldAlsoWork() throws Exception { // * credentials error @Test public void testInputsToSignInAPI() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest5_0.java b/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest5_0.java index d2d9c21f7..e8f19f6b3 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest5_0.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest5_0.java @@ -131,7 +131,8 @@ public void testSignUpWithFakeEmailMarksTheEmailAsVerified() throws Exception { assertNotNull(jsonUser.get("timeJoined")); assert (!jsonUser.get("isPrimaryUser").getAsBoolean()); assert (jsonUser.get("emails").getAsJsonArray().size() == 1); - assert (jsonUser.get("emails").getAsJsonArray().get(0).getAsString().equals("user1.google@@stfakeemail.supertokens.com")); + assert (jsonUser.get("emails").getAsJsonArray().get(0).getAsString() + .equals("user1.google@@stfakeemail.supertokens.com")); assert (jsonUser.get("phoneNumbers").getAsJsonArray().size() == 0); assert (jsonUser.get("thirdParty").getAsJsonArray().size() == 0); assert (jsonUser.get("loginMethods").getAsJsonArray().size() == 1); diff --git a/src/test/java/io/supertokens/test/emailverification/DeleteExpiredEmailVerificationTokensCronjobTest.java b/src/test/java/io/supertokens/test/emailverification/DeleteExpiredEmailVerificationTokensCronjobTest.java index a036ebfae..e3fcd7a0e 100644 --- a/src/test/java/io/supertokens/test/emailverification/DeleteExpiredEmailVerificationTokensCronjobTest.java +++ b/src/test/java/io/supertokens/test/emailverification/DeleteExpiredEmailVerificationTokensCronjobTest.java @@ -67,22 +67,29 @@ public void checkingCronJob() throws Exception { AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test1@example.com", "password"); - String tok = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email); - String tok2 = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email); + String tok = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), + user.loginMethods[0].email); + String tok2 = EmailVerification.generateEmailVerificationToken(process.getProcess(), + user.getSupertokensUserId(), user.loginMethods[0].email); Thread.sleep(2000); - String tok3 = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email); - String tok4 = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email); + String tok3 = EmailVerification.generateEmailVerificationToken(process.getProcess(), + user.getSupertokensUserId(), user.loginMethods[0].email); + String tok4 = EmailVerification.generateEmailVerificationToken(process.getProcess(), + user.getSupertokensUserId(), user.loginMethods[0].email); assert (((EmailVerificationSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllEmailVerificationTokenInfoForUser(new TenantIdentifier(null, null, null), user.getSupertokensUserId(), user.loginMethods[0].email).length == + .getAllEmailVerificationTokenInfoForUser(new TenantIdentifier(null, null, null), + user.getSupertokensUserId(), user.loginMethods[0].email).length == 4); Thread.sleep(3500); - EmailVerificationTokenInfo[] tokens = ((EmailVerificationSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllEmailVerificationTokenInfoForUser(new TenantIdentifier(null, null, null), user.getSupertokensUserId(), user.loginMethods[0].email); + EmailVerificationTokenInfo[] tokens = ((EmailVerificationSQLStorage) StorageLayer.getStorage( + process.getProcess())) + .getAllEmailVerificationTokenInfoForUser(new TenantIdentifier(null, null, null), + user.getSupertokensUserId(), user.loginMethods[0].email); assert (tokens.length == 2); diff --git a/src/test/java/io/supertokens/test/emailverification/EmailVerificationTest.java b/src/test/java/io/supertokens/test/emailverification/EmailVerificationTest.java index 94c9a4238..44bb452c4 100644 --- a/src/test/java/io/supertokens/test/emailverification/EmailVerificationTest.java +++ b/src/test/java/io/supertokens/test/emailverification/EmailVerificationTest.java @@ -80,13 +80,17 @@ public void testGeneratingEmailVerificationTokenTwoTimes() throws Exception { } AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); - String token1 = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email); - String token2 = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email); + String token1 = EmailVerification.generateEmailVerificationToken(process.getProcess(), + user.getSupertokensUserId(), user.loginMethods[0].email); + String token2 = EmailVerification.generateEmailVerificationToken(process.getProcess(), + user.getSupertokensUserId(), user.loginMethods[0].email); assertNotEquals(token1, token2); - EmailVerificationTokenInfo[] tokenInfo = ((EmailVerificationSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllEmailVerificationTokenInfoForUser(new TenantIdentifier(null, null, null), user.getSupertokensUserId(), user.loginMethods[0].email); + EmailVerificationTokenInfo[] tokenInfo = ((EmailVerificationSQLStorage) StorageLayer.getStorage( + process.getProcess())) + .getAllEmailVerificationTokenInfoForUser(new TenantIdentifier(null, null, null), + user.getSupertokensUserId(), user.loginMethods[0].email); assertEquals(tokenInfo.length, 2); assertTrue((tokenInfo[0].token.equals(io.supertokens.utils.Utils.hashSHA256(token1))) @@ -111,14 +115,17 @@ public void testVerifyingEmailAndGeneratingToken() throws Exception { } AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); - String token = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email); + String token = EmailVerification.generateEmailVerificationToken(process.getProcess(), + user.getSupertokensUserId(), user.loginMethods[0].email); EmailVerification.verifyEmail(process.getProcess(), token); - assertTrue(EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email)); + assertTrue(EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), + user.loginMethods[0].email)); try { - EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email); + EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), + user.loginMethods[0].email); throw new Exception("should not come here"); } catch (EmailAlreadyVerifiedException ignored) { } @@ -162,11 +169,14 @@ public void testGeneratingTwoTokenVerifyOtherTokenShouldThrowAnError() throws Ex } AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); - String token1 = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email); - String token2 = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email); + String token1 = EmailVerification.generateEmailVerificationToken(process.getProcess(), + user.getSupertokensUserId(), user.loginMethods[0].email); + String token2 = EmailVerification.generateEmailVerificationToken(process.getProcess(), + user.getSupertokensUserId(), user.loginMethods[0].email); EmailVerification.verifyEmail(process.getProcess(), token1); - assertTrue(EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email)); + assertTrue(EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), + user.loginMethods[0].email)); try { EmailVerification.verifyEmail(process.getProcess(), token2); @@ -195,7 +205,8 @@ public void useAnExpiredTokenItShouldThrowAnError() throws Exception { } AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); - String token = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email); + String token = EmailVerification.generateEmailVerificationToken(process.getProcess(), + user.getSupertokensUserId(), user.loginMethods[0].email); Thread.sleep(20); @@ -224,7 +235,8 @@ public void testFormatOfEmailVerificationToken() throws Exception { AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); for (int i = 0; i < 100; i++) { - String verifyToken = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), + String verifyToken = EmailVerification.generateEmailVerificationToken(process.getProcess(), + user.getSupertokensUserId(), user.loginMethods[0].email); assertEquals(verifyToken.length(), 128); assertFalse(verifyToken.contains("+")); @@ -287,15 +299,18 @@ public void verifyEmail() throws Exception { AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "password"); - assert (!EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email)); + assert (!EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), + user.loginMethods[0].email)); - String token = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email); + String token = EmailVerification.generateEmailVerificationToken(process.getProcess(), + user.getSupertokensUserId(), user.loginMethods[0].email); assert (token != null); EmailVerification.verifyEmail(process.getProcess(), token); - assert (EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email)); + assert (EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), + user.loginMethods[0].email)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -314,10 +329,12 @@ public void testVerifyingEmailAndThenUnverify() throws Exception { } AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); - String token = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email); + String token = EmailVerification.generateEmailVerificationToken(process.getProcess(), + user.getSupertokensUserId(), user.loginMethods[0].email); EmailVerification.verifyEmail(process.getProcess(), token); - assertTrue(EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email)); + assertTrue(EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), + user.loginMethods[0].email)); ((EmailVerificationSQLStorage) StorageLayer.getStorage(process.getProcess())).startTransaction(con -> { try { @@ -330,7 +347,8 @@ public void testVerifyingEmailAndThenUnverify() throws Exception { return null; }); - assertFalse(EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email)); + assertFalse(EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), + user.loginMethods[0].email)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -349,10 +367,12 @@ public void testVerifyingSameEmailTwice() throws Exception { } AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); - String token = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email); + String token = EmailVerification.generateEmailVerificationToken(process.getProcess(), + user.getSupertokensUserId(), user.loginMethods[0].email); EmailVerification.verifyEmail(process.getProcess(), token); - assertTrue(EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email)); + assertTrue(EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), + user.loginMethods[0].email)); ((EmailVerificationSQLStorage) StorageLayer.getStorage(process.getProcess())).startTransaction(con -> { try { @@ -365,7 +385,8 @@ public void testVerifyingSameEmailTwice() throws Exception { return null; }); - assertTrue(EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), user.loginMethods[0].email)); + assertTrue(EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), + user.loginMethods[0].email)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/emailverification/EmailVerificationWithUserIdMappingTest.java b/src/test/java/io/supertokens/test/emailverification/EmailVerificationWithUserIdMappingTest.java index 94c35f015..b85e4425f 100644 --- a/src/test/java/io/supertokens/test/emailverification/EmailVerificationWithUserIdMappingTest.java +++ b/src/test/java/io/supertokens/test/emailverification/EmailVerificationWithUserIdMappingTest.java @@ -90,7 +90,8 @@ public void testUserIdMappingCreationAfterEmailVerificationForThirdPartyUser() t return; } - AuthRecipeUserInfo user = ThirdParty.signInUp(process.getProcess(), "google", "googleid1", "test@example.com", true).user; + AuthRecipeUserInfo user = ThirdParty.signInUp(process.getProcess(), "google", "googleid1", "test@example.com", + true).user; try { String token = EmailVerification.generateEmailVerificationToken(process.getProcess(), user.getSupertokensUserId(), "test@example.com"); @@ -125,7 +126,8 @@ public void testUserIdMappingCreationAfterEmailVerificationForPasswordlessUser() Passwordless.CreateCodeResponse code = Passwordless.createCode(process.getProcess(), "test@example.com", null, null, null); - AuthRecipeUserInfo user = Passwordless.consumeCode(process.getProcess(), code.deviceId, code.deviceIdHash, code.userInputCode, null, true).user; + AuthRecipeUserInfo user = Passwordless.consumeCode(process.getProcess(), code.deviceId, code.deviceIdHash, + code.userInputCode, null, true).user; try { String token = EmailVerification.generateEmailVerificationToken(process.getProcess(), @@ -145,14 +147,16 @@ public void testUserIdMappingCreationAfterEmailVerificationForPasswordlessUser() assertTrue(userInfo.loginMethods[0].verified); assertTrue(EmailVerification.isEmailVerified(process.getProcess(), "euid", "test@example.com")); - assertFalse(EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), "test@example.com")); + assertFalse(EmailVerification.isEmailVerified(process.getProcess(), user.getSupertokensUserId(), + "test@example.com")); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @Test - public void testUserIdMappingCreationAfterEmailVerificationForPasswordlessUserWithOlderCDIBehaviour() throws Exception { + public void testUserIdMappingCreationAfterEmailVerificationForPasswordlessUserWithOlderCDIBehaviour() + throws Exception { String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); @@ -170,7 +174,8 @@ public void testUserIdMappingCreationAfterEmailVerificationForPasswordlessUserWi // create mapping // this should not be allowed try { - UserIdMapping.createUserIdMapping(process.getProcess(), user.getSupertokensUserId(), "euid", null, false, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user.getSupertokensUserId(), "euid", null, false, + false); fail(); } catch (Exception e) { assert e.getMessage().contains("UserId is already in use in EmailVerification recipe"); diff --git a/src/test/java/io/supertokens/test/emailverification/api/IsEmailVerifiedAPITest2_7.java b/src/test/java/io/supertokens/test/emailverification/api/IsEmailVerifiedAPITest2_7.java index 6618d7bf3..e33c8246e 100644 --- a/src/test/java/io/supertokens/test/emailverification/api/IsEmailVerifiedAPITest2_7.java +++ b/src/test/java/io/supertokens/test/emailverification/api/IsEmailVerifiedAPITest2_7.java @@ -51,7 +51,7 @@ public void beforeEach() { @Test public void testBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -95,7 +95,7 @@ public void testBadInput() throws Exception { // Check good input works @Test public void testGoodInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -161,7 +161,7 @@ public void testGoodInput() throws Exception { // Check for all types of output @Test public void testAllTypesOfOutput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/httpRequest/HttpRequestForTesting.java b/src/test/java/io/supertokens/test/httpRequest/HttpRequestForTesting.java index 623a7129d..876b473c4 100644 --- a/src/test/java/io/supertokens/test/httpRequest/HttpRequestForTesting.java +++ b/src/test/java/io/supertokens/test/httpRequest/HttpRequestForTesting.java @@ -62,7 +62,8 @@ private static boolean isJsonValid(String jsonInString) { @SuppressWarnings("unchecked") public static T sendGETRequest(Main main, String requestID, String url, Map params, - int connectionTimeoutMS, int readTimeoutMS, Integer version, String cdiVersion, String rid) + int connectionTimeoutMS, int readTimeoutMS, Integer version, String cdiVersion, + String rid) throws IOException, io.supertokens.test.httpRequest.HttpResponseException { StringBuilder paramBuilder = new StringBuilder(); @@ -130,8 +131,10 @@ public static T sendGETRequest(Main main, String requestID, String url, Map< @SuppressWarnings("unchecked") public static T sendJsonRequest(Main main, String requestID, String url, JsonElement requestBody, - int connectionTimeoutMS, int readTimeoutMS, Integer version, String cdiVersion, String method, - String apiKey, String rid) throws IOException, io.supertokens.test.httpRequest.HttpResponseException { + int connectionTimeoutMS, int readTimeoutMS, Integer version, String cdiVersion, + String method, + String apiKey, String rid) + throws IOException, io.supertokens.test.httpRequest.HttpResponseException { URL obj = getURL(main, requestID, url); InputStream inputStream = null; HttpURLConnection con = null; @@ -197,101 +200,107 @@ public static T sendJsonRequest(Main main, String requestID, String url, Jso } public static T sendJsonPOSTRequest(Main main, String requestID, String url, JsonElement requestBody, - int connectionTimeoutMS, int readTimeoutMS, Integer version, String cdiVersion, String rid) + int connectionTimeoutMS, int readTimeoutMS, Integer version, + String cdiVersion, String rid) throws IOException, io.supertokens.test.httpRequest.HttpResponseException { return sendJsonRequest(main, requestID, url, requestBody, connectionTimeoutMS, readTimeoutMS, version, cdiVersion, "POST", null, rid); } public static T sendJsonPOSTRequest(Main main, String requestID, String url, JsonElement requestBody, - int connectionTimeoutMS, int readTimeoutMS, Integer version, String cdiVersion, String apiKey, String rid) + int connectionTimeoutMS, int readTimeoutMS, Integer version, + String cdiVersion, String apiKey, String rid) throws IOException, io.supertokens.test.httpRequest.HttpResponseException { return sendJsonRequest(main, requestID, url, requestBody, connectionTimeoutMS, readTimeoutMS, version, cdiVersion, "POST", apiKey, rid); } public static T sendJsonPUTRequest(Main main, String requestID, String url, JsonElement requestBody, - int connectionTimeoutMS, int readTimeoutMS, Integer version, String cdiVersion, String rid) + int connectionTimeoutMS, int readTimeoutMS, Integer version, + String cdiVersion, String rid) throws IOException, io.supertokens.test.httpRequest.HttpResponseException { return sendJsonRequest(main, requestID, url, requestBody, connectionTimeoutMS, readTimeoutMS, version, cdiVersion, "PUT", null, rid); } public static T sendJsonDELETERequest(Main main, String requestID, String url, JsonElement requestBody, - int connectionTimeoutMS, int readTimeoutMS, Integer version, String cdiVersion, String rid) + int connectionTimeoutMS, int readTimeoutMS, Integer version, + String cdiVersion, String rid) throws IOException, HttpResponseException { return sendJsonRequest(main, requestID, url, requestBody, connectionTimeoutMS, readTimeoutMS, version, cdiVersion, "DELETE", null, rid); } @SuppressWarnings("unchecked") - public static T sendJsonDELETERequestWithQueryParams(Main main, String requestID, String url, Map params, - int connectionTimeoutMS, int readTimeoutMS, Integer version, String cdiVersion, String rid) + public static T sendJsonDELETERequestWithQueryParams(Main main, String requestID, String url, + Map params, + int connectionTimeoutMS, int readTimeoutMS, + Integer version, String cdiVersion, String rid) throws IOException, HttpResponseException { - StringBuilder paramBuilder = new StringBuilder(); + StringBuilder paramBuilder = new StringBuilder(); - if (params != null) { - for (Map.Entry entry : params.entrySet()) { - paramBuilder.append(entry.getKey()).append("=") - .append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)).append("&"); - } - } - String paramsStr = paramBuilder.toString(); - if (!paramsStr.equals("")) { - paramsStr = paramsStr.substring(0, paramsStr.length() - 1); - url = url + "?" + paramsStr; + if (params != null) { + for (Map.Entry entry : params.entrySet()) { + paramBuilder.append(entry.getKey()).append("=") + .append(URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8)).append("&"); + } + } + String paramsStr = paramBuilder.toString(); + if (!paramsStr.equals("")) { + paramsStr = paramsStr.substring(0, paramsStr.length() - 1); + url = url + "?" + paramsStr; + } + URL obj = getURL(main, requestID, url); + InputStream inputStream = null; + HttpURLConnection con = null; + + try { + con = (HttpURLConnection) obj.openConnection(); + con.setRequestMethod("DELETE"); + con.setConnectTimeout(connectionTimeoutMS); + con.setReadTimeout(readTimeoutMS + 1000); + if (version != null) { + con.setRequestProperty("api-version", version + ""); + } + if (cdiVersion != null) { + con.setRequestProperty("cdi-version", cdiVersion); + } + if (rid != null) { + con.setRequestProperty("rId", rid); + } + + int responseCode = con.getResponseCode(); + + if (responseCode < STATUS_CODE_ERROR_THRESHOLD) { + inputStream = con.getInputStream(); + } else { + inputStream = con.getErrorStream(); + } + + StringBuilder response = new StringBuilder(); + try (BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { + String inputLine; + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); } - URL obj = getURL(main, requestID, url); - InputStream inputStream = null; - HttpURLConnection con = null; - - try { - con = (HttpURLConnection) obj.openConnection(); - con.setRequestMethod("DELETE"); - con.setConnectTimeout(connectionTimeoutMS); - con.setReadTimeout(readTimeoutMS + 1000); - if (version != null) { - con.setRequestProperty("api-version", version + ""); - } - if (cdiVersion != null) { - con.setRequestProperty("cdi-version", cdiVersion); - } - if (rid != null) { - con.setRequestProperty("rId", rid); - } - - int responseCode = con.getResponseCode(); - - if (responseCode < STATUS_CODE_ERROR_THRESHOLD) { - inputStream = con.getInputStream(); - } else { - inputStream = con.getErrorStream(); - } - - StringBuilder response = new StringBuilder(); - try (BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { - String inputLine; - while ((inputLine = in.readLine()) != null) { - response.append(inputLine); - } - } - if (responseCode < STATUS_CODE_ERROR_THRESHOLD) { - if (!isJsonValid(response.toString())) { - return (T) response.toString(); - } - return (T) (new JsonParser().parse(response.toString())); - } - throw new io.supertokens.test.httpRequest.HttpResponseException(responseCode, response.toString()); - } finally { - if (inputStream != null) { - inputStream.close(); - } - - if (con != null) { - con.disconnect(); - } + } + if (responseCode < STATUS_CODE_ERROR_THRESHOLD) { + if (!isJsonValid(response.toString())) { + return (T) response.toString(); } + return (T) (new JsonParser().parse(response.toString())); + } + throw new io.supertokens.test.httpRequest.HttpResponseException(responseCode, response.toString()); + } finally { + if (inputStream != null) { + inputStream.close(); + } + + if (con != null) { + con.disconnect(); + } } + } public static String getMultitenantUrl(TenantIdentifier tenantIdentifier, String path) { StringBuilder sb = new StringBuilder(); diff --git a/src/test/java/io/supertokens/test/jwt/JWKSTest.java b/src/test/java/io/supertokens/test/jwt/JWKSTest.java index ec85fba81..758da024a 100644 --- a/src/test/java/io/supertokens/test/jwt/JWKSTest.java +++ b/src/test/java/io/supertokens/test/jwt/JWKSTest.java @@ -63,7 +63,7 @@ public void beforeEach() { */ @Test public void testThatThereAreTheSameNumberOfJWKSAsSupportedAlgorithmsBeforeJWTCreation() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -81,7 +81,7 @@ public void testThatThereAreTheSameNumberOfJWKSAsSupportedAlgorithmsBeforeJWTCre */ @Test public void testThatNoNewJWKIsCreatedDuringJWTCreation() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -110,7 +110,7 @@ public void testThatNoNewJWKIsCreatedDuringJWTCreation() throws Exception { */ @Test public void testThatJWKListContainsValidKeyForCreatedJWT() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -120,7 +120,8 @@ public void testThatJWKListContainsValidKeyForCreatedJWT() throws Exception { String jwksDomain = "http://localhost"; long validity = 3600; - String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity, false); + String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity, + false); DecodedJWT decodedJWT = JWT.decode(jwt); String headerKeyId = decodedJWT.getHeaderClaim("kid").asString(); @@ -146,7 +147,7 @@ public void testThatJWKListContainsValidKeyForCreatedJWT() throws Exception { */ @Test public void testThatAValidPublicKeyCanBeCreatedFromJWK() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -182,7 +183,7 @@ public void testThatAValidPublicKeyCanBeCreatedFromJWK() throws Exception { */ @Test public void testThatJWKCanBeUsedForJWTVerification() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -192,7 +193,8 @@ public void testThatJWKCanBeUsedForJWTVerification() throws Exception { String jwksDomain = "http://localhost"; long validity = 3600; - String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity, false); + String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity, + false); DecodedJWT decodedJWT = JWT.decode(jwt); String headerKeyId = decodedJWT.getHeaderClaim("kid").asString(); @@ -247,7 +249,7 @@ public String getPrivateKeyId() { */ @Test public void testThatJWKModulusIsUnsigned() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/jwt/JWTCreateTest.java b/src/test/java/io/supertokens/test/jwt/JWTCreateTest.java index e602b7da6..fdebac573 100644 --- a/src/test/java/io/supertokens/test/jwt/JWTCreateTest.java +++ b/src/test/java/io/supertokens/test/jwt/JWTCreateTest.java @@ -54,7 +54,7 @@ public void beforeEach() { */ @Test public void testNormalFunctioningOfCreateToken() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -75,7 +75,7 @@ public void testNormalFunctioningOfCreateToken() throws Exception { */ @Test public void testCreateTokenWithAlreadyExistingKey() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -98,7 +98,7 @@ public void testCreateTokenWithAlreadyExistingKey() throws Exception { */ @Test public void testNormalFunctioningOfCreateTokenWithLongValidity() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -108,7 +108,8 @@ public void testNormalFunctioningOfCreateTokenWithLongValidity() throws Exceptio String jwksDomain = "http://localhost"; long validity = 63072000; - String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity, false); + String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity, + false); DecodedJWT decodedJWT = JWT.decode(jwt); @@ -126,7 +127,7 @@ public void testNormalFunctioningOfCreateTokenWithLongValidity() throws Exceptio */ @Test public void testInvalidAlgorithmThrowsError() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -152,7 +153,7 @@ public void testInvalidAlgorithmThrowsError() throws Exception { */ @Test public void testThatDecodedJWTHasAValidHeader() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -162,7 +163,8 @@ public void testThatDecodedJWTHasAValidHeader() throws Exception { String jwksDomain = "http://localhost"; long validity = 3600; - String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity, false); + String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity, + false); DecodedJWT decodedJWT = JWT.decode(jwt); @@ -196,7 +198,7 @@ public void testThatDecodedJWTHasAValidHeader() throws Exception { */ @Test public void testThatDecodedJWTPayloadHasRequiredClaims() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -209,7 +211,8 @@ public void testThatDecodedJWTPayloadHasRequiredClaims() throws Exception { long expectedIssuedAtTime = System.currentTimeMillis() / 1000; long expectedExpiry = expectedIssuedAtTime + validity; - String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity, false); + String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity, + false); DecodedJWT decodedJWT = JWT.decode(jwt); @@ -242,7 +245,7 @@ public void testThatDecodedJWTPayloadHasRequiredClaims() throws Exception { */ @Test public void testThatDecodedJWTPayloadHasCustomProperties() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -256,7 +259,8 @@ public void testThatDecodedJWTPayloadHasCustomProperties() throws Exception { String jwksDomain = "http://localhost"; long validity = 3600; - String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity, false); + String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity, + false); DecodedJWT decodedJWT = JWT.decode(jwt); @@ -264,7 +268,8 @@ public void testThatDecodedJWTPayloadHasCustomProperties() throws Exception { if (customClaim.isNull()) { throw new Exception( - "Decoded JWT does not contain properties from payload passed to JWTSigningFunctions.createJWTToken"); + "Decoded JWT does not contain properties from payload passed to JWTSigningFunctions" + + ".createJWTToken"); } if (!customClaim.asString().equals(customClaimValue)) { @@ -280,7 +285,7 @@ public void testThatDecodedJWTPayloadHasCustomProperties() throws Exception { */ @Test public void testThatDecodedJWTUsesCustomIssuer() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -291,7 +296,8 @@ public void testThatDecodedJWTUsesCustomIssuer() throws Exception { String jwksDomain = "http://localhost"; long validity = 3600; - String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity, false); + String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, payload, jwksDomain, validity, + false); DecodedJWT decodedJWT = JWT.decode(jwt); String issuer = decodedJWT.getIssuer(); diff --git a/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_21.java b/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_21.java index 9aa285fcc..9bc89b71a 100644 --- a/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_21.java +++ b/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_21.java @@ -56,12 +56,13 @@ public void beforeEach() { @Test public void testThatNewDynamicKeysAreAdded() throws Exception { Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "0.00027"); // 1 second - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); JsonObject oldResponse = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/recipe/jwt/jwks", null, 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), + "http://localhost:3567/recipe/jwt/jwks", null, 1000, 1000, null, + Utils.getCdiVersionStringLatestForTests(), "jwt"); JsonArray oldKeys = oldResponse.getAsJsonArray("keys"); @@ -70,7 +71,8 @@ public void testThatNewDynamicKeysAreAdded() throws Exception { Thread.sleep(1500); JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/recipe/jwt/jwks", null, 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), + "http://localhost:3567/recipe/jwt/jwks", null, 1000, 1000, null, + Utils.getCdiVersionStringLatestForTests(), "jwt"); JsonArray keys = response.getAsJsonArray("keys"); @@ -83,12 +85,13 @@ public void testThatNewDynamicKeysAreAdded() throws Exception { @Test public void testThatNewDynamicKeysAreReflectedIfAddedByAnotherCore() throws Exception { Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "0.00027"); // 1 second - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); JsonObject oldResponse = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/recipe/jwt/jwks", null, 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), + "http://localhost:3567/recipe/jwt/jwks", null, 1000, 1000, null, + Utils.getCdiVersionStringLatestForTests(), "jwt"); JsonArray oldKeys = oldResponse.getAsJsonArray("keys"); @@ -97,10 +100,12 @@ public void testThatNewDynamicKeysAreReflectedIfAddedByAnotherCore() throws Exce Thread.sleep(1500); // Simulate another core adding a new key - List keyList = AccessTokenSigningKey.getInstance(process.getProcess()).getOrCreateAndGetSigningKeys(); + List keyList = AccessTokenSigningKey.getInstance(process.getProcess()) + .getOrCreateAndGetSigningKeys(); JsonObject responseAfterWait = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/recipe/jwt/jwks", null, 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), + "http://localhost:3567/recipe/jwt/jwks", null, 1000, 1000, null, + Utils.getCdiVersionStringLatestForTests(), "jwt"); JsonArray keys = responseAfterWait.getAsJsonArray("keys"); @@ -120,7 +125,7 @@ public void testThatNewDynamicKeysAreReflectedIfAddedByAnotherCore() throws Exce @Test public void testThatKeysContainsMatchingKeyIdForAccessToken() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -140,11 +145,13 @@ public void testThatKeysContainsMatchingKeyIdForAccessToken() throws Exception { JsonObject createResponse = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/recipe/session", request, 1000, 1000, null, SemVer.v2_21.get(), "session"); - DecodedJWT decodedJWT = JWT.decode(createResponse.get("accessToken").getAsJsonObject().get("token").getAsString()); + DecodedJWT decodedJWT = JWT.decode( + createResponse.get("accessToken").getAsJsonObject().get("token").getAsString()); String keyIdFromHeader = decodedJWT.getHeaderClaim("kid").asString(); JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/recipe/jwt/jwks", null, 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), + "http://localhost:3567/recipe/jwt/jwks", null, 1000, 1000, null, + Utils.getCdiVersionStringLatestForTests(), "jwt"); JsonArray keys = response.getAsJsonArray("keys"); @@ -167,7 +174,7 @@ public void testThatKeysContainsMatchingKeyIdForAccessToken() throws Exception { @Test public void testThatKeysContainsMatchingKeyIdForStaticAccessToken() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -187,11 +194,13 @@ public void testThatKeysContainsMatchingKeyIdForStaticAccessToken() throws Excep JsonObject createResponse = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/recipe/session", request, 1000, 1000, null, SemVer.v2_21.get(), "session"); - DecodedJWT decodedJWT = JWT.decode(createResponse.get("accessToken").getAsJsonObject().get("token").getAsString()); + DecodedJWT decodedJWT = JWT.decode( + createResponse.get("accessToken").getAsJsonObject().get("token").getAsString()); String keyIdFromHeader = decodedJWT.getHeaderClaim("kid").asString(); JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/recipe/jwt/jwks", null, 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), + "http://localhost:3567/recipe/jwt/jwks", null, 1000, 1000, null, + Utils.getCdiVersionStringLatestForTests(), "jwt"); JsonArray keys = response.getAsJsonArray("keys"); diff --git a/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_9.java b/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_9.java index fa328ae55..44acf84f3 100644 --- a/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_9.java +++ b/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_9.java @@ -62,7 +62,7 @@ public void beforeEach() { */ @Test public void testThatGettingKeysAfterCreatingJWTDoesNotReturnEmpty() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -92,7 +92,7 @@ public void testThatGettingKeysAfterCreatingJWTDoesNotReturnEmpty() throws Excep */ @Test public void testThatKeysContainsMatchingKeyId() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -139,7 +139,7 @@ public void testThatKeysContainsMatchingKeyId() throws Exception { */ @Test public void testThatKeyFromResponseCanBeUsedForJWTVerification() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_21.java b/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_21.java index 943a8f218..53a984c5c 100644 --- a/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_21.java +++ b/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_21.java @@ -49,7 +49,7 @@ public void beforeEach() { @Test public void testThatStaticSignedJWTHasValidHeader() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -84,7 +84,7 @@ public void testThatStaticSignedJWTHasValidHeader() throws Exception { @Test public void testThatDynamicSignedJWTHasValidHeader() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_9.java b/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_9.java index 382680608..794dbfeb0 100644 --- a/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_9.java +++ b/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_9.java @@ -60,7 +60,7 @@ public void beforeEach() { */ @Test public void testThatNullAlgorithmThrowsError() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -89,7 +89,7 @@ public void testThatNullAlgorithmThrowsError() throws Exception { */ @Test public void testThatWrongAlgorithmReturnsUnsupportedError() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -114,7 +114,7 @@ public void testThatWrongAlgorithmReturnsUnsupportedError() throws Exception { */ @Test public void testThatNullJwksDomainThrowsError() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -143,7 +143,7 @@ public void testThatNullJwksDomainThrowsError() throws Exception { */ @Test public void testThatNullPayloadThrowsError() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -171,7 +171,7 @@ public void testThatNullPayloadThrowsError() throws Exception { */ @Test public void testThatNonJSONParseablePayloadThrowsError() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -200,7 +200,7 @@ public void testThatNonJSONParseablePayloadThrowsError() throws Exception { */ @Test public void testThatNullValidityThrowsError() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -229,7 +229,7 @@ public void testThatNullValidityThrowsError() throws Exception { */ @Test public void testThatNegativeValidityThrowsError() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -259,7 +259,7 @@ public void testThatNegativeValidityThrowsError() throws Exception { */ @Test public void testThatCallingWithValidParamsSucceeds() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -286,7 +286,7 @@ public void testThatCallingWithValidParamsSucceeds() throws Exception { */ @Test public void testThatReturnedJWTHasValidHeader() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -322,7 +322,7 @@ public void testThatReturnedJWTHasValidHeader() throws Exception { */ @Test public void testThatDecodedJWTHasCustomPayload() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -358,7 +358,7 @@ public void testThatDecodedJWTHasCustomPayload() throws Exception { */ @Test public void testThatComplexJsonForCustomPayloadWorksFine() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/mfa/api/CreatePrimaryUserAPITest.java b/src/test/java/io/supertokens/test/mfa/api/CreatePrimaryUserAPITest.java index c53bb1e2b..2b80f332d 100644 --- a/src/test/java/io/supertokens/test/mfa/api/CreatePrimaryUserAPITest.java +++ b/src/test/java/io/supertokens/test/mfa/api/CreatePrimaryUserAPITest.java @@ -273,7 +273,8 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", @@ -318,7 +319,8 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccount() throws Ex "pass1234"); AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + emailPasswordUser1.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -358,7 +360,8 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU "pass1234"); UserIdMapping.createUserIdMapping(process.main, emailPasswordUser.getSupertokensUserId(), "r1", null, false); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", @@ -404,7 +407,8 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa "pass1234"); AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + emailPasswordUser1.getSupertokensUserId()); { JsonObject params = new JsonObject(); diff --git a/src/test/java/io/supertokens/test/mfa/api/LinkAccountsAPITest.java b/src/test/java/io/supertokens/test/mfa/api/LinkAccountsAPITest.java index 2743c25fa..07a803d0a 100644 --- a/src/test/java/io/supertokens/test/mfa/api/LinkAccountsAPITest.java +++ b/src/test/java/io/supertokens/test/mfa/api/LinkAccountsAPITest.java @@ -275,7 +275,8 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", @@ -326,18 +327,21 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser "pass1234"); UserIdMapping.createUserIdMapping(process.main, emailPasswordUser.getSupertokensUserId(), "e1", null, false); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", "test2@example.com"); - UserIdMapping.createUserIdMapping(process.main, signInUpResponse.user.getSupertokensUserId(), "e2", null, false); + UserIdMapping.createUserIdMapping(process.main, signInUpResponse.user.getSupertokensUserId(), "e2", null, + false); AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); ThirdParty.SignInUpResponse signInUpResponse2 = ThirdParty.signInUp(process.main, "fb", "user-fb", "test@example.com"); - UserIdMapping.createUserIdMapping(process.main, signInUpResponse2.user.getSupertokensUserId(), "e3", null, false); + UserIdMapping.createUserIdMapping(process.main, signInUpResponse2.user.getSupertokensUserId(), "e3", null, + false); { @@ -380,7 +384,8 @@ public void linkingUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exceptio "pass1234"); AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); @@ -431,7 +436,8 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa UserIdMapping.createUserIdMapping(process.main, emailPasswordUser2.getSupertokensUserId(), "r2", null, false); AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); @@ -599,7 +605,8 @@ public void linkingUserFailsCauseAlreadyLinkedToAnotherAccountReturnsUserObject( "pass1234"); AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); diff --git a/src/test/java/io/supertokens/test/multitenant/AppTenantUserTest.java b/src/test/java/io/supertokens/test/multitenant/AppTenantUserTest.java index aec8e8dff..0dc0f0565 100644 --- a/src/test/java/io/supertokens/test/multitenant/AppTenantUserTest.java +++ b/src/test/java/io/supertokens/test/multitenant/AppTenantUserTest.java @@ -224,7 +224,8 @@ null, null, new JsonObject() continue; } - AuthRecipeUserInfo user = EmailPassword.signUp(app, appStorage, process.getProcess(), "test@example.com", "password"); + AuthRecipeUserInfo user = EmailPassword.signUp(app, appStorage, process.getProcess(), "test@example.com", + "password"); String userId = user.getSupertokensUserId(); Multitenancy.addUserIdToTenant(process.getProcess(), tenant, tenantStorage, userId); @@ -292,7 +293,8 @@ null, null, new JsonObject() Storage tenantStorage = ( StorageLayer.getStorage(tenant, process.getProcess())); - AuthRecipeUserInfo user = EmailPassword.signUp(tenant, tenantStorage, process.getProcess(), "test@example.com", "password"); + AuthRecipeUserInfo user = EmailPassword.signUp(tenant, tenantStorage, process.getProcess(), "test@example.com", + "password"); String userId = user.getSupertokensUserId(); Multitenancy.deleteTenant(tenant, process.getProcess()); diff --git a/src/test/java/io/supertokens/test/multitenant/ConfigTest.java b/src/test/java/io/supertokens/test/multitenant/ConfigTest.java index 042000504..ee4a14e44 100644 --- a/src/test/java/io/supertokens/test/multitenant/ConfigTest.java +++ b/src/test/java/io/supertokens/test/multitenant/ConfigTest.java @@ -690,7 +690,8 @@ public void testInvalidCasesOfTenantCreation() ); fail(); } catch (BadPermissionException e) { - assertEquals("You must use the default or same connectionUriDomain to create/update a connectionUriDomain", e.getMessage()); + assertEquals("You must use the default or same connectionUriDomain to create/update a connectionUriDomain", + e.getMessage()); } try { @@ -1123,13 +1124,13 @@ public void testConfigNormalisation() throws Exception { CoreConfig coreConfig = Config.getConfig(tenantIdentifier, process.getProcess()); // Check for previous value in the hierarchy - assertEquals((i+1) * 1000, coreConfig.getEmailVerificationTokenLifetime()); + assertEquals((i + 1) * 1000, coreConfig.getEmailVerificationTokenLifetime()); } { // set a new value and test that it works JsonObject coreConfigJson = new JsonObject(); - coreConfigJson.addProperty("email_verification_token_lifetime", (i+2) * 1000); + coreConfigJson.addProperty("email_verification_token_lifetime", (i + 2) * 1000); StorageLayer.getStorage(new TenantIdentifier(null, null, null), process.getProcess()) .modifyConfigToAddANewUserPoolForTesting(coreConfigJson, 1); @@ -1142,7 +1143,7 @@ public void testConfigNormalisation() throws Exception { ), false); CoreConfig coreConfig2 = Config.getConfig(tenantIdentifier, process.getProcess()); - assertEquals((i+2) * 1000, coreConfig2.getEmailVerificationTokenLifetime()); + assertEquals((i + 2) * 1000, coreConfig2.getEmailVerificationTokenLifetime()); } } @@ -1431,13 +1432,14 @@ public void testThatConfigChangesInAppReloadsConfigInTenant() throws Exception { new ThirdPartyConfig(true, null), new PasswordlessConfig(true), null, null, coreConfig - ), false);Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), new TenantConfig( - t1, - new EmailPasswordConfig(true), - new ThirdPartyConfig(true, null), - new PasswordlessConfig(true), - null, null, coreConfig - ), false); + ), false); + Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), new TenantConfig( + t1, + new EmailPasswordConfig(true), + new ThirdPartyConfig(true, null), + new PasswordlessConfig(true), + null, null, coreConfig + ), false); assertNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.TENANTS_CHANGED_DURING_REFRESH_FROM_DB)); @@ -1652,7 +1654,8 @@ public void testThatConfigChangesReloadsSigningKeys() throws Exception { { ProcessState.getInstance(process.getProcess()).clear(); - AccessTokenSigningKey accessTokenSigningKeyBefore = AccessTokenSigningKey.getInstance(t1, process.getProcess()); + AccessTokenSigningKey accessTokenSigningKeyBefore = AccessTokenSigningKey.getInstance(t1, + process.getProcess()); RefreshTokenKey refreshTokenKeyBefore = RefreshTokenKey.getInstance(t1, process.getProcess()); JWTSigningKey jwtSigningKeyBefore = JWTSigningKey.getInstance(t1, process.getProcess()); SigningKeys signingKeysBefore = SigningKeys.getInstance(t1, process.getProcess()); @@ -1668,7 +1671,8 @@ public void testThatConfigChangesReloadsSigningKeys() throws Exception { assertNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.TENANTS_CHANGED_DURING_REFRESH_FROM_DB)); - AccessTokenSigningKey accessTokenSigningKeyAfter = AccessTokenSigningKey.getInstance(t1, process.getProcess()); + AccessTokenSigningKey accessTokenSigningKeyAfter = AccessTokenSigningKey.getInstance(t1, + process.getProcess()); RefreshTokenKey refreshTokenKeyAfter = RefreshTokenKey.getInstance(t1, process.getProcess()); JWTSigningKey jwtSigningKeyAfter = JWTSigningKey.getInstance(t1, process.getProcess()); SigningKeys signingKeysAfter = SigningKeys.getInstance(t1, process.getProcess()); @@ -1680,7 +1684,8 @@ public void testThatConfigChangesReloadsSigningKeys() throws Exception { } { - AccessTokenSigningKey accessTokenSigningKeyBefore = AccessTokenSigningKey.getInstance(t1, process.getProcess()); + AccessTokenSigningKey accessTokenSigningKeyBefore = AccessTokenSigningKey.getInstance(t1, + process.getProcess()); RefreshTokenKey refreshTokenKeyBefore = RefreshTokenKey.getInstance(t1, process.getProcess()); JWTSigningKey jwtSigningKeyBefore = JWTSigningKey.getInstance(t1, process.getProcess()); SigningKeys signingKeysBefore = SigningKeys.getInstance(t1, process.getProcess()); @@ -1695,7 +1700,8 @@ public void testThatConfigChangesReloadsSigningKeys() throws Exception { null, null, coreConfig ), false); - AccessTokenSigningKey accessTokenSigningKeyAfter = AccessTokenSigningKey.getInstance(t1, process.getProcess()); + AccessTokenSigningKey accessTokenSigningKeyAfter = AccessTokenSigningKey.getInstance(t1, + process.getProcess()); RefreshTokenKey refreshTokenKeyAfter = RefreshTokenKey.getInstance(t1, process.getProcess()); JWTSigningKey jwtSigningKeyAfter = JWTSigningKey.getInstance(t1, process.getProcess()); SigningKeys signingKeysAfter = SigningKeys.getInstance(t1, process.getProcess()); @@ -1781,15 +1787,18 @@ public void testLoadAllTenantConfigWithDifferentConfigSavedInTheDb() throws Exce assertEquals( 300, - Config.getConfig(new TenantIdentifier(null, "a2", null), process.getProcess()).getEmailVerificationTokenLifetime() + Config.getConfig(new TenantIdentifier(null, "a2", null), process.getProcess()) + .getEmailVerificationTokenLifetime() ); assertEquals( 400, - Config.getConfig(new TenantIdentifier(null, "a2", "t1"), process.getProcess()).getEmailVerificationTokenLifetime() + Config.getConfig(new TenantIdentifier(null, "a2", "t1"), process.getProcess()) + .getEmailVerificationTokenLifetime() ); assertEquals( 100, - Config.getConfig(new TenantIdentifier(null, "a1", null), process.getProcess()).getEmailVerificationTokenLifetime() + Config.getConfig(new TenantIdentifier(null, "a1", null), process.getProcess()) + .getEmailVerificationTokenLifetime() ); process.kill(); @@ -1937,7 +1946,7 @@ public void testAllConflictingConfigs() throws Exception { process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); - for (int i=0; i> uniqueUserPoolIdsTenants = StorageLayer.getTenantsWithUniqueUserPoolId(process.getProcess()); - Cronjobs.addCronjob(process.getProcess(), LoadOnlyCUDTest.PerAppCronjob.getInstance(process.getProcess(), uniqueUserPoolIdsTenants)); + List> uniqueUserPoolIdsTenants = StorageLayer.getTenantsWithUniqueUserPoolId( + process.getProcess()); + Cronjobs.addCronjob(process.getProcess(), + LoadOnlyCUDTest.PerAppCronjob.getInstance(process.getProcess(), uniqueUserPoolIdsTenants)); Thread.sleep(3000); - Set appIdentifiersFromCron = PerAppCronjob.getInstance(process.getProcess(), uniqueUserPoolIdsTenants).appIdentifiers; + Set appIdentifiersFromCron = PerAppCronjob.getInstance(process.getProcess(), + uniqueUserPoolIdsTenants).appIdentifiers; assertEquals(2, appIdentifiersFromCron.size()); for (AppIdentifier app : appIdentifiersFromCron) { assertNotEquals("localhost.org", app.getConnectionUriDomain()); @@ -256,10 +259,12 @@ private PerAppCronjob(Main main, List> tenantsInfo) { public static LoadOnlyCUDTest.PerAppCronjob getInstance(Main main, List> tenantsInfo) { try { - return (LoadOnlyCUDTest.PerAppCronjob) main.getResourceDistributor().getResource(new TenantIdentifier(null, null, null), RESOURCE_ID); + return (LoadOnlyCUDTest.PerAppCronjob) main.getResourceDistributor() + .getResource(new TenantIdentifier(null, null, null), RESOURCE_ID); } catch (TenantOrAppNotFoundException e) { return (LoadOnlyCUDTest.PerAppCronjob) main.getResourceDistributor() - .setResource(new TenantIdentifier(null, null, null), RESOURCE_ID, new LoadOnlyCUDTest.PerAppCronjob(main, tenantsInfo)); + .setResource(new TenantIdentifier(null, null, null), RESOURCE_ID, + new LoadOnlyCUDTest.PerAppCronjob(main, tenantsInfo)); } } diff --git a/src/test/java/io/supertokens/test/multitenant/LogTest.java b/src/test/java/io/supertokens/test/multitenant/LogTest.java index 073848b24..5c3e1ea10 100644 --- a/src/test/java/io/supertokens/test/multitenant/LogTest.java +++ b/src/test/java/io/supertokens/test/multitenant/LogTest.java @@ -146,7 +146,8 @@ public void testLogThatEachLineIsUniqueOnStartup() throws Exception { uniqueLines.add(line); } - assertEquals(uniqueLines.size(), lines.length - 1); // we have 1 repeating line which initialises connection pool + assertEquals(uniqueLines.size(), + lines.length - 1); // we have 1 repeating line which initialises connection pool assertEquals(7, Multitenancy.getAllTenants(process.getProcess()).length); diff --git a/src/test/java/io/supertokens/test/multitenant/RequestConnectionUriDomainTest.java b/src/test/java/io/supertokens/test/multitenant/RequestConnectionUriDomainTest.java index 16612be7c..e86800142 100644 --- a/src/test/java/io/supertokens/test/multitenant/RequestConnectionUriDomainTest.java +++ b/src/test/java/io/supertokens/test/multitenant/RequestConnectionUriDomainTest.java @@ -144,14 +144,16 @@ public void basicTestingWithDifferentAPIKey() StorageLayer.getStorage(new TenantIdentifier(null, null, null), process.getProcess()) .modifyConfigToAddANewUserPoolForTesting(tenant2Config, 3); - Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), new TenantConfig(new TenantIdentifier("localhost", null, null), new EmailPasswordConfig(false), + Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), + new TenantConfig(new TenantIdentifier("localhost", null, null), new EmailPasswordConfig(false), new ThirdPartyConfig(false, new ThirdPartyConfig.Provider[0]), new PasswordlessConfig(false), - null, null, tenantConfig), false); - Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), new TenantConfig(new TenantIdentifier("127.0.0.1", null, null), new EmailPasswordConfig(false), + null, null, tenantConfig), false); + Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), + new TenantConfig(new TenantIdentifier("127.0.0.1", null, null), new EmailPasswordConfig(false), new ThirdPartyConfig(false, new ThirdPartyConfig.Provider[0]), new PasswordlessConfig(false), - null, null, tenant2Config), false); + null, null, tenant2Config), false); Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { diff --git a/src/test/java/io/supertokens/test/multitenant/StorageLayerTest.java b/src/test/java/io/supertokens/test/multitenant/StorageLayerTest.java index d8067cada..8f33ec1b5 100644 --- a/src/test/java/io/supertokens/test/multitenant/StorageLayerTest.java +++ b/src/test/java/io/supertokens/test/multitenant/StorageLayerTest.java @@ -40,7 +40,10 @@ import org.junit.rules.TestRule; import java.io.IOException; -import java.util.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @@ -779,7 +782,8 @@ null, null, new JsonObject() "https://auth.example.com", true, new ThirdPartyConfig.UserInfoMap( - new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", "email_verified1"), + new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", + "email_verified1"), new ThirdPartyConfig.UserInfoMapKeyValue("id2", "email2", "email_verified2") ) ) @@ -889,7 +893,8 @@ public void testOverwriteTenantOfNonExistantTenantThrowsTenantOrAppNotFoundExcep "https://auth.example.com", true, new ThirdPartyConfig.UserInfoMap( - new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", "email_verified1"), + new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", + "email_verified1"), new ThirdPartyConfig.UserInfoMapKeyValue("id2", "email2", "email_verified2") ) ) @@ -964,7 +969,8 @@ public void testCreateTenantWithDuplicateProviderIdThrowsException() "https://auth.example.com", true, new ThirdPartyConfig.UserInfoMap( - new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", "email_verified1"), + new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", + "email_verified1"), new ThirdPartyConfig.UserInfoMapKeyValue("id2", "email2", "email_verified2") ) ), @@ -992,7 +998,8 @@ public void testCreateTenantWithDuplicateProviderIdThrowsException() "https://auth.example.com", true, new ThirdPartyConfig.UserInfoMap( - new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", "email_verified1"), + new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", + "email_verified1"), new ThirdPartyConfig.UserInfoMapKeyValue("id2", "email2", "email_verified2") ) ) @@ -1068,7 +1075,8 @@ public void testCreateDuplicateTenantWithDuplicateProviderIdThrowsDuplicateTenan "https://auth.example.com", true, new ThirdPartyConfig.UserInfoMap( - new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", "email_verified1"), + new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", + "email_verified1"), new ThirdPartyConfig.UserInfoMapKeyValue("id2", "email2", "email_verified2") ) ) @@ -1109,7 +1117,8 @@ null, null, new JsonObject() "https://auth.example.com", true, new ThirdPartyConfig.UserInfoMap( - new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", "email_verified1"), + new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", + "email_verified1"), new ThirdPartyConfig.UserInfoMapKeyValue("id2", "email2", "email_verified2") ) ), @@ -1137,7 +1146,8 @@ null, null, new JsonObject() "https://auth.example.com", true, new ThirdPartyConfig.UserInfoMap( - new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", "email_verified1"), + new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", + "email_verified1"), new ThirdPartyConfig.UserInfoMapKeyValue("id2", "email2", "email_verified2") ) ) @@ -1213,7 +1223,8 @@ public void testCreateDuplicateTenantWithDuplicateProviderClientTypeThrowsDuplic "https://auth.example.com", true, new ThirdPartyConfig.UserInfoMap( - new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", "email_verified1"), + new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", + "email_verified1"), new ThirdPartyConfig.UserInfoMapKeyValue("id2", "email2", "email_verified2") ) ) @@ -1262,7 +1273,8 @@ null, null, new JsonObject() "https://auth.example.com", true, new ThirdPartyConfig.UserInfoMap( - new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", "email_verified1"), + new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", + "email_verified1"), new ThirdPartyConfig.UserInfoMapKeyValue("id2", "email2", "email_verified2") ) ) @@ -1346,7 +1358,8 @@ public void testCreateTenantWithDuplicateClientTypeThrowsException() "https://auth.example.com", true, new ThirdPartyConfig.UserInfoMap( - new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", "email_verified1"), + new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", + "email_verified1"), new ThirdPartyConfig.UserInfoMapKeyValue("id2", "email2", "email_verified2") ) ), @@ -1374,7 +1387,8 @@ public void testCreateTenantWithDuplicateClientTypeThrowsException() "https://auth.example.com", true, new ThirdPartyConfig.UserInfoMap( - new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", "email_verified1"), + new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", + "email_verified1"), new ThirdPartyConfig.UserInfoMapKeyValue("id2", "email2", "email_verified2") ) ) @@ -1450,7 +1464,8 @@ public void testOverwriteTenantWithDuplicateProviderIdThrowsException() "https://auth.example.com", true, new ThirdPartyConfig.UserInfoMap( - new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", "email_verified1"), + new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", + "email_verified1"), new ThirdPartyConfig.UserInfoMapKeyValue("id2", "email2", "email_verified2") ) ), @@ -1478,7 +1493,8 @@ public void testOverwriteTenantWithDuplicateProviderIdThrowsException() "https://auth.example.com", true, new ThirdPartyConfig.UserInfoMap( - new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", "email_verified1"), + new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", + "email_verified1"), new ThirdPartyConfig.UserInfoMapKeyValue("id2", "email2", "email_verified2") ) ) @@ -1562,7 +1578,8 @@ public void testOverwriteTenantWithDuplicateClientTypeThrowsException() "https://auth.example.com", true, new ThirdPartyConfig.UserInfoMap( - new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", "email_verified1"), + new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", + "email_verified1"), new ThirdPartyConfig.UserInfoMapKeyValue("id2", "email2", "email_verified2") ) ), @@ -1590,7 +1607,8 @@ public void testOverwriteTenantWithDuplicateClientTypeThrowsException() "https://auth.example.com", true, new ThirdPartyConfig.UserInfoMap( - new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", "email_verified1"), + new ThirdPartyConfig.UserInfoMapKeyValue("id1", "email1", + "email_verified1"), new ThirdPartyConfig.UserInfoMapKeyValue("id2", "email2", "email_verified2") ) ) @@ -1689,7 +1707,9 @@ null, null, new JsonObject() )); break; } catch (Exception e) { - if (e.getMessage().toLowerCase().contains("request timed out") || e.getMessage().contains("concurrent delete") || e.getMessage().contains("concurrent update")) { + if (e.getMessage().toLowerCase().contains("request timed out") || + e.getMessage().contains("concurrent delete") || + e.getMessage().contains("concurrent update")) { // retry, because connection was timed out, or // in case of postgres, number of retries may not be enough, we retry here anyway continue; @@ -1962,12 +1982,14 @@ public void testStorageDoesNotLoadAgainAfterTenantDeletionWhenRefreshedFromDb() ), false); - String userPoolId = StorageLayer.getStorage(new TenantIdentifier(null, null, "t1"), process.getProcess()).getUserPoolId(); + String userPoolId = StorageLayer.getStorage(new TenantIdentifier(null, null, "t1"), process.getProcess()) + .getUserPoolId(); { Set userPoolIds = new HashSet<>(); - Map existingStorages = process.getProcess() - .getResourceDistributor().getAllResourcesWithResourceKey(StorageLayer.RESOURCE_KEY); + Map existingStorages = + process.getProcess() + .getResourceDistributor().getAllResourcesWithResourceKey(StorageLayer.RESOURCE_KEY); for (ResourceDistributor.SingletonResource sl : existingStorages.values()) { userPoolIds.add(((StorageLayer) sl).getUnderlyingStorage().getUserPoolId()); @@ -1976,12 +1998,14 @@ public void testStorageDoesNotLoadAgainAfterTenantDeletionWhenRefreshedFromDb() } Multitenancy.deleteTenant(new TenantIdentifier(null, null, "t1"), process.getProcess()); - MultitenancyHelper.getInstance(process.getProcess()).refreshTenantsInCoreBasedOnChangesInCoreConfigOrIfTenantListChanged(true); + MultitenancyHelper.getInstance(process.getProcess()) + .refreshTenantsInCoreBasedOnChangesInCoreConfigOrIfTenantListChanged(true); { Set userPoolIds = new HashSet<>(); - Map existingStorages = process.getProcess() - .getResourceDistributor().getAllResourcesWithResourceKey(StorageLayer.RESOURCE_KEY); + Map existingStorages = + process.getProcess() + .getResourceDistributor().getAllResourcesWithResourceKey(StorageLayer.RESOURCE_KEY); for (ResourceDistributor.SingletonResource sl : existingStorages.values()) { userPoolIds.add(((StorageLayer) sl).getUnderlyingStorage().getUserPoolId()); @@ -1990,12 +2014,14 @@ public void testStorageDoesNotLoadAgainAfterTenantDeletionWhenRefreshedFromDb() } Multitenancy.deleteTenant(new TenantIdentifier(null, null, "t2"), process.getProcess()); - MultitenancyHelper.getInstance(process.getProcess()).refreshTenantsInCoreBasedOnChangesInCoreConfigOrIfTenantListChanged(true); + MultitenancyHelper.getInstance(process.getProcess()) + .refreshTenantsInCoreBasedOnChangesInCoreConfigOrIfTenantListChanged(true); { Set userPoolIds = new HashSet<>(); - Map existingStorages = process.getProcess() - .getResourceDistributor().getAllResourcesWithResourceKey(StorageLayer.RESOURCE_KEY); + Map existingStorages = + process.getProcess() + .getResourceDistributor().getAllResourcesWithResourceKey(StorageLayer.RESOURCE_KEY); for (ResourceDistributor.SingletonResource sl : existingStorages.values()) { userPoolIds.add(((StorageLayer) sl).getUnderlyingStorage().getUserPoolId()); @@ -2008,7 +2034,8 @@ public void testStorageDoesNotLoadAgainAfterTenantDeletionWhenRefreshedFromDb() } @Test - public void testThatOriginalStorageIsNotClosedIfTheStorageForATenantChangesAndTheOriginalStorageIsUsedByAnotherTenant() throws Exception { + public void testThatOriginalStorageIsNotClosedIfTheStorageForATenantChangesAndTheOriginalStorageIsUsedByAnotherTenant() + throws Exception { String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); diff --git a/src/test/java/io/supertokens/test/multitenant/TestAppData.java b/src/test/java/io/supertokens/test/multitenant/TestAppData.java index 4f2b33f89..dd2315aed 100644 --- a/src/test/java/io/supertokens/test/multitenant/TestAppData.java +++ b/src/test/java/io/supertokens/test/multitenant/TestAppData.java @@ -104,7 +104,8 @@ public void testThatDeletingAppDeleteDataFromAllTables() throws Exception { return; } - String[] tablesToIgnore = new String[]{"tenant_thirdparty_provider_clients", "tenant_thirdparty_providers", "tenant_first_factors", "tenant_required_secondary_factors"}; + String[] tablesToIgnore = new String[]{"tenant_thirdparty_provider_clients", "tenant_thirdparty_providers", + "tenant_first_factors", "tenant_required_secondary_factors"}; TenantIdentifier app = new TenantIdentifier(null, "a1", null); diff --git a/src/test/java/io/supertokens/test/multitenant/TestProviderEquality.java b/src/test/java/io/supertokens/test/multitenant/TestProviderEquality.java index 28fc7c7ed..d1e2aeb2a 100644 --- a/src/test/java/io/supertokens/test/multitenant/TestProviderEquality.java +++ b/src/test/java/io/supertokens/test/multitenant/TestProviderEquality.java @@ -37,7 +37,7 @@ public void testProviderEqualityChecksForAllFields() { Constructor constructor = ThirdPartyConfig.Provider.class.getConstructors()[0]; Parameter[] parameters = constructor.getParameters(); Field[] fields = ThirdPartyConfig.Provider.class.getDeclaredFields(); - assert(parameters.length == fields.length); + assert (parameters.length == fields.length); JsonObject baseObject = new JsonObject(); @@ -137,7 +137,7 @@ public void testProviderClientEqualityChecksForAllFields() { Constructor constructor = ThirdPartyConfig.ProviderClient.class.getConstructors()[0]; Parameter[] parameters = constructor.getParameters(); Field[] fields = ThirdPartyConfig.ProviderClient.class.getDeclaredFields(); - assert(parameters.length == fields.length); + assert (parameters.length == fields.length); JsonObject baseObject = new JsonObject(); @@ -193,8 +193,10 @@ private void testProviderClientField(String name, Class type, JsonObject base throw new RuntimeException("Unsupported type"); } - ThirdPartyConfig.ProviderClient providerClient1 = new Gson().fromJson(testObject1, ThirdPartyConfig.ProviderClient.class); - ThirdPartyConfig.ProviderClient providerClient1copy = new Gson().fromJson(testObject1, ThirdPartyConfig.ProviderClient.class); + ThirdPartyConfig.ProviderClient providerClient1 = new Gson().fromJson(testObject1, + ThirdPartyConfig.ProviderClient.class); + ThirdPartyConfig.ProviderClient providerClient1copy = new Gson().fromJson(testObject1, + ThirdPartyConfig.ProviderClient.class); JsonObject testObject2 = new Gson().fromJson(baseObject, JsonObject.class); if (type == String.class) { @@ -213,8 +215,10 @@ private void testProviderClientField(String name, Class type, JsonObject base throw new RuntimeException("Unsupported type"); } - ThirdPartyConfig.ProviderClient providerClient2 = new Gson().fromJson(testObject2, ThirdPartyConfig.ProviderClient.class); - ThirdPartyConfig.ProviderClient providerClient2copy = new Gson().fromJson(testObject2, ThirdPartyConfig.ProviderClient.class); + ThirdPartyConfig.ProviderClient providerClient2 = new Gson().fromJson(testObject2, + ThirdPartyConfig.ProviderClient.class); + ThirdPartyConfig.ProviderClient providerClient2copy = new Gson().fromJson(testObject2, + ThirdPartyConfig.ProviderClient.class); assertNotEquals(providerClient1, providerClient2); assertEquals(providerClient1, providerClient1copy); assertEquals(providerClient2, providerClient2copy); @@ -225,7 +229,7 @@ public void testUserInfoMapEqualityChecksForAllFields() { Constructor constructor = ThirdPartyConfig.UserInfoMap.class.getConstructors()[0]; Parameter[] parameters = constructor.getParameters(); Field[] fields = ThirdPartyConfig.UserInfoMap.class.getDeclaredFields(); - assert(parameters.length == fields.length); + assert (parameters.length == fields.length); JsonObject baseObject = new JsonObject(); @@ -269,8 +273,10 @@ private void testUserInfoMapField(String name, Class type, JsonObject baseObj throw new RuntimeException("Unsupported type"); } - ThirdPartyConfig.UserInfoMap userInfoMap1 = new Gson().fromJson(testObject1, ThirdPartyConfig.UserInfoMap.class); - ThirdPartyConfig.UserInfoMap userInfoMap1copy = new Gson().fromJson(testObject1, ThirdPartyConfig.UserInfoMap.class); + ThirdPartyConfig.UserInfoMap userInfoMap1 = new Gson().fromJson(testObject1, + ThirdPartyConfig.UserInfoMap.class); + ThirdPartyConfig.UserInfoMap userInfoMap1copy = new Gson().fromJson(testObject1, + ThirdPartyConfig.UserInfoMap.class); JsonObject testObject2 = new Gson().fromJson(baseObject, JsonObject.class); if (type == ThirdPartyConfig.UserInfoMapKeyValue.class) { @@ -283,8 +289,10 @@ private void testUserInfoMapField(String name, Class type, JsonObject baseObj throw new RuntimeException("Unsupported type"); } - ThirdPartyConfig.UserInfoMap userInfoMap2 = new Gson().fromJson(testObject2, ThirdPartyConfig.UserInfoMap.class); - ThirdPartyConfig.UserInfoMap userInfoMap2copy = new Gson().fromJson(testObject2, ThirdPartyConfig.UserInfoMap.class); + ThirdPartyConfig.UserInfoMap userInfoMap2 = new Gson().fromJson(testObject2, + ThirdPartyConfig.UserInfoMap.class); + ThirdPartyConfig.UserInfoMap userInfoMap2copy = new Gson().fromJson(testObject2, + ThirdPartyConfig.UserInfoMap.class); assertNotEquals(userInfoMap1, userInfoMap2); assertEquals(userInfoMap1, userInfoMap1copy); assertEquals(userInfoMap2, userInfoMap2copy); @@ -295,7 +303,7 @@ public void testUserInfoMapKeyValueEqualityChecksForAllFields() { Constructor constructor = ThirdPartyConfig.UserInfoMapKeyValue.class.getConstructors()[0]; Parameter[] parameters = constructor.getParameters(); Field[] fields = ThirdPartyConfig.UserInfoMapKeyValue.class.getDeclaredFields(); - assert(parameters.length == fields.length); + assert (parameters.length == fields.length); JsonObject baseObject = new JsonObject(); @@ -331,8 +339,10 @@ private void testUserInfoMapKeyValueField(String name, Class type, JsonObject throw new RuntimeException("Unsupported type"); } - ThirdPartyConfig.UserInfoMapKeyValue userInfoMap1 = new Gson().fromJson(testObject1, ThirdPartyConfig.UserInfoMapKeyValue.class); - ThirdPartyConfig.UserInfoMapKeyValue userInfoMap1copy = new Gson().fromJson(testObject1, ThirdPartyConfig.UserInfoMapKeyValue.class); + ThirdPartyConfig.UserInfoMapKeyValue userInfoMap1 = new Gson().fromJson(testObject1, + ThirdPartyConfig.UserInfoMapKeyValue.class); + ThirdPartyConfig.UserInfoMapKeyValue userInfoMap1copy = new Gson().fromJson(testObject1, + ThirdPartyConfig.UserInfoMapKeyValue.class); JsonObject testObject2 = new Gson().fromJson(baseObject, JsonObject.class); if (type == String.class) { @@ -342,8 +352,10 @@ private void testUserInfoMapKeyValueField(String name, Class type, JsonObject throw new RuntimeException("Unsupported type"); } - ThirdPartyConfig.UserInfoMapKeyValue userInfoMap2 = new Gson().fromJson(testObject2, ThirdPartyConfig.UserInfoMapKeyValue.class); - ThirdPartyConfig.UserInfoMapKeyValue userInfoMap2copy = new Gson().fromJson(testObject2, ThirdPartyConfig.UserInfoMapKeyValue.class); + ThirdPartyConfig.UserInfoMapKeyValue userInfoMap2 = new Gson().fromJson(testObject2, + ThirdPartyConfig.UserInfoMapKeyValue.class); + ThirdPartyConfig.UserInfoMapKeyValue userInfoMap2copy = new Gson().fromJson(testObject2, + ThirdPartyConfig.UserInfoMapKeyValue.class); assertNotEquals(userInfoMap1, userInfoMap2); assertEquals(userInfoMap1, userInfoMap1copy); assertEquals(userInfoMap2, userInfoMap2copy); diff --git a/src/test/java/io/supertokens/test/multitenant/api/GetTenantCoreConfigForDashboardAPITest.java b/src/test/java/io/supertokens/test/multitenant/api/GetTenantCoreConfigForDashboardAPITest.java index c761dabbc..b1a600e11 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/GetTenantCoreConfigForDashboardAPITest.java +++ b/src/test/java/io/supertokens/test/multitenant/api/GetTenantCoreConfigForDashboardAPITest.java @@ -60,7 +60,7 @@ public void beforeEach() { @Test public void testRetrievingConfigProperties() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -77,7 +77,8 @@ public void testRetrievingConfigProperties() throws Exception { JsonArray result = response.get("config").getAsJsonArray(); try { - String[] fields = new String[]{"key", "valueType", "value", "description", "isDifferentAcrossTenants", "possibleValues", "isNullable", "defaultValue", "isPluginProperty", "isPluginPropertyEditable"}; + String[] fields = new String[]{"key", "valueType", "value", "description", "isDifferentAcrossTenants", + "possibleValues", "isNullable", "defaultValue", "isPluginProperty", "isPluginPropertyEditable"}; for (int i = 0; i < result.size(); i++) { JsonObject config = result.get(i).getAsJsonObject(); @@ -112,7 +113,7 @@ public void testRetrievingConfigProperties() throws Exception { @Test public void testMatchConfigPropertiesDescription() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -122,8 +123,8 @@ public void testMatchConfigPropertiesDescription() throws Exception { // we don't have a description for core_config_version // and webserver_https_enabled is not present in the config.yaml file // so we skip these properties. - String[] ignoredProperties = { "access_token_signing_key_update_interval", "core_config_version", - "webserver_https_enabled" }; + String[] ignoredProperties = {"access_token_signing_key_update_interval", "core_config_version", + "webserver_https_enabled"}; // Match the descriptions in the config.yaml file with the descriptions in the // CoreConfig class diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestApp3_0.java b/src/test/java/io/supertokens/test/multitenant/api/TestApp3_0.java index 45aca083d..e970010ee 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestApp3_0.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestApp3_0.java @@ -342,8 +342,10 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } }); - String[] valueForCreate = new String[]{"a1", "a-1", "a-B-1", "CAPS1", "MixedCase", "capsinquery", "mixedcaseinquery"}; - String[] valueForQuery = new String[]{"a1", "a-1", "A-b-1", "CAPS1", "MixedCase", "CAPSINQUERY", "MixedCaseInQuery"}; + String[] valueForCreate = new String[]{"a1", "a-1", "a-B-1", "CAPS1", "MixedCase", "capsinquery", + "mixedcaseinquery"}; + String[] valueForQuery = new String[]{"a1", "a-1", "A-b-1", "CAPS1", "MixedCase", "CAPSINQUERY", + "MixedCaseInQuery"}; if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; @@ -379,7 +381,8 @@ public void testDifferentValuesForAppIdThatShouldNotWork() throws Exception { valueForCreate[i], true, true, true, new JsonObject()); } catch (HttpResponseException e) { - assertTrue(e.getMessage().contains("appId can only contain letters, numbers and hyphens") || e.getMessage().contains("appId must not start with 'appid-'")); + assertTrue(e.getMessage().contains("appId can only contain letters, numbers and hyphens") || + e.getMessage().contains("appId must not start with 'appid-'")); } } } @@ -549,13 +552,25 @@ public void testInvalidTypedValueInCoreConfigWhileCreatingApp() throws Exception }; String[] expectedErrorMessages = new String[]{ - "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type long", // access_token_validity - "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type long", // access_token_validity - "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type long", // access_token_validity + "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type " + + "long", + // access_token_validity + "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type " + + "long", + // access_token_validity + "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type " + + "long", + // access_token_validity null, - "Http error. Status Code: 400. Message: Invalid core config: 'disable_telemetry' must be of type boolean", // disable_telemetry - "Http error. Status Code: 400. Message: Invalid core config: 'postgresql_connection_pool_size' must be of type int", // postgresql_connection_pool_size - "Http error. Status Code: 400. Message: Invalid core config: 'mysql_connection_pool_size' must be of type int", // mysql_connection_pool_size + "Http error. Status Code: 400. Message: Invalid core config: 'disable_telemetry' must be of type " + + "boolean", + // disable_telemetry + "Http error. Status Code: 400. Message: Invalid core config: 'postgresql_connection_pool_size' must " + + "be of type int", + // postgresql_connection_pool_size + "Http error. Status Code: 400. Message: Invalid core config: 'mysql_connection_pool_size' must be of " + + "type int", + // mysql_connection_pool_size }; for (int i = 0; i < properties.length; i++) { @@ -564,8 +579,7 @@ public void testInvalidTypedValueInCoreConfigWhileCreatingApp() throws Exception JsonObject config = new JsonObject(); if (values[i] == null) { config.add(properties[i], null); - } - else if (values[i] instanceof String) { + } else if (values[i] instanceof String) { config.addProperty(properties[i], (String) values[i]); } else if (values[i] instanceof Boolean) { config.addProperty(properties[i], (Boolean) values[i]); @@ -616,14 +630,18 @@ public void testInvalidCoreConfig() throws Exception { fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Invalid core config: 'refresh_token_validity' must be strictly greater than 'access_token_validity'.", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Invalid core config: 'refresh_token_validity' must be" + + " strictly greater than 'access_token_validity'.", + e.getMessage()); } } } - private static JsonObject createApp(Main main, TenantIdentifier sourceTenant, String appId, Boolean emailPasswordEnabled, - Boolean thirdPartyEnabled, Boolean passwordlessEnabled, - JsonObject coreConfig) throws HttpResponseException, IOException { + private static JsonObject createApp(Main main, TenantIdentifier sourceTenant, String appId, + Boolean emailPasswordEnabled, + Boolean thirdPartyEnabled, Boolean passwordlessEnabled, + JsonObject coreConfig) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("appId", appId); if (emailPasswordEnabled != null) { diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestApp5_0.java b/src/test/java/io/supertokens/test/multitenant/api/TestApp5_0.java index 6f50896f3..7e6da758c 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestApp5_0.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestApp5_0.java @@ -344,8 +344,10 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } }); - String[] valueForCreate = new String[]{"a1", "a-1", "a-B-1", "CAPS1", "MixedCase", "capsinquery", "mixedcaseinquery"}; - String[] valueForQuery = new String[]{"a1", "a-1", "A-b-1", "CAPS1", "MixedCase", "CAPSINQUERY", "MixedCaseInQuery"}; + String[] valueForCreate = new String[]{"a1", "a-1", "a-B-1", "CAPS1", "MixedCase", "capsinquery", + "mixedcaseinquery"}; + String[] valueForQuery = new String[]{"a1", "a-1", "A-b-1", "CAPS1", "MixedCase", "CAPSINQUERY", + "MixedCaseInQuery"}; if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; @@ -381,7 +383,8 @@ public void testDifferentValuesForAppIdThatShouldNotWork() throws Exception { valueForCreate[i], true, true, true, new JsonObject()); } catch (HttpResponseException e) { - assertTrue(e.getMessage().contains("appId can only contain letters, numbers and hyphens") || e.getMessage().contains("appId must not start with 'appid-'")); + assertTrue(e.getMessage().contains("appId can only contain letters, numbers and hyphens") || + e.getMessage().contains("appId must not start with 'appid-'")); } } } @@ -551,13 +554,25 @@ public void testInvalidTypedValueInCoreConfigWhileCreatingApp() throws Exception }; String[] expectedErrorMessages = new String[]{ - "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type long", // access_token_validity - "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type long", // access_token_validity - "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type long", // access_token_validity + "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type " + + "long", + // access_token_validity + "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type " + + "long", + // access_token_validity + "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type " + + "long", + // access_token_validity null, - "Http error. Status Code: 400. Message: Invalid core config: 'disable_telemetry' must be of type boolean", // disable_telemetry - "Http error. Status Code: 400. Message: Invalid core config: 'postgresql_connection_pool_size' must be of type int", // postgresql_connection_pool_size - "Http error. Status Code: 400. Message: Invalid core config: 'mysql_connection_pool_size' must be of type int", // mysql_connection_pool_size + "Http error. Status Code: 400. Message: Invalid core config: 'disable_telemetry' must be of type " + + "boolean", + // disable_telemetry + "Http error. Status Code: 400. Message: Invalid core config: 'postgresql_connection_pool_size' must " + + "be of type int", + // postgresql_connection_pool_size + "Http error. Status Code: 400. Message: Invalid core config: 'mysql_connection_pool_size' must be of " + + "type int", + // mysql_connection_pool_size }; for (int i = 0; i < properties.length; i++) { @@ -566,8 +581,7 @@ public void testInvalidTypedValueInCoreConfigWhileCreatingApp() throws Exception JsonObject config = new JsonObject(); if (values[i] == null) { config.add(properties[i], null); - } - else if (values[i] instanceof String) { + } else if (values[i] instanceof String) { config.addProperty(properties[i], (String) values[i]); } else if (values[i] instanceof Boolean) { config.addProperty(properties[i], (Boolean) values[i]); @@ -618,7 +632,10 @@ public void testInvalidCoreConfig() throws Exception { fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Invalid core config: 'refresh_token_validity' must be strictly greater than 'access_token_validity'.", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Invalid core config: 'refresh_token_validity' must be" + + " strictly greater than 'access_token_validity'.", + e.getMessage()); } } } @@ -708,7 +725,8 @@ public void testFirstFactorsArray() throws Exception { assertEquals(7, tenant.entrySet().size()); assertTrue(tenant.get("firstFactors").isJsonArray()); assertEquals(4, tenant.get("firstFactors").getAsJsonArray().size()); - assertEquals(Set.of(firstFactors), Set.of(new Gson().fromJson(tenant.get("firstFactors").getAsJsonArray(), String[].class))); + assertEquals(Set.of(firstFactors), + Set.of(new Gson().fromJson(tenant.get("firstFactors").getAsJsonArray(), String[].class))); response = createApp( process.getProcess(), @@ -760,7 +778,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(7, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); response = createApp( process.getProcess(), @@ -775,7 +794,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(7, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); // custom factors requiredSecondaryFactors = new String[]{"biometric"}; @@ -792,7 +812,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(7, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); // test both requiredSecondaryFactors = new String[]{"otp-phone", "emailpassword", "biometric", "custom"}; @@ -809,7 +830,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(7, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(4, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(Set.of(requiredSecondaryFactors), Set.of(new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class))); + assertEquals(Set.of(requiredSecondaryFactors), + Set.of(new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class))); response = createApp( process.getProcess(), @@ -845,7 +867,9 @@ public void testDuplicateValuesInFirstFactorsAndRequiredSecondaryFactors() throw fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: firstFactors input should not contain duplicate values", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: firstFactors input should not contain duplicate values", + e.getMessage()); } try { @@ -858,7 +882,10 @@ public void testDuplicateValuesInFirstFactorsAndRequiredSecondaryFactors() throw fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: requiredSecondaryFactors input should not contain duplicate values", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: requiredSecondaryFactors input should not contain " + + "duplicate values", + e.getMessage()); } } @@ -872,11 +899,11 @@ public void testFirstFactorArrayValueValidationBasedOnDisabledRecipe() throws Ex StorageLayer.getBaseStorage(process.getProcess()).modifyConfigToAddANewUserPoolForTesting(config, 1); createApp( - process.getProcess(), - new TenantIdentifier(null, null, null), - "a1", true, true, true, - false, null, false, null, - config); + process.getProcess(), + new TenantIdentifier(null, null, null), + "a1", true, true, true, + false, null, false, null, + config); { try { @@ -890,7 +917,8 @@ public void testFirstFactorArrayValueValidationBasedOnDisabledRecipe() throws Ex } catch (HttpResponseException e) { assertEquals(400, e.statusCode); assertEquals( - "Http error. Status Code: 400. Message: firstFactors cannot be empty. Set null instead to remove all first factors.", + "Http error. Status Code: 400. Message: firstFactors cannot be empty. Set null instead to " + + "remove all first factors.", e.getMessage()); } } @@ -907,7 +935,10 @@ public void testFirstFactorArrayValueValidationBasedOnDisabledRecipe() throws Ex fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Invalid core config: firstFactors should not contain 'emailpassword' because emailPassword is disabled for the tenant.", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Invalid core config: firstFactors should not contain " + + "'emailpassword' because emailPassword is disabled for the tenant.", + e.getMessage()); } { @@ -929,7 +960,10 @@ public void testFirstFactorArrayValueValidationBasedOnDisabledRecipe() throws Ex fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Invalid core config: firstFactors should not contain 'emailpassword' because emailPassword is disabled for the tenant.", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Invalid core config: firstFactors should not contain " + + "'emailpassword' because emailPassword is disabled for the tenant.", + e.getMessage()); } } @@ -945,7 +979,10 @@ public void testFirstFactorArrayValueValidationBasedOnDisabledRecipe() throws Ex fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Invalid core config: firstFactors should not contain 'otp-email' because passwordless is disabled for the tenant.", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Invalid core config: firstFactors should not contain " + + "'otp-email' because passwordless is disabled for the tenant.", + e.getMessage()); } { @@ -967,7 +1004,10 @@ public void testFirstFactorArrayValueValidationBasedOnDisabledRecipe() throws Ex fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Invalid core config: firstFactors should not contain 'otp-email' because passwordless is disabled for the tenant.", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Invalid core config: firstFactors should not contain " + + "'otp-email' because passwordless is disabled for the tenant.", + e.getMessage()); } } @@ -983,7 +1023,10 @@ public void testFirstFactorArrayValueValidationBasedOnDisabledRecipe() throws Ex fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Invalid core config: firstFactors should not contain 'thirdparty' because thirdParty is disabled for the tenant.", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Invalid core config: firstFactors should not contain " + + "'thirdparty' because thirdParty is disabled for the tenant.", + e.getMessage()); } { @@ -1005,7 +1048,10 @@ public void testFirstFactorArrayValueValidationBasedOnDisabledRecipe() throws Ex fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Invalid core config: firstFactors should not contain 'thirdparty' because thirdParty is disabled for the tenant.", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Invalid core config: firstFactors should not contain " + + "'thirdparty' because thirdParty is disabled for the tenant.", + e.getMessage()); } } @@ -1039,7 +1085,8 @@ public void testRequiredSecondaryFactorArrayValueValidationBasedOnDisabledRecipe } catch (HttpResponseException e) { assertEquals(400, e.statusCode); assertEquals( - "Http error. Status Code: 400. Message: requiredSecondaryFactors cannot be empty. Set null instead to remove all required secondary factors.", + "Http error. Status Code: 400. Message: requiredSecondaryFactors cannot be empty. Set null " + + "instead to remove all required secondary factors.", e.getMessage()); } } @@ -1056,7 +1103,10 @@ public void testRequiredSecondaryFactorArrayValueValidationBasedOnDisabledRecipe fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Invalid core config: requiredSecondaryFactors should not contain 'emailpassword' because emailPassword is disabled for the tenant.", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Invalid core config: requiredSecondaryFactors should " + + "not contain 'emailpassword' because emailPassword is disabled for the tenant.", + e.getMessage()); } { @@ -1078,7 +1128,10 @@ public void testRequiredSecondaryFactorArrayValueValidationBasedOnDisabledRecipe fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Invalid core config: requiredSecondaryFactors should not contain 'emailpassword' because emailPassword is disabled for the tenant.", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Invalid core config: requiredSecondaryFactors should " + + "not contain 'emailpassword' because emailPassword is disabled for the tenant.", + e.getMessage()); } } @@ -1094,7 +1147,10 @@ public void testRequiredSecondaryFactorArrayValueValidationBasedOnDisabledRecipe fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Invalid core config: requiredSecondaryFactors should not contain 'otp-email' because passwordless is disabled for the tenant.", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Invalid core config: requiredSecondaryFactors should " + + "not contain 'otp-email' because passwordless is disabled for the tenant.", + e.getMessage()); } { @@ -1116,7 +1172,10 @@ public void testRequiredSecondaryFactorArrayValueValidationBasedOnDisabledRecipe fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Invalid core config: requiredSecondaryFactors should not contain 'otp-email' because passwordless is disabled for the tenant.", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Invalid core config: requiredSecondaryFactors should " + + "not contain 'otp-email' because passwordless is disabled for the tenant.", + e.getMessage()); } } @@ -1132,7 +1191,10 @@ public void testRequiredSecondaryFactorArrayValueValidationBasedOnDisabledRecipe fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Invalid core config: requiredSecondaryFactors should not contain 'thirdparty' because thirdParty is disabled for the tenant.", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Invalid core config: requiredSecondaryFactors should " + + "not contain 'thirdparty' because thirdParty is disabled for the tenant.", + e.getMessage()); } { @@ -1154,20 +1216,25 @@ public void testRequiredSecondaryFactorArrayValueValidationBasedOnDisabledRecipe fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Invalid core config: requiredSecondaryFactors should not contain 'thirdparty' because thirdParty is disabled for the tenant.", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Invalid core config: requiredSecondaryFactors should " + + "not contain 'thirdparty' because thirdParty is disabled for the tenant.", + e.getMessage()); } } } - private static JsonObject createApp(Main main, TenantIdentifier sourceTenant, String appId, Boolean emailPasswordEnabled, + private static JsonObject createApp(Main main, TenantIdentifier sourceTenant, String appId, + Boolean emailPasswordEnabled, Boolean thirdPartyEnabled, Boolean passwordlessEnabled, JsonObject coreConfig) throws HttpResponseException, IOException { return createApp(main, sourceTenant, appId, emailPasswordEnabled, thirdPartyEnabled, passwordlessEnabled, false, null, false, null, coreConfig); } - private static JsonObject createApp(Main main, TenantIdentifier sourceTenant, String appId, Boolean emailPasswordEnabled, - Boolean thirdPartyEnabled, Boolean passwordlessEnabled, + private static JsonObject createApp(Main main, TenantIdentifier sourceTenant, String appId, + Boolean emailPasswordEnabled, + Boolean thirdPartyEnabled, Boolean passwordlessEnabled, boolean setFirstFactors, String[] firstFactors, boolean setRequiredSecondaryFactors, String[] requiredSecondaryFactors, JsonObject coreConfig) throws HttpResponseException, IOException { diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestApp5_1.java b/src/test/java/io/supertokens/test/multitenant/api/TestApp5_1.java index c5eb0416f..320231971 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestApp5_1.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestApp5_1.java @@ -334,8 +334,10 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } }); - String[] valueForCreate = new String[]{"a1", "a-1", "a-B-1", "CAPS1", "MixedCase", "capsinquery", "mixedcaseinquery"}; - String[] valueForQuery = new String[]{"a1", "a-1", "A-b-1", "CAPS1", "MixedCase", "CAPSINQUERY", "MixedCaseInQuery"}; + String[] valueForCreate = new String[]{"a1", "a-1", "a-B-1", "CAPS1", "MixedCase", "capsinquery", + "mixedcaseinquery"}; + String[] valueForQuery = new String[]{"a1", "a-1", "A-b-1", "CAPS1", "MixedCase", "CAPSINQUERY", + "MixedCaseInQuery"}; if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; @@ -372,7 +374,8 @@ public void testDifferentValuesForAppIdThatShouldNotWork() throws Exception { valueForCreate[i], true, new String[]{"emailpassword", "thirdparty", "otp-email"}, false, null, new JsonObject()); } catch (HttpResponseException e) { - assertTrue(e.getMessage().contains("appId can only contain letters, numbers and hyphens") || e.getMessage().contains("appId must not start with 'appid-'")); + assertTrue(e.getMessage().contains("appId can only contain letters, numbers and hyphens") || + e.getMessage().contains("appId must not start with 'appid-'")); } } } @@ -534,13 +537,25 @@ public void testInvalidTypedValueInCoreConfigWhileCreatingApp() throws Exception }; String[] expectedErrorMessages = new String[]{ - "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type long", // access_token_validity - "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type long", // access_token_validity - "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type long", // access_token_validity + "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type " + + "long", + // access_token_validity + "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type " + + "long", + // access_token_validity + "Http error. Status Code: 400. Message: Invalid core config: 'access_token_validity' must be of type " + + "long", + // access_token_validity null, - "Http error. Status Code: 400. Message: Invalid core config: 'disable_telemetry' must be of type boolean", // disable_telemetry - "Http error. Status Code: 400. Message: Invalid core config: 'postgresql_connection_pool_size' must be of type int", // postgresql_connection_pool_size - "Http error. Status Code: 400. Message: Invalid core config: 'mysql_connection_pool_size' must be of type int", // mysql_connection_pool_size + "Http error. Status Code: 400. Message: Invalid core config: 'disable_telemetry' must be of type " + + "boolean", + // disable_telemetry + "Http error. Status Code: 400. Message: Invalid core config: 'postgresql_connection_pool_size' must " + + "be of type int", + // postgresql_connection_pool_size + "Http error. Status Code: 400. Message: Invalid core config: 'mysql_connection_pool_size' must be of " + + "type int", + // mysql_connection_pool_size }; for (int i = 0; i < properties.length; i++) { @@ -549,8 +564,7 @@ public void testInvalidTypedValueInCoreConfigWhileCreatingApp() throws Exception JsonObject config = new JsonObject(); if (values[i] == null) { config.add(properties[i], null); - } - else if (values[i] instanceof String) { + } else if (values[i] instanceof String) { config.addProperty(properties[i], (String) values[i]); } else if (values[i] instanceof Boolean) { config.addProperty(properties[i], (Boolean) values[i]); @@ -601,7 +615,10 @@ public void testInvalidCoreConfig() throws Exception { fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Invalid core config: 'refresh_token_validity' must be strictly greater than 'access_token_validity'.", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Invalid core config: 'refresh_token_validity' must be" + + " strictly greater than 'access_token_validity'.", + e.getMessage()); } } } @@ -688,7 +705,8 @@ public void testFirstFactorsArray() throws Exception { assertEquals(5, tenant.entrySet().size()); assertTrue(tenant.get("firstFactors").isJsonArray()); assertEquals(4, tenant.get("firstFactors").getAsJsonArray().size()); - assertEquals(Set.of(firstFactors), Set.of(new Gson().fromJson(tenant.get("firstFactors").getAsJsonArray(), String[].class))); + assertEquals(Set.of(firstFactors), + Set.of(new Gson().fromJson(tenant.get("firstFactors").getAsJsonArray(), String[].class))); response = createApp( process.getProcess(), @@ -738,7 +756,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(5, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); response = createApp( process.getProcess(), @@ -752,7 +771,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(5, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); // custom factors requiredSecondaryFactors = new String[]{"biometric"}; @@ -768,7 +788,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(5, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); // test both requiredSecondaryFactors = new String[]{"otp-phone", "emailpassword", "biometric", "custom"}; @@ -784,7 +805,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(5, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(4, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(Set.of(requiredSecondaryFactors), Set.of(new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class))); + assertEquals(Set.of(requiredSecondaryFactors), + Set.of(new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class))); response = createApp( process.getProcess(), @@ -818,7 +840,9 @@ public void testDuplicateValuesInFirstFactorsAndRequiredSecondaryFactors() throw fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: firstFactors input should not contain duplicate values", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: firstFactors input should not contain duplicate values", + e.getMessage()); } try { @@ -830,7 +854,10 @@ public void testDuplicateValuesInFirstFactorsAndRequiredSecondaryFactors() throw fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: requiredSecondaryFactors input should not contain duplicate values", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: requiredSecondaryFactors input should not contain " + + "duplicate values", + e.getMessage()); } } diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain3_0.java b/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain3_0.java index b523bb367..4418ebd30 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain3_0.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain3_0.java @@ -359,7 +359,7 @@ public void testDeleteConnectionUriDomainWorks() throws Exception { @Test public void testDifferentValuesForCUDThatShouldWork() throws Exception { String[] valueForCreate = new String[]{"localhost:3567", "LOCALHOST:3567", "loCalHost:3567", "127.0.0.1:3567"}; - String[] valueForQuery = new String[]{"localhost:3567", "LOCALHOST:3567", "LOCALhoST:3567", "127.0.0.1:3567"}; + String[] valueForQuery = new String[]{"localhost:3567", "LOCALHOST:3567", "LOCALhoST:3567", "127.0.0.1:3567"}; if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; @@ -428,7 +428,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO @Test public void testCUDsThatAreSame() throws Exception { - String[] valueForCreate = new String[]{"localhost:3567", "LOCALHOST:3567", "loCalHost:3567", "localhost", "localhost:12345"}; + String[] valueForCreate = new String[]{"localhost:3567", "LOCALHOST:3567", "loCalHost:3567", "localhost", + "localhost:12345"}; if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; @@ -511,7 +512,8 @@ public void testDefaultRecipesEnabledWhileCreatingCUD() throws Exception { private static JsonObject createConnectionUriDomain(Main main, TenantIdentifier sourceTenant, String connectionUriDomain, Boolean emailPasswordEnabled, Boolean thirdPartyEnabled, Boolean passwordlessEnabled, - JsonObject coreConfig) throws HttpResponseException, IOException { + JsonObject coreConfig) + throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); if (connectionUriDomain != null) { requestBody.addProperty("connectionUriDomain", connectionUriDomain); @@ -550,13 +552,14 @@ private static JsonObject listConnectionUriDomains(TenantIdentifier sourceTenant } private static JsonObject deleteConnectionUriDomain(TenantIdentifier sourceTenant, String connectionUriDomain, - Main main) + Main main) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("connectionUriDomain", connectionUriDomain); JsonObject response = HttpRequestForTesting.sendJsonPOSTRequest(main, "", - HttpRequestForTesting.getMultitenantUrl(sourceTenant, "/recipe/multitenancy/connectionuridomain/remove"), + HttpRequestForTesting.getMultitenantUrl(sourceTenant, + "/recipe/multitenancy/connectionuridomain/remove"), requestBody, 1000, 2500, null, SemVer.v3_0.get(), "multitenancy"); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_0.java b/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_0.java index eb09f95b1..186f8fafa 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_0.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_0.java @@ -359,7 +359,7 @@ public void testDeleteConnectionUriDomainWorks() throws Exception { @Test public void testDifferentValuesForCUDThatShouldWork() throws Exception { String[] valueForCreate = new String[]{"localhost:3567", "LOCALHOST:3567", "loCalHost:3567", "127.0.0.1:3567"}; - String[] valueForQuery = new String[]{"localhost:3567", "LOCALHOST:3567", "LOCALhoST:3567", "127.0.0.1:3567"}; + String[] valueForQuery = new String[]{"localhost:3567", "LOCALHOST:3567", "LOCALhoST:3567", "127.0.0.1:3567"}; if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; @@ -428,7 +428,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO @Test public void testCUDsThatAreSame() throws Exception { - String[] valueForCreate = new String[]{"localhost:3567", "LOCALHOST:3567", "loCalHost:3567", "localhost", "localhost:12345"}; + String[] valueForCreate = new String[]{"localhost:3567", "LOCALHOST:3567", "loCalHost:3567", "localhost", + "localhost:12345"}; if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; @@ -598,7 +599,8 @@ public void testFirstFactorsArray() throws Exception { assertEquals(7, tenant.entrySet().size()); assertTrue(tenant.get("firstFactors").isJsonArray()); assertEquals(4, tenant.get("firstFactors").getAsJsonArray().size()); - assertEquals(Set.of(firstFactors), Set.of(new Gson().fromJson(tenant.get("firstFactors").getAsJsonArray(), String[].class))); + assertEquals(Set.of(firstFactors), + Set.of(new Gson().fromJson(tenant.get("firstFactors").getAsJsonArray(), String[].class))); response = createConnectionUriDomain( process.getProcess(), @@ -654,7 +656,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(7, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); response = createConnectionUriDomain( process.getProcess(), @@ -669,7 +672,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(7, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); // custom factors requiredSecondaryFactors = new String[]{"biometric"}; @@ -686,7 +690,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(7, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); // test both requiredSecondaryFactors = new String[]{"otp-phone", "emailpassword", "biometric", "custom"}; @@ -703,7 +708,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(7, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(4, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(Set.of(requiredSecondaryFactors), Set.of(new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class))); + assertEquals(Set.of(requiredSecondaryFactors), + Set.of(new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class))); response = createConnectionUriDomain( process.getProcess(), @@ -739,7 +745,9 @@ public void testDuplicateValuesInFirstFactorsAndRequiredSecondaryFactors() throw fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: firstFactors input should not contain duplicate values", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: firstFactors input should not contain duplicate values", + e.getMessage()); } try { @@ -752,15 +760,20 @@ public void testDuplicateValuesInFirstFactorsAndRequiredSecondaryFactors() throw fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: requiredSecondaryFactors input should not contain duplicate values", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: requiredSecondaryFactors input should not contain " + + "duplicate values", + e.getMessage()); } } private static JsonObject createConnectionUriDomain(Main main, TenantIdentifier sourceTenant, String connectionUriDomain, Boolean emailPasswordEnabled, Boolean thirdPartyEnabled, Boolean passwordlessEnabled, - JsonObject coreConfig) throws HttpResponseException, IOException { - return createConnectionUriDomain(main, sourceTenant, connectionUriDomain, emailPasswordEnabled, thirdPartyEnabled, + JsonObject coreConfig) + throws HttpResponseException, IOException { + return createConnectionUriDomain(main, sourceTenant, connectionUriDomain, emailPasswordEnabled, + thirdPartyEnabled, passwordlessEnabled, false, null, false, null, coreConfig); } @@ -768,8 +781,10 @@ private static JsonObject createConnectionUriDomain(Main main, TenantIdentifier String connectionUriDomain, Boolean emailPasswordEnabled, Boolean thirdPartyEnabled, Boolean passwordlessEnabled, boolean setFirstFactors, String[] firstFactors, - boolean setRequiredSecondaryFactors, String[] requiredSecondaryFactors, - JsonObject coreConfig) throws HttpResponseException, IOException { + boolean setRequiredSecondaryFactors, + String[] requiredSecondaryFactors, + JsonObject coreConfig) + throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); if (connectionUriDomain != null) { requestBody.addProperty("connectionUriDomain", connectionUriDomain); @@ -814,13 +829,14 @@ private static JsonObject listConnectionUriDomains(TenantIdentifier sourceTenant } private static JsonObject deleteConnectionUriDomain(TenantIdentifier sourceTenant, String connectionUriDomain, - Main main) + Main main) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("connectionUriDomain", connectionUriDomain); JsonObject response = HttpRequestForTesting.sendJsonPOSTRequest(main, "", - HttpRequestForTesting.getMultitenantUrl(sourceTenant, "/recipe/multitenancy/connectionuridomain/remove"), + HttpRequestForTesting.getMultitenantUrl(sourceTenant, + "/recipe/multitenancy/connectionuridomain/remove"), requestBody, 1000, 2500, null, SemVer.v5_0.get(), "multitenancy"); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_1.java b/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_1.java index 3472893e5..065c3b0d7 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_1.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_1.java @@ -344,7 +344,7 @@ public void testDeleteConnectionUriDomainWorks() throws Exception { @Test public void testDifferentValuesForCUDThatShouldWork() throws Exception { String[] valueForCreate = new String[]{"localhost:3567", "LOCALHOST:3567", "loCalHost:3567", "127.0.0.1:3567"}; - String[] valueForQuery = new String[]{"localhost:3567", "LOCALHOST:3567", "LOCALhoST:3567", "127.0.0.1:3567"}; + String[] valueForQuery = new String[]{"localhost:3567", "LOCALHOST:3567", "LOCALhoST:3567", "127.0.0.1:3567"}; if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; @@ -365,7 +365,7 @@ public void testDifferentValuesForCUDThatShouldWork() throws Exception { this.process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES - .MULTI_TENANCY}); + .MULTI_TENANCY}); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -415,7 +415,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO @Test public void testCUDsThatAreSame() throws Exception { String[] valueForCreate = new String[]{"localhost:3567", "LOCALHOST:3567", "loCalHost:3567", "localhost", - "localhost:12345"}; + "localhost:12345"}; if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; @@ -579,7 +579,8 @@ public void testFirstFactorsArray() throws Exception { assertEquals(5, tenant.entrySet().size()); assertTrue(tenant.get("firstFactors").isJsonArray()); assertEquals(4, tenant.get("firstFactors").getAsJsonArray().size()); - assertEquals(Set.of(firstFactors), Set.of(new Gson().fromJson(tenant.get("firstFactors").getAsJsonArray(), String[].class))); + assertEquals(Set.of(firstFactors), + Set.of(new Gson().fromJson(tenant.get("firstFactors").getAsJsonArray(), String[].class))); response = createConnectionUriDomain( process.getProcess(), @@ -633,7 +634,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(5, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); response = createConnectionUriDomain( process.getProcess(), @@ -647,7 +649,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(5, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); // custom factors requiredSecondaryFactors = new String[]{"biometric"}; @@ -663,7 +666,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(5, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); // test both requiredSecondaryFactors = new String[]{"otp-phone", "emailpassword", "biometric", "custom"}; @@ -679,7 +683,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(5, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(4, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(Set.of(requiredSecondaryFactors), Set.of(new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class))); + assertEquals(Set.of(requiredSecondaryFactors), + Set.of(new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class))); response = createConnectionUriDomain( process.getProcess(), @@ -718,7 +723,9 @@ public void testDuplicateValuesInFirstFactorsAndRequiredSecondaryFactors() throw fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: firstFactors input should not contain duplicate values", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: firstFactors input should not contain duplicate values", + e.getMessage()); } try { @@ -731,15 +738,20 @@ public void testDuplicateValuesInFirstFactorsAndRequiredSecondaryFactors() throw fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: requiredSecondaryFactors input should not contain duplicate values", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: requiredSecondaryFactors input should not contain " + + "duplicate values", + e.getMessage()); } } private static JsonObject createConnectionUriDomain(Main main, TenantIdentifier sourceTenant, String connectionUriDomain, boolean setFirstFactors, String[] firstFactors, - boolean setRequiredSecondaryFactors, String[] requiredSecondaryFactors, - JsonObject coreConfig) throws HttpResponseException, IOException { + boolean setRequiredSecondaryFactors, + String[] requiredSecondaryFactors, + JsonObject coreConfig) + throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); if (connectionUriDomain != null) { requestBody.addProperty("connectionUriDomain", connectionUriDomain); @@ -776,13 +788,14 @@ private static JsonObject listConnectionUriDomains(TenantIdentifier sourceTenant } private static JsonObject deleteConnectionUriDomain(TenantIdentifier sourceTenant, String connectionUriDomain, - Main main) + Main main) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("connectionUriDomain", connectionUriDomain); JsonObject response = HttpRequestForTesting.sendJsonPOSTRequest(main, "", - HttpRequestForTesting.getMultitenantUrl(sourceTenant, "/recipe/multitenancy/connectionuridomain/remove"), + HttpRequestForTesting.getMultitenantUrl(sourceTenant, + "/recipe/multitenancy/connectionuridomain/remove"), requestBody, 1000, 2500, null, SemVer.v5_1.get(), "multitenancy"); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestMultitenancyAPIHelper.java b/src/test/java/io/supertokens/test/multitenant/api/TestMultitenancyAPIHelper.java index 6a836486a..43791e1ce 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestMultitenancyAPIHelper.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestMultitenancyAPIHelper.java @@ -35,19 +35,25 @@ import static org.junit.Assert.assertEquals; public class TestMultitenancyAPIHelper { - public static JsonObject createConnectionUriDomain(Main main, TenantIdentifier sourceTenant, String connectionUriDomain, Boolean emailPasswordEnabled, + public static JsonObject createConnectionUriDomain(Main main, TenantIdentifier sourceTenant, + String connectionUriDomain, Boolean emailPasswordEnabled, Boolean thirdPartyEnabled, Boolean passwordlessEnabled, - JsonObject coreConfig) throws HttpResponseException, IOException { - return createConnectionUriDomain(main, sourceTenant, connectionUriDomain, emailPasswordEnabled, thirdPartyEnabled, + JsonObject coreConfig) + throws HttpResponseException, IOException { + return createConnectionUriDomain(main, sourceTenant, connectionUriDomain, emailPasswordEnabled, + thirdPartyEnabled, passwordlessEnabled, false, null, false, null, coreConfig, SemVer.v3_0); } - public static JsonObject createConnectionUriDomain(Main main, TenantIdentifier sourceTenant, String connectionUriDomain, Boolean emailPasswordEnabled, + public static JsonObject createConnectionUriDomain(Main main, TenantIdentifier sourceTenant, + String connectionUriDomain, Boolean emailPasswordEnabled, Boolean thirdPartyEnabled, Boolean passwordlessEnabled, boolean setFirstFactors, String[] firstFactors, - boolean setRequiredSecondaryFactors, String[] requiredSecondaryFactors, - JsonObject coreConfig, SemVer version) throws HttpResponseException, IOException { + boolean setRequiredSecondaryFactors, + String[] requiredSecondaryFactors, + JsonObject coreConfig, SemVer version) + throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); if (connectionUriDomain != null) { requestBody.addProperty("connectionUriDomain", connectionUriDomain); @@ -98,7 +104,8 @@ public static JsonObject deleteConnectionUriDomain(TenantIdentifier sourceTenant requestBody.addProperty("connectionUriDomain", connectionUriDomain); JsonObject response = HttpRequestForTesting.sendJsonPOSTRequest(main, "", - HttpRequestForTesting.getMultitenantUrl(sourceTenant, "/recipe/multitenancy/connectionuridomain/remove"), + HttpRequestForTesting.getMultitenantUrl(sourceTenant, + "/recipe/multitenancy/connectionuridomain/remove"), requestBody, 1000, 2500, null, SemVer.v3_0.get(), "multitenancy"); @@ -106,18 +113,21 @@ public static JsonObject deleteConnectionUriDomain(TenantIdentifier sourceTenant return response; } - public static JsonObject createApp(Main main, TenantIdentifier sourceTenant, String appId, Boolean emailPasswordEnabled, + public static JsonObject createApp(Main main, TenantIdentifier sourceTenant, String appId, + Boolean emailPasswordEnabled, Boolean thirdPartyEnabled, Boolean passwordlessEnabled, JsonObject coreConfig) throws HttpResponseException, IOException { return createApp(main, sourceTenant, appId, emailPasswordEnabled, thirdPartyEnabled, passwordlessEnabled, false, null, false, null, coreConfig, SemVer.v3_0); } - public static JsonObject createApp(Main main, TenantIdentifier sourceTenant, String appId, Boolean emailPasswordEnabled, + public static JsonObject createApp(Main main, TenantIdentifier sourceTenant, String appId, + Boolean emailPasswordEnabled, Boolean thirdPartyEnabled, Boolean passwordlessEnabled, boolean setFirstFactors, String[] firstFactors, boolean setRequiredSecondaryFactors, String[] requiredSecondaryFactors, - JsonObject coreConfig, SemVer version) throws HttpResponseException, IOException { + JsonObject coreConfig, SemVer version) + throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("appId", appId); if (emailPasswordEnabled != null) { @@ -171,18 +181,21 @@ public static JsonObject deleteApp(TenantIdentifier sourceTenant, String appId, return response; } - public static JsonObject createTenant(Main main, TenantIdentifier sourceTenant, String tenantId, Boolean emailPasswordEnabled, + public static JsonObject createTenant(Main main, TenantIdentifier sourceTenant, String tenantId, + Boolean emailPasswordEnabled, Boolean thirdPartyEnabled, Boolean passwordlessEnabled, JsonObject coreConfig) throws HttpResponseException, IOException { return createTenant(main, sourceTenant, tenantId, emailPasswordEnabled, thirdPartyEnabled, passwordlessEnabled, false, null, false, null, coreConfig, SemVer.v3_0); } - public static JsonObject createTenant(Main main, TenantIdentifier sourceTenant, String tenantId, Boolean emailPasswordEnabled, + public static JsonObject createTenant(Main main, TenantIdentifier sourceTenant, String tenantId, + Boolean emailPasswordEnabled, Boolean thirdPartyEnabled, Boolean passwordlessEnabled, boolean setFirstFactors, String[] firstFactors, boolean setRequiredSecondaryFactors, String[] requiredSecondaryFactors, - JsonObject coreConfig, SemVer version) throws HttpResponseException, IOException { + JsonObject coreConfig, SemVer version) + throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("tenantId", tenantId); if (emailPasswordEnabled != null) { @@ -281,12 +294,15 @@ public static JsonObject disassociateUserFromTenant(TenantIdentifier tenantIdent return response; } - public static JsonObject addOrUpdateThirdPartyProviderConfig(TenantIdentifier tenantIdentifier, ThirdPartyConfig.Provider provider, Main main) + public static JsonObject addOrUpdateThirdPartyProviderConfig(TenantIdentifier tenantIdentifier, + ThirdPartyConfig.Provider provider, Main main) throws HttpResponseException, IOException { return addOrUpdateThirdPartyProviderConfig(tenantIdentifier, provider, false, main); } - public static JsonObject addOrUpdateThirdPartyProviderConfig(TenantIdentifier tenantIdentifier, ThirdPartyConfig.Provider provider, boolean skipValidation, Main main) + public static JsonObject addOrUpdateThirdPartyProviderConfig(TenantIdentifier tenantIdentifier, + ThirdPartyConfig.Provider provider, + boolean skipValidation, Main main) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); JsonObject tpConfig = provider.toJson(); @@ -308,7 +324,8 @@ public static JsonObject deleteThirdPartyProvider(TenantIdentifier tenantIdentif requestBody.addProperty("thirdPartyId", thirdPartyId); JsonObject response = HttpRequestForTesting.sendJsonPOSTRequest(main, "", - HttpRequestForTesting.getMultitenantUrl(tenantIdentifier, "/recipe/multitenancy/config/thirdparty/remove"), + HttpRequestForTesting.getMultitenantUrl(tenantIdentifier, + "/recipe/multitenancy/config/thirdparty/remove"), requestBody, 1000, 2500, null, SemVer.v3_0.get(), "multitenancy"); @@ -316,7 +333,8 @@ public static JsonObject deleteThirdPartyProvider(TenantIdentifier tenantIdentif return response; } - public static JsonObject listUsers(TenantIdentifier sourceTenant, String paginationToken, String limit, String includeRecipeIds, Main main) + public static JsonObject listUsers(TenantIdentifier sourceTenant, String paginationToken, String limit, + String includeRecipeIds, Main main) throws HttpResponseException, IOException { Map params = new HashMap<>(); if (paginationToken != null) { @@ -347,7 +365,8 @@ public static JsonObject epSignUp(TenantIdentifier tenantIdentifier, String emai return signUpResponse.getAsJsonObject("user"); } - public static JsonObject epSignUpAndGetResponse(TenantIdentifier tenantIdentifier, String email, String password, Main main, SemVer version) + public static JsonObject epSignUpAndGetResponse(TenantIdentifier tenantIdentifier, String email, String password, + Main main, SemVer version) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("email", email); @@ -359,7 +378,8 @@ public static JsonObject epSignUpAndGetResponse(TenantIdentifier tenantIdentifie return signUpResponse; } - public static JsonObject epSignInAndGetResponse(TenantIdentifier tenantIdentifier, String email, String password, Main main, SemVer version) + public static JsonObject epSignInAndGetResponse(TenantIdentifier tenantIdentifier, String email, String password, + Main main, SemVer version) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("email", email); @@ -371,7 +391,8 @@ public static JsonObject epSignInAndGetResponse(TenantIdentifier tenantIdentifie return signUpResponse; } - public static JsonObject tpSignInUp(TenantIdentifier tenantIdentifier, String thirdPartyId, String thirdPartyUserId, String email, Main main) + public static JsonObject tpSignInUp(TenantIdentifier tenantIdentifier, String thirdPartyId, String thirdPartyUserId, + String email, Main main) throws HttpResponseException, IOException { JsonObject emailObject = new JsonObject(); emailObject.addProperty("id", email); @@ -381,14 +402,16 @@ public static JsonObject tpSignInUp(TenantIdentifier tenantIdentifier, String th signUpRequestBody.addProperty("thirdPartyUserId", thirdPartyUserId); signUpRequestBody.add("email", emailObject); - JsonObject response = tpSignInUpAndGetResponse(tenantIdentifier, thirdPartyId, thirdPartyUserId, email, main, SemVer.v3_0); + JsonObject response = tpSignInUpAndGetResponse(tenantIdentifier, thirdPartyId, thirdPartyUserId, email, main, + SemVer.v3_0); assertEquals("OK", response.get("status").getAsString()); assertEquals(3, response.entrySet().size()); return response.get("user").getAsJsonObject(); } - public static JsonObject tpSignInUpAndGetResponse(TenantIdentifier tenantIdentifier, String thirdPartyId, String thirdPartyUserId, String email, Main main, SemVer version) + public static JsonObject tpSignInUpAndGetResponse(TenantIdentifier tenantIdentifier, String thirdPartyId, + String thirdPartyUserId, String email, Main main, SemVer version) throws HttpResponseException, IOException { JsonObject emailObject = new JsonObject(); emailObject.addProperty("id", email); @@ -423,7 +446,8 @@ private static JsonObject createCodeWithEmail(TenantIdentifier tenantIdentifier, return createCodeWithEmail(tenantIdentifier, email, main, SemVer.v3_0); } - private static JsonObject createCodeWithEmail(TenantIdentifier tenantIdentifier, String email, Main main, SemVer version) + private static JsonObject createCodeWithEmail(TenantIdentifier tenantIdentifier, String email, Main main, + SemVer version) throws HttpResponseException, IOException { String exampleCode = generateRandomString(6); JsonObject createCodeRequestBody = new JsonObject(); @@ -454,13 +478,15 @@ private static JsonObject consumeCode(TenantIdentifier tenantIdentifier, String consumeCodeRequestBody.addProperty("preAuthSessionId", preAuthSessionId); consumeCodeRequestBody.addProperty("userInputCode", userInputCode); - JsonObject response = consumeCodeAndGetResponse(tenantIdentifier, deviceId, preAuthSessionId, userInputCode, main, version); + JsonObject response = consumeCodeAndGetResponse(tenantIdentifier, deviceId, preAuthSessionId, userInputCode, + main, version); assertEquals("OK", response.get("status").getAsString()); return response.get("user").getAsJsonObject(); } - private static JsonObject consumeCodeAndGetResponse(TenantIdentifier tenantIdentifier, String deviceId, String preAuthSessionId, - String userInputCode, Main main, SemVer version) + private static JsonObject consumeCodeAndGetResponse(TenantIdentifier tenantIdentifier, String deviceId, + String preAuthSessionId, + String userInputCode, Main main, SemVer version) throws HttpResponseException, IOException { JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("deviceId", deviceId); @@ -489,19 +515,24 @@ private static JsonObject consumeCodeAndGetResponse(TenantIdentifier tenantIdent public static JsonObject plSignInUpEmail(TenantIdentifier tenantIdentifier, String email, Main main) throws HttpResponseException, IOException { JsonObject code = createCodeWithEmail(tenantIdentifier, email, main); - return consumeCode(tenantIdentifier, code.get("deviceId").getAsString(), code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString(), main); + return consumeCode(tenantIdentifier, code.get("deviceId").getAsString(), + code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString(), main); } - public static JsonObject plSignInUpWithEmailOTP(TenantIdentifier tenantIdentifier, String email, Main main, SemVer version) + public static JsonObject plSignInUpWithEmailOTP(TenantIdentifier tenantIdentifier, String email, Main main, + SemVer version) throws HttpResponseException, IOException { JsonObject code = createCodeWithEmail(tenantIdentifier, email, main, version); - return consumeCodeAndGetResponse(tenantIdentifier, code.get("deviceId").getAsString(), code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString(), main, version); + return consumeCodeAndGetResponse(tenantIdentifier, code.get("deviceId").getAsString(), + code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString(), main, version); } - public static JsonObject plSignInUpWithEmailLink(TenantIdentifier tenantIdentifier, String email, Main main, SemVer version) + public static JsonObject plSignInUpWithEmailLink(TenantIdentifier tenantIdentifier, String email, Main main, + SemVer version) throws HttpResponseException, IOException { JsonObject code = createCodeWithEmail(tenantIdentifier, email, main, version); - return consumeCodeAndGetResponse(tenantIdentifier, code.get("preAuthSessionId").getAsString(), code.get("linkCode").getAsString(), main, version); + return consumeCodeAndGetResponse(tenantIdentifier, code.get("preAuthSessionId").getAsString(), + code.get("linkCode").getAsString(), main, version); } private static JsonObject createCodeWithNumber(TenantIdentifier tenantIdentifier, String phoneNumber, Main main) @@ -509,7 +540,8 @@ private static JsonObject createCodeWithNumber(TenantIdentifier tenantIdentifier return createCodeWithNumber(tenantIdentifier, phoneNumber, main, SemVer.v3_0); } - private static JsonObject createCodeWithNumber(TenantIdentifier tenantIdentifier, String phoneNumber, Main main, SemVer version) + private static JsonObject createCodeWithNumber(TenantIdentifier tenantIdentifier, String phoneNumber, Main main, + SemVer version) throws HttpResponseException, IOException { JsonObject createCodeRequestBody = new JsonObject(); createCodeRequestBody.addProperty("phoneNumber", phoneNumber); @@ -528,19 +560,24 @@ private static JsonObject createCodeWithNumber(TenantIdentifier tenantIdentifier public static JsonObject plSignInUpNumber(TenantIdentifier tenantIdentifier, String phoneNumber, Main main) throws HttpResponseException, IOException { JsonObject code = createCodeWithNumber(tenantIdentifier, phoneNumber, main); - return consumeCode(tenantIdentifier, code.get("deviceId").getAsString(), code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString(), main); + return consumeCode(tenantIdentifier, code.get("deviceId").getAsString(), + code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString(), main); } - public static JsonObject plSignInUpWithPhoneOTP(TenantIdentifier tenantIdentifier, String phoneNumber, Main main, SemVer version) + public static JsonObject plSignInUpWithPhoneOTP(TenantIdentifier tenantIdentifier, String phoneNumber, Main main, + SemVer version) throws HttpResponseException, IOException { JsonObject code = createCodeWithNumber(tenantIdentifier, phoneNumber, main, version); - return consumeCodeAndGetResponse(tenantIdentifier, code.get("deviceId").getAsString(), code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString(), main, version); + return consumeCodeAndGetResponse(tenantIdentifier, code.get("deviceId").getAsString(), + code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString(), main, version); } - public static JsonObject plSignInUpWithPhoneLink(TenantIdentifier tenantIdentifier, String phoneNumber, Main main, SemVer version) + public static JsonObject plSignInUpWithPhoneLink(TenantIdentifier tenantIdentifier, String phoneNumber, Main main, + SemVer version) throws HttpResponseException, IOException { JsonObject code = createCodeWithNumber(tenantIdentifier, phoneNumber, main, version); - return consumeCodeAndGetResponse(tenantIdentifier, code.get("preAuthSessionId").getAsString(), code.get("linkCode").getAsString(), main, version); + return consumeCodeAndGetResponse(tenantIdentifier, code.get("preAuthSessionId").getAsString(), + code.get("linkCode").getAsString(), main, version); } public static void addLicense(String licenseKey, Main main) throws HttpResponseException, IOException { @@ -574,7 +611,8 @@ public static JsonObject getEpUserById(TenantIdentifier tenantIdentifier, String return userResponse.getAsJsonObject("user"); } - public static void createUserIdMapping(TenantIdentifier tenantIdentifier, String supertokensUserId, String externalUserId, Main main) + public static void createUserIdMapping(TenantIdentifier tenantIdentifier, String supertokensUserId, + String externalUserId, Main main) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("superTokensUserId", supertokensUserId); @@ -599,7 +637,7 @@ public static JsonObject getUserById(TenantIdentifier tenantIdentifier, String u } public static JsonObject updateUserMetadata(TenantIdentifier tenantIdentifier, String userId, JsonObject metadata, - Main main) + Main main) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("userId", userId); @@ -641,7 +679,8 @@ public static void addRoleToUser(TenantIdentifier tenantIdentifier, String userI requestBody.addProperty("userId", userId); JsonObject response = HttpRequestForTesting.sendJsonPUTRequest(main, "", - HttpRequestForTesting.getMultitenantUrl(tenantIdentifier,"/recipe/user/role"), requestBody, 1000, 1000, null, + HttpRequestForTesting.getMultitenantUrl(tenantIdentifier, "/recipe/user/role"), requestBody, 1000, 1000, + null, WebserverAPI.getLatestCDIVersion().get(), "userroles"); assertEquals(2, response.entrySet().size()); @@ -653,7 +692,8 @@ public static JsonObject getUserRoles(TenantIdentifier tenantIdentifier, String HashMap QUERY_PARAMS = new HashMap<>(); QUERY_PARAMS.put("userId", userId); JsonObject response = HttpRequestForTesting.sendGETRequest(main, "", - HttpRequestForTesting.getMultitenantUrl(tenantIdentifier,"/recipe/user/roles"), QUERY_PARAMS, 1000, 1000, null, + HttpRequestForTesting.getMultitenantUrl(tenantIdentifier, "/recipe/user/roles"), QUERY_PARAMS, 1000, + 1000, null, WebserverAPI.getLatestCDIVersion().get(), "userroles"); return response; } @@ -664,7 +704,8 @@ public static void deleteRole(TenantIdentifier tenantIdentifier, String role, Ma request.addProperty("role", role); JsonObject response = HttpRequestForTesting.sendJsonPOSTRequest(main, "", - HttpRequestForTesting.getMultitenantUrl(tenantIdentifier,"/recipe/role/remove"), request, 1000, 1000, null, + HttpRequestForTesting.getMultitenantUrl(tenantIdentifier, "/recipe/role/remove"), request, 1000, 1000, + null, WebserverAPI.getLatestCDIVersion().get(), "userroles"); assertEquals(2, response.entrySet().size()); assertEquals("OK", response.get("status").getAsString()); @@ -677,7 +718,7 @@ public static void verifyEmail(TenantIdentifier tenantIdentifier, String userId, requestBody.addProperty("email", email); JsonObject response = HttpRequestForTesting.sendJsonPOSTRequest(main, "", - HttpRequestForTesting.getMultitenantUrl(tenantIdentifier,"/recipe/user/email/verify/token"), + HttpRequestForTesting.getMultitenantUrl(tenantIdentifier, "/recipe/user/email/verify/token"), requestBody, 1000, 1000, null, WebserverAPI.getLatestCDIVersion().get(), "emailverification"); @@ -689,7 +730,8 @@ public static void verifyEmail(TenantIdentifier tenantIdentifier, String userId, verifyResponseBody.addProperty("token", response.get("token").getAsString()); JsonObject response2 = HttpRequestForTesting.sendJsonPOSTRequest(main, "", - HttpRequestForTesting.getMultitenantUrl(tenantIdentifier, "/recipe/user/email/verify"), verifyResponseBody, 1000, 1000, null, + HttpRequestForTesting.getMultitenantUrl(tenantIdentifier, "/recipe/user/email/verify"), + verifyResponseBody, 1000, 1000, null, WebserverAPI.getLatestCDIVersion().get(), "emailverification"); assertEquals(response2.entrySet().size(), 3); @@ -703,7 +745,8 @@ public static void unverifyEmail(TenantIdentifier tenantIdentifier, String userI body.addProperty("email", email); HttpRequestForTesting.sendJsonPOSTRequest(main, "", - HttpRequestForTesting.getMultitenantUrl(tenantIdentifier,"/recipe/user/email/verify/remove"), body, 1000, 1000, null, + HttpRequestForTesting.getMultitenantUrl(tenantIdentifier, "/recipe/user/email/verify/remove"), body, + 1000, 1000, null, WebserverAPI.getLatestCDIVersion().get(), RECIPE_ID.EMAIL_VERIFICATION.toString()); } } diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestPermissionChecks.java b/src/test/java/io/supertokens/test/multitenant/api/TestPermissionChecks.java index e2f9e4a32..0538e2c63 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestPermissionChecks.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestPermissionChecks.java @@ -88,15 +88,18 @@ public void testPermissionsForListConnectionUriDomains() throws Exception { TestCase[] testCases = new TestCase[]{ new TestCase( new TenantIdentifier("127.0.0.1", null, null), null, - "Only the public tenantId, public appId and default connectionUriDomain is allowed to list all connectionUriDomains and appIds associated with this core" + "Only the public tenantId, public appId and default connectionUriDomain is allowed to list " + + "all connectionUriDomains and appIds associated with this core" ), new TestCase( new TenantIdentifier(null, "a1", null), null, - "Only the public tenantId, public appId and default connectionUriDomain is allowed to list all connectionUriDomains and appIds associated with this core" + "Only the public tenantId, public appId and default connectionUriDomain is allowed to list " + + "all connectionUriDomains and appIds associated with this core" ), new TestCase( new TenantIdentifier(null, null, "t1"), null, - "Only the public tenantId, public appId and default connectionUriDomain is allowed to list all connectionUriDomains and appIds associated with this core" + "Only the public tenantId, public appId and default connectionUriDomain is allowed to list " + + "all connectionUriDomains and appIds associated with this core" ), new TestCase( new TenantIdentifier(null, null, null), null, null @@ -147,19 +150,23 @@ public void testPermissionsForListApps() throws Exception { TestCase[] testCases = new TestCase[]{ new TestCase( new TenantIdentifier("127.0.0.1", "a1", null), null, - "Only the public tenantId and public appId is allowed to list all apps associated with this connection uri domain" + "Only the public tenantId and public appId is allowed to list all apps associated with this " + + "connection uri domain" ), new TestCase( new TenantIdentifier("127.0.0.1", null, "t1"), null, - "Only the public tenantId and public appId is allowed to list all apps associated with this connection uri domain" + "Only the public tenantId and public appId is allowed to list all apps associated with this " + + "connection uri domain" ), new TestCase( new TenantIdentifier(null, "a1", null), null, - "Only the public tenantId and public appId is allowed to list all apps associated with this connection uri domain" + "Only the public tenantId and public appId is allowed to list all apps associated with this " + + "connection uri domain" ), new TestCase( new TenantIdentifier(null, null, "t1"), null, - "Only the public tenantId and public appId is allowed to list all apps associated with this connection uri domain" + "Only the public tenantId and public appId is allowed to list all apps associated with this " + + "connection uri domain" ), new TestCase( new TenantIdentifier(null, null, null), null, null @@ -518,7 +525,8 @@ public void testConnectionUriDomainValidationUtil() throws Exception { } assertEquals("abccom", io.supertokens.webserver.Utils.normalizeAndValidateConnectionUriDomain("abccom", false)); - assertEquals("local_host", io.supertokens.webserver.Utils.normalizeAndValidateConnectionUriDomain("local_host", false)); + assertEquals("local_host", + io.supertokens.webserver.Utils.normalizeAndValidateConnectionUriDomain("local_host", false)); } @Test @@ -581,7 +589,9 @@ public void testPermissionsForCreateOrUpdateApp() throws Exception { } if (StorageLayer.isInMemDb(process.getProcess())) { - if (!testCase.sourceTenant.getConnectionUriDomain().equals(TenantIdentifier.DEFAULT_CONNECTION_URI) || !testCase.targetTenant.getConnectionUriDomain().equals(TenantIdentifier.DEFAULT_CONNECTION_URI)) { + if (!testCase.sourceTenant.getConnectionUriDomain().equals(TenantIdentifier.DEFAULT_CONNECTION_URI) || + !testCase.targetTenant.getConnectionUriDomain() + .equals(TenantIdentifier.DEFAULT_CONNECTION_URI)) { process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -751,7 +761,9 @@ public void testPermissionsForCreateOrUpdateTenant() throws Exception { } if (StorageLayer.isInMemDb(process.getProcess())) { - if (!testCase.sourceTenant.getConnectionUriDomain().equals(TenantIdentifier.DEFAULT_CONNECTION_URI) || !testCase.targetTenant.getConnectionUriDomain().equals(TenantIdentifier.DEFAULT_CONNECTION_URI)) { + if (!testCase.sourceTenant.getConnectionUriDomain().equals(TenantIdentifier.DEFAULT_CONNECTION_URI) || + !testCase.targetTenant.getConnectionUriDomain() + .equals(TenantIdentifier.DEFAULT_CONNECTION_URI)) { process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -872,7 +884,8 @@ public void testPermissionsForDeleteConnectionUriDomain() throws Exception { new TestCase( new TenantIdentifier("127.0.0.1", null, null), new TenantIdentifier("127.0.0.1", null, null), - "Only the public tenantId, public appId and default connectionUriDomain is allowed to delete a connectionUriDomain" + "Only the public tenantId, public appId and default connectionUriDomain is allowed to delete " + + "a connectionUriDomain" ), }; @@ -971,7 +984,9 @@ public void testPermissionsForDeleteApp() throws Exception { } if (StorageLayer.isInMemDb(process.getProcess())) { - if (!testCase.sourceTenant.getConnectionUriDomain().equals(TenantIdentifier.DEFAULT_CONNECTION_URI) || !testCase.targetTenant.getConnectionUriDomain().equals(TenantIdentifier.DEFAULT_CONNECTION_URI)) { + if (!testCase.sourceTenant.getConnectionUriDomain().equals(TenantIdentifier.DEFAULT_CONNECTION_URI) || + !testCase.targetTenant.getConnectionUriDomain() + .equals(TenantIdentifier.DEFAULT_CONNECTION_URI)) { process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -1081,7 +1096,9 @@ public void testPermissionsForDeleteTenant() throws Exception { } if (StorageLayer.isInMemDb(process.getProcess())) { - if (!testCase.sourceTenant.getConnectionUriDomain().equals(TenantIdentifier.DEFAULT_CONNECTION_URI) || !testCase.targetTenant.getConnectionUriDomain().equals(TenantIdentifier.DEFAULT_CONNECTION_URI)) { + if (!testCase.sourceTenant.getConnectionUriDomain().equals(TenantIdentifier.DEFAULT_CONNECTION_URI) || + !testCase.targetTenant.getConnectionUriDomain() + .equals(TenantIdentifier.DEFAULT_CONNECTION_URI)) { process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestSkipValidationInCreateThirdParty.java b/src/test/java/io/supertokens/test/multitenant/api/TestSkipValidationInCreateThirdParty.java index c12c89021..4afd19185 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestSkipValidationInCreateThirdParty.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestSkipValidationInCreateThirdParty.java @@ -77,14 +77,17 @@ null, null, new JsonObject() TestMultitenancyAPIHelper.addOrUpdateThirdPartyProviderConfig(new TenantIdentifier(null, "a1", null), new ThirdPartyConfig.Provider( "boxy-saml", "Boxy SAML", new ThirdPartyConfig.ProviderClient[]{ - new ThirdPartyConfig.ProviderClient("web", "clientid", "clientsecret", null, null, additionalConfig) + new ThirdPartyConfig.ProviderClient("web", "clientid", "clientsecret", null, null, + additionalConfig) }, null, null, null, null, null, null, null, null, null, null, null ), process.getProcess()); fail(); } catch (HttpResponseException e) { - assertTrue(e.getMessage().contains("a non empty string value must be specified for boxyURL in the additionalConfig for Boxy SAML provider")); + assertTrue(e.getMessage().contains( + "a non empty string value must be specified for boxyURL in the additionalConfig for Boxy SAML " + + "provider")); } TestMultitenancyAPIHelper.addOrUpdateThirdPartyProviderConfig(new TenantIdentifier(null, "a1", null), diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestTenant3_0.java b/src/test/java/io/supertokens/test/multitenant/api/TestTenant3_0.java index 9346b4bb1..345a12c91 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestTenant3_0.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestTenant3_0.java @@ -290,8 +290,10 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } }); - String[] valueForCreate = new String[]{"a1", "a-1", "a-B-1", "CAPS1", "MixedCase", "capsinquery", "mixedcaseinquery"}; - String[] valueForQuery = new String[]{"a1", "a-1", "A-b-1", "CAPS1", "MixedCase", "CAPSINQUERY", "MixedCaseInQuery"}; + String[] valueForCreate = new String[]{"a1", "a-1", "a-B-1", "CAPS1", "MixedCase", "capsinquery", + "mixedcaseinquery"}; + String[] valueForQuery = new String[]{"a1", "a-1", "A-b-1", "CAPS1", "MixedCase", "CAPSINQUERY", + "MixedCaseInQuery"}; if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; @@ -318,7 +320,8 @@ public void testDifferentValuesForTenantIdThatShouldNotWork() throws Exception { return; } - String[] valueForCreate = new String[]{"a_b", "1", "1a", "appid-hello", "AppId-Hello", "recipe", "reCipe", "CONFIG", "users", "Users"}; + String[] valueForCreate = new String[]{"a_b", "1", "1a", "appid-hello", "AppId-Hello", "recipe", "reCipe", + "CONFIG", "users", "Users"}; for (int i = 0; i < valueForCreate.length; i++) { try { createTenant( @@ -359,9 +362,9 @@ public void testDefaultRecipesEnabledWhileCreatingTenant() throws Exception { } private static JsonObject createTenant(Main main, TenantIdentifier sourceTenant, String tenantId, - Boolean emailPasswordEnabled, - Boolean thirdPartyEnabled, Boolean passwordlessEnabled, - JsonObject coreConfig) throws HttpResponseException, IOException { + Boolean emailPasswordEnabled, + Boolean thirdPartyEnabled, Boolean passwordlessEnabled, + JsonObject coreConfig) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("tenantId", tenantId); if (emailPasswordEnabled != null) { diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_0.java b/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_0.java index ba903d78c..32df2f0d0 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_0.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_0.java @@ -292,8 +292,10 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } }); - String[] valueForCreate = new String[]{"a1", "a-1", "a-B-1", "CAPS1", "MixedCase", "capsinquery", "mixedcaseinquery"}; - String[] valueForQuery = new String[]{"a1", "a-1", "A-b-1", "CAPS1", "MixedCase", "CAPSINQUERY", "MixedCaseInQuery"}; + String[] valueForCreate = new String[]{"a1", "a-1", "a-B-1", "CAPS1", "MixedCase", "capsinquery", + "mixedcaseinquery"}; + String[] valueForQuery = new String[]{"a1", "a-1", "A-b-1", "CAPS1", "MixedCase", "CAPSINQUERY", + "MixedCaseInQuery"}; if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; @@ -320,7 +322,8 @@ public void testDifferentValuesForTenantIdThatShouldNotWork() throws Exception { return; } - String[] valueForCreate = new String[]{"a_b", "1", "1a", "appid-hello", "AppId-Hello", "recipe", "reCipe", "CONFIG", "users", "Users"}; + String[] valueForCreate = new String[]{"a_b", "1", "1a", "appid-hello", "AppId-Hello", "recipe", "reCipe", + "CONFIG", "users", "Users"}; for (int i = 0; i < valueForCreate.length; i++) { try { createTenant( @@ -448,7 +451,8 @@ public void testFirstFactorsArray() throws Exception { assertEquals(7, tenant.entrySet().size()); assertTrue(tenant.get("firstFactors").isJsonArray()); assertEquals(4, tenant.get("firstFactors").getAsJsonArray().size()); - assertEquals(Set.of(firstFactors), Set.of(new Gson().fromJson(tenant.get("firstFactors").getAsJsonArray(), String[].class))); + assertEquals(Set.of(firstFactors), + Set.of(new Gson().fromJson(tenant.get("firstFactors").getAsJsonArray(), String[].class))); response = createTenant( process.getProcess(), @@ -501,7 +505,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(7, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); response = createTenant( process.getProcess(), @@ -516,7 +521,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(7, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); // custom factors requiredSecondaryFactors = new String[]{"biometric"}; @@ -533,7 +539,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(7, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); // test both requiredSecondaryFactors = new String[]{"otp-phone", "emailpassword", "biometric", "custom"}; @@ -550,7 +557,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(7, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(4, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(Set.of(requiredSecondaryFactors), Set.of(new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class))); + assertEquals(Set.of(requiredSecondaryFactors), + Set.of(new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class))); response = createTenant( process.getProcess(), @@ -586,7 +594,9 @@ public void testDuplicateValuesInFirstFactorsAndRequiredSecondaryFactors() throw fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: firstFactors input should not contain duplicate values", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: firstFactors input should not contain duplicate values", + e.getMessage()); } try { @@ -599,7 +609,10 @@ public void testDuplicateValuesInFirstFactorsAndRequiredSecondaryFactors() throw fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: requiredSecondaryFactors input should not contain duplicate values", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: requiredSecondaryFactors input should not contain " + + "duplicate values", + e.getMessage()); } } @@ -612,11 +625,11 @@ private static JsonObject createTenant(Main main, TenantIdentifier sourceTenant, } private static JsonObject createTenant(Main main, TenantIdentifier sourceTenant, String tenantId, - Boolean emailPasswordEnabled, - Boolean thirdPartyEnabled, Boolean passwordlessEnabled, + Boolean emailPasswordEnabled, + Boolean thirdPartyEnabled, Boolean passwordlessEnabled, boolean setFirstFactors, String[] firstFactors, boolean setRequiredSecondaryFactors, String[] requiredSecondaryFactors, - JsonObject coreConfig) throws HttpResponseException, IOException { + JsonObject coreConfig) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("tenantId", tenantId); if (emailPasswordEnabled != null) { diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_1.java b/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_1.java index 6c631d18b..728e65625 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_1.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_1.java @@ -296,8 +296,10 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } }); - String[] valueForCreate = new String[]{"a1", "a-1", "a-B-1", "CAPS1", "MixedCase", "capsinquery", "mixedcaseinquery"}; - String[] valueForQuery = new String[]{"a1", "a-1", "A-b-1", "CAPS1", "MixedCase", "CAPSINQUERY", "MixedCaseInQuery"}; + String[] valueForCreate = new String[]{"a1", "a-1", "a-B-1", "CAPS1", "MixedCase", "capsinquery", + "mixedcaseinquery"}; + String[] valueForQuery = new String[]{"a1", "a-1", "A-b-1", "CAPS1", "MixedCase", "CAPSINQUERY", + "MixedCaseInQuery"}; if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; @@ -324,7 +326,8 @@ public void testDifferentValuesForTenantIdThatShouldNotWork() throws Exception { return; } - String[] valueForCreate = new String[]{"a_b", "1", "1a", "appid-hello", "AppId-Hello", "recipe", "reCipe", "CONFIG", "users", "Users"}; + String[] valueForCreate = new String[]{"a_b", "1", "1a", "appid-hello", "AppId-Hello", "recipe", "reCipe", + "CONFIG", "users", "Users"}; for (int i = 0; i < valueForCreate.length; i++) { try { createTenant( @@ -453,7 +456,8 @@ public void testFirstFactorsArray() throws Exception { assertEquals(5, tenant.entrySet().size()); assertTrue(tenant.get("firstFactors").isJsonArray()); assertEquals(4, tenant.get("firstFactors").getAsJsonArray().size()); - assertEquals(Set.of(firstFactors), Set.of(new Gson().fromJson(tenant.get("firstFactors").getAsJsonArray(), String[].class))); + assertEquals(Set.of(firstFactors), + Set.of(new Gson().fromJson(tenant.get("firstFactors").getAsJsonArray(), String[].class))); response = createTenant( process.getProcess(), @@ -503,7 +507,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(6, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); response = createTenant( process.getProcess(), @@ -517,7 +522,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(6, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); // custom factors requiredSecondaryFactors = new String[]{"biometric"}; @@ -533,7 +539,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(6, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(1, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(requiredSecondaryFactors, new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); + assertEquals(requiredSecondaryFactors, + new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class)); // test both requiredSecondaryFactors = new String[]{"otp-phone", "emailpassword", "biometric", "custom"}; @@ -549,7 +556,8 @@ public void testRequiredSecondaryFactorsArray() throws Exception { assertEquals(6, tenant.entrySet().size()); assertTrue(tenant.get("requiredSecondaryFactors").isJsonArray()); assertEquals(4, tenant.get("requiredSecondaryFactors").getAsJsonArray().size()); - assertEquals(Set.of(requiredSecondaryFactors), Set.of(new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class))); + assertEquals(Set.of(requiredSecondaryFactors), + Set.of(new Gson().fromJson(tenant.get("requiredSecondaryFactors").getAsJsonArray(), String[].class))); response = createTenant( process.getProcess(), @@ -583,7 +591,9 @@ public void testDuplicateValuesInFirstFactorsAndRequiredSecondaryFactors() throw fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: firstFactors input should not contain duplicate values", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: firstFactors input should not contain duplicate values", + e.getMessage()); } try { @@ -595,14 +605,17 @@ public void testDuplicateValuesInFirstFactorsAndRequiredSecondaryFactors() throw fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: requiredSecondaryFactors input should not contain duplicate values", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: requiredSecondaryFactors input should not contain " + + "duplicate values", + e.getMessage()); } } private static JsonObject createTenant(Main main, TenantIdentifier sourceTenant, String tenantId, boolean setFirstFactors, String[] firstFactors, boolean setRequiredSecondaryFactors, String[] requiredSecondaryFactors, - JsonObject coreConfig) throws HttpResponseException, IOException { + JsonObject coreConfig) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("tenantId", tenantId); if (setFirstFactors || firstFactors != null) { diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationAndRecipeEnabledChecksAcrossVersions.java b/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationAndRecipeEnabledChecksAcrossVersions.java index 5d3c2b222..8fb3720ae 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationAndRecipeEnabledChecksAcrossVersions.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationAndRecipeEnabledChecksAcrossVersions.java @@ -96,7 +96,8 @@ public void testDefaultBooleanBehavioursWithTenantCreatedIn3_0() throws Exceptio assertTrue(checkPasswordlessSignIn(new TenantIdentifier(null, "a1", null), SemVer.v5_1)); assertTrue(checkThirdPartySignInUp(new TenantIdentifier(null, "a1", null), SemVer.v5_1)); - createTenant_3_0(process.getProcess(), new TenantIdentifier(null, "a1", null), "t1", null, null, null, new JsonObject()); + createTenant_3_0(process.getProcess(), new TenantIdentifier(null, "a1", null), "t1", null, null, null, + new JsonObject()); assertFalse(checkEmailPasswordSignIn(new TenantIdentifier(null, "a1", "t1"), SemVer.v3_0)); assertFalse(checkPasswordlessSignIn(new TenantIdentifier(null, "a1", "t1"), SemVer.v3_0)); assertFalse(checkThirdPartySignInUp(new TenantIdentifier(null, "a1", "t1"), SemVer.v3_0)); @@ -116,7 +117,8 @@ public void testDefaultBooleanBehavioursWithTenantCreatedIn5_0() throws Exceptio return; } - createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a1", null, null, null, false, null, false, null, new JsonObject()); + createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a1", null, null, null, false, null, false, + null, new JsonObject()); assertTrue(checkEmailPasswordSignIn(new TenantIdentifier(null, "a1", null), SemVer.v3_0)); assertTrue(checkPasswordlessSignIn(new TenantIdentifier(null, "a1", null), SemVer.v3_0)); assertTrue(checkThirdPartySignInUp(new TenantIdentifier(null, "a1", null), SemVer.v3_0)); @@ -129,7 +131,8 @@ public void testDefaultBooleanBehavioursWithTenantCreatedIn5_0() throws Exceptio assertTrue(checkPasswordlessSignIn(new TenantIdentifier(null, "a1", null), SemVer.v5_1)); assertTrue(checkThirdPartySignInUp(new TenantIdentifier(null, "a1", null), SemVer.v5_1)); - createTenant_5_0(process.getProcess(), new TenantIdentifier(null, "a1", null), "t1", null, null, null, false, null, false, null, new JsonObject()); + createTenant_5_0(process.getProcess(), new TenantIdentifier(null, "a1", null), "t1", null, null, null, false, + null, false, null, new JsonObject()); assertFalse(checkEmailPasswordSignIn(new TenantIdentifier(null, "a1", "t1"), SemVer.v3_0)); assertFalse(checkPasswordlessSignIn(new TenantIdentifier(null, "a1", "t1"), SemVer.v3_0)); assertFalse(checkThirdPartySignInUp(new TenantIdentifier(null, "a1", "t1"), SemVer.v3_0)); @@ -149,7 +152,8 @@ public void testDefaultBooleanBehavioursWithTenantCreatedIn5_1() throws Exceptio return; } - createApp_5_1(process.getProcess(), TenantIdentifier.BASE_TENANT, "a1", false, null, false, null, new JsonObject()); + createApp_5_1(process.getProcess(), TenantIdentifier.BASE_TENANT, "a1", false, null, false, null, + new JsonObject()); assertTrue(checkEmailPasswordSignIn(new TenantIdentifier(null, "a1", null), SemVer.v3_0)); assertTrue(checkPasswordlessSignIn(new TenantIdentifier(null, "a1", null), SemVer.v3_0)); assertTrue(checkThirdPartySignInUp(new TenantIdentifier(null, "a1", null), SemVer.v3_0)); @@ -162,7 +166,8 @@ public void testDefaultBooleanBehavioursWithTenantCreatedIn5_1() throws Exceptio assertTrue(checkPasswordlessSignIn(new TenantIdentifier(null, "a1", null), SemVer.v5_1)); assertTrue(checkThirdPartySignInUp(new TenantIdentifier(null, "a1", null), SemVer.v5_1)); - createTenant_5_1(process.getProcess(), new TenantIdentifier(null, "a1", null), "t1", false, null, false, null, new JsonObject()); + createTenant_5_1(process.getProcess(), new TenantIdentifier(null, "a1", null), "t1", false, null, false, null, + new JsonObject()); assertFalse(checkEmailPasswordSignIn(new TenantIdentifier(null, "a1", "t1"), SemVer.v3_0)); assertFalse(checkPasswordlessSignIn(new TenantIdentifier(null, "a1", "t1"), SemVer.v3_0)); assertFalse(checkThirdPartySignInUp(new TenantIdentifier(null, "a1", "t1"), SemVer.v3_0)); @@ -229,7 +234,8 @@ public void testDisableRecipeWithTenantCreatedIn5_0() throws Exception { return; } - createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a1", false, null, null, false, null, false, null, new JsonObject()); + createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a1", false, null, null, false, null, false, + null, new JsonObject()); assertFalse(checkEmailPasswordSignIn(new TenantIdentifier(null, "a1", null), SemVer.v3_0)); assertTrue(checkPasswordlessSignIn(new TenantIdentifier(null, "a1", null), SemVer.v3_0)); assertTrue(checkThirdPartySignInUp(new TenantIdentifier(null, "a1", null), SemVer.v3_0)); @@ -242,7 +248,8 @@ public void testDisableRecipeWithTenantCreatedIn5_0() throws Exception { assertTrue(checkPasswordlessSignIn(new TenantIdentifier(null, "a1", null), SemVer.v5_1)); assertTrue(checkThirdPartySignInUp(new TenantIdentifier(null, "a1", null), SemVer.v5_1)); - createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a2", null, false, null, false, null, false, null, new JsonObject()); + createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a2", null, false, null, false, null, false, + null, new JsonObject()); assertTrue(checkEmailPasswordSignIn(new TenantIdentifier(null, "a2", null), SemVer.v3_0)); assertTrue(checkPasswordlessSignIn(new TenantIdentifier(null, "a2", null), SemVer.v3_0)); assertFalse(checkThirdPartySignInUp(new TenantIdentifier(null, "a2", null), SemVer.v3_0)); @@ -255,7 +262,8 @@ public void testDisableRecipeWithTenantCreatedIn5_0() throws Exception { assertTrue(checkPasswordlessSignIn(new TenantIdentifier(null, "a2", null), SemVer.v5_1)); assertTrue(checkThirdPartySignInUp(new TenantIdentifier(null, "a2", null), SemVer.v5_1)); - createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a3", null, null, false, false, null, false, null, new JsonObject()); + createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a3", null, null, false, false, null, false, + null, new JsonObject()); assertTrue(checkEmailPasswordSignIn(new TenantIdentifier(null, "a3", null), SemVer.v3_0)); assertFalse(checkPasswordlessSignIn(new TenantIdentifier(null, "a3", null), SemVer.v3_0)); assertTrue(checkThirdPartySignInUp(new TenantIdentifier(null, "a3", null), SemVer.v3_0)); @@ -276,17 +284,20 @@ public void testFirstFactorsAffectsBooleansInCDI3_0() throws Exception { return; } - createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a1", null, null, null, true, new String[]{"emailpassword"}, false, null, new JsonObject()); + createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a1", null, null, null, true, + new String[]{"emailpassword"}, false, null, new JsonObject()); assertTrue(checkEmailPasswordSignIn(new TenantIdentifier(null, "a1", null), SemVer.v3_0)); assertFalse(checkPasswordlessSignIn(new TenantIdentifier(null, "a1", null), SemVer.v3_0)); assertFalse(checkThirdPartySignInUp(new TenantIdentifier(null, "a1", null), SemVer.v3_0)); - createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a2", null, null, null, true, new String[]{"thirdparty"}, false, null, new JsonObject()); + createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a2", null, null, null, true, + new String[]{"thirdparty"}, false, null, new JsonObject()); assertFalse(checkEmailPasswordSignIn(new TenantIdentifier(null, "a2", null), SemVer.v3_0)); assertFalse(checkPasswordlessSignIn(new TenantIdentifier(null, "a2", null), SemVer.v3_0)); assertTrue(checkThirdPartySignInUp(new TenantIdentifier(null, "a2", null), SemVer.v3_0)); - createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a3", null, null, null, true, new String[]{"otp-email"}, false, null, new JsonObject()); + createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a3", null, null, null, true, + new String[]{"otp-email"}, false, null, new JsonObject()); assertFalse(checkEmailPasswordSignIn(new TenantIdentifier(null, "a3", null), SemVer.v3_0)); assertTrue(checkPasswordlessSignIn(new TenantIdentifier(null, "a3", null), SemVer.v3_0)); assertFalse(checkThirdPartySignInUp(new TenantIdentifier(null, "a3", null), SemVer.v3_0)); @@ -296,7 +307,8 @@ public void testFirstFactorsAffectsBooleansInCDI3_0() throws Exception { private boolean checkEmailPasswordSignIn(TenantIdentifier tenantIdentifier, SemVer version) throws IOException { try { - TestMultitenancyAPIHelper.epSignUpAndGetResponse(tenantIdentifier, "user"+(userCount++)+"@example.com", "password123!", process.getProcess(), version); + TestMultitenancyAPIHelper.epSignUpAndGetResponse(tenantIdentifier, "user" + (userCount++) + "@example.com", + "password123!", process.getProcess(), version); } catch (HttpResponseException e) { if (e.statusCode == 403) { return false; @@ -308,7 +320,8 @@ private boolean checkEmailPasswordSignIn(TenantIdentifier tenantIdentifier, SemV private boolean checkPasswordlessSignIn(TenantIdentifier tenantIdentifier, SemVer version) throws IOException { try { - TestMultitenancyAPIHelper.plSignInUpWithEmailOTP(tenantIdentifier, "user"+(userCount++)+"@example.com", process.getProcess(), version); + TestMultitenancyAPIHelper.plSignInUpWithEmailOTP(tenantIdentifier, "user" + (userCount++) + "@example.com", + process.getProcess(), version); } catch (HttpResponseException e) { if (e.statusCode == 403) { return false; @@ -320,7 +333,8 @@ private boolean checkPasswordlessSignIn(TenantIdentifier tenantIdentifier, SemVe private boolean checkThirdPartySignInUp(TenantIdentifier tenantIdentifier, SemVer version) throws IOException { try { - TestMultitenancyAPIHelper.tpSignInUpAndGetResponse(tenantIdentifier, "google", "googleid"+(userCount), "user"+userCount+"@example.com", process.getProcess(), version); + TestMultitenancyAPIHelper.tpSignInUpAndGetResponse(tenantIdentifier, "google", "googleid" + (userCount), + "user" + userCount + "@example.com", process.getProcess(), version); userCount++; } catch (HttpResponseException e) { if (e.statusCode == 403) { @@ -332,9 +346,9 @@ private boolean checkThirdPartySignInUp(TenantIdentifier tenantIdentifier, SemVe } private static JsonObject createApp_3_0(Main main, TenantIdentifier sourceTenant, String appId, - Boolean emailPasswordEnabled, - Boolean thirdPartyEnabled, Boolean passwordlessEnabled, - JsonObject coreConfig) throws HttpResponseException, IOException { + Boolean emailPasswordEnabled, + Boolean thirdPartyEnabled, Boolean passwordlessEnabled, + JsonObject coreConfig) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("appId", appId); if (emailPasswordEnabled != null) { @@ -405,7 +419,7 @@ private static JsonObject createApp_5_0(Main main, TenantIdentifier sourceTenant } private static JsonObject createOrUpdateApp_5_0(Main main, TenantIdentifier sourceTenant, String appId, - JsonObject requestBody) throws HttpResponseException, IOException { + JsonObject requestBody) throws HttpResponseException, IOException { requestBody.addProperty("appId", appId); JsonObject response = HttpRequestForTesting.sendJsonPUTRequest(main, "", @@ -441,7 +455,7 @@ private static JsonObject createApp_5_1(Main main, TenantIdentifier sourceTenant } private static JsonObject createOrUpdateApp_5_1(Main main, TenantIdentifier sourceTenant, String appId, - JsonObject requestBody) throws HttpResponseException, IOException { + JsonObject requestBody) throws HttpResponseException, IOException { requestBody.addProperty("appId", appId); JsonObject response = HttpRequestForTesting.sendJsonPUTRequest(main, "", @@ -529,9 +543,9 @@ private static JsonObject deleteTenant(TenantIdentifier sourceTenant, String ten } private static JsonObject createTenant_3_0(Main main, TenantIdentifier sourceTenant, String tenantId, - Boolean emailPasswordEnabled, - Boolean thirdPartyEnabled, Boolean passwordlessEnabled, - JsonObject coreConfig) throws HttpResponseException, IOException { + Boolean emailPasswordEnabled, + Boolean thirdPartyEnabled, Boolean passwordlessEnabled, + JsonObject coreConfig) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("tenantId", tenantId); if (emailPasswordEnabled != null) { @@ -556,7 +570,8 @@ private static JsonObject createTenant_3_0(Main main, TenantIdentifier sourceTen } private static JsonObject createOrUpdateTenant_3_0(Main main, TenantIdentifier sourceTenant, String tenantId, - JsonObject requestBody) throws HttpResponseException, IOException { + JsonObject requestBody) + throws HttpResponseException, IOException { requestBody.addProperty("tenantId", tenantId); JsonObject response = HttpRequestForTesting.sendJsonPUTRequest(main, "", @@ -604,7 +619,8 @@ private static JsonObject createTenant_5_0(Main main, TenantIdentifier sourceTen } private static JsonObject createOrUpdateTenant_5_0(Main main, TenantIdentifier sourceTenant, String tenantId, - JsonObject requestBody) throws HttpResponseException, IOException { + JsonObject requestBody) + throws HttpResponseException, IOException { requestBody.addProperty("tenantId", tenantId); JsonObject response = HttpRequestForTesting.sendJsonPUTRequest(main, "", @@ -641,7 +657,8 @@ private static JsonObject createTenant_5_1(Main main, TenantIdentifier sourceTen } private static JsonObject createOrUpdateTenant_5_1(Main main, TenantIdentifier sourceTenant, String tenantId, - JsonObject requestBody) throws HttpResponseException, IOException { + JsonObject requestBody) + throws HttpResponseException, IOException { requestBody.addProperty("tenantId", tenantId); JsonObject response = HttpRequestForTesting.sendJsonPUTRequest(main, "", @@ -671,6 +688,7 @@ private static class CrossVersionTestCaseStep { private static enum OperationType { CREATE_APP, CREATE_TENANT, UPDATE_APP, UPDATE_TENANT } + SemVer version; OperationType operation; JsonObject body; diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationBehaviour.java b/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationBehaviour.java index 99a49ba1a..fea2ea6fe 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationBehaviour.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationBehaviour.java @@ -128,10 +128,11 @@ public void testDefaultStateWhenNothingIsPassedWhileCreatingAppAndTenant_3_0() t assertEquals("public", tenant.get("tenantId").getAsString()); assertTrue(tenant.has("thirdParty")); // firstFactors and requiredSecondaryFactors should be null - assertTrue( tenant.get("thirdParty").getAsJsonObject().has("providers")); + assertTrue(tenant.get("thirdParty").getAsJsonObject().has("providers")); } - createTenant_3_0(process.getProcess(), new TenantIdentifier(null, "a1", null), "t1", null, null, null, new JsonObject()); + createTenant_3_0(process.getProcess(), new TenantIdentifier(null, "a1", null), "t1", null, null, null, + new JsonObject()); { // Get using CDI 3.0 @@ -169,7 +170,7 @@ public void testDefaultStateWhenNothingIsPassedWhileCreatingAppAndTenant_3_0() t assertTrue(tenant.has("thirdParty")); assertEquals(new JsonArray(), tenant.get("firstFactors").getAsJsonArray()); // requiredSecondaryFactors should be null - assertTrue( tenant.get("thirdParty").getAsJsonObject().has("providers")); + assertTrue(tenant.get("thirdParty").getAsJsonObject().has("providers")); } } @@ -179,7 +180,8 @@ public void testDefaultStateWhenNothingIsPassedWhileCreatingAppAndTenant_5_0() t return; } - createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a1", null, null, null, false, null, false, null, new JsonObject()); + createApp_5_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "a1", null, null, null, false, null, false, + null, new JsonObject()); { // Get using CDI 3.0 JsonObject tenant = getTenant_3_0(new TenantIdentifier(null, "a1", null), process.getProcess()); @@ -215,10 +217,11 @@ public void testDefaultStateWhenNothingIsPassedWhileCreatingAppAndTenant_5_0() t assertEquals("public", tenant.get("tenantId").getAsString()); assertTrue(tenant.has("thirdParty")); // firstFactors and requiredSecondaryFactors should be null - assertTrue( tenant.get("thirdParty").getAsJsonObject().has("providers")); + assertTrue(tenant.get("thirdParty").getAsJsonObject().has("providers")); } - createTenant_5_0(process.getProcess(), new TenantIdentifier(null, "a1", null), "t1", null, null, null, false, null, false, null, new JsonObject()); + createTenant_5_0(process.getProcess(), new TenantIdentifier(null, "a1", null), "t1", null, null, null, false, + null, false, null, new JsonObject()); { // Get using CDI 3.0 @@ -256,7 +259,7 @@ public void testDefaultStateWhenNothingIsPassedWhileCreatingAppAndTenant_5_0() t assertTrue(tenant.has("thirdParty")); assertEquals(new JsonArray(), tenant.get("firstFactors").getAsJsonArray()); // requiredSecondaryFactors should be null - assertTrue( tenant.get("thirdParty").getAsJsonObject().has("providers")); + assertTrue(tenant.get("thirdParty").getAsJsonObject().has("providers")); } } @@ -266,7 +269,8 @@ public void testDefaultStateWhenNothingIsPassedWhileCreatingAppAndTenant_5_1() t return; } - createApp_5_1(process.getProcess(), TenantIdentifier.BASE_TENANT, "a1", false, null, false, null, new JsonObject()); + createApp_5_1(process.getProcess(), TenantIdentifier.BASE_TENANT, "a1", false, null, false, null, + new JsonObject()); { // Get using CDI 3.0 JsonObject tenant = getTenant_3_0(new TenantIdentifier(null, "a1", null), process.getProcess()); @@ -302,10 +306,11 @@ public void testDefaultStateWhenNothingIsPassedWhileCreatingAppAndTenant_5_1() t assertEquals("public", tenant.get("tenantId").getAsString()); assertTrue(tenant.has("thirdParty")); // firstFactors and requiredSecondaryFactors should be null - assertTrue( tenant.get("thirdParty").getAsJsonObject().has("providers")); + assertTrue(tenant.get("thirdParty").getAsJsonObject().has("providers")); } - createTenant_5_1(process.getProcess(), new TenantIdentifier(null, "a1", null), "t1", false, null, false, null, new JsonObject()); + createTenant_5_1(process.getProcess(), new TenantIdentifier(null, "a1", null), "t1", false, null, false, null, + new JsonObject()); { // Get using CDI 3.0 @@ -344,7 +349,7 @@ public void testDefaultStateWhenNothingIsPassedWhileCreatingAppAndTenant_5_1() t assertTrue(tenant.has("firstFactors")); assertEquals(0, tenant.get("firstFactors").getAsJsonArray().size()); // requiredSecondaryFactors should be null - assertTrue( tenant.get("thirdParty").getAsJsonObject().has("providers")); + assertTrue(tenant.get("thirdParty").getAsJsonObject().has("providers")); } } @@ -354,7 +359,8 @@ public void testCreationOfAppAndTenantUsingFirstFactors() throws Exception { return; } - createApp_5_1(process.getProcess(), TenantIdentifier.BASE_TENANT, "a1", true, new String[]{"emailpassword", "otp-phone"}, false, null, new JsonObject()); + createApp_5_1(process.getProcess(), TenantIdentifier.BASE_TENANT, "a1", true, + new String[]{"emailpassword", "otp-phone"}, false, null, new JsonObject()); { // Get using CDI 3.0 @@ -395,12 +401,14 @@ public void testCreationOfAppAndTenantUsingFirstFactors() throws Exception { assertTrue(tenant.has("firstFactors")); assertEquals(2, tenant.get("firstFactors").getAsJsonArray().size()); // requiredSecondaryFactors should be null - assertTrue( tenant.get("thirdParty").getAsJsonObject().has("providers")); + assertTrue(tenant.get("thirdParty").getAsJsonObject().has("providers")); } - createTenant_5_1(process.getProcess(), new TenantIdentifier(null, "a1", null), "t1", true, new String[]{"emailpassword", "otp-phone"}, false, null, new JsonObject()); + createTenant_5_1(process.getProcess(), new TenantIdentifier(null, "a1", null), "t1", true, + new String[]{"emailpassword", "otp-phone"}, false, null, new JsonObject()); TestMultitenancyAPIHelper.addOrUpdateThirdPartyProviderConfig(new TenantIdentifier(null, "a1", "t1"), - new ThirdPartyConfig.Provider("google", "name", null, null, null, null, null, null, null, null, null, null, null, null), process.getProcess()); + new ThirdPartyConfig.Provider("google", "name", null, null, null, null, null, null, null, null, null, + null, null, null), process.getProcess()); { // Get using CDI 3.0 @@ -454,7 +462,8 @@ public void shouldBeAbleToEnableRecipesForTenantCreatedInOlderCDI() throws Excep createTenant_3_0(process.getProcess(), TenantIdentifier.BASE_TENANT, "t1", null, null, null, new JsonObject()); // Enable emailpassword and passwordless using firstFactors input - createTenant_5_1(process.getProcess(), TenantIdentifier.BASE_TENANT, "t1", true, new String[]{"emailpassword", "otp-phone"}, false, null, new JsonObject()); + createTenant_5_1(process.getProcess(), TenantIdentifier.BASE_TENANT, "t1", true, + new String[]{"emailpassword", "otp-phone"}, false, null, new JsonObject()); { // Get using CDI 3.0 @@ -544,7 +553,8 @@ public void testCrossVersionCreateAndUpdateCases() throws Exception { } else { throw new Exception("Invalid version"); } - tenantConfig = BaseCreateOrUpdate.createBaseConfigForVersionForTest(version, tenantIdentifier, isV2); + tenantConfig = BaseCreateOrUpdate.createBaseConfigForVersionForTest(version, tenantIdentifier, + isV2); tenantConfig = BaseCreateOrUpdate.applyTenantUpdatesForTest(tenantConfig, version, isV2, jsonObject.get("cbody").getAsJsonObject()); @@ -595,7 +605,8 @@ public void testCrossVersionCreateAndUpdateCases() throws Exception { System.out.println(c); } - private void validateState(JsonObject jsonObject, TenantConfig tenantConfig, JsonObject jsonLesserThanOrEqualTo40, JsonObject json50, JsonObject jsonV251) { + private void validateState(JsonObject jsonObject, TenantConfig tenantConfig, JsonObject jsonLesserThanOrEqualTo40, + JsonObject json50, JsonObject jsonV251) { JsonObject state = jsonObject.get("tenantState").getAsJsonObject(); JsonObject g4 = jsonObject.get("g4").getAsJsonObject(); JsonObject g5 = jsonObject.get("g5").getAsJsonObject(); @@ -606,8 +617,10 @@ private void validateState(JsonObject jsonObject, TenantConfig tenantConfig, Jso assertEquals(state.get("emailPasswordEnabled").getAsBoolean(), tenantConfig.emailPasswordConfig.enabled); assertEquals(state.get("thirdPartyEnabled").getAsBoolean(), tenantConfig.thirdPartyConfig.enabled); assertEquals(state.get("passwordlessEnabled").getAsBoolean(), tenantConfig.passwordlessConfig.enabled); - assertEquals(jsonArrayToStringSet(state.get("firstFactors")), stringArrayToStringSet(tenantConfig.firstFactors)); - assertEquals(jsonArrayToStringSet(state.get("requiredSecondaryFactors")), stringArrayToStringSet(tenantConfig.requiredSecondaryFactors)); + assertEquals(jsonArrayToStringSet(state.get("firstFactors")), + stringArrayToStringSet(tenantConfig.firstFactors)); + assertEquals(jsonArrayToStringSet(state.get("requiredSecondaryFactors")), + stringArrayToStringSet(tenantConfig.requiredSecondaryFactors)); } } @@ -634,9 +647,9 @@ private Set stringArrayToStringSet(String[] firstFactors) { } private static JsonObject createApp_3_0(Main main, TenantIdentifier sourceTenant, String appId, - Boolean emailPasswordEnabled, - Boolean thirdPartyEnabled, Boolean passwordlessEnabled, - JsonObject coreConfig) throws HttpResponseException, IOException { + Boolean emailPasswordEnabled, + Boolean thirdPartyEnabled, Boolean passwordlessEnabled, + JsonObject coreConfig) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("appId", appId); if (emailPasswordEnabled != null) { @@ -707,7 +720,7 @@ private static JsonObject createApp_5_0(Main main, TenantIdentifier sourceTenant } private static JsonObject createOrUpdateApp_5_0(Main main, TenantIdentifier sourceTenant, String appId, - JsonObject requestBody) throws HttpResponseException, IOException { + JsonObject requestBody) throws HttpResponseException, IOException { requestBody.addProperty("appId", appId); JsonObject response = HttpRequestForTesting.sendJsonPUTRequest(main, "", @@ -743,7 +756,7 @@ private static JsonObject createApp_5_1(Main main, TenantIdentifier sourceTenant } private static JsonObject createOrUpdateApp_5_1(Main main, TenantIdentifier sourceTenant, String appId, - JsonObject requestBody) throws HttpResponseException, IOException { + JsonObject requestBody) throws HttpResponseException, IOException { requestBody.addProperty("appId", appId); JsonObject response = HttpRequestForTesting.sendJsonPUTRequest(main, "", @@ -831,9 +844,9 @@ private static JsonObject deleteTenant(TenantIdentifier sourceTenant, String ten } private static JsonObject createTenant_3_0(Main main, TenantIdentifier sourceTenant, String tenantId, - Boolean emailPasswordEnabled, - Boolean thirdPartyEnabled, Boolean passwordlessEnabled, - JsonObject coreConfig) throws HttpResponseException, IOException { + Boolean emailPasswordEnabled, + Boolean thirdPartyEnabled, Boolean passwordlessEnabled, + JsonObject coreConfig) throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("tenantId", tenantId); if (emailPasswordEnabled != null) { @@ -858,7 +871,8 @@ private static JsonObject createTenant_3_0(Main main, TenantIdentifier sourceTen } private static JsonObject createOrUpdateTenant_3_0(Main main, TenantIdentifier sourceTenant, String tenantId, - JsonObject requestBody) throws HttpResponseException, IOException { + JsonObject requestBody) + throws HttpResponseException, IOException { requestBody.addProperty("tenantId", tenantId); JsonObject response = HttpRequestForTesting.sendJsonPUTRequest(main, "", @@ -906,7 +920,8 @@ private static JsonObject createTenant_5_0(Main main, TenantIdentifier sourceTen } private static JsonObject createOrUpdateTenant_5_0(Main main, TenantIdentifier sourceTenant, String tenantId, - JsonObject requestBody) throws HttpResponseException, IOException { + JsonObject requestBody) + throws HttpResponseException, IOException { requestBody.addProperty("tenantId", tenantId); JsonObject response = HttpRequestForTesting.sendJsonPUTRequest(main, "", @@ -943,7 +958,8 @@ private static JsonObject createTenant_5_1(Main main, TenantIdentifier sourceTen } private static JsonObject createOrUpdateTenant_5_1(Main main, TenantIdentifier sourceTenant, String tenantId, - JsonObject requestBody) throws HttpResponseException, IOException { + JsonObject requestBody) + throws HttpResponseException, IOException { requestBody.addProperty("tenantId", tenantId); JsonObject response = HttpRequestForTesting.sendJsonPUTRequest(main, "", @@ -973,6 +989,7 @@ private static class CrossVersionTestCaseStep { private static enum OperationType { CREATE_APP, CREATE_TENANT, UPDATE_APP, UPDATE_TENANT } + SemVer version; OperationType operation; JsonObject body; diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestTenantUserAssociation.java b/src/test/java/io/supertokens/test/multitenant/api/TestTenantUserAssociation.java index cf7457e6d..6907017cb 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestTenantUserAssociation.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestTenantUserAssociation.java @@ -369,7 +369,8 @@ public void testPasswordlessUsersHaveTenantIds2() throws Exception { Multitenancy.removeUserIdFromTenant(process.getProcess(), t1, t1Storage, consumeCodeResponse.user.getSupertokensUserId(), null); - user = Passwordless.getUserById(t1.toAppIdentifier(), t1Storage, consumeCodeResponse.user.getSupertokensUserId()); + user = Passwordless.getUserById(t1.toAppIdentifier(), t1Storage, + consumeCodeResponse.user.getSupertokensUserId()); assertArrayEquals(new String[]{"t2"}, user.tenantIds.toArray()); } @@ -521,14 +522,16 @@ public void testThatUserWithSameEmailCannotBeAssociatedToATenantForEp() throws E } createTenants(); - JsonObject user1 = TestMultitenancyAPIHelper.epSignUp(new TenantIdentifier(null, "a1", "t1"), "user@example.com", + JsonObject user1 = TestMultitenancyAPIHelper.epSignUp(new TenantIdentifier(null, "a1", "t1"), + "user@example.com", "password", process.getProcess()); String userId1 = user1.get("id").getAsString(); TestMultitenancyAPIHelper.epSignUp(new TenantIdentifier(null, "a1", "t2"), "user@example.com", "password", process.getProcess()); - JsonObject response = TestMultitenancyAPIHelper.associateUserToTenant(new TenantIdentifier(null, "a1", "t2"), userId1, process.getProcess()); + JsonObject response = TestMultitenancyAPIHelper.associateUserToTenant(new TenantIdentifier(null, "a1", "t2"), + userId1, process.getProcess()); assertEquals("EMAIL_ALREADY_EXISTS_ERROR", response.getAsJsonPrimitive("status").getAsString()); } @@ -539,14 +542,17 @@ public void testThatUserWithSameThirdPartyInfoCannotBeAssociatedToATenantForTp() } createTenants(); - JsonObject user1 = TestMultitenancyAPIHelper.tpSignInUp(new TenantIdentifier(null, "a1", "t1"), "google", "google-user", "user@example.com", + JsonObject user1 = TestMultitenancyAPIHelper.tpSignInUp(new TenantIdentifier(null, "a1", "t1"), "google", + "google-user", "user@example.com", process.getProcess()); String userId1 = user1.get("id").getAsString(); - TestMultitenancyAPIHelper.tpSignInUp(new TenantIdentifier(null, "a1", "t2"), "google", "google-user", "user@example.com", + TestMultitenancyAPIHelper.tpSignInUp(new TenantIdentifier(null, "a1", "t2"), "google", "google-user", + "user@example.com", process.getProcess()); - JsonObject response = TestMultitenancyAPIHelper.associateUserToTenant(new TenantIdentifier(null, "a1", "t2"), userId1, process.getProcess()); + JsonObject response = TestMultitenancyAPIHelper.associateUserToTenant(new TenantIdentifier(null, "a1", "t2"), + userId1, process.getProcess()); assertEquals("THIRD_PARTY_USER_ALREADY_EXISTS_ERROR", response.getAsJsonPrimitive("status").getAsString()); } @@ -557,14 +563,16 @@ public void testThatUserWithSameEmailCannotBeAssociatedToATenantForPless() throw } createTenants(); - JsonObject user1 = TestMultitenancyAPIHelper.plSignInUpEmail(new TenantIdentifier(null, "a1", "t1"), "user@example.com", + JsonObject user1 = TestMultitenancyAPIHelper.plSignInUpEmail(new TenantIdentifier(null, "a1", "t1"), + "user@example.com", process.getProcess()); String userId1 = user1.get("id").getAsString(); TestMultitenancyAPIHelper.plSignInUpEmail(new TenantIdentifier(null, "a1", "t2"), "user@example.com", process.getProcess()); - JsonObject response = TestMultitenancyAPIHelper.associateUserToTenant(new TenantIdentifier(null, "a1", "t2"), userId1, process.getProcess()); + JsonObject response = TestMultitenancyAPIHelper.associateUserToTenant(new TenantIdentifier(null, "a1", "t2"), + userId1, process.getProcess()); assertEquals("EMAIL_ALREADY_EXISTS_ERROR", response.getAsJsonPrimitive("status").getAsString()); } @@ -575,14 +583,16 @@ public void testThatUserWithSamePhoneCannotBeAssociatedToATenantForPless() throw } createTenants(); - JsonObject user1 = TestMultitenancyAPIHelper.plSignInUpNumber(new TenantIdentifier(null, "a1", "t1"), "+919876543210", + JsonObject user1 = TestMultitenancyAPIHelper.plSignInUpNumber(new TenantIdentifier(null, "a1", "t1"), + "+919876543210", process.getProcess()); String userId1 = user1.get("id").getAsString(); TestMultitenancyAPIHelper.plSignInUpNumber(new TenantIdentifier(null, "a1", "t2"), "+919876543210", process.getProcess()); - JsonObject response = TestMultitenancyAPIHelper.associateUserToTenant(new TenantIdentifier(null, "a1", "t2"), userId1, process.getProcess()); + JsonObject response = TestMultitenancyAPIHelper.associateUserToTenant(new TenantIdentifier(null, "a1", "t2"), + userId1, process.getProcess()); assertEquals("PHONE_NUMBER_ALREADY_EXISTS_ERROR", response.getAsJsonPrimitive("status").getAsString()); } } diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestThirdPartyProvider.java b/src/test/java/io/supertokens/test/multitenant/api/TestThirdPartyProvider.java index b20851bd3..2c1e56c01 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestThirdPartyProvider.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestThirdPartyProvider.java @@ -105,7 +105,8 @@ public void testAddThirdPartyConfig() throws Exception { assertTrue(response.get("createdNew").getAsBoolean()); response = TestMultitenancyAPIHelper.getTenant(new TenantIdentifier(null, null, null), process.getProcess()); - JsonObject resultProvider = response.get("thirdParty").getAsJsonObject().get("providers").getAsJsonArray().get(0).getAsJsonObject(); + JsonObject resultProvider = response.get("thirdParty").getAsJsonObject().get("providers").getAsJsonArray() + .get(0).getAsJsonObject(); assertEquals(new Gson().toJsonTree(provider), resultProvider); } @@ -143,7 +144,8 @@ public void testAddThirdPartyConfigWithNullValues() throws Exception { assertTrue(response.get("createdNew").getAsBoolean()); response = TestMultitenancyAPIHelper.getTenant(new TenantIdentifier(null, null, null), process.getProcess()); - JsonObject resultProvider = response.get("thirdParty").getAsJsonObject().get("providers").getAsJsonArray().get(0).getAsJsonObject(); + JsonObject resultProvider = response.get("thirdParty").getAsJsonObject().get("providers").getAsJsonArray() + .get(0).getAsJsonObject(); assertEquals(provider.toJson(), resultProvider); } @@ -210,7 +212,8 @@ public void testUpdateThirdPartyConfig() throws Exception { assertFalse(response.get("createdNew").getAsBoolean()); response = TestMultitenancyAPIHelper.getTenant(new TenantIdentifier(null, null, null), process.getProcess()); - JsonObject resultProvider = response.get("thirdParty").getAsJsonObject().get("providers").getAsJsonArray().get(0).getAsJsonObject(); + JsonObject resultProvider = response.get("thirdParty").getAsJsonObject().get("providers").getAsJsonArray() + .get(0).getAsJsonObject(); assertEquals(new Gson().toJsonTree(provider), resultProvider); } @@ -243,11 +246,13 @@ public void testDeleteThirdPartyConfig() throws Exception { ); assertTrue(response.get("createdNew").getAsBoolean()); - response = TestMultitenancyAPIHelper.deleteThirdPartyProvider(new TenantIdentifier(null, null, null), "google", process.getProcess()); + response = TestMultitenancyAPIHelper.deleteThirdPartyProvider(new TenantIdentifier(null, null, null), "google", + process.getProcess()); assertTrue(response.get("didConfigExist").getAsBoolean()); // delete again - response = TestMultitenancyAPIHelper.deleteThirdPartyProvider(new TenantIdentifier(null, null, null), "google", process.getProcess()); + response = TestMultitenancyAPIHelper.deleteThirdPartyProvider(new TenantIdentifier(null, null, null), "google", + process.getProcess()); assertFalse(response.get("didConfigExist").getAsBoolean()); } } diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestWithNonAuthRecipes.java b/src/test/java/io/supertokens/test/multitenant/api/TestWithNonAuthRecipes.java index 1819ded24..595342476 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestWithNonAuthRecipes.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestWithNonAuthRecipes.java @@ -117,17 +117,21 @@ public void testThatUserMetadataIsSavedInTheStorageWhereUserExists() throws Exce Storage t1Storage = (StorageLayer.getStorage(t1, process.getProcess())); // Create users - AuthRecipeUserInfo user1 = EmailPassword.signUp(t0, t0Storage, process.getProcess(), "test@example.com", "password123"); - AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test@example.com", "password123"); + AuthRecipeUserInfo user1 = EmailPassword.signUp(t0, t0Storage, process.getProcess(), "test@example.com", + "password123"); + AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test@example.com", + "password123"); UserIdMapping.populateExternalUserIdForUsers(t0.toAppIdentifier(), t0Storage, new AuthRecipeUserInfo[]{user1}); UserIdMapping.populateExternalUserIdForUsers(t0.toAppIdentifier(), t1Storage, new AuthRecipeUserInfo[]{user2}); // Check that get user by ID works fine - JsonObject jsonUser1 = TestMultitenancyAPIHelper.getUserById(t0, user1.getSupertokensUserId(), process.getProcess()); + JsonObject jsonUser1 = TestMultitenancyAPIHelper.getUserById(t0, user1.getSupertokensUserId(), + process.getProcess()); assertEquals(user1.toJson(), jsonUser1.get("user").getAsJsonObject()); - JsonObject jsonUser2 = TestMultitenancyAPIHelper.getUserById(t0, user2.getSupertokensUserId(), process.getProcess()); + JsonObject jsonUser2 = TestMultitenancyAPIHelper.getUserById(t0, user2.getSupertokensUserId(), + process.getProcess()); assertEquals(user2.toJson(), jsonUser2.get("user").getAsJsonObject()); JsonObject metadata = new JsonObject(); @@ -135,7 +139,8 @@ public void testThatUserMetadataIsSavedInTheStorageWhereUserExists() throws Exce { // Add metadata for user2 using t0 and ensure get user works fine - TestMultitenancyAPIHelper.updateUserMetadata(t0, user2.getSupertokensUserId(), metadata, process.getProcess()); + TestMultitenancyAPIHelper.updateUserMetadata(t0, user2.getSupertokensUserId(), metadata, + process.getProcess()); jsonUser2 = TestMultitenancyAPIHelper.getUserById(t0, user2.getSupertokensUserId(), process.getProcess()); assertEquals(user2.toJson(), jsonUser2.get("user").getAsJsonObject()); @@ -151,7 +156,8 @@ public void testThatUserMetadataIsSavedInTheStorageWhereUserExists() throws Exce { // Add metadata using t1 results in 403 try { - TestMultitenancyAPIHelper.updateUserMetadata(t1, user1.getSupertokensUserId(), metadata, process.getProcess()); + TestMultitenancyAPIHelper.updateUserMetadata(t1, user1.getSupertokensUserId(), metadata, + process.getProcess()); fail(); } catch (HttpResponseException e) { assertEquals(403, e.statusCode); @@ -160,7 +166,8 @@ public void testThatUserMetadataIsSavedInTheStorageWhereUserExists() throws Exce { // Add metadata for user1 using t0 and ensure get user works fine - TestMultitenancyAPIHelper.updateUserMetadata(t0, user1.getSupertokensUserId(), metadata, process.getProcess()); + TestMultitenancyAPIHelper.updateUserMetadata(t0, user1.getSupertokensUserId(), metadata, + process.getProcess()); jsonUser1 = TestMultitenancyAPIHelper.getUserById(t0, user1.getSupertokensUserId(), process.getProcess()); assertEquals(user1.toJson(), jsonUser1.get("user").getAsJsonObject()); @@ -177,12 +184,16 @@ public void testThatUserMetadataIsSavedInTheStorageWhereUserExists() throws Exce UserMetadataSQLStorage t1UserMetadataStorage = StorageUtils.getUserMetadataStorage(t1Storage); // Ensure that the metadata is saved in the correct storage - assertNotNull(t0UserMetadataStorage.getUserMetadata(t0.toAppIdentifier(), user1.getSupertokensUserId())); // ensure t0 storage does not have user2's metadata - assertNotNull(t1UserMetadataStorage.getUserMetadata(t0.toAppIdentifier(), user2.getSupertokensUserId())); // ensure t1 storage does not have user1's metadata + assertNotNull(t0UserMetadataStorage.getUserMetadata(t0.toAppIdentifier(), + user1.getSupertokensUserId())); // ensure t0 storage does not have user2's metadata + assertNotNull(t1UserMetadataStorage.getUserMetadata(t0.toAppIdentifier(), + user2.getSupertokensUserId())); // ensure t1 storage does not have user1's metadata // Ensure that the metadata is not stored in the wrong storage - assertNull(t0UserMetadataStorage.getUserMetadata(t0.toAppIdentifier(), user2.getSupertokensUserId())); // ensure t0 storage does not have user2's metadata - assertNull(t1UserMetadataStorage.getUserMetadata(t0.toAppIdentifier(), user1.getSupertokensUserId())); // ensure t1 storage does not have user1's metadata + assertNull(t0UserMetadataStorage.getUserMetadata(t0.toAppIdentifier(), + user2.getSupertokensUserId())); // ensure t0 storage does not have user2's metadata + assertNull(t1UserMetadataStorage.getUserMetadata(t0.toAppIdentifier(), + user1.getSupertokensUserId())); // ensure t1 storage does not have user1's metadata // Try deleting metadata try { @@ -193,8 +204,10 @@ public void testThatUserMetadataIsSavedInTheStorageWhereUserExists() throws Exce } TestMultitenancyAPIHelper.removeMetadata(t0, user1.getSupertokensUserId(), process.getProcess()); TestMultitenancyAPIHelper.removeMetadata(t0, user2.getSupertokensUserId(), process.getProcess()); - assertNull(t0UserMetadataStorage.getUserMetadata(t0.toAppIdentifier(), user1.getSupertokensUserId())); // ensure t0 storage does not have user2's metadata - assertNull(t1UserMetadataStorage.getUserMetadata(t0.toAppIdentifier(), user2.getSupertokensUserId())); // ensure t1 storage does not have user1's metadata + assertNull(t0UserMetadataStorage.getUserMetadata(t0.toAppIdentifier(), + user1.getSupertokensUserId())); // ensure t0 storage does not have user2's metadata + assertNull(t1UserMetadataStorage.getUserMetadata(t0.toAppIdentifier(), + user2.getSupertokensUserId())); // ensure t1 storage does not have user1's metadata } @Test @@ -214,18 +227,22 @@ public void testThatRoleIsStoredInPublicTenantAndUserRoleMappingInTheUserTenantS Storage t1Storage = (StorageLayer.getStorage(t1, process.getProcess())); // Create users - AuthRecipeUserInfo user1 = EmailPassword.signUp(t0, t0Storage, process.getProcess(), "test@example.com", "password123"); - AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test@example.com", "password123"); + AuthRecipeUserInfo user1 = EmailPassword.signUp(t0, t0Storage, process.getProcess(), "test@example.com", + "password123"); + AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test@example.com", + "password123"); UserIdMapping.populateExternalUserIdForUsers(t0.toAppIdentifier(), t0Storage, new AuthRecipeUserInfo[]{user1}); UserIdMapping.populateExternalUserIdForUsers(t1.toAppIdentifier(), t1Storage, new AuthRecipeUserInfo[]{user2}); { // Check that get user by ID works fine - JsonObject jsonUser1 = TestMultitenancyAPIHelper.getUserById(t0, user1.getSupertokensUserId(), process.getProcess()); + JsonObject jsonUser1 = TestMultitenancyAPIHelper.getUserById(t0, user1.getSupertokensUserId(), + process.getProcess()); assertEquals(user1.toJson(), jsonUser1.get("user").getAsJsonObject()); - JsonObject jsonUser2 = TestMultitenancyAPIHelper.getUserById(t0, user2.getSupertokensUserId(), process.getProcess()); + JsonObject jsonUser2 = TestMultitenancyAPIHelper.getUserById(t0, user2.getSupertokensUserId(), + process.getProcess()); assertEquals(user2.toJson(), jsonUser2.get("user").getAsJsonObject()); } @@ -244,20 +261,24 @@ public void testThatRoleIsStoredInPublicTenantAndUserRoleMappingInTheUserTenantS { // Check that get user by ID works fine - JsonObject jsonUser1 = TestMultitenancyAPIHelper.getUserById(t0, user1.getSupertokensUserId(), process.getProcess()); + JsonObject jsonUser1 = TestMultitenancyAPIHelper.getUserById(t0, user1.getSupertokensUserId(), + process.getProcess()); assertEquals(user1.toJson(), jsonUser1.get("user").getAsJsonObject()); - JsonObject jsonUser2 = TestMultitenancyAPIHelper.getUserById(t0, user2.getSupertokensUserId(), process.getProcess()); + JsonObject jsonUser2 = TestMultitenancyAPIHelper.getUserById(t0, user2.getSupertokensUserId(), + process.getProcess()); assertEquals(user2.toJson(), jsonUser2.get("user").getAsJsonObject()); } { - JsonObject user1Roles = TestMultitenancyAPIHelper.getUserRoles(t0, user1.getSupertokensUserId(), process.getProcess()); + JsonObject user1Roles = TestMultitenancyAPIHelper.getUserRoles(t0, user1.getSupertokensUserId(), + process.getProcess()); assertEquals(1, user1Roles.get("roles").getAsJsonArray().size()); user1Roles = TestMultitenancyAPIHelper.getUserRoles(t1, user1.getSupertokensUserId(), process.getProcess()); assertEquals(0, user1Roles.get("roles").getAsJsonArray().size()); - JsonObject user2Roles = TestMultitenancyAPIHelper.getUserRoles(t0, user2.getSupertokensUserId(), process.getProcess()); + JsonObject user2Roles = TestMultitenancyAPIHelper.getUserRoles(t0, user2.getSupertokensUserId(), + process.getProcess()); assertEquals(0, user2Roles.get("roles").getAsJsonArray().size()); user2Roles = TestMultitenancyAPIHelper.getUserRoles(t1, user2.getSupertokensUserId(), process.getProcess()); assertEquals(1, user2Roles.get("roles").getAsJsonArray().size()); @@ -274,12 +295,14 @@ public void testThatRoleIsStoredInPublicTenantAndUserRoleMappingInTheUserTenantS TestMultitenancyAPIHelper.deleteRole(t0, "role2", process.getProcess()); { - JsonObject user1Roles = TestMultitenancyAPIHelper.getUserRoles(t0, user1.getSupertokensUserId(), process.getProcess()); + JsonObject user1Roles = TestMultitenancyAPIHelper.getUserRoles(t0, user1.getSupertokensUserId(), + process.getProcess()); assertEquals(0, user1Roles.get("roles").getAsJsonArray().size()); user1Roles = TestMultitenancyAPIHelper.getUserRoles(t1, user1.getSupertokensUserId(), process.getProcess()); assertEquals(0, user1Roles.get("roles").getAsJsonArray().size()); - JsonObject user2Roles = TestMultitenancyAPIHelper.getUserRoles(t0, user2.getSupertokensUserId(), process.getProcess()); + JsonObject user2Roles = TestMultitenancyAPIHelper.getUserRoles(t0, user2.getSupertokensUserId(), + process.getProcess()); assertEquals(0, user2Roles.get("roles").getAsJsonArray().size()); user2Roles = TestMultitenancyAPIHelper.getUserRoles(t1, user2.getSupertokensUserId(), process.getProcess()); assertEquals(0, user2Roles.get("roles").getAsJsonArray().size()); @@ -287,10 +310,12 @@ public void testThatRoleIsStoredInPublicTenantAndUserRoleMappingInTheUserTenantS { // Check that get user by ID works fine - JsonObject jsonUser1 = TestMultitenancyAPIHelper.getUserById(t0, user1.getSupertokensUserId(), process.getProcess()); + JsonObject jsonUser1 = TestMultitenancyAPIHelper.getUserById(t0, user1.getSupertokensUserId(), + process.getProcess()); assertEquals(user1.toJson(), jsonUser1.get("user").getAsJsonObject()); - JsonObject jsonUser2 = TestMultitenancyAPIHelper.getUserById(t0, user2.getSupertokensUserId(), process.getProcess()); + JsonObject jsonUser2 = TestMultitenancyAPIHelper.getUserById(t0, user2.getSupertokensUserId(), + process.getProcess()); assertEquals(user2.toJson(), jsonUser2.get("user").getAsJsonObject()); } } @@ -312,22 +337,27 @@ public void testEmailVerificationWithUsersOnDifferentTenantStorages() throws Exc Storage t1Storage = (StorageLayer.getStorage(t1, process.getProcess())); // Create users - AuthRecipeUserInfo user1 = EmailPassword.signUp(t0, t0Storage, process.getProcess(), "test@example.com", "password123"); - AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test@example.com", "password123"); + AuthRecipeUserInfo user1 = EmailPassword.signUp(t0, t0Storage, process.getProcess(), "test@example.com", + "password123"); + AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test@example.com", + "password123"); UserIdMapping.populateExternalUserIdForUsers(t0.toAppIdentifier(), t0Storage, new AuthRecipeUserInfo[]{user1}); UserIdMapping.populateExternalUserIdForUsers(t1.toAppIdentifier(), t1Storage, new AuthRecipeUserInfo[]{user2}); // Check that get user by ID works fine - JsonObject jsonUser1 = TestMultitenancyAPIHelper.getUserById(t0, user1.getSupertokensUserId(), process.getProcess()); + JsonObject jsonUser1 = TestMultitenancyAPIHelper.getUserById(t0, user1.getSupertokensUserId(), + process.getProcess()); assertEquals(user1.toJson(), jsonUser1.get("user").getAsJsonObject()); - JsonObject jsonUser2 = TestMultitenancyAPIHelper.getUserById(t0, user2.getSupertokensUserId(), process.getProcess()); + JsonObject jsonUser2 = TestMultitenancyAPIHelper.getUserById(t0, user2.getSupertokensUserId(), + process.getProcess()); assertEquals(user2.toJson(), jsonUser2.get("user").getAsJsonObject()); { // Add email verification for user2 using t1 and ensure get user works fine - TestMultitenancyAPIHelper.verifyEmail(t1, user2.getSupertokensUserId(), "test@example.com", process.getProcess()); + TestMultitenancyAPIHelper.verifyEmail(t1, user2.getSupertokensUserId(), "test@example.com", + process.getProcess()); jsonUser2 = TestMultitenancyAPIHelper.getUserById(t0, user2.getSupertokensUserId(), process.getProcess()); user2.loginMethods[0].setVerified(); @@ -344,7 +374,8 @@ public void testEmailVerificationWithUsersOnDifferentTenantStorages() throws Exc { // Add email verification for user1 using t0 and ensure get user works fine - TestMultitenancyAPIHelper.verifyEmail(t0, user1.getSupertokensUserId(), "test@example.com", process.getProcess()); + TestMultitenancyAPIHelper.verifyEmail(t0, user1.getSupertokensUserId(), "test@example.com", + process.getProcess()); jsonUser1 = TestMultitenancyAPIHelper.getUserById(t0, user1.getSupertokensUserId(), process.getProcess()); user1.loginMethods[0].setVerified(); @@ -366,20 +397,27 @@ public void testEmailVerificationWithUsersOnDifferentTenantStorages() throws Exc assertTrue(t1EvStorage.isEmailVerified(t0.toAppIdentifier(), user2.getSupertokensUserId(), "test@example.com")); // Ensure that the metadata is not stored in the wrong storage - assertFalse(t0EvStorage.isEmailVerified(t0.toAppIdentifier(), user2.getSupertokensUserId(), "test@example.com")); // ensure t0 storage does not have user2's ev - assertFalse(t1EvStorage.isEmailVerified(t0.toAppIdentifier(), user1.getSupertokensUserId(), "test@example.com")); // ensure t1 storage does not have user1's ev + assertFalse(t0EvStorage.isEmailVerified(t0.toAppIdentifier(), user2.getSupertokensUserId(), + "test@example.com")); // ensure t0 storage does not have user2's ev + assertFalse(t1EvStorage.isEmailVerified(t0.toAppIdentifier(), user1.getSupertokensUserId(), + "test@example.com")); // ensure t1 storage does not have user1's ev // Try unverify try { - TestMultitenancyAPIHelper.unverifyEmail(t1, user1.getSupertokensUserId(), "test@example.com", process.getProcess()); + TestMultitenancyAPIHelper.unverifyEmail(t1, user1.getSupertokensUserId(), "test@example.com", + process.getProcess()); fail(); } catch (HttpResponseException e) { assertEquals(403, e.statusCode); } - TestMultitenancyAPIHelper.unverifyEmail(t0, user1.getSupertokensUserId(), "test@example.com", process.getProcess()); - TestMultitenancyAPIHelper.unverifyEmail(t0, user2.getSupertokensUserId(), "test@example.com", process.getProcess()); - assertFalse(t1EvStorage.isEmailVerified(t0.toAppIdentifier(), user2.getSupertokensUserId(), "test@example.com")); // ensure t1 storage does not have user2's ev - assertFalse(t0EvStorage.isEmailVerified(t0.toAppIdentifier(), user1.getSupertokensUserId(), "test@example.com")); // ensure t0 storage does not have user1's ev + TestMultitenancyAPIHelper.unverifyEmail(t0, user1.getSupertokensUserId(), "test@example.com", + process.getProcess()); + TestMultitenancyAPIHelper.unverifyEmail(t0, user2.getSupertokensUserId(), "test@example.com", + process.getProcess()); + assertFalse(t1EvStorage.isEmailVerified(t0.toAppIdentifier(), user2.getSupertokensUserId(), + "test@example.com")); // ensure t1 storage does not have user2's ev + assertFalse(t0EvStorage.isEmailVerified(t0.toAppIdentifier(), user1.getSupertokensUserId(), + "test@example.com")); // ensure t0 storage does not have user1's ev } @Test @@ -399,8 +437,10 @@ public void testSessionCannotGetAcrossAllStorageOrRevokedAcrossAllTenantsFromNon Storage t1Storage = (StorageLayer.getStorage(t1, process.getProcess())); // Create users - AuthRecipeUserInfo user1 = EmailPassword.signUp(t0, t0Storage, process.getProcess(), "test@example.com", "password123"); - AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test@example.com", "password123"); + AuthRecipeUserInfo user1 = EmailPassword.signUp(t0, t0Storage, process.getProcess(), "test@example.com", + "password123"); + AuthRecipeUserInfo user2 = EmailPassword.signUp(t1, t1Storage, process.getProcess(), "test@example.com", + "password123"); UserIdMapping.populateExternalUserIdForUsers(t0.toAppIdentifier(), t0Storage, new AuthRecipeUserInfo[]{user1}); UserIdMapping.populateExternalUserIdForUsers(t1.toAppIdentifier(), t1Storage, new AuthRecipeUserInfo[]{user2}); @@ -421,7 +461,8 @@ public void testSessionCannotGetAcrossAllStorageOrRevokedAcrossAllTenantsFromNon "session"); assertEquals("OK", sessionResponse.get("status").getAsString()); assertEquals(1, sessionResponse.get("sessionHandles").getAsJsonArray().size()); - assertEquals(sess1.session.handle, sessionResponse.get("sessionHandles").getAsJsonArray().get(0).getAsString()); + assertEquals(sess1.session.handle, + sessionResponse.get("sessionHandles").getAsJsonArray().get(0).getAsString()); } { diff --git a/src/test/java/io/supertokens/test/multitenant/generator/ConfigGenerator.java b/src/test/java/io/supertokens/test/multitenant/generator/ConfigGenerator.java index c24db6d31..beb5f2728 100644 --- a/src/test/java/io/supertokens/test/multitenant/generator/ConfigGenerator.java +++ b/src/test/java/io/supertokens/test/multitenant/generator/ConfigGenerator.java @@ -120,7 +120,8 @@ public static GeneratedValueAndExpectation generate(Class type, Object[] gene // Take just the class name and load the generator class from `io.supertokens.test.multitenant.generator` String[] classNameParts = type.getName().split("\\."); - Class generatorClass = Class.forName("io.supertokens.test.multitenant.generator.Generate" + classNameParts[classNameParts.length-1].replace('$', '_')); + Class generatorClass = Class.forName("io.supertokens.test.multitenant.generator.Generate" + + classNameParts[classNameParts.length - 1].replace('$', '_')); // Use the first constructor // Also expecting declared fields are the parameters to the constructor @@ -129,14 +130,14 @@ public static GeneratedValueAndExpectation generate(Class type, Object[] gene Parameter[] parameters = constructor.getParameters(); Field[] fields = type.getDeclaredFields(); - assert(parameters.length == fields.length); // Expecting same number of declared fields and constructor params + assert (parameters.length == fields.length); // Expecting same number of declared fields and constructor params Object[] constructorParamValues = new Object[parameters.length]; HashMap expectations = new HashMap<>(); // Map for field to Expectation for (int i = 0; i < parameters.length; i++) { Parameter parameter = parameters[i]; Field field = fields[i]; - assert(parameter.getType() == field.getType()); + assert (parameter.getType() == field.getType()); Class[] paramTypes = new Class[generateParams.length]; for (int paramIdx = 0; paramIdx < generateParams.length; paramIdx++) { diff --git a/src/test/java/io/supertokens/test/multitenant/generator/GenerateEmailPasswordConfig.java b/src/test/java/io/supertokens/test/multitenant/generator/GenerateEmailPasswordConfig.java index 39e4af66f..19f8c6524 100644 --- a/src/test/java/io/supertokens/test/multitenant/generator/GenerateEmailPasswordConfig.java +++ b/src/test/java/io/supertokens/test/multitenant/generator/GenerateEmailPasswordConfig.java @@ -20,7 +20,7 @@ public class GenerateEmailPasswordConfig { public static ConfigGenerator.GeneratedValueAndExpectation generate_enabled() { - boolean enabled = new Random().nextBoolean(); + boolean enabled = new Random().nextBoolean(); return new ConfigGenerator.GeneratedValueAndExpectation( enabled, new ConfigGenerator.Expectation("ok", enabled)); diff --git a/src/test/java/io/supertokens/test/multitenant/generator/GeneratePasswordlessConfig.java b/src/test/java/io/supertokens/test/multitenant/generator/GeneratePasswordlessConfig.java index c7586579a..7cac6425b 100644 --- a/src/test/java/io/supertokens/test/multitenant/generator/GeneratePasswordlessConfig.java +++ b/src/test/java/io/supertokens/test/multitenant/generator/GeneratePasswordlessConfig.java @@ -20,7 +20,7 @@ public class GeneratePasswordlessConfig { public static ConfigGenerator.GeneratedValueAndExpectation generate_enabled() { - boolean enabled = new Random().nextBoolean(); + boolean enabled = new Random().nextBoolean(); return new ConfigGenerator.GeneratedValueAndExpectation( enabled, new ConfigGenerator.Expectation("ok", enabled)); diff --git a/src/test/java/io/supertokens/test/multitenant/generator/GenerateTenantConfig.java b/src/test/java/io/supertokens/test/multitenant/generator/GenerateTenantConfig.java index abb633f26..e365fe96e 100644 --- a/src/test/java/io/supertokens/test/multitenant/generator/GenerateTenantConfig.java +++ b/src/test/java/io/supertokens/test/multitenant/generator/GenerateTenantConfig.java @@ -119,6 +119,7 @@ public static ConfigGenerator.GeneratedValueAndExpectation generate_requiredSeco public static ConfigGenerator.GeneratedValueAndExpectation generate_coreConfig() { // TODO: - return new ConfigGenerator.GeneratedValueAndExpectation(new JsonObject(), new ConfigGenerator.Expectation("ok", new JsonObject())); + return new ConfigGenerator.GeneratedValueAndExpectation(new JsonObject(), + new ConfigGenerator.Expectation("ok", new JsonObject())); } } diff --git a/src/test/java/io/supertokens/test/multitenant/generator/GenerateThirdPartyConfig.java b/src/test/java/io/supertokens/test/multitenant/generator/GenerateThirdPartyConfig.java index 00c7c76f5..11473d91e 100644 --- a/src/test/java/io/supertokens/test/multitenant/generator/GenerateThirdPartyConfig.java +++ b/src/test/java/io/supertokens/test/multitenant/generator/GenerateThirdPartyConfig.java @@ -46,7 +46,7 @@ public static String[] generate() { boolean includeDuplicates = new Random().nextDouble() < 0.1; String[] providers = new String[numProviders]; - for (int i=0; i < numProviders; i++) { + for (int i = 0; i < numProviders; i++) { while (true) { if (r.nextDouble() < 0.02) { providers[i] = null; @@ -70,7 +70,7 @@ public static String[] generate() { } public static ConfigGenerator.GeneratedValueAndExpectation generate_enabled() { - boolean enabled = new Random().nextBoolean(); + boolean enabled = new Random().nextBoolean(); return new ConfigGenerator.GeneratedValueAndExpectation( enabled, new ConfigGenerator.Expectation("ok", enabled)); @@ -102,14 +102,15 @@ public static ConfigGenerator.GeneratedValueAndExpectation generate_providers() HashSet thirdPartyIdSet = new HashSet<>(); - for (int i=0; i clientTypeSet = new HashSet<>(); - for (int i=0; i= 4.0 - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), email, null, null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), email, null, + null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); consumeCodeRequestBody.addProperty("linkCode", createResp.linkCode); @@ -144,7 +146,8 @@ public void testPasswordlessLoginSetsEmailVerified_v4_0() throws Exception { { // Email verification is set for CDI >= 4.0, for returning user - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), email, null, null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), email, null, + null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); consumeCodeRequestBody.addProperty("linkCode", createResp.linkCode); @@ -185,7 +188,8 @@ public void testWithAccountLinking() throws Exception { EmailVerification.unverifyEmail(process.getProcess(), user2.getSupertokensUserId(), "test@example.com"); { - Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), "test@example.com", null, null, null); + Passwordless.CreateCodeResponse createResp = Passwordless.createCode(process.getProcess(), + "test@example.com", null, null, null); JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("preAuthSessionId", createResp.deviceIdHash); consumeCodeRequestBody.addProperty("linkCode", createResp.linkCode); @@ -194,8 +198,11 @@ public void testWithAccountLinking() throws Exception { "http://localhost:3567/recipe/signinup/code/consume", consumeCodeRequestBody, 1000, 1000, null, SemVer.v4_0.get(), "passwordless"); - assertTrue(EmailVerification.isEmailVerified(process.getProcess(), user2.getSupertokensUserId(), "test@example.com")); - assertTrue(response.get("user").getAsJsonObject().get("loginMethods").getAsJsonArray().get(1).getAsJsonObject().get("verified").getAsBoolean()); + assertTrue(EmailVerification.isEmailVerified(process.getProcess(), user2.getSupertokensUserId(), + "test@example.com")); + assertTrue( + response.get("user").getAsJsonObject().get("loginMethods").getAsJsonArray().get(1).getAsJsonObject() + .get("verified").getAsBoolean()); } process.kill(); diff --git a/src/test/java/io/supertokens/test/passwordless/api/MultitenantAPITest.java b/src/test/java/io/supertokens/test/passwordless/api/MultitenantAPITest.java index 028e0dae1..7afde422f 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/MultitenantAPITest.java +++ b/src/test/java/io/supertokens/test/passwordless/api/MultitenantAPITest.java @@ -248,7 +248,8 @@ private void unsuccessfulConsumeCode(TenantIdentifier tenantIdentifier, String p assertEquals("RESTART_FLOW_ERROR", response.get("status").getAsString()); } - private JsonObject consumeCode(TenantIdentifier tenantIdentifier, String deviceId, String preAuthSessionId, String userInputCode) + private JsonObject consumeCode(TenantIdentifier tenantIdentifier, String deviceId, String preAuthSessionId, + String userInputCode) throws HttpResponseException, IOException { JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("deviceId", deviceId); @@ -263,7 +264,8 @@ private JsonObject consumeCode(TenantIdentifier tenantIdentifier, String deviceI return response.get("user").getAsJsonObject(); } - private void unsuccessfulConsumeCode(TenantIdentifier tenantIdentifier, String deviceId, String preAuthSessionId, String userInputCode) + private void unsuccessfulConsumeCode(TenantIdentifier tenantIdentifier, String deviceId, String preAuthSessionId, + String userInputCode) throws HttpResponseException, IOException { JsonObject consumeCodeRequestBody = new JsonObject(); consumeCodeRequestBody.addProperty("deviceId", deviceId); @@ -280,25 +282,29 @@ private void unsuccessfulConsumeCode(TenantIdentifier tenantIdentifier, String d private JsonObject signInUpEmailUsingLinkCode(TenantIdentifier tenantIdentifier, String email) throws HttpResponseException, IOException { JsonObject code = createCodeWithEmail(tenantIdentifier, email); - return consumeCode(tenantIdentifier, code.get("preAuthSessionId").getAsString(), code.get("linkCode").getAsString()); + return consumeCode(tenantIdentifier, code.get("preAuthSessionId").getAsString(), + code.get("linkCode").getAsString()); } private JsonObject signInUpEmailUsingUserInputCode(TenantIdentifier tenantIdentifier, String email) throws HttpResponseException, IOException { JsonObject code = createCodeWithEmail(tenantIdentifier, email); - return consumeCode(tenantIdentifier, code.get("deviceId").getAsString(), code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString()); + return consumeCode(tenantIdentifier, code.get("deviceId").getAsString(), + code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString()); } private JsonObject signInUpNumberUsingLinkCode(TenantIdentifier tenantIdentifier, String phoneNumber) throws HttpResponseException, IOException { JsonObject code = createCodeWithNumber(tenantIdentifier, phoneNumber); - return consumeCode(tenantIdentifier, code.get("preAuthSessionId").getAsString(), code.get("linkCode").getAsString()); + return consumeCode(tenantIdentifier, code.get("preAuthSessionId").getAsString(), + code.get("linkCode").getAsString()); } private JsonObject signInUpNumberUsingUserInputCode(TenantIdentifier tenantIdentifier, String phoneNumber) throws HttpResponseException, IOException { JsonObject code = createCodeWithNumber(tenantIdentifier, phoneNumber); - return consumeCode(tenantIdentifier, code.get("deviceId").getAsString(), code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString()); + return consumeCode(tenantIdentifier, code.get("deviceId").getAsString(), + code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString()); } private JsonObject getUserUsingId(TenantIdentifier tenantIdentifier, String userId) @@ -423,41 +429,49 @@ public void testCreateCodeOnOneTenantAndConsumeOnAnotherDoesNotWork() throws Exc TenantIdentifier[] tenants = new TenantIdentifier[]{t1, t2, t3}; for (TenantIdentifier createTenant : tenants) { - for (TenantIdentifier consumeTenant: tenants) { + for (TenantIdentifier consumeTenant : tenants) { { // email with link code JsonObject code = createCodeWithEmail(createTenant, "user@example.com"); if (createTenant.equals(consumeTenant)) { - consumeCode(consumeTenant, code.get("preAuthSessionId").getAsString(), code.get("linkCode").getAsString()); + consumeCode(consumeTenant, code.get("preAuthSessionId").getAsString(), + code.get("linkCode").getAsString()); } else { - unsuccessfulConsumeCode(consumeTenant, code.get("preAuthSessionId").getAsString(), code.get("linkCode").getAsString()); + unsuccessfulConsumeCode(consumeTenant, code.get("preAuthSessionId").getAsString(), + code.get("linkCode").getAsString()); } } { // email with user input code JsonObject code = createCodeWithEmail(createTenant, "user@example.com"); if (createTenant.equals(consumeTenant)) { - consumeCode(consumeTenant, code.get("deviceId").getAsString(), code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString()); + consumeCode(consumeTenant, code.get("deviceId").getAsString(), + code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString()); } else { - unsuccessfulConsumeCode(consumeTenant, code.get("deviceId").getAsString(), code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString()); + unsuccessfulConsumeCode(consumeTenant, code.get("deviceId").getAsString(), + code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString()); } } { // phoneNumber with link code JsonObject code = createCodeWithNumber(createTenant, "+442071838750"); if (createTenant.equals(consumeTenant)) { - consumeCode(consumeTenant, code.get("preAuthSessionId").getAsString(), code.get("linkCode").getAsString()); + consumeCode(consumeTenant, code.get("preAuthSessionId").getAsString(), + code.get("linkCode").getAsString()); } else { - unsuccessfulConsumeCode(consumeTenant, code.get("preAuthSessionId").getAsString(), code.get("linkCode").getAsString()); + unsuccessfulConsumeCode(consumeTenant, code.get("preAuthSessionId").getAsString(), + code.get("linkCode").getAsString()); } } { // phoneNumber with user input code JsonObject code = createCodeWithNumber(createTenant, "+442071838750"); if (createTenant.equals(consumeTenant)) { - consumeCode(consumeTenant, code.get("deviceId").getAsString(), code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString()); + consumeCode(consumeTenant, code.get("deviceId").getAsString(), + code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString()); } else { - unsuccessfulConsumeCode(consumeTenant, code.get("deviceId").getAsString(), code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString()); + unsuccessfulConsumeCode(consumeTenant, code.get("deviceId").getAsString(), + code.get("preAuthSessionId").getAsString(), code.get("userInputCode").getAsString()); } } } @@ -465,7 +479,8 @@ public void testCreateCodeOnOneTenantAndConsumeOnAnotherDoesNotWork() throws Exc } @Test - public void testGetUserUsingIdReturnsUserFromTheRightTenantWhileQueryingFromAnyTenantInTheSameApp() throws Exception { + public void testGetUserUsingIdReturnsUserFromTheRightTenantWhileQueryingFromAnyTenantInTheSameApp() + throws Exception { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCheckCodeAPITest5_0.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCheckCodeAPITest5_0.java index 4d8b9fe42..597246d98 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCheckCodeAPITest5_0.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCheckCodeAPITest5_0.java @@ -53,7 +53,7 @@ public void beforeEach() { @Test public void testBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -101,7 +101,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -124,7 +125,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -146,7 +148,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } { @@ -166,7 +169,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } { @@ -186,7 +190,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -274,7 +279,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -287,7 +293,7 @@ public void testBadInput() throws Exception { @Test public void testLinkCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -320,7 +326,7 @@ public void testLinkCode() throws Exception { @Test public void testExpiredLinkCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("passwordless_code_lifetime", "100"); @@ -355,7 +361,7 @@ public void testExpiredLinkCode() throws Exception { @Test public void testUserInputCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -389,7 +395,7 @@ public void testUserInputCode() throws Exception { @Test public void testUserInputCodeDoesNotDeleteTheCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -430,7 +436,7 @@ public void testUserInputCodeDoesNotDeleteTheCode() throws Exception { @Test public void testExpiredUserInputCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("passwordless_code_lifetime", "100"); TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); @@ -466,7 +472,7 @@ public void testExpiredUserInputCode() throws Exception { @Test public void testIncorrectUserInputCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("passwordless_max_code_input_attempts", "2"); // Only 2 code entries permitted (1 retry) @@ -506,7 +512,7 @@ public void testIncorrectUserInputCode() throws Exception { @Test public void testConsumeCodeWithoutCreatingUser() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -535,7 +541,8 @@ public void testConsumeCodeWithoutCreatingUser() throws Exception { int activeUsers = ActiveUsers.countUsersActiveSince(process.getProcess(), startTs); assert (activeUsers == 0); - assertEquals(0, AuthRecipe.getUsersCount(process.getProcess(), null)); // ensure that no user was actually created + assertEquals(0, + AuthRecipe.getUsersCount(process.getProcess(), null)); // ensure that no user was actually created process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -543,7 +550,7 @@ public void testConsumeCodeWithoutCreatingUser() throws Exception { @Test public void testVerifyCodeReturnsUserIfItAlreadyExists() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -582,7 +589,7 @@ public void testVerifyCodeReturnsUserIfItAlreadyExists() throws Exception { @Test public void testBadInputWithoutCreatingUser() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -631,7 +638,8 @@ public void testBadInputWithoutCreatingUser() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -655,7 +663,8 @@ public void testBadInputWithoutCreatingUser() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -678,7 +687,8 @@ public void testBadInputWithoutCreatingUser() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } { @@ -699,7 +709,8 @@ public void testBadInputWithoutCreatingUser() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } { @@ -720,7 +731,8 @@ public void testBadInputWithoutCreatingUser() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -812,7 +824,8 @@ public void testBadInputWithoutCreatingUser() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -825,7 +838,7 @@ public void testBadInputWithoutCreatingUser() throws Exception { @Test public void testLinkCodeWithoutCreatingUser() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -858,7 +871,7 @@ public void testLinkCodeWithoutCreatingUser() throws Exception { @Test public void testExpiredLinkCodeWithoutCreatingUser() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("passwordless_code_lifetime", "100"); @@ -894,7 +907,7 @@ public void testExpiredLinkCodeWithoutCreatingUser() throws Exception { @Test public void testExpiredUserInputCodeWithoutCreatingUser() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("passwordless_code_lifetime", "100"); TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); @@ -931,7 +944,7 @@ public void testExpiredUserInputCodeWithoutCreatingUser() throws Exception { @Test public void testIncorrectUserInputCodeWithoutCreatingUser() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("passwordless_max_code_input_attempts", "2"); // Only 2 code entries permitted (1 retry) diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest2_11.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest2_11.java index 57870a19e..ab91ab835 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest2_11.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest2_11.java @@ -55,7 +55,7 @@ public void beforeEach() { @Test public void testBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -103,7 +103,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -126,7 +127,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -148,7 +150,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } { @@ -168,7 +171,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } { @@ -188,7 +192,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -276,7 +281,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -289,7 +295,7 @@ public void testBadInput() throws Exception { @Test public void testLinkCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -322,7 +328,7 @@ public void testLinkCode() throws Exception { @Test public void testExpiredLinkCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("passwordless_code_lifetime", "100"); @@ -357,7 +363,7 @@ public void testExpiredLinkCode() throws Exception { @Test public void testUserInputCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -391,7 +397,7 @@ public void testUserInputCode() throws Exception { @Test public void testExpiredUserInputCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("passwordless_code_lifetime", "100"); TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); @@ -427,7 +433,7 @@ public void testExpiredUserInputCode() throws Exception { @Test public void testIncorrectUserInputCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("passwordless_max_code_input_attempts", "2"); // Only 2 code entries permitted (1 retry) diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest5_0.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest5_0.java index b52fde519..b0e29aa69 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest5_0.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest5_0.java @@ -52,7 +52,7 @@ public void beforeEach() { @Test public void testBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -100,7 +100,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -123,7 +124,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -145,7 +147,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } { @@ -165,7 +168,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } { @@ -185,7 +189,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -273,7 +278,8 @@ public void testBadInput() throws Exception { assertNotNull(error); assertEquals(400, error.statusCode); assertEquals( - "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or deviceId+userInputCode", + "Http error. Status Code: 400. Message: Please provide exactly one of linkCode or " + + "deviceId+userInputCode", error.getMessage()); } @@ -286,7 +292,7 @@ public void testBadInput() throws Exception { @Test public void testLinkCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -319,7 +325,7 @@ public void testLinkCode() throws Exception { @Test public void testExpiredLinkCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("passwordless_code_lifetime", "100"); @@ -354,7 +360,7 @@ public void testExpiredLinkCode() throws Exception { @Test public void testUserInputCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -388,7 +394,7 @@ public void testUserInputCode() throws Exception { @Test public void testExpiredUserInputCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("passwordless_code_lifetime", "100"); TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); @@ -424,7 +430,7 @@ public void testExpiredUserInputCode() throws Exception { @Test public void testIncorrectUserInputCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("passwordless_max_code_input_attempts", "2"); // Only 2 code entries permitted (1 retry) diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest.java index 2a511eff1..dc1f79f61 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest.java @@ -71,7 +71,7 @@ public void testPhoneNumberNormalisation() throws Exception { JsonObject createCodeResponse = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/recipe/signinup/code", createCodeRequestBody, 1000, 1000, null, WebserverAPI.getLatestCDIVersion().get(), "passwordless"); - + assertEquals("OK", createCodeResponse.get("status").getAsString()); HashMap params = new HashMap<>(); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest2_11.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest2_11.java index 596382a61..2d3cb7215 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest2_11.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest2_11.java @@ -53,7 +53,7 @@ public void beforeEach() { @Test public void testEmail() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -77,7 +77,7 @@ public void testEmail() throws Exception { @Test public void testEmailWithUserInputCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -102,7 +102,7 @@ public void testEmailWithUserInputCode() throws Exception { @Test public void testPhone() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -125,7 +125,7 @@ public void testPhone() throws Exception { @Test public void testPhoneWithUserInputCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -150,7 +150,7 @@ public void testPhoneWithUserInputCode() throws Exception { @Test public void testResend() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -181,7 +181,7 @@ public void testResend() throws Exception { @Test public void testResendWithUserInputCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -214,7 +214,7 @@ public void testResendWithUserInputCode() throws Exception { @Test public void testResendWithAlreadyUsedUserInputCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -248,7 +248,7 @@ public void testResendWithAlreadyUsedUserInputCode() throws Exception { @Test public void testResendWithNonExistantDeviceId() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -272,7 +272,7 @@ public void testResendWithNonExistantDeviceId() throws Exception { @Test public void testAllIds() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -307,7 +307,7 @@ public void testAllIds() throws Exception { @Test public void testEmailAndPhone() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -341,7 +341,7 @@ public void testEmailAndPhone() throws Exception { @Test public void testEmailAndDeviceId() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -375,7 +375,7 @@ public void testEmailAndDeviceId() throws Exception { @Test public void testPhoneAndDeviceId() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -414,7 +414,7 @@ public void testPhoneAndDeviceId() throws Exception { */ @Test public void testMalformedDeviceId() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -450,7 +450,7 @@ public void testMalformedDeviceId() throws Exception { */ @Test public void testUserInputCode() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -483,7 +483,7 @@ public void testUserInputCode() throws Exception { @Test public void testNoParams() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodesAPITest.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodesAPITest.java index 28d687e85..9d80fefd4 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodesAPITest.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodesAPITest.java @@ -71,7 +71,8 @@ public void testDeleteByUnnormalisedPhoneNumber() throws Exception { String deviceIdHash = "pZ9SP0USbXbejGFO6qx7x3JBjupJZVtw4RkFiNtJGqc"; String linkCodeHash = "wo5UcFFVSblZEd1KOUOl-dpJ5zpSr_Qsor1Eg4TzDRE"; - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), null, normalisedPhoneNumber, "linkCodeSalt", + storage.createDeviceWithCode(new TenantIdentifier(null, null, null), null, normalisedPhoneNumber, + "linkCodeSalt", new PasswordlessCode(codeId, deviceIdHash, linkCodeHash, System.currentTimeMillis())); JsonObject removeCodesRequestBody = new JsonObject(); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest.java index 774772bba..f2a57bfc7 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest.java @@ -44,94 +44,94 @@ import static org.junit.Assert.assertNotNull; public class PasswordlessGetCodesAPITest { - @Rule - public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule watchman = Utils.getOnFailure(); - @AfterClass - public static void afterTesting() { - Utils.afterTesting(); - } - - @Before - public void beforeEach() { - Utils.reset(); - } - - @Test - public void testGetCodesWithUnnormalisedPhoneNumber() throws Exception { - String[] args = { "../" }; - - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); - assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); - - if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { - return; + @AfterClass + public static void afterTesting() { + Utils.afterTesting(); } - PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); - String phoneNumber = "+44-207 183 8750"; - String normalisedPhoneNumber = io.supertokens.utils.Utils.normalizeIfPhoneNumber(phoneNumber); - String codeId = io.supertokens.utils.Utils.getUUID(); - - String deviceIdHash = "pZ9SP0USbXbejGFO6qx7x3JBjupJZVtw4RkFiNtJGqc="; - String linkCodeHash = "wo5UcFFVSblZEd1KOUOl-dpJ5zpSr_Qsor1Eg4TzDRE"; - - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), null, normalisedPhoneNumber, - "linkCodeSalt", - new PasswordlessCode(codeId, deviceIdHash, linkCodeHash, System.currentTimeMillis())); - assertEquals(1, - storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), normalisedPhoneNumber).length); - - HashMap map = new HashMap<>(); - map.put("phoneNumber", phoneNumber); - JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/recipe/signinup/codes", map, 1000, 1000, null, - WebserverAPI.getLatestCDIVersion().get(), "passwordless"); - - assertEquals("OK", response.get("status").getAsString()); - assertEquals(2, response.entrySet().size()); - assert (response.has("devices")); - JsonArray jsonDeviceList = response.get("devices").getAsJsonArray(); - assertEquals(1, jsonDeviceList.size()); - checkDevice(jsonDeviceList, 0, null, normalisedPhoneNumber, deviceIdHash, new String[] { codeId }); - process.kill(); - assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); - } - - private void checkDevice(JsonArray jsonDeviceList, int ind, String email, String phoneNumber, String deviceIdHash, - String[] codeIds) { - JsonObject device = jsonDeviceList.get(ind).getAsJsonObject(); - - assertEquals(deviceIdHash, device.get("preAuthSessionId").getAsString()); - assertEquals(0, device.get("failedCodeInputAttemptCount").getAsInt()); - - if (email == null) { - assert (!device.has("email")); - } else { - assertEquals(email, device.get("email").getAsString()); + @Before + public void beforeEach() { + Utils.reset(); } - if (phoneNumber == null) { - assert (!device.has("phoneNumber")); - } else { - assertEquals(phoneNumber, device.get("phoneNumber").getAsString()); + @Test + public void testGetCodesWithUnnormalisedPhoneNumber() throws Exception { + String[] args = {"../"}; + + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); + + if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { + return; + } + + PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); + String phoneNumber = "+44-207 183 8750"; + String normalisedPhoneNumber = io.supertokens.utils.Utils.normalizeIfPhoneNumber(phoneNumber); + String codeId = io.supertokens.utils.Utils.getUUID(); + + String deviceIdHash = "pZ9SP0USbXbejGFO6qx7x3JBjupJZVtw4RkFiNtJGqc="; + String linkCodeHash = "wo5UcFFVSblZEd1KOUOl-dpJ5zpSr_Qsor1Eg4TzDRE"; + + storage.createDeviceWithCode(new TenantIdentifier(null, null, null), null, normalisedPhoneNumber, + "linkCodeSalt", + new PasswordlessCode(codeId, deviceIdHash, linkCodeHash, System.currentTimeMillis())); + assertEquals(1, + storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), normalisedPhoneNumber).length); + + HashMap map = new HashMap<>(); + map.put("phoneNumber", phoneNumber); + JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", + "http://localhost:3567/recipe/signinup/codes", map, 1000, 1000, null, + WebserverAPI.getLatestCDIVersion().get(), "passwordless"); + + assertEquals("OK", response.get("status").getAsString()); + assertEquals(2, response.entrySet().size()); + assert (response.has("devices")); + JsonArray jsonDeviceList = response.get("devices").getAsJsonArray(); + assertEquals(1, jsonDeviceList.size()); + checkDevice(jsonDeviceList, 0, null, normalisedPhoneNumber, deviceIdHash, new String[]{codeId}); + process.kill(); + assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } - assert (device.has("codes")); - JsonArray jsonCodeList = device.get("codes").getAsJsonArray(); - assertEquals(codeIds.length, jsonCodeList.size()); - for (int i = 0; i < codeIds.length; ++i) { - checkCodeInJsonArray(jsonCodeList, i, codeIds[i]); + private void checkDevice(JsonArray jsonDeviceList, int ind, String email, String phoneNumber, String deviceIdHash, + String[] codeIds) { + JsonObject device = jsonDeviceList.get(ind).getAsJsonObject(); + + assertEquals(deviceIdHash, device.get("preAuthSessionId").getAsString()); + assertEquals(0, device.get("failedCodeInputAttemptCount").getAsInt()); + + if (email == null) { + assert (!device.has("email")); + } else { + assertEquals(email, device.get("email").getAsString()); + } + + if (phoneNumber == null) { + assert (!device.has("phoneNumber")); + } else { + assertEquals(phoneNumber, device.get("phoneNumber").getAsString()); + } + + assert (device.has("codes")); + JsonArray jsonCodeList = device.get("codes").getAsJsonArray(); + assertEquals(codeIds.length, jsonCodeList.size()); + for (int i = 0; i < codeIds.length; ++i) { + checkCodeInJsonArray(jsonCodeList, i, codeIds[i]); + } + + assertEquals(4, device.entrySet().size()); } - assertEquals(4, device.entrySet().size()); - } - - private void checkCodeInJsonArray(JsonArray jsonCodeList, int index, String codeId2) { - JsonObject code = jsonCodeList.get(index).getAsJsonObject(); - assertEquals(codeId2, code.get("codeId").getAsString()); - assert (code.has("timeCreated")); - assert (code.has("codeLifetime")); - assertEquals(3, code.entrySet().size()); - } + private void checkCodeInJsonArray(JsonArray jsonCodeList, int index, String codeId2) { + JsonObject code = jsonCodeList.get(index).getAsJsonObject(); + assertEquals(codeId2, code.get("codeId").getAsString()); + assert (code.has("timeCreated")); + assert (code.has("codeLifetime")); + assertEquals(3, code.entrySet().size()); + } } diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest2_11.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest2_11.java index cc5965c25..aa52b54bc 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest2_11.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest2_11.java @@ -58,7 +58,7 @@ public void beforeEach() { @Test public void testBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -128,7 +128,7 @@ public void testBadInput() throws Exception { @Test public void testGetCodesNoMatch() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -154,7 +154,7 @@ public void testGetCodesNoMatch() throws Exception { @Test public void testGetCodes() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -205,7 +205,7 @@ public void testGetCodes() throws Exception { JsonArray jsonDeviceList = response.get("devices").getAsJsonArray(); assertEquals(1, jsonDeviceList.size()); - checkDevice(jsonDeviceList, 0, email, null, deviceIdHash, new String[] { codeId }); + checkDevice(jsonDeviceList, 0, email, null, deviceIdHash, new String[]{codeId}); } process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -213,7 +213,7 @@ public void testGetCodes() throws Exception { @Test public void testGetCodesWithEmail() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -261,7 +261,7 @@ public void testGetCodesWithEmail() throws Exception { assert (response.has("devices")); JsonArray jsonDeviceList = response.get("devices").getAsJsonArray(); assertEquals(1, jsonDeviceList.size()); - checkDevice(jsonDeviceList, 0, email, null, deviceIdHash, new String[] { codeId }); + checkDevice(jsonDeviceList, 0, email, null, deviceIdHash, new String[]{codeId}); } } process.kill(); @@ -270,7 +270,7 @@ public void testGetCodesWithEmail() throws Exception { @Test public void testGetCodesWithPhoneNumber() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -319,7 +319,7 @@ public void testGetCodesWithPhoneNumber() throws Exception { assert (response.has("devices")); JsonArray jsonDeviceList = response.get("devices").getAsJsonArray(); assertEquals(1, jsonDeviceList.size()); - checkDevice(jsonDeviceList, 0, null, phoneNumber, deviceIdHash, new String[] { codeId }); + checkDevice(jsonDeviceList, 0, null, phoneNumber, deviceIdHash, new String[]{codeId}); } } process.kill(); @@ -328,7 +328,7 @@ public void testGetCodesWithPhoneNumber() throws Exception { @Test public void testGetCodesWithDeviceID() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -379,7 +379,7 @@ public void testGetCodesWithDeviceID() throws Exception { JsonArray jsonDeviceList = response.get("devices").getAsJsonArray(); assertEquals(1, jsonDeviceList.size()); checkDevice(jsonDeviceList, 0, null, phoneNumber, createCodeResponse.deviceIdHash, - new String[] { createCodeResponse.codeId }); + new String[]{createCodeResponse.codeId}); } } process.kill(); @@ -387,7 +387,7 @@ public void testGetCodesWithDeviceID() throws Exception { } private void checkDevice(JsonArray jsonDeviceList, int ind, String email, String phoneNumber, String deviceIdHash, - String[] codeIds) { + String[] codeIds) { JsonObject device = jsonDeviceList.get(ind).getAsJsonObject(); assertEquals(deviceIdHash, device.get("preAuthSessionId").getAsString()); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest.java index 58265510d..f73f29831 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest.java @@ -40,55 +40,56 @@ import static org.junit.Assert.assertNotNull; public class PasswordlessUserGetAPITest { - @Rule - public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule watchman = Utils.getOnFailure(); - @AfterClass - public static void afterTesting() { - Utils.afterTesting(); - } - - @Before - public void beforeEach() { - Utils.reset(); - } - - @Test - public void testGetUserWithUnnormalisedPhoneNumber() throws Exception { - String[] args = { "../" }; - - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); - assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); - - if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { - return; + @AfterClass + public static void afterTesting() { + Utils.afterTesting(); } - PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); - - // length of user ID needs to be 36 character long, otherwise it throws error - // with postgres DB - String userId = "pZ9SP0USbXbejGFO6qx7x3JBjupJZVtw4RkD"; - String phoneNumber = "+44-207 183 8750"; - String normalisedPhoneNumber = io.supertokens.utils.Utils.normalizeIfPhoneNumber(phoneNumber); - - storage.createUser(new TenantIdentifier(null, null, null), - userId, null, normalisedPhoneNumber, System.currentTimeMillis()); - { - HashMap map = new HashMap<>(); - map.put("phoneNumber", phoneNumber); - JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/recipe/user", map, 1000, 1000, null, WebserverAPI.getLatestCDIVersion().get(), - "passwordless"); - - assertEquals("OK", response.get("status").getAsString()); - assert (response.has("user")); - JsonObject user = response.get("user").getAsJsonObject(); - assertEquals(user.get("phoneNumbers").getAsJsonArray().get(0).getAsString(), normalisedPhoneNumber); + @Before + public void beforeEach() { + Utils.reset(); } - process.kill(); - assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); - } + @Test + public void testGetUserWithUnnormalisedPhoneNumber() throws Exception { + String[] args = {"../"}; + + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); + + if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { + return; + } + + PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); + + // length of user ID needs to be 36 character long, otherwise it throws error + // with postgres DB + String userId = "pZ9SP0USbXbejGFO6qx7x3JBjupJZVtw4RkD"; + String phoneNumber = "+44-207 183 8750"; + String normalisedPhoneNumber = io.supertokens.utils.Utils.normalizeIfPhoneNumber(phoneNumber); + + storage.createUser(new TenantIdentifier(null, null, null), + userId, null, normalisedPhoneNumber, System.currentTimeMillis()); + { + HashMap map = new HashMap<>(); + map.put("phoneNumber", phoneNumber); + JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", + "http://localhost:3567/recipe/user", map, 1000, 1000, null, + WebserverAPI.getLatestCDIVersion().get(), + "passwordless"); + + assertEquals("OK", response.get("status").getAsString()); + assert (response.has("user")); + JsonObject user = response.get("user").getAsJsonObject(); + assertEquals(user.get("phoneNumbers").getAsJsonArray().get(0).getAsString(), normalisedPhoneNumber); + } + + process.kill(); + assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); + } } diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest2_11.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest2_11.java index 92d1b580d..2684715ac 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest2_11.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest2_11.java @@ -59,7 +59,7 @@ public void beforeEach() { @Test public void testBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -155,7 +155,7 @@ public void testBadInput() throws Exception { @Test public void testGoodInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -250,7 +250,8 @@ public void testGetUserForUsersOfOtherRecipeIds() throws Exception { } AuthRecipeUserInfo user1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "password"); - AuthRecipeUserInfo user2 = ThirdParty.signInUp(process.getProcess(), "google", "googleid", "test@example.com").user; + AuthRecipeUserInfo user2 = ThirdParty.signInUp(process.getProcess(), "google", "googleid", + "test@example.com").user; { HashMap map = new HashMap<>(); diff --git a/src/test/java/io/supertokens/test/session/AccessTokenSigningKeyTest.java b/src/test/java/io/supertokens/test/session/AccessTokenSigningKeyTest.java index b3e0d052b..6fc311ef8 100644 --- a/src/test/java/io/supertokens/test/session/AccessTokenSigningKeyTest.java +++ b/src/test/java/io/supertokens/test/session/AccessTokenSigningKeyTest.java @@ -78,7 +78,8 @@ public void legacySigningKeysAreMigratedProperly() throws InterruptedException, String signingKey = rsaKeys.toString(); KeyValueInfo newKey = new KeyValueInfo(signingKey, System.currentTimeMillis()); SessionStorage sessionStorage = (SessionStorage) StorageLayer.getStorage(process.getProcess()); - sessionStorage.removeAccessTokenSigningKeysBefore(new AppIdentifier(null, null), System.currentTimeMillis() + 1000); + sessionStorage.removeAccessTokenSigningKeysBefore(new AppIdentifier(null, null), + System.currentTimeMillis() + 1000); sessionStorage.setKeyValue(new TenantIdentifier(null, null, null), "access_token_signing_key", newKey); AccessTokenSigningKey accessTokenSigningKeyInstance = AccessTokenSigningKey.getInstance(process.getProcess()); accessTokenSigningKeyInstance.transferLegacyKeyToNewTable(); @@ -108,7 +109,8 @@ public void getDynamicKeysReturnsOrdered() throws Exception { // 2 seconds in the past SessionStorage sessionStorage = (SessionStorage) StorageLayer.getStorage(process.getProcess()); - sessionStorage.removeAccessTokenSigningKeysBefore(new AppIdentifier(null, null), System.currentTimeMillis() + 1000); + sessionStorage.removeAccessTokenSigningKeysBefore(new AppIdentifier(null, null), + System.currentTimeMillis() + 1000); sessionStorage.setKeyValue(new TenantIdentifier(null, null, null), "access_token_signing_key", legacyKey); AccessTokenSigningKey accessTokenSigningKeyInstance = AccessTokenSigningKey.getInstance(process.getProcess()); diff --git a/src/test/java/io/supertokens/test/session/DeleteExpiredSessionsTest.java b/src/test/java/io/supertokens/test/session/DeleteExpiredSessionsTest.java index d7fc5bb5c..dc609a1c4 100644 --- a/src/test/java/io/supertokens/test/session/DeleteExpiredSessionsTest.java +++ b/src/test/java/io/supertokens/test/session/DeleteExpiredSessionsTest.java @@ -45,7 +45,7 @@ public void beforeEach() { @Test public void intervalTimeSecondsDeleteExpiredSessionsTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/session/JWTDataTest.java b/src/test/java/io/supertokens/test/session/JWTDataTest.java index 23708f293..d4a0e6c0b 100644 --- a/src/test/java/io/supertokens/test/session/JWTDataTest.java +++ b/src/test/java/io/supertokens/test/session/JWTDataTest.java @@ -72,7 +72,8 @@ public void testVerifyJWTPayloadChangePayloadUsingSessionHandle() throws Excepti // change JWT payload using session handle JsonObject newUserDataInJwt = new JsonObject(); newUserDataInJwt.addProperty("key", "value2"); - Session.updateSession(process.getProcess(), sessionInfo.session.handle, null, newUserDataInJwt, AccessToken.getLatestVersion()); + Session.updateSession(process.getProcess(), sessionInfo.session.handle, null, newUserDataInJwt, + AccessToken.getLatestVersion()); // check that this change is reflected @@ -107,7 +108,8 @@ public void testVerifyJWTPayloadChangeToEmptyPayloadUsingSessionHandle() throws // change JWT payload to be empty using session handle JsonObject emptyUserDataInJwt = new JsonObject(); - Session.updateSession(process.getProcess(), sessionInfo.session.handle, null, emptyUserDataInJwt, AccessToken.getLatestVersion()); + Session.updateSession(process.getProcess(), sessionInfo.session.handle, null, emptyUserDataInJwt, + AccessToken.getLatestVersion()); // check this is reflected assertEquals(Session.getJWTData(process.getProcess(), sessionInfo.session.handle), emptyUserDataInJwt); @@ -140,7 +142,8 @@ public void testVerifyJWTPayloadSetPayloadToNullUsingSessionHandle() throws Exce assertEquals(sessionInfo.session.userDataInJWT, userDataInJWT); // change JWT payload to be null - Session.updateSession(process.getProcess(), sessionInfo.session.handle, userDataInDatabase, null, AccessToken.getLatestVersion()); + Session.updateSession(process.getProcess(), sessionInfo.session.handle, userDataInDatabase, null, + AccessToken.getLatestVersion()); // check that jwtData does not change assertEquals(Session.getJWTData(process.getProcess(), sessionInfo.session.handle), userDataInJWT); @@ -182,7 +185,8 @@ public void testExpireSessionCallUpdateAndCheckUnauthorised() throws Exception { // call update function try { - Session.updateSession(process.getProcess(), sessionInfo.session.handle, null, newUserDataInJWT, AccessToken.getLatestVersion()); + Session.updateSession(process.getProcess(), sessionInfo.session.handle, null, newUserDataInJWT, + AccessToken.getLatestVersion()); fail(); } catch (UnauthorisedException e) { assertEquals(e.getMessage(), "Session does not exist."); @@ -254,7 +258,8 @@ public void testUpdatePayloadGetSessionWithoutBlacklistingShouldNotChangeToken() JsonObject newUserDataInJWT = new JsonObject(); newUserDataInJWT.addProperty("key", "value2"); - Session.updateSession(process.getProcess(), sessionInfo.session.handle, null, newUserDataInJWT, AccessToken.getLatestVersion()); + Session.updateSession(process.getProcess(), sessionInfo.session.handle, null, newUserDataInJWT, + AccessToken.getLatestVersion()); SessionInformationHolder newInfo = Session.getSession(process.getProcess(), sessionInfo.accessToken.token, sessionInfo.antiCsrfToken, false, true, false); @@ -291,7 +296,8 @@ public void testUpdatePayloadGetSessionWithBlacklistingShouldNotChangeToken() th JsonObject newUserDataInJWT = new JsonObject(); newUserDataInJWT.addProperty("key", "value2"); - Session.updateSession(process.getProcess(), sessionInfo.session.handle, null, newUserDataInJWT, AccessToken.getLatestVersion()); + Session.updateSession(process.getProcess(), sessionInfo.session.handle, null, newUserDataInJWT, + AccessToken.getLatestVersion()); SessionInformationHolder newInfo = Session.getSession(process.getProcess(), sessionInfo.accessToken.token, sessionInfo.antiCsrfToken, false, true, true); @@ -319,7 +325,7 @@ public void testUpdatePayloadGetSessionWithBlacklistingShouldNotChangeToken() th @Test public void testNormalRefreshAndGetShouldNotUpdateJWTPayloadV2() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/session/JWTTest.java b/src/test/java/io/supertokens/test/session/JWTTest.java index 4b1583e03..c4519e4e2 100644 --- a/src/test/java/io/supertokens/test/session/JWTTest.java +++ b/src/test/java/io/supertokens/test/session/JWTTest.java @@ -54,8 +54,10 @@ public void validUsage() throws Exception { { TestInput input = new TestInput("value"); io.supertokens.utils.Utils.PubPriKey rsa = io.supertokens.utils.Utils.generateNewPubPriKey(); - String token = JWT.createAndSignLegacyAccessToken(new Gson().toJsonTree(input), rsa.privateKey, AccessToken.VERSION.V1); - TestInput output = new Gson().fromJson(JWT.verifyJWTAndGetPayload(JWT.preParseJWTInfo(token), rsa.publicKey).payload, + String token = JWT.createAndSignLegacyAccessToken(new Gson().toJsonTree(input), rsa.privateKey, + AccessToken.VERSION.V1); + TestInput output = new Gson().fromJson( + JWT.verifyJWTAndGetPayload(JWT.preParseJWTInfo(token), rsa.publicKey).payload, TestInput.class); assertEquals(input, output); } @@ -63,8 +65,10 @@ public void validUsage() throws Exception { { TestInput input = new TestInput("value"); io.supertokens.utils.Utils.PubPriKey rsa = io.supertokens.utils.Utils.generateNewPubPriKey(); - String token = JWT.createAndSignLegacyAccessToken(new Gson().toJsonTree(input), rsa.privateKey, AccessToken.VERSION.V2); - TestInput output = new Gson().fromJson(JWT.verifyJWTAndGetPayload(JWT.preParseJWTInfo(token), rsa.publicKey).payload, + String token = JWT.createAndSignLegacyAccessToken(new Gson().toJsonTree(input), rsa.privateKey, + AccessToken.VERSION.V2); + TestInput output = new Gson().fromJson( + JWT.verifyJWTAndGetPayload(JWT.preParseJWTInfo(token), rsa.publicKey).payload, TestInput.class); assertEquals(input, output); } @@ -76,7 +80,8 @@ public void wrongSignatureUsage() throws Exception { { TestInput input = new TestInput("value"); io.supertokens.utils.Utils.PubPriKey rsa = io.supertokens.utils.Utils.generateNewPubPriKey(); - String token = JWT.createAndSignLegacyAccessToken(new Gson().toJsonTree(input), rsa.privateKey, AccessToken.VERSION.V1); + String token = JWT.createAndSignLegacyAccessToken(new Gson().toJsonTree(input), rsa.privateKey, + AccessToken.VERSION.V1); try { JWT.verifyJWTAndGetPayload(JWT.preParseJWTInfo(token), "signingKey2"); fail(); @@ -88,7 +93,8 @@ public void wrongSignatureUsage() throws Exception { { TestInput input = new TestInput("value"); io.supertokens.utils.Utils.PubPriKey rsa = io.supertokens.utils.Utils.generateNewPubPriKey(); - String token = JWT.createAndSignLegacyAccessToken(new Gson().toJsonTree(input), rsa.privateKey, AccessToken.VERSION.V2); + String token = JWT.createAndSignLegacyAccessToken(new Gson().toJsonTree(input), rsa.privateKey, + AccessToken.VERSION.V2); try { JWT.verifyJWTAndGetPayload(JWT.preParseJWTInfo(token), "signingKey2"); fail(); diff --git a/src/test/java/io/supertokens/test/session/RefreshTokenTest.java b/src/test/java/io/supertokens/test/session/RefreshTokenTest.java index f4251db19..4bedf4e62 100644 --- a/src/test/java/io/supertokens/test/session/RefreshTokenTest.java +++ b/src/test/java/io/supertokens/test/session/RefreshTokenTest.java @@ -65,7 +65,8 @@ public void encryptAndDecryptWorksWithSameKey() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { String key = "1000" - + ":79a6cbeb2066a3ab80f951037b90cc52bc216d9507998454184daeb3ef47cf387aab9c65e5fc69209fa6f0f67aee486c9d292cfc159a41c4b02415ba669f3219:d305504825a1b109"; + + + ":79a6cbeb2066a3ab80f951037b90cc52bc216d9507998454184daeb3ef47cf387aab9c65e5fc69209fa6f0f67aee486c9d292cfc159a41c4b02415ba669f3219:d305504825a1b109"; String message = "I am to be encrypted and then decrypted"; String enc = io.supertokens.utils.Utils.encrypt(message, key); String dec = io.supertokens.utils.Utils.decrypt(enc, key); @@ -77,7 +78,8 @@ public void encryptAndDecryptDoesNotWorksWithDifferentKey() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { String key = "1000" - + ":79a6cbeb2066a3ab80f951037b90cc52bc216d9507998454184daeb3ef47cf387aab9c65e5fc69209fa6f0f67aee486c9d292cfc159a41c4b02415ba669f3219:d305504825a1b109"; + + + ":79a6cbeb2066a3ab80f951037b90cc52bc216d9507998454184daeb3ef47cf387aab9c65e5fc69209fa6f0f67aee486c9d292cfc159a41c4b02415ba669f3219:d305504825a1b109"; String message = "I am to be encrypted and then decrypted"; String enc = io.supertokens.utils.Utils.encrypt(message, key); try { @@ -104,7 +106,7 @@ public void createRefreshTokenAndLoadAfterProcessRestart() throws InterruptedException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, StorageQueryException, StorageTransactionLogicException, UnauthorisedException { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -143,7 +145,7 @@ public void createRefreshTokenButVerifyWithDifferentSigningKeyFailure() throws InterruptedException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, StorageQueryException, StorageTransactionLogicException { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/session/SessionGetJWTDataTest.java b/src/test/java/io/supertokens/test/session/SessionGetJWTDataTest.java index f3831cd7c..ac1a9f07a 100644 --- a/src/test/java/io/supertokens/test/session/SessionGetJWTDataTest.java +++ b/src/test/java/io/supertokens/test/session/SessionGetJWTDataTest.java @@ -50,7 +50,7 @@ public void beforeEach() { // * handle -> check this is reflected @Test public void testVerifyJWTPayloadChangePayloadUsingSessionHandle() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -71,7 +71,8 @@ public void testVerifyJWTPayloadChangePayloadUsingSessionHandle() throws Excepti // change JWT payload using session handle JsonObject newUserDataInJwt = new JsonObject(); newUserDataInJwt.addProperty("key", "value2"); - Session.updateSession(process.getProcess(), sessionInfo.session.handle, null, newUserDataInJwt, AccessToken.getLatestVersion()); + Session.updateSession(process.getProcess(), sessionInfo.session.handle, null, newUserDataInJwt, + AccessToken.getLatestVersion()); // check that this change is reflected @@ -87,7 +88,7 @@ public void testVerifyJWTPayloadChangePayloadUsingSessionHandle() throws Excepti // * session handle -> check this is reflected @Test public void testVerifyJWTPayloadChangeToEmptyPayloadUsingSessionHandle() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -107,7 +108,8 @@ public void testVerifyJWTPayloadChangeToEmptyPayloadUsingSessionHandle() throws // change JWT payload to be empty using session handle JsonObject emptyUserDataInJwt = new JsonObject(); - Session.updateSession(process.getProcess(), sessionInfo.session.handle, null, emptyUserDataInJwt, AccessToken.getLatestVersion()); + Session.updateSession(process.getProcess(), sessionInfo.session.handle, null, emptyUserDataInJwt, + AccessToken.getLatestVersion()); // check this is reflected assertEquals(Session.getSession(process.getProcess(), sessionInfo.session.handle).userDataInJWT, @@ -122,7 +124,7 @@ public void testVerifyJWTPayloadChangeToEmptyPayloadUsingSessionHandle() throws // * function -> check that JWT payload has not changed is reflected @Test public void testVerifyJWTPayloadSetPayloadToNullUsingSessionHandle() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -141,7 +143,8 @@ public void testVerifyJWTPayloadSetPayloadToNullUsingSessionHandle() throws Exce assertEquals(sessionInfo.session.userDataInJWT, userDataInJWT); // change JWT payload to be null - Session.updateSession(process.getProcess(), sessionInfo.session.handle, userDataInDatabase, null, AccessToken.getLatestVersion()); + Session.updateSession(process.getProcess(), sessionInfo.session.handle, userDataInDatabase, null, + AccessToken.getLatestVersion()); // check that jwtData does not change assertEquals(Session.getSession(process.getProcess(), sessionInfo.session.handle).userDataInJWT, userDataInJWT); @@ -154,7 +157,7 @@ public void testVerifyJWTPayloadSetPayloadToNullUsingSessionHandle() throws Exce @Test public void testExpireSessionCallGetAndCheckUnauthorised() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("refresh_token_validity", "" + 1.0 / 60);// 1 second validity (value in mins) @@ -190,7 +193,7 @@ public void testExpireSessionCallGetAndCheckUnauthorised() throws Exception { @Test public void testRevokedSessionCallGetAndCheckUnauthorised() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -206,7 +209,7 @@ public void testRevokedSessionCallGetAndCheckUnauthorised() throws Exception { userDataInDatabase); // Revoke the session - String[] sessionHandles = { sessionInfo.session.handle }; + String[] sessionHandles = {sessionInfo.session.handle}; Session.revokeSessionUsingSessionHandles(process.getProcess(), sessionHandles); // call update function @@ -223,7 +226,7 @@ public void testRevokedSessionCallGetAndCheckUnauthorised() throws Exception { @Test public void testGetSessionWithExpiredAccessTokenDoesNotThrowError() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("access_token_validity", "1");// 1 second validity diff --git a/src/test/java/io/supertokens/test/session/SessionGetSessionDataTest.java b/src/test/java/io/supertokens/test/session/SessionGetSessionDataTest.java index fd8805f81..bca8f54d0 100644 --- a/src/test/java/io/supertokens/test/session/SessionGetSessionDataTest.java +++ b/src/test/java/io/supertokens/test/session/SessionGetSessionDataTest.java @@ -56,7 +56,7 @@ public void beforeEach() { @Test public void updateSessionInfo() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -79,7 +79,8 @@ public void updateSessionInfo() throws Exception { JsonArray arr = new JsonArray(); userDataInDatabase2.add("key3", arr); - Session.updateSession(process.getProcess(), sessionInfo.session.handle, userDataInDatabase2, null, AccessToken.getLatestVersion()); + Session.updateSession(process.getProcess(), sessionInfo.session.handle, userDataInDatabase2, null, + AccessToken.getLatestVersion()); JsonObject sessionDataAfterUpdate = Session.getSession(process.getProcess(), sessionInfo.session.handle).userDataInDatabase; @@ -95,7 +96,7 @@ public void updateSessionInfo() throws Exception { @Test public void gettingAndUpdatingSessionDataForNonExistentSession() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -107,7 +108,8 @@ public void gettingAndUpdatingSessionDataForNonExistentSession() throws Exceptio } try { - Session.updateSession(process.getProcess(), "random", new JsonObject(), null, AccessToken.getLatestVersion()); + Session.updateSession(process.getProcess(), "random", new JsonObject(), null, + AccessToken.getLatestVersion()); fail(); } catch (UnauthorisedException e) { assertEquals(e.getMessage(), "Session does not exist."); diff --git a/src/test/java/io/supertokens/test/session/SessionGetUserIDTest.java b/src/test/java/io/supertokens/test/session/SessionGetUserIDTest.java index c8856c1d6..5886bcf59 100644 --- a/src/test/java/io/supertokens/test/session/SessionGetUserIDTest.java +++ b/src/test/java/io/supertokens/test/session/SessionGetUserIDTest.java @@ -62,7 +62,7 @@ public void beforeEach() { // * -> Verify that user id returned is the same as the payload used when creating the session @Test public void testUserIdReturnedFromGetSessionIsCorrect() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/session/SessionTest1.java b/src/test/java/io/supertokens/test/session/SessionTest1.java index 6159173fc..bd8a7ce0a 100644 --- a/src/test/java/io/supertokens/test/session/SessionTest1.java +++ b/src/test/java/io/supertokens/test/session/SessionTest1.java @@ -336,7 +336,7 @@ public void createAndGetSessionWithSigningKeyChangeV2() throws Exception { Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "0.00027"); // 1 second Utils.setValueInConfig("access_token_validity", "1"); // 1 second - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -451,7 +451,8 @@ public void refreshSessionTestWithAntiCsrf() throws Exception { } SessionInformationHolder refreshedSession2 = Session.refreshSession(process.getProcess(), - refreshedSession.refreshToken.token, refreshedSession.antiCsrfToken, true, AccessToken.getLatestVersion()); + refreshedSession.refreshToken.token, refreshedSession.antiCsrfToken, true, + AccessToken.getLatestVersion()); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); @@ -536,7 +537,8 @@ public void refreshSessionTestWithNoAntiCsrf() throws Exception { } SessionInformationHolder refreshedSession2 = Session.refreshSession(process.getProcess(), - refreshedSession.refreshToken.token, refreshedSession.antiCsrfToken, false, AccessToken.getLatestVersion()); + refreshedSession.refreshToken.token, refreshedSession.antiCsrfToken, false, + AccessToken.getLatestVersion()); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); @@ -651,7 +653,8 @@ public void refreshTokenExpiresAfterShortTime() throws Exception { Thread.sleep(500); SessionInformationHolder newRefreshedSession2 = Session.refreshSession(main, - newRefreshedSession.refreshToken.token, newRefreshedSession.antiCsrfToken, false, AccessToken.getLatestVersion()); + newRefreshedSession.refreshToken.token, newRefreshedSession.antiCsrfToken, false, + AccessToken.getLatestVersion()); assert newRefreshedSession2.refreshToken != null; assert newRefreshedSession2.accessToken != null; assertNotEquals(newRefreshedSession.accessToken.token, newRefreshedSession2.accessToken.token); @@ -662,7 +665,8 @@ public void refreshTokenExpiresAfterShortTime() throws Exception { Thread.sleep(500); SessionInformationHolder newRefreshedSession3 = Session.refreshSession(main, - newRefreshedSession2.refreshToken.token, newRefreshedSession2.antiCsrfToken, false, AccessToken.getLatestVersion()); + newRefreshedSession2.refreshToken.token, newRefreshedSession2.antiCsrfToken, false, + AccessToken.getLatestVersion()); assert newRefreshedSession3.refreshToken != null; assert newRefreshedSession3.accessToken != null; assertNotEquals(newRefreshedSession3.accessToken.token, newRefreshedSession2.accessToken.token); diff --git a/src/test/java/io/supertokens/test/session/SessionTest3.java b/src/test/java/io/supertokens/test/session/SessionTest3.java index 965b59aa2..6b15047ef 100644 --- a/src/test/java/io/supertokens/test/session/SessionTest3.java +++ b/src/test/java/io/supertokens/test/session/SessionTest3.java @@ -70,7 +70,7 @@ public void beforeEach() { @Test public void revokeSessionWithBlacklistingRefreshSessionAndGetSessionThrows() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -137,7 +137,8 @@ public void removeSessionFromDbButAccessTokenStillValidUntilExpiry() throws Exce assertEquals(Session.revokeSessionUsingSessionHandles(process.getProcess(), new String[]{sessionInfo.session.handle})[0], sessionInfo.session.handle); - Session.getSession(process.getProcess(), sessionInfo.accessToken.token, sessionInfo.antiCsrfToken, false, true, false); + Session.getSession(process.getProcess(), sessionInfo.accessToken.token, sessionInfo.antiCsrfToken, false, true, + false); Thread.sleep(2500); @@ -200,7 +201,8 @@ public void revokeAllSessionsForUserWithoutBlacklisting() throws Exception { assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); - Session.getSession(process.getProcess(), sessionInfo.accessToken.token, sessionInfo.antiCsrfToken, false, true, false); + Session.getSession(process.getProcess(), sessionInfo.accessToken.token, sessionInfo.antiCsrfToken, false, true, + false); Session.getSession(process.getProcess(), sessionInfo2.accessToken.token, sessionInfo2.antiCsrfToken, false, true, false); Session.getSession(process.getProcess(), sessionInfo3.accessToken.token, sessionInfo3.antiCsrfToken, false, diff --git a/src/test/java/io/supertokens/test/session/SessionTest4.java b/src/test/java/io/supertokens/test/session/SessionTest4.java index a57adf8b1..6295cc7c5 100644 --- a/src/test/java/io/supertokens/test/session/SessionTest4.java +++ b/src/test/java/io/supertokens/test/session/SessionTest4.java @@ -133,7 +133,8 @@ public void gettingAndUpdatingSessionDataForNonExistantSession() throws Exceptio } try { - Session.updateSession(process.getProcess(), "random", new JsonObject(), null, AccessToken.getLatestVersion()); + Session.updateSession(process.getProcess(), "random", new JsonObject(), null, + AccessToken.getLatestVersion()); fail(); } catch (UnauthorisedException e) { assertEquals(e.getMessage(), "Session does not exist."); @@ -234,7 +235,8 @@ public void verifyAccessTokenThatIsBelongsToGrandparentRefreshToken() throws Exc assert refreshedSession.accessToken != null; SessionInformationHolder refreshedSession2 = Session.refreshSession(process.getProcess(), - refreshedSession.refreshToken.token, refreshedSession.antiCsrfToken, false, AccessToken.getLatestVersion()); + refreshedSession.refreshToken.token, refreshedSession.antiCsrfToken, false, + AccessToken.getLatestVersion()); assert refreshedSession2.refreshToken != null; Session.refreshSession(process.getProcess(), refreshedSession2.refreshToken.token, @@ -318,13 +320,15 @@ public void checkThatExpiredSessionIsNotReturnedForUserNorCanItBeUpdated() throw } try { - Session.updateSession(process.getProcess(), expiredSession.session.handle, new JsonObject(), null, AccessToken.getLatestVersion()); + Session.updateSession(process.getProcess(), expiredSession.session.handle, new JsonObject(), null, + AccessToken.getLatestVersion()); throw new Exception("Test failed"); } catch (UnauthorisedException ignored) { } Session.getSession(process.getProcess(), nonExpiredSession.session.handle); - Session.updateSession(process.getProcess(), nonExpiredSession.session.handle, new JsonObject(), null, AccessToken.getLatestVersion()); + Session.updateSession(process.getProcess(), nonExpiredSession.session.handle, new JsonObject(), null, + AccessToken.getLatestVersion()); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -404,7 +408,8 @@ public void createNewSessionAndUpdateSession() throws Exception { JsonObject jwtData = new JsonObject(); jwtData.addProperty("test", "value"); - Session.updateSession(process.main, sessionInfo.session.handle, sessionData, jwtData, AccessToken.getLatestVersion()); + Session.updateSession(process.main, sessionInfo.session.handle, sessionData, jwtData, + AccessToken.getLatestVersion()); io.supertokens.pluginInterface.session.SessionInfo sessionInfo2 = Session.getSession(process.main, sessionInfo.session.handle); diff --git a/src/test/java/io/supertokens/test/session/SessionTest5.java b/src/test/java/io/supertokens/test/session/SessionTest5.java index fd3931049..2bb2c6c7a 100644 --- a/src/test/java/io/supertokens/test/session/SessionTest5.java +++ b/src/test/java/io/supertokens/test/session/SessionTest5.java @@ -309,7 +309,8 @@ public void checkRefreshKidChangesAfterDynamicSigningKeyChange() throws Exceptio SessionInformationHolder createInfo = Session.createNewSession(process.getProcess(), userId, userDataInJWT, userDataInDatabase, false, AccessToken.getLatestVersion(), false); - SessionInformationHolder createInfoStatic = Session.createNewSession(process.getProcess(), userId, userDataInJWT, + SessionInformationHolder createInfoStatic = Session.createNewSession(process.getProcess(), userId, + userDataInJWT, userDataInDatabase, false, AccessToken.getLatestVersion(), true); Thread.sleep(1500); @@ -372,7 +373,8 @@ public void checkDynamicKeyOverlap() throws Exception { assertEquals(2, signingKeysInstance.getDynamicKeys().size()); assertEquals(3, signingKeysInstance.getAllKeys().size()); - SessionInformationHolder createInfoAfterOverlap = Session.createNewSession(process.getProcess(), userId, userDataInJWT, + SessionInformationHolder createInfoAfterOverlap = Session.createNewSession(process.getProcess(), userId, + userDataInJWT, userDataInDatabase, false, AccessToken.getLatestVersion(), false); JWT.JWTPreParseInfo preParseInfoAfterOverlap = JWT.preParseJWTInfo(createInfoAfterOverlap.accessToken.token); diff --git a/src/test/java/io/supertokens/test/session/SessionTest6.java b/src/test/java/io/supertokens/test/session/SessionTest6.java index 6a8f6c89d..5db3fa98e 100644 --- a/src/test/java/io/supertokens/test/session/SessionTest6.java +++ b/src/test/java/io/supertokens/test/session/SessionTest6.java @@ -68,14 +68,16 @@ public void createRefreshSwitchVerify() throws Exception { userDataInDatabase, false, AccessToken.getLatestVersion(), false); checkIfUsingStaticKey(sessionInfo, false); - sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), sessionInfo.refreshToken.token, + sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), + sessionInfo.refreshToken.token, sessionInfo.antiCsrfToken, false, AccessToken.getLatestVersion(), true); assert sessionInfo.refreshToken != null; assert sessionInfo.accessToken != null; checkIfUsingStaticKey(sessionInfo, true); - SessionInformationHolder verifiedSession = Session.getSession(process.getProcess(), sessionInfo.accessToken.token, + SessionInformationHolder verifiedSession = Session.getSession(process.getProcess(), + sessionInfo.accessToken.token, sessionInfo.antiCsrfToken, false, true, false); checkIfUsingStaticKey(verifiedSession, true); @@ -83,6 +85,7 @@ public void createRefreshSwitchVerify() throws Exception { process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } + @Test public void createRefreshSwitchRegen() throws Exception { String[] args = {"../"}; @@ -99,7 +102,8 @@ public void createRefreshSwitchRegen() throws Exception { userDataInDatabase, false, AccessToken.getLatestVersion(), false); checkIfUsingStaticKey(sessionInfo, false); - sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), sessionInfo.refreshToken.token, + sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), + sessionInfo.refreshToken.token, sessionInfo.antiCsrfToken, false, AccessToken.getLatestVersion(), true); assert sessionInfo.refreshToken != null; assert sessionInfo.accessToken != null; @@ -133,17 +137,20 @@ public void createRefreshRefreshSwitchVerify() throws Exception { userDataInDatabase, false, AccessToken.getLatestVersion(), false); checkIfUsingStaticKey(sessionInfo, false); - sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), sessionInfo.refreshToken.token, + sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), + sessionInfo.refreshToken.token, sessionInfo.antiCsrfToken, false, AccessToken.getLatestVersion(), false); - sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), sessionInfo.refreshToken.token, + sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), + sessionInfo.refreshToken.token, sessionInfo.antiCsrfToken, false, AccessToken.getLatestVersion(), true); assert sessionInfo.refreshToken != null; assert sessionInfo.accessToken != null; checkIfUsingStaticKey(sessionInfo, true); - SessionInformationHolder verifiedSession = Session.getSession(process.getProcess(), sessionInfo.accessToken.token, + SessionInformationHolder verifiedSession = Session.getSession(process.getProcess(), + sessionInfo.accessToken.token, sessionInfo.antiCsrfToken, false, true, false); checkIfUsingStaticKey(verifiedSession, true); @@ -151,6 +158,7 @@ public void createRefreshRefreshSwitchVerify() throws Exception { process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } + @Test public void createRefreshRefreshSwitchRegen() throws Exception { String[] args = {"../"}; @@ -167,10 +175,12 @@ public void createRefreshRefreshSwitchRegen() throws Exception { userDataInDatabase, false, AccessToken.getLatestVersion(), false); checkIfUsingStaticKey(sessionInfo, false); - sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), sessionInfo.refreshToken.token, + sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), + sessionInfo.refreshToken.token, sessionInfo.antiCsrfToken, false, AccessToken.getLatestVersion(), false); - sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), sessionInfo.refreshToken.token, + sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), + sessionInfo.refreshToken.token, sessionInfo.antiCsrfToken, false, AccessToken.getLatestVersion(), true); assert sessionInfo.refreshToken != null; assert sessionInfo.accessToken != null; @@ -188,7 +198,8 @@ public void createRefreshRefreshSwitchRegen() throws Exception { assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } - private static void checkIfUsingStaticKey(SessionInformationHolder info, boolean shouldBeStatic) throws JWT.JWTException { + private static void checkIfUsingStaticKey(SessionInformationHolder info, boolean shouldBeStatic) + throws JWT.JWTException { assert info.accessToken != null; JWT.JWTPreParseInfo tokenInfo = JWT.preParseJWTInfo(info.accessToken.token); assert tokenInfo.kid != null; diff --git a/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_21.java b/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_21.java index 47b5ff992..113351bc0 100644 --- a/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_21.java +++ b/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_21.java @@ -44,7 +44,7 @@ public void beforeEach() { @Test public void checkApi404s() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -52,7 +52,8 @@ public void checkApi404s() throws Exception { io.supertokens.test.httpRequest.HttpResponseException caught = null; try { HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", - "http://localhost:3567/recipe/handshake", null, 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), + "http://localhost:3567/recipe/handshake", null, 1000, 1000, null, + Utils.getCdiVersionStringLatestForTests(), "session"); } catch (io.supertokens.test.httpRequest.HttpResponseException e) { caught = e; diff --git a/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_21.java b/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_21.java index fcaa8f92a..dc37a864a 100644 --- a/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_21.java +++ b/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_21.java @@ -50,7 +50,7 @@ public void beforeEach() { @Test public void testThatAddingProtectedPropsThrow() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_7.java index ec3c64093..f97ae664b 100644 --- a/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_7.java @@ -51,7 +51,7 @@ public void beforeEach() { // * - create session with some JWT payload -> change JWT payload using API -> check this is reflected in db @Test public void testCreateSessionWithPayloadChangePayloadWithApiAndCheckChangeReflectedInDB() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -106,7 +106,7 @@ public void testCreateSessionWithPayloadChangePayloadWithApiAndCheckChangeReflec // reflected in db @Test public void testCreateSessionWithJwtPayloadChangePayloadToEmptyUsingSessionCheckIfReflectedInDB() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -157,7 +157,7 @@ public void testCreateSessionWithJwtPayloadChangePayloadToEmptyUsingSessionCheck // * - create session -> let it expire, remove from db -> call update API -> make sure you get unauthorised error @Test public void testCreateSessionLetItExpireCallPutAPIAndCheckUnauthorised() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("access_token_validity", "1");// 1 second validity Utils.setValueInConfig("refresh_token_validity", "" + 1.0 / 60);// 1 second validity (value in mins) @@ -217,7 +217,7 @@ public void testCreateSessionLetItExpireCallPutAPIAndCheckUnauthorised() throws @Test public void testCreateSessionLetItExpreRemoveFromDBCallGetAPIAndCheckUnauthorised() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("access_token_validity", "1");// 1 second validity Utils.setValueInConfig("refresh_token_validity", "" + 1.0 / 60);// 1 second validity (value in mins) @@ -276,7 +276,7 @@ public void testCreateSessionLetItExpreRemoveFromDBCallGetAPIAndCheckUnauthorise @Test public void testJWTDataAPI() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -322,7 +322,8 @@ public void testJWTDataAPI() throws Exception { "http://localhost:3567/recipe/jwt/data", params, 1000, 1000, null, SemVer.v2_7.get(), "session"); assertEquals(getJwtData.get("status").getAsString(), "OK"); - assertEquals(getJwtData.get("userDataInJWT").getAsJsonObject().get("key").getAsString(), "łukasz 馬 / 马 value2"); + assertEquals(getJwtData.get("userDataInJWT").getAsJsonObject().get("key").getAsString(), + "łukasz 馬 / 马 value2"); assertEquals(getJwtData.entrySet().size(), 2); process.kill(); @@ -332,7 +333,7 @@ public void testJWTDataAPI() throws Exception { @Test public void testBapInputJWTDataAPI() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/session/api/MultitenantAPITest.java b/src/test/java/io/supertokens/test/session/api/MultitenantAPITest.java index 5dba07850..67272e0a2 100644 --- a/src/test/java/io/supertokens/test/session/api/MultitenantAPITest.java +++ b/src/test/java/io/supertokens/test/session/api/MultitenantAPITest.java @@ -420,13 +420,15 @@ public void testAccessTokensContainsTid() throws Exception { { JsonObject session = createSession(t1, "userid", new JsonObject(), new JsonObject()); - JWT.JWTInfo accessTokenInfo = JWT.getPayloadWithoutVerifying(session.get("accessToken").getAsJsonObject().get("token").getAsString()); + JWT.JWTInfo accessTokenInfo = JWT.getPayloadWithoutVerifying( + session.get("accessToken").getAsJsonObject().get("token").getAsString()); assertEquals(t1.getTenantId(), accessTokenInfo.payload.get("tId").getAsString()); } { JsonObject session = createSession(t2, "userid", new JsonObject(), new JsonObject()); - JWT.JWTInfo accessTokenInfo = JWT.getPayloadWithoutVerifying(session.get("accessToken").getAsJsonObject().get("token").getAsString()); + JWT.JWTInfo accessTokenInfo = JWT.getPayloadWithoutVerifying( + session.get("accessToken").getAsJsonObject().get("token").getAsString()); assertEquals(t2.getTenantId(), accessTokenInfo.payload.get("tId").getAsString()); } } @@ -545,7 +547,7 @@ public void testFetchAndRevokeSessionForUserOperatesPerTenantIfTheFlagIsSetToFal assertEquals(1, allSessionHandles.length); assertEquals(sessionHandles.get(2), allSessionHandles[0]); } - + // Revoke sessions { String[] revokedSessionHandles = revokeAllUserSessionsAcrossAllTenants(t1, "userid", false); @@ -569,7 +571,9 @@ public void testFetchAndRevokeSessionForUserOperatesPerTenantIfTheFlagIsSetToFal assertEquals(0, allSessionHandles.length); } - private String[] getAllUserSessionsAcrossAllTenants(TenantIdentifier tenantIdentifier, String userid, Boolean fetchAcrossAllTenants) throws HttpResponseException, IOException { + private String[] getAllUserSessionsAcrossAllTenants(TenantIdentifier tenantIdentifier, String userid, + Boolean fetchAcrossAllTenants) + throws HttpResponseException, IOException { Map params = new HashMap<>(); if (fetchAcrossAllTenants != null) { params.put("fetchAcrossAllTenants", fetchAcrossAllTenants.toString()); @@ -589,7 +593,9 @@ private String[] getAllUserSessionsAcrossAllTenants(TenantIdentifier tenantIdent return sessionHandles; } - private String[] revokeAllUserSessionsAcrossAllTenants(TenantIdentifier tenantIdentifier, String userid, Boolean revokeAcrossAllTenants) throws HttpResponseException, IOException { + private String[] revokeAllUserSessionsAcrossAllTenants(TenantIdentifier tenantIdentifier, String userid, + Boolean revokeAcrossAllTenants) + throws HttpResponseException, IOException { JsonObject requestBody = new JsonObject(); requestBody.addProperty("userId", userid); if (revokeAcrossAllTenants != null) { diff --git a/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest2_21.java b/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest2_21.java index 9be3bbcd7..a909961e5 100644 --- a/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest2_21.java +++ b/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest2_21.java @@ -47,7 +47,7 @@ public void beforeEach() { @Test public void checkRefreshWithProtectedFieldInPayload() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -75,8 +75,8 @@ public void checkRefreshWithProtectedFieldInPayload() throws Exception { sessionRefreshBody.addProperty("enableAntiCsrf", false); JsonObject response = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", - "http://localhost:3567/recipe/session/refresh", sessionRefreshBody, 1000, 1000, null, - SemVer.v2_21.get(), "session"); + "http://localhost:3567/recipe/session/refresh", sessionRefreshBody, 1000, 1000, null, + SemVer.v2_21.get(), "session"); assertEquals(response.entrySet().size(), 2); assertEquals(response.get("status").getAsString(), "UNAUTHORISED"); @@ -85,7 +85,7 @@ public void checkRefreshWithProtectedFieldInPayload() throws Exception { @Test public void successOutputWithValidRefreshTokenTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -125,7 +125,7 @@ public void successOutputWithValidRefreshTokenTest() throws Exception { } private static void checkRefreshSessionResponse(JsonObject response, TestingProcessManager.TestingProcess process, - String userId, JsonObject userDataInJWT, boolean hasAntiCsrf) { + String userId, JsonObject userDataInJWT, boolean hasAntiCsrf) { assertNotNull(response.get("session").getAsJsonObject().get("handle").getAsString()); assertEquals(response.get("session").getAsJsonObject().get("userId").getAsString(), userId); diff --git a/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest3_0.java b/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest3_0.java index 167bdacf2..3d0c0c880 100644 --- a/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest3_0.java +++ b/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest3_0.java @@ -50,7 +50,7 @@ public void beforeEach() { @Test public void successOutputWithValidRefreshTokenTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -91,7 +91,7 @@ public void successOutputWithValidRefreshTokenTest() throws Exception { @Test public void successOutputUpgradeWithNonStaticKeySessionTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -132,7 +132,7 @@ public void successOutputUpgradeWithNonStaticKeySessionTest() throws Exception { @Test public void successOutputUpgradeWithStaticKeySessionTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -172,7 +172,8 @@ public void successOutputUpgradeWithStaticKeySessionTest() throws Exception { } private static void checkRefreshSessionResponse(JsonObject response, TestingProcessManager.TestingProcess process, - String userId, JsonObject userDataInJWT, boolean hasAntiCsrf, boolean useStaticKey) throws + String userId, JsonObject userDataInJWT, boolean hasAntiCsrf, + boolean useStaticKey) throws JWT.JWTException { assertNotNull(response.get("session").getAsJsonObject().get("handle").getAsString()); @@ -187,12 +188,13 @@ private static void checkRefreshSessionResponse(JsonObject response, TestingProc assertTrue(response.get("accessToken").getAsJsonObject().has("createdTime")); assertEquals(response.get("accessToken").getAsJsonObject().entrySet().size(), 3); - JWT.JWTPreParseInfo tokenInfo = JWT.preParseJWTInfo(response.get("accessToken").getAsJsonObject().get("token").getAsString()); + JWT.JWTPreParseInfo tokenInfo = JWT.preParseJWTInfo( + response.get("accessToken").getAsJsonObject().get("token").getAsString()); if (useStaticKey) { - assert(tokenInfo.kid.startsWith("s-")); + assert (tokenInfo.kid.startsWith("s-")); } else { - assert(tokenInfo.kid.startsWith("d-")); + assert (tokenInfo.kid.startsWith("d-")); } assertTrue(response.get("refreshToken").getAsJsonObject().has("token")); diff --git a/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest5_0.java b/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest5_0.java index 6feb65fc2..901605dd1 100644 --- a/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest5_0.java +++ b/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest5_0.java @@ -51,7 +51,7 @@ public void beforeEach() { @Test public void badInputMissingUseDynamicSigningKey() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -86,7 +86,8 @@ public void badInputMissingUseDynamicSigningKey() throws Exception { SemVer.v5_0.get(), "session"); } catch (io.supertokens.test.httpRequest.HttpResponseException e) { assertEquals(e.getMessage(), - "Http error. Status Code: 400. Message: Field name 'useDynamicSigningKey' is invalid in JSON input"); + "Http error. Status Code: 400. Message: Field name 'useDynamicSigningKey' is invalid in JSON " + + "input"); } @@ -96,7 +97,7 @@ public void badInputMissingUseDynamicSigningKey() throws Exception { @Test public void successOutputUpgradeWithNonStaticKeySessionTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -137,7 +138,7 @@ public void successOutputUpgradeWithNonStaticKeySessionTest() throws Exception { @Test public void successOutputUpgradeWithStaticKeySessionTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -178,7 +179,7 @@ public void successOutputUpgradeWithStaticKeySessionTest() throws Exception { @Test public void successOutputWithStaticKeySessionTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -219,7 +220,7 @@ public void successOutputWithStaticKeySessionTest() throws Exception { @Test public void successOutputWithNonStaticKeySessionTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -260,7 +261,7 @@ public void successOutputWithNonStaticKeySessionTest() throws Exception { @Test public void successOutputSwitchingWithStaticKeySessionTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -302,7 +303,7 @@ public void successOutputSwitchingWithStaticKeySessionTest() throws Exception { @Test public void successOutputSwitchingWithNonStaticKeySessionTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -341,8 +342,10 @@ public void successOutputSwitchingWithNonStaticKeySessionTest() throws Exception process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } + private static void checkRefreshSessionResponse(JsonObject response, TestingProcessManager.TestingProcess process, - String userId, JsonObject userDataInJWT, boolean hasAntiCsrf, boolean useStaticKey) throws + String userId, JsonObject userDataInJWT, boolean hasAntiCsrf, + boolean useStaticKey) throws JWT.JWTException { assertNotNull(response.get("session").getAsJsonObject().get("handle").getAsString()); @@ -358,12 +361,13 @@ private static void checkRefreshSessionResponse(JsonObject response, TestingProc assertTrue(response.get("accessToken").getAsJsonObject().has("createdTime")); assertEquals(response.get("accessToken").getAsJsonObject().entrySet().size(), 3); - JWT.JWTPreParseInfo tokenInfo = JWT.preParseJWTInfo(response.get("accessToken").getAsJsonObject().get("token").getAsString()); - + JWT.JWTPreParseInfo tokenInfo = JWT.preParseJWTInfo( + response.get("accessToken").getAsJsonObject().get("token").getAsString()); + if (useStaticKey) { - assert(tokenInfo.kid.startsWith("s-")); + assert (tokenInfo.kid.startsWith("s-")); } else { - assert(tokenInfo.kid.startsWith("d-")); + assert (tokenInfo.kid.startsWith("d-")); } assertTrue(response.get("refreshToken").getAsJsonObject().has("token")); diff --git a/src/test/java/io/supertokens/test/session/api/SessionAPITest2_21.java b/src/test/java/io/supertokens/test/session/api/SessionAPITest2_21.java index 3aac56cd2..abfb4ed0e 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionAPITest2_21.java +++ b/src/test/java/io/supertokens/test/session/api/SessionAPITest2_21.java @@ -55,7 +55,7 @@ public void beforeEach() { @Test public void successOutputCheck() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -78,7 +78,8 @@ public void successOutputCheck() throws Exception { checkSessionResponse(response, process, userId, userDataInJWT, false); assertFalse(response.has("antiCsrfToken")); - String iat = "" + JWT.getPayloadWithoutVerifying(response.get("accessToken").getAsJsonObject().get("token").getAsString()).payload.get("iat").getAsInt(); + String iat = "" + JWT.getPayloadWithoutVerifying( + response.get("accessToken").getAsJsonObject().get("token").getAsString()).payload.get("iat").getAsInt(); assertEquals(10, iat.length()); //noinspection ResultOfMethodCallIgnored Long.parseLong(iat); // We are checking that this doesn't throw, it would if it was in exponential form @@ -91,7 +92,7 @@ public void successOutputCheck() throws Exception { @Test public void badInputTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -159,7 +160,7 @@ public void badInputTest() throws Exception { @Test public void successOutputCheckWithStatic() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -187,7 +188,8 @@ public void successOutputCheckWithStatic() throws Exception { } public static void checkSessionResponse(JsonObject response, TestingProcessManager.TestingProcess process, - String userId, JsonObject userDataInJWT, boolean isStatic) throws JWT.JWTException { + String userId, JsonObject userDataInJWT, boolean isStatic) + throws JWT.JWTException { assertNotNull(response.get("session").getAsJsonObject().get("handle").getAsString()); assertEquals(response.get("session").getAsJsonObject().get("userId").getAsString(), userId); assertEquals(response.get("session").getAsJsonObject().get("userDataInJWT").getAsJsonObject().toString(), @@ -204,7 +206,8 @@ public static void checkSessionResponse(JsonObject response, TestingProcessManag assertTrue(response.get("refreshToken").getAsJsonObject().has("createdTime")); assertEquals(response.get("refreshToken").getAsJsonObject().entrySet().size(), 3); - JWT.JWTPreParseInfo preParseInfo = JWT.preParseJWTInfo(response.get("accessToken").getAsJsonObject().get("token").getAsString()); + JWT.JWTPreParseInfo preParseInfo = JWT.preParseJWTInfo( + response.get("accessToken").getAsJsonObject().get("token").getAsString()); assertEquals(preParseInfo.version, AccessToken.VERSION.V3); assertNotNull(preParseInfo.kid); @@ -228,12 +231,14 @@ public static void checkSessionResponse(JsonObject response, TestingProcessManag Base64.getUrlDecoder().decode(preParseInfo.signature); - JsonObject payload = new JsonParser().parse(new String(Base64.getUrlDecoder().decode(preParseInfo.payload), StandardCharsets.UTF_8)).getAsJsonObject(); + JsonObject payload = new JsonParser().parse( + new String(Base64.getUrlDecoder().decode(preParseInfo.payload), StandardCharsets.UTF_8)) + .getAsJsonObject(); assertFalse(payload.has("userData")); for (Map.Entry entry : userDataInJWT.entrySet()) { - assertTrue(payload.has(entry.getKey())); - assertEquals(payload.get(entry.getKey()).toString(), userDataInJWT.get(entry.getKey()).toString()); + assertTrue(payload.has(entry.getKey())); + assertEquals(payload.get(entry.getKey()).toString(), userDataInJWT.get(entry.getKey()).toString()); } } } diff --git a/src/test/java/io/supertokens/test/session/api/SessionAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/SessionAPITest2_7.java index c1353fcfb..93b65c4e6 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/SessionAPITest2_7.java @@ -52,7 +52,7 @@ public void beforeEach() { @Test public void successOutputCheckWithAntiCsrfWithCookieDomain() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("cookie_domain", "localhost"); @@ -84,7 +84,7 @@ public void successOutputCheckWithAntiCsrfWithCookieDomain() throws Exception { @Test public void successOutputCheckWithAntiCsrf() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -115,7 +115,7 @@ public void successOutputCheckWithAntiCsrf() throws Exception { @Test public void successOutputCheckWithNoAntiCsrf() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -145,7 +145,7 @@ public void successOutputCheckWithNoAntiCsrf() throws Exception { @Test public void badInputTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -247,7 +247,7 @@ public void badInputTest() throws Exception { } public static void checkSessionResponse(JsonObject response, TestingProcessManager.TestingProcess process, - String userId, JsonObject userDataInJWT) { + String userId, JsonObject userDataInJWT) { assertNotNull(response.get("session").getAsJsonObject().get("handle").getAsString()); assertEquals(response.get("session").getAsJsonObject().get("userId").getAsString(), userId); assertEquals(response.get("session").getAsJsonObject().get("userDataInJWT").getAsJsonObject().toString(), diff --git a/src/test/java/io/supertokens/test/session/api/SessionAPITest2_9.java b/src/test/java/io/supertokens/test/session/api/SessionAPITest2_9.java index ff2cfd6a2..a9615bbc1 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionAPITest2_9.java +++ b/src/test/java/io/supertokens/test/session/api/SessionAPITest2_9.java @@ -112,7 +112,7 @@ public void activeUsersTest() throws Exception { @Test public void successOutputCheckWithAntiCsrfWithCookieDomain() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("cookie_domain", "localhost"); @@ -146,7 +146,7 @@ public void successOutputCheckWithAntiCsrfWithCookieDomain() throws Exception { @Test public void successOutputCheckWithAntiCsrf() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -177,7 +177,7 @@ public void successOutputCheckWithAntiCsrf() throws Exception { @Test public void successOutputCheckWithNoAntiCsrf() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -208,7 +208,7 @@ public void successOutputCheckWithNoAntiCsrf() throws Exception { public void successOutputCheckWithStaticAccessTokenSigningKey() throws Exception { Utils.setValueInConfig("access_token_signing_key_dynamic", "false"); - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -236,7 +236,7 @@ public void successOutputCheckWithStaticAccessTokenSigningKey() throws Exception @Test public void successOutputCheckWithNullsInPayload() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -268,7 +268,7 @@ public void successOutputCheckWithNullsInPayload() throws Exception { @Test public void badInputTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -368,7 +368,7 @@ public void badInputTest() throws Exception { } public static void checkSessionResponse(JsonObject response, TestingProcessManager.TestingProcess process, - String userId, JsonObject userDataInJWT) throws JWT.JWTException { + String userId, JsonObject userDataInJWT) throws JWT.JWTException { assertNotNull(response.get("session").getAsJsonObject().get("handle").getAsString()); assertEquals(response.get("session").getAsJsonObject().get("userId").getAsString(), userId); assertEquals(response.get("session").getAsJsonObject().get("userDataInJWT").getAsJsonObject().toString(), @@ -401,7 +401,8 @@ public static void checkSessionResponse(JsonObject response, TestingProcessManag assertEquals(respPubKeyList.get(i).getAsJsonObject().entrySet().size(), 3); } - JWT.JWTPreParseInfo preParseInfo = JWT.preParseJWTInfo(response.get("accessToken").getAsJsonObject().get("token").getAsString()); + JWT.JWTPreParseInfo preParseInfo = JWT.preParseJWTInfo( + response.get("accessToken").getAsJsonObject().get("token").getAsString()); assertEquals(preParseInfo.version, AccessToken.VERSION.V2); assertNull(preParseInfo.kid); Base64.getDecoder().decode(preParseInfo.header); @@ -409,7 +410,8 @@ public static void checkSessionResponse(JsonObject response, TestingProcessManag Base64.getDecoder().decode(preParseInfo.signature); - JsonObject payload = new JsonParser().parse(io.supertokens.utils.Utils.convertFromBase64(preParseInfo.payload)).getAsJsonObject(); + JsonObject payload = new JsonParser().parse(io.supertokens.utils.Utils.convertFromBase64(preParseInfo.payload)) + .getAsJsonObject(); assertTrue(payload.has("userData")); assertEquals(payload.get("userData").getAsJsonObject().toString(), userDataInJWT.toString()); } diff --git a/src/test/java/io/supertokens/test/session/api/SessionAPITest4_0.java b/src/test/java/io/supertokens/test/session/api/SessionAPITest4_0.java index c34c2fbb2..442f887c1 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionAPITest4_0.java +++ b/src/test/java/io/supertokens/test/session/api/SessionAPITest4_0.java @@ -57,7 +57,7 @@ public void beforeEach() { @Test public void successOutputCheck() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -80,7 +80,8 @@ public void successOutputCheck() throws Exception { checkSessionResponse(response, process, userId, userDataInJWT, false); assertFalse(response.has("antiCsrfToken")); - String iat = "" + JWT.getPayloadWithoutVerifying(response.get("accessToken").getAsJsonObject().get("token").getAsString()).payload.get("iat").getAsInt(); + String iat = "" + JWT.getPayloadWithoutVerifying( + response.get("accessToken").getAsJsonObject().get("token").getAsString()).payload.get("iat").getAsInt(); assertEquals(10, iat.length()); //noinspection ResultOfMethodCallIgnored Long.parseLong(iat); // We are checking that this doesn't throw, it would if it was in exponential form @@ -93,7 +94,7 @@ public void successOutputCheck() throws Exception { @Test public void badInputTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -197,7 +198,7 @@ public void badInputTest() throws Exception { @Test public void successOutputCheckWithStatic() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -225,7 +226,8 @@ public void successOutputCheckWithStatic() throws Exception { } public static void checkSessionResponse(JsonObject response, TestingProcessManager.TestingProcess process, - String userId, JsonObject userDataInJWT, boolean isStatic) throws JWT.JWTException { + String userId, JsonObject userDataInJWT, boolean isStatic) + throws JWT.JWTException { assertNotNull(response.get("session").getAsJsonObject().get("handle").getAsString()); assertEquals(response.get("session").getAsJsonObject().get("userId").getAsString(), userId); assertEquals(response.get("session").getAsJsonObject().get("userDataInJWT").getAsJsonObject().toString(), @@ -244,7 +246,8 @@ public static void checkSessionResponse(JsonObject response, TestingProcessManag assertTrue(response.get("refreshToken").getAsJsonObject().has("createdTime")); assertEquals(response.get("refreshToken").getAsJsonObject().entrySet().size(), 3); - JWT.JWTPreParseInfo preParseInfo = JWT.preParseJWTInfo(response.get("accessToken").getAsJsonObject().get("token").getAsString()); + JWT.JWTPreParseInfo preParseInfo = JWT.preParseJWTInfo( + response.get("accessToken").getAsJsonObject().get("token").getAsString()); assertEquals(preParseInfo.version, AccessToken.VERSION.V5); assertNotNull(preParseInfo.kid); @@ -268,12 +271,14 @@ public static void checkSessionResponse(JsonObject response, TestingProcessManag Base64.getUrlDecoder().decode(preParseInfo.signature); - JsonObject payload = new JsonParser().parse(new String(Base64.getUrlDecoder().decode(preParseInfo.payload), StandardCharsets.UTF_8)).getAsJsonObject(); + JsonObject payload = new JsonParser().parse( + new String(Base64.getUrlDecoder().decode(preParseInfo.payload), StandardCharsets.UTF_8)) + .getAsJsonObject(); assertFalse(payload.has("userData")); for (Map.Entry entry : userDataInJWT.entrySet()) { - assertTrue(payload.has(entry.getKey())); - assertEquals(payload.get(entry.getKey()).toString(), userDataInJWT.get(entry.getKey()).toString()); + assertTrue(payload.has(entry.getKey())); + assertEquals(payload.get(entry.getKey()).toString(), userDataInJWT.get(entry.getKey()).toString()); } } } diff --git a/src/test/java/io/supertokens/test/session/api/SessionDataAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/SessionDataAPITest2_7.java index 9509cc94f..edcad5c7d 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionDataAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/SessionDataAPITest2_7.java @@ -51,7 +51,7 @@ public void beforeEach() { @Test public void inputErrorsInSessionUserAPITest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -132,7 +132,7 @@ public void inputErrorsInSessionUserAPITest() throws Exception { @Test public void getRequestSuccessOutputCheckTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; String sessionJsonInput = "{\n" + "\t\"userId\": \"UserID\",\n" + "\t\"userDataInJWT\": {\n" + "\t\t\"userData1\": \"temp1\",\n" + "\t\t\"userData2\": \"temp2\"\n" + "\t},\n" @@ -183,7 +183,7 @@ public void getRequestSuccessOutputCheckTest() throws Exception { @Test public void putRequestSuccessOutputCheckTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; String sessionJsonInput = "{\n" + "\t\"userId\": \"UserID\",\n" + "\t\"userDataInJWT\": {\n" + "\t\t\"userData1\": \"temp1\",\n" + "\t\t\"userData2\": \"temp2\"\n" + "\t},\n" diff --git a/src/test/java/io/supertokens/test/session/api/SessionGetAPIJWTTest2_8.java b/src/test/java/io/supertokens/test/session/api/SessionGetAPIJWTTest2_8.java index 8512bad0c..8c067969a 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionGetAPIJWTTest2_8.java +++ b/src/test/java/io/supertokens/test/session/api/SessionGetAPIJWTTest2_8.java @@ -51,7 +51,7 @@ public void beforeEach() { @Test public void testAPIFailuresWithBadInputParameters() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -88,7 +88,7 @@ public void testAPIFailuresWithBadInputParameters() throws Exception { @Test public void testGetRequestWithNoSessionReturnsUnauthorised() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -110,7 +110,7 @@ public void testGetRequestWithNoSessionReturnsUnauthorised() throws Exception { @Test public void testThatGetWithValidParametersWorks() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; String sessionJsonInput = "{\n" + "\t\"userId\": \"UserID\",\n" + "\t\"userDataInJWT\": {\n" + "\t\t\"userData1\": \"temp1\",\n" + "\t\t\"userData2\": \"temp2\"\n" + "\t},\n" diff --git a/src/test/java/io/supertokens/test/session/api/SessionRegenerateAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/SessionRegenerateAPITest2_7.java index 3f4076e21..9eddd6c88 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionRegenerateAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/SessionRegenerateAPITest2_7.java @@ -48,7 +48,7 @@ public void beforeEach() { @Test public void testCallRegenerateAPIWithNewJwtPayloadAndCheckResponses() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -110,7 +110,7 @@ public void testCallRegenerateAPIWithNewJwtPayloadAndCheckResponses() throws Exc @Test public void testWaitForAccessTokenToExpireCallRegenerateWithNewJWTPayloadAndCheckResponses() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("access_token_validity", "1"); TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); @@ -171,7 +171,7 @@ public void testWaitForAccessTokenToExpireCallRegenerateWithNewJWTPayloadAndChec @Test public void testRefreshTokenExpiryCallRegenerateAPIWithNewPayloadAndCheckResponse() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("refresh_token_validity", "" + 1.0 / 60);// 1 second validity (value in mins) TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); @@ -228,7 +228,7 @@ public void testRefreshTokenExpiryCallRegenerateAPIWithNewPayloadAndCheckRespons @Test public void testCallRegenerateAPIWithProtectedFieldInJWTV2Token() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/session/api/SessionRemoveAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/SessionRemoveAPITest2_7.java index ee86fc937..04daf5538 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionRemoveAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/SessionRemoveAPITest2_7.java @@ -57,7 +57,7 @@ public void beforeEach() { @Test public void activeUsersTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -68,46 +68,46 @@ public void activeUsersTest() throws Exception { // Case where we don't have userId: { - // create sessions s1, s2 - String userId = "userId"; - JsonObject userDataInJWT = new JsonObject(); - userDataInJWT.addProperty("key", "value"); - JsonObject userDataInDatabase = new JsonObject(); - userDataInDatabase.addProperty("key", "value"); + // create sessions s1, s2 + String userId = "userId"; + JsonObject userDataInJWT = new JsonObject(); + userDataInJWT.addProperty("key", "value"); + JsonObject userDataInDatabase = new JsonObject(); + userDataInDatabase.addProperty("key", "value"); - JsonObject sessionRequest = new JsonObject(); - sessionRequest.addProperty("userId", userId); - sessionRequest.add("userDataInJWT", userDataInJWT); - sessionRequest.add("userDataInDatabase", userDataInDatabase); - sessionRequest.addProperty("enableAntiCsrf", false); + JsonObject sessionRequest = new JsonObject(); + sessionRequest.addProperty("userId", userId); + sessionRequest.add("userDataInJWT", userDataInJWT); + sessionRequest.add("userDataInDatabase", userDataInDatabase); + sessionRequest.addProperty("enableAntiCsrf", false); - // create session s1 - JsonObject s1Info = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", - "http://localhost:3567/recipe/session", sessionRequest, 1000, 1000, 2, SemVer.v2_7.get(), - "session"); - assertEquals(s1Info.get("status").getAsString(), "OK"); + // create session s1 + JsonObject s1Info = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", + "http://localhost:3567/recipe/session", sessionRequest, 1000, 1000, 2, SemVer.v2_7.get(), + "session"); + assertEquals(s1Info.get("status").getAsString(), "OK"); - // create session s2 - JsonObject s2Info = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", - "http://localhost:3567/recipe/session", sessionRequest, 1000, 1000, 2, SemVer.v2_7.get(), - "session"); - assertEquals(s2Info.get("status").getAsString(), "OK"); + // create session s2 + JsonObject s2Info = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", + "http://localhost:3567/recipe/session", sessionRequest, 1000, 1000, 2, SemVer.v2_7.get(), + "session"); + assertEquals(s2Info.get("status").getAsString(), "OK"); - // remove s2 and make sure they are returned - Thread.sleep(1); // ensures a unique timestamp - long checkpoint1 = System.currentTimeMillis(); + // remove s2 and make sure they are returned + Thread.sleep(1); // ensures a unique timestamp + long checkpoint1 = System.currentTimeMillis(); - JsonObject sessionRemoveBody = new JsonObject(); - JsonArray sessionHandles = new JsonArray(); - sessionHandles.add(new JsonPrimitive(s2Info.get("session").getAsJsonObject().get("handle").getAsString())); - sessionRemoveBody.add("sessionHandles", sessionHandles); + JsonObject sessionRemoveBody = new JsonObject(); + JsonArray sessionHandles = new JsonArray(); + sessionHandles.add(new JsonPrimitive(s2Info.get("session").getAsJsonObject().get("handle").getAsString())); + sessionRemoveBody.add("sessionHandles", sessionHandles); - HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", - "http://localhost:3567/recipe/session/remove", sessionRemoveBody, 1000, 1000, null, - SemVer.v2_7.get(), "session"); + HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", + "http://localhost:3567/recipe/session/remove", sessionRemoveBody, 1000, 1000, null, + SemVer.v2_7.get(), "session"); - int activeUsers = ActiveUsers.countUsersActiveSince(process.getProcess(), checkpoint1); - assert (activeUsers == 0); // user ID is not set so not counted as active (we don't have userId) + int activeUsers = ActiveUsers.countUsersActiveSince(process.getProcess(), checkpoint1); + assert (activeUsers == 0); // user ID is not set so not counted as active (we don't have userId) } // Case where we have UserId: @@ -166,7 +166,7 @@ public void activeUsersTest() throws Exception { // * only s1 and s3 are returned. @Test public void testRemovingMultipleSessionsGivesCorrectOutput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -255,7 +255,7 @@ public void testRemovingMultipleSessionsGivesCorrectOutput() throws Exception { @Test public void testRevoking1SessionUsingSessionHandle() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -309,7 +309,7 @@ public void testRevoking1SessionUsingSessionHandle() throws Exception { @Test public void testRemovingSessionByUserId() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/session/api/SessionUserAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/SessionUserAPITest2_7.java index 940564d03..3aaa6d72f 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionUserAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/SessionUserAPITest2_7.java @@ -50,7 +50,7 @@ public void beforeEach() { @Test public void inputErrorsInSessionUserAPITest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -84,7 +84,7 @@ public void inputErrorsInSessionUserAPITest() throws Exception { @Test public void differentPossibleSessionUserAPIOutputTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; String createSessionJsonInput = "{" + "\"userId\": \"UserID\"," + "\"userDataInJWT\": {" + "\"userData1\": \"temp1\"," + "\"userData2\": \"temp2\"" + "}," + "\"userDataInDatabase\": {" @@ -164,7 +164,7 @@ public void differentPossibleSessionUserAPIOutputTest() throws Exception { @Test public void multipleUsersMultipleSessionTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; HashMap map = new HashMap<>(); diff --git a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_21.java b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_21.java index 583cb0fec..9bddccfdc 100644 --- a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_21.java +++ b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_21.java @@ -49,7 +49,7 @@ public void beforeEach() { @Test public void successOutputCheckV2AccessToken() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -95,7 +95,7 @@ public void successOutputCheckV2AccessToken() throws Exception { @Test public void successOutputCheckV3AccessToken() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -140,7 +140,7 @@ public void successOutputCheckV3AccessToken() throws Exception { @Test public void successOutputCheckNewAccessTokenUpgradeToV3() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -199,7 +199,7 @@ public void successOutputCheckNewAccessTokenUpgradeToV3() throws Exception { @Test public void checkDatabaseParamTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -243,7 +243,8 @@ public void checkDatabaseParamTest() throws Exception { } { JsonObject request = new JsonObject(); - request.addProperty("accessToken", sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString()); + request.addProperty("accessToken", + sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString()); request.addProperty("doAntiCsrfCheck", true); request.addProperty("enableAntiCsrf", false); request.addProperty("checkDatabase", false); diff --git a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_7.java index 69faf32dc..addff469b 100644 --- a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_7.java @@ -48,7 +48,7 @@ public void beforeEach() { @Test public void successOutputCheckNoNewAccessToken() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -94,7 +94,7 @@ public void successOutputCheckNoNewAccessToken() throws Exception { @Test public void successOutputCheckNewAccessToken() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -153,7 +153,7 @@ public void successOutputCheckNewAccessToken() throws Exception { @Test public void successOutputCheckNewAccessTokenWithCookieDomain() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("cookie_domain", "localhost"); TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); @@ -217,7 +217,7 @@ public void unauthorisedOutputCheck() throws Exception { Utils.setValueInConfig("access_token_blacklisting", "true"); - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -266,7 +266,7 @@ public void tryRefreshTokenOutputCheck() throws Exception { Utils.setValueInConfig("access_token_blacklisting", "true"); - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -290,7 +290,7 @@ public void tryRefreshTokenOutputCheck() throws Exception { @Test public void badInputTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_9.java b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_9.java index 48559aa2c..2c5926437 100644 --- a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_9.java +++ b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_9.java @@ -50,7 +50,7 @@ public void beforeEach() { @Test public void successOutputCheckNoNewAccessToken() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -105,7 +105,7 @@ public void successOutputCheckNoNewAccessToken() throws Exception { @Test public void successOutputCheckNewAccessToken() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -173,7 +173,7 @@ public void successOutputCheckNewAccessToken() throws Exception { @Test public void successOutputCheckNewAccessTokenWithCookieDomain() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; Utils.setValueInConfig("cookie_domain", "localhost"); TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); @@ -246,7 +246,7 @@ public void unauthorisedOutputCheck() throws Exception { Utils.setValueInConfig("access_token_blacklisting", "true"); - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -295,7 +295,7 @@ public void tryRefreshTokenOutputCheck() throws Exception { Utils.setValueInConfig("access_token_blacklisting", "true"); - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -319,7 +319,7 @@ public void tryRefreshTokenOutputCheck() throws Exception { @Test public void badInputTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest3_0.java b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest3_0.java index 5273845fc..188822c26 100644 --- a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest3_0.java +++ b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest3_0.java @@ -55,7 +55,7 @@ public void beforeEach() { @Test public void successOutputCheckV3AccessToken() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -100,7 +100,7 @@ public void successOutputCheckV3AccessToken() throws Exception { @Test public void checkThattIdIsNotPresentInV3() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -169,7 +169,7 @@ public void checkThattIdIsNotPresentInV3() throws Exception { @Test public void successOutputCheckNewAccessTokenUpgradeToV4() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -259,7 +259,7 @@ public void successOutputCheckNewAccessTokenUpgradeToV4() throws Exception { @Test public void testAccessTokenInfoOnV3AccessTokenPointsToPublicTenant() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -278,7 +278,8 @@ public void testAccessTokenInfoOnV3AccessTokenPointsToPublicTenant() throws Exce "http://localhost:3567/recipe/session", sessionRequest, 1000, 1000, null, SemVer.v2_21.get(), "session"); - AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(new AppIdentifier(null, null), process.getProcess(), sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(), + AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(new AppIdentifier(null, null), + process.getProcess(), sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(), false); assertEquals(TenantIdentifier.DEFAULT_TENANT_ID, accessTokenInfo.tenantIdentifier.getTenantId()); @@ -289,7 +290,7 @@ public void testAccessTokenInfoOnV3AccessTokenPointsToPublicTenant() throws Exce @Test public void testV4AccessTokenOnOlderCDIWorksFine() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -334,7 +335,7 @@ public void testV4AccessTokenOnOlderCDIWorksFine() throws Exception { @Test public void testV3AccessTokenWithCustomtIdPayload() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -354,7 +355,8 @@ public void testV3AccessTokenWithCustomtIdPayload() throws Exception { "http://localhost:3567/recipe/session", sessionRequest, 1000, 1000, null, SemVer.v2_21.get(), "session"); - AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(new AppIdentifier(null, null), process.getProcess(), sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(), + AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(new AppIdentifier(null, null), + process.getProcess(), sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(), false); assertEquals(TenantIdentifier.DEFAULT_TENANT_ID, accessTokenInfo.tenantIdentifier.getTenantId()); @@ -367,7 +369,8 @@ public void testV3AccessTokenWithCustomtIdPayload() throws Exception { } JsonObject sessionRefreshRequest = new JsonObject(); - sessionRefreshRequest.addProperty("refreshToken", sessionInfo.get("refreshToken").getAsJsonObject().get("token").getAsString()); + sessionRefreshRequest.addProperty("refreshToken", + sessionInfo.get("refreshToken").getAsJsonObject().get("token").getAsString()); sessionRefreshRequest.addProperty("enableAntiCsrf", false); JsonObject sessionRefreshResponse = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", @@ -388,7 +391,7 @@ public void testV3AccessTokenWithCustomtIdPayload() throws Exception { @Test public void testV3AccessTokenWithCustomtIdPayloadAfterRefreshInV4() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -408,13 +411,15 @@ public void testV3AccessTokenWithCustomtIdPayloadAfterRefreshInV4() throws Excep "http://localhost:3567/recipe/session", sessionRequest, 1000, 1000, null, SemVer.v2_21.get(), "session"); - AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(new AppIdentifier(null, null), process.getProcess(), sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(), + AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(new AppIdentifier(null, null), + process.getProcess(), sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(), false); assertEquals(TenantIdentifier.DEFAULT_TENANT_ID, accessTokenInfo.tenantIdentifier.getTenantId()); JsonObject sessionRefreshRequest = new JsonObject(); - sessionRefreshRequest.addProperty("refreshToken", sessionInfo.get("refreshToken").getAsJsonObject().get("token").getAsString()); + sessionRefreshRequest.addProperty("refreshToken", + sessionInfo.get("refreshToken").getAsJsonObject().get("token").getAsString()); sessionRefreshRequest.addProperty("enableAntiCsrf", false); JsonObject sessionRefreshResponse = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", diff --git a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest4_0.java b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest4_0.java index a4a2ea7b4..a6770005f 100644 --- a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest4_0.java +++ b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest4_0.java @@ -54,7 +54,7 @@ public void beforeEach() { @Test public void successOutputCheckV4AccessToken() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -100,7 +100,7 @@ public void successOutputCheckV4AccessToken() throws Exception { @Test public void checkThatrecipeUserIdIsNotPresentInV4() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -172,7 +172,7 @@ public void checkThatrecipeUserIdIsNotPresentInV4() throws Exception { @Test public void successOutputCheckNewAccessTokenUpgradeToV5() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -262,7 +262,7 @@ public void successOutputCheckNewAccessTokenUpgradeToV5() throws Exception { @Test public void testV5AccessTokenOnOlderCDIWorksFine() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -308,7 +308,7 @@ public void testV5AccessTokenOnOlderCDIWorksFine() throws Exception { @Test public void testV4AccessTokenWithCustomtIdPayload() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -328,7 +328,8 @@ public void testV4AccessTokenWithCustomtIdPayload() throws Exception { "http://localhost:3567/recipe/session", sessionRequest, 1000, 1000, null, SemVer.v3_0.get(), "session"); - AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(new AppIdentifier(null, null), process.getProcess(), sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(), + AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(new AppIdentifier(null, null), + process.getProcess(), sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(), false); assertEquals(TenantIdentifier.DEFAULT_TENANT_ID, accessTokenInfo.tenantIdentifier.getTenantId()); @@ -341,7 +342,8 @@ public void testV4AccessTokenWithCustomtIdPayload() throws Exception { } JsonObject sessionRefreshRequest = new JsonObject(); - sessionRefreshRequest.addProperty("refreshToken", sessionInfo.get("refreshToken").getAsJsonObject().get("token").getAsString()); + sessionRefreshRequest.addProperty("refreshToken", + sessionInfo.get("refreshToken").getAsJsonObject().get("token").getAsString()); sessionRefreshRequest.addProperty("enableAntiCsrf", false); JsonObject sessionRefreshResponse = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", @@ -362,7 +364,7 @@ public void testV4AccessTokenWithCustomtIdPayload() throws Exception { @Test public void testV4AccessTokenWithCustomtIdPayloadAfterRefreshInV5() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -382,13 +384,15 @@ public void testV4AccessTokenWithCustomtIdPayloadAfterRefreshInV5() throws Excep "http://localhost:3567/recipe/session", sessionRequest, 1000, 1000, null, SemVer.v3_0.get(), "session"); - AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(new AppIdentifier(null, null), process.getProcess(), sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(), + AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(new AppIdentifier(null, null), + process.getProcess(), sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(), false); assertEquals(TenantIdentifier.DEFAULT_TENANT_ID, accessTokenInfo.tenantIdentifier.getTenantId()); JsonObject sessionRefreshRequest = new JsonObject(); - sessionRefreshRequest.addProperty("refreshToken", sessionInfo.get("refreshToken").getAsJsonObject().get("token").getAsString()); + sessionRefreshRequest.addProperty("refreshToken", + sessionInfo.get("refreshToken").getAsJsonObject().get("token").getAsString()); sessionRefreshRequest.addProperty("enableAntiCsrf", false); JsonObject sessionRefreshResponse = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", diff --git a/src/test/java/io/supertokens/test/session/api/VersionTest.java b/src/test/java/io/supertokens/test/session/api/VersionTest.java index 25b09c62a..f97e6df29 100644 --- a/src/test/java/io/supertokens/test/session/api/VersionTest.java +++ b/src/test/java/io/supertokens/test/session/api/VersionTest.java @@ -72,7 +72,7 @@ private JsonObject getSession(Main main, String version, String sessionHandle) @Test public void testVerifySessionAcrossVersions() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -107,7 +107,8 @@ public void testVerifySessionAcrossVersions() throws Exception { { // Session verify // Should be verified as is without the need for refresh JsonObject request = new JsonObject(); - request.addProperty("accessToken", sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString()); + request.addProperty("accessToken", + sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString()); request.addProperty("doAntiCsrfCheck", true); request.addProperty("enableAntiCsrf", false); request.addProperty("checkDatabase", false); @@ -118,12 +119,17 @@ public void testVerifySessionAcrossVersions() throws Exception { junit.framework.TestCase.assertEquals(response.get("status").getAsString(), "OK"); assertNotNull(response.get("session").getAsJsonObject().get("handle").getAsString()); - junit.framework.TestCase.assertEquals(response.get("session").getAsJsonObject().get("userId").getAsString(), userId); - junit.framework.TestCase.assertEquals(response.get("session").getAsJsonObject().get("userDataInJWT").getAsJsonObject(), userDataInJWT); + junit.framework.TestCase.assertEquals( + response.get("session").getAsJsonObject().get("userId").getAsString(), userId); + junit.framework.TestCase.assertEquals( + response.get("session").getAsJsonObject().get("userDataInJWT").getAsJsonObject(), + userDataInJWT); if (getCDIVersionForAccessTokenVersion(updateVersion).lesserThan(SemVer.v3_0)) { - junit.framework.TestCase.assertEquals(response.get("session").getAsJsonObject().entrySet().size(), 3); + junit.framework.TestCase.assertEquals( + response.get("session").getAsJsonObject().entrySet().size(), 3); } else { - junit.framework.TestCase.assertEquals(response.get("session").getAsJsonObject().entrySet().size(), 4); + junit.framework.TestCase.assertEquals( + response.get("session").getAsJsonObject().entrySet().size(), 4); } } } @@ -135,7 +141,7 @@ public void testVerifySessionAcrossVersions() throws Exception { @Test public void testRegenerateAcrossVersions() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -167,20 +173,26 @@ public void testRegenerateAcrossVersions() throws Exception { newUserDataInJWT.addProperty("key2", "value2"); newUserDataInJWT.add("nullProp", JsonNull.INSTANCE); JsonObject sessionRegenerateRequest = new JsonObject(); - sessionRegenerateRequest.addProperty("accessToken", sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString()); + sessionRegenerateRequest.addProperty("accessToken", + sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString()); sessionRegenerateRequest.add("userDataInJWT", newUserDataInJWT); String accessToken = sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(); - AccessToken.AccessTokenInfo accessTokenInfoBefore = AccessToken.getInfoFromAccessToken(process.getProcess(), + AccessToken.AccessTokenInfo accessTokenInfoBefore = AccessToken.getInfoFromAccessToken( + process.getProcess(), accessToken, false); - JsonObject sessionRegenerateResponse = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", - "http://localhost:3567/recipe/session/regenerate", sessionRegenerateRequest, 1000, 1000, null, + JsonObject sessionRegenerateResponse = HttpRequestForTesting.sendJsonPOSTRequest( + process.getProcess(), "", + "http://localhost:3567/recipe/session/regenerate", sessionRegenerateRequest, 1000, 1000, + null, getCDIVersionForAccessTokenVersion(updateVersion).get(), "session"); - AccessToken.AccessTokenInfo accessTokenInfoAfter = AccessToken.getInfoFromAccessToken(process.getProcess(), - sessionRegenerateResponse.get("accessToken").getAsJsonObject().get("token").getAsString(), false); + AccessToken.AccessTokenInfo accessTokenInfoAfter = AccessToken.getInfoFromAccessToken( + process.getProcess(), + sessionRegenerateResponse.get("accessToken").getAsJsonObject().get("token").getAsString(), + false); assertEquals(accessTokenInfoBefore.version, accessTokenInfoAfter.version); } @@ -193,7 +205,7 @@ public void testRegenerateAcrossVersions() throws Exception { @Test public void testSessionRefreshAcrossVersions() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -222,17 +234,21 @@ public void testSessionRefreshAcrossVersions() throws Exception { { // Session regenerate // Should not update the version JsonObject sessionRefreshRequest = new JsonObject(); - sessionRefreshRequest.addProperty("refreshToken", sessionInfo.get("refreshToken").getAsJsonObject().get("token").getAsString()); + sessionRefreshRequest.addProperty("refreshToken", + sessionInfo.get("refreshToken").getAsJsonObject().get("token").getAsString()); sessionRefreshRequest.addProperty("enableAntiCsrf", false); String accessToken = sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(); - JsonObject sessionRefreshResponse = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", + JsonObject sessionRefreshResponse = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), + "", "http://localhost:3567/recipe/session/refresh", sessionRefreshRequest, 1000, 1000, null, getCDIVersionForAccessTokenVersion(updateVersion).get(), "session"); - AccessToken.AccessTokenInfo accessTokenInfoAfter = AccessToken.getInfoFromAccessToken(process.getProcess(), - sessionRefreshResponse.get("accessToken").getAsJsonObject().get("token").getAsString(), false); + AccessToken.AccessTokenInfo accessTokenInfoAfter = AccessToken.getInfoFromAccessToken( + process.getProcess(), + sessionRefreshResponse.get("accessToken").getAsJsonObject().get("token").getAsString(), + false); assertEquals(AccessToken.getVersionFromString(updateVersion), accessTokenInfoAfter.version); } @@ -245,7 +261,7 @@ public void testSessionRefreshAcrossVersions() throws Exception { @Test public void testUpdateSessionDataAcrossVersions() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -276,7 +292,8 @@ public void testUpdateSessionDataAcrossVersions() throws Exception { newUserDataInDatabase.addProperty("key2", "value2"); JsonObject putRequestBody = new JsonObject(); - putRequestBody.addProperty("sessionHandle", sessionInfo.get("session").getAsJsonObject().get("handle").getAsString()); + putRequestBody.addProperty("sessionHandle", + sessionInfo.get("session").getAsJsonObject().get("handle").getAsString()); putRequestBody.add("userDataInDatabase", newUserDataInDatabase); JsonObject sessionDataResponse = HttpRequestForTesting.sendJsonPUTRequest(process.getProcess(), "", @@ -285,7 +302,8 @@ public void testUpdateSessionDataAcrossVersions() throws Exception { assertEquals("OK", sessionDataResponse.get("status").getAsString()); - JsonObject newSessionInfo = getSession(process.getProcess(), updateVersion, sessionInfo.get("session").getAsJsonObject().get("handle").getAsString()); + JsonObject newSessionInfo = getSession(process.getProcess(), updateVersion, + sessionInfo.get("session").getAsJsonObject().get("handle").getAsString()); assertEquals(newUserDataInDatabase, newSessionInfo.get("userDataInDatabase").getAsJsonObject()); } } @@ -297,7 +315,7 @@ public void testUpdateSessionDataAcrossVersions() throws Exception { @Test public void testUpdateJWTDataAcrossVersions() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -328,7 +346,8 @@ public void testUpdateJWTDataAcrossVersions() throws Exception { newUserDataInDatabase.addProperty("key2", "value2"); JsonObject putRequestBody = new JsonObject(); - putRequestBody.addProperty("sessionHandle", sessionInfo.get("session").getAsJsonObject().get("handle").getAsString()); + putRequestBody.addProperty("sessionHandle", + sessionInfo.get("session").getAsJsonObject().get("handle").getAsString()); putRequestBody.add("userDataInJWT", newUserDataInDatabase); JsonObject sessionDataResponse = HttpRequestForTesting.sendJsonPUTRequest(process.getProcess(), "", @@ -337,7 +356,8 @@ public void testUpdateJWTDataAcrossVersions() throws Exception { assertEquals("OK", sessionDataResponse.get("status").getAsString()); - JsonObject newSessionInfo = getSession(process.getProcess(), updateVersion, sessionInfo.get("session").getAsJsonObject().get("handle").getAsString()); + JsonObject newSessionInfo = getSession(process.getProcess(), updateVersion, + sessionInfo.get("session").getAsJsonObject().get("handle").getAsString()); assertEquals(newUserDataInDatabase, newSessionInfo.get("userDataInJWT").getAsJsonObject()); } } diff --git a/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest.java b/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest.java index bf1da6392..b9f7f114a 100644 --- a/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest.java +++ b/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest.java @@ -388,12 +388,15 @@ public void testGetUserFunctions() throws Exception { checkSignInUpResponse(signUpResponse, thirdPartyUserId, thirdPartyId, email, true); - AuthRecipeUserInfo getUserInfoFromId = ThirdParty.getUser(process.getProcess(), signUpResponse.user.getSupertokensUserId()); + AuthRecipeUserInfo getUserInfoFromId = ThirdParty.getUser(process.getProcess(), + signUpResponse.user.getSupertokensUserId()); assertEquals(getUserInfoFromId.getSupertokensUserId(), signUpResponse.user.getSupertokensUserId()); assertEquals(getUserInfoFromId.timeJoined, signUpResponse.user.timeJoined); assertEquals(getUserInfoFromId.loginMethods[0].email, signUpResponse.user.loginMethods[0].email); - assertEquals(getUserInfoFromId.loginMethods[0].thirdParty.userId, signUpResponse.user.loginMethods[0].thirdParty.userId); - assertEquals(getUserInfoFromId.loginMethods[0].thirdParty.id, signUpResponse.user.loginMethods[0].thirdParty.id); + assertEquals(getUserInfoFromId.loginMethods[0].thirdParty.userId, + signUpResponse.user.loginMethods[0].thirdParty.userId); + assertEquals(getUserInfoFromId.loginMethods[0].thirdParty.id, + signUpResponse.user.loginMethods[0].thirdParty.id); AuthRecipeUserInfo getUserInfoFromThirdParty = ThirdParty.getUser(process.getProcess(), signUpResponse.user.loginMethods[0].thirdParty.id, diff --git a/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest2_7.java b/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest2_7.java index d7b7818cc..fa0e467d0 100644 --- a/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest2_7.java +++ b/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest2_7.java @@ -400,12 +400,15 @@ public void testGetUserFunctions() throws Exception { checkSignInUpResponse(signUpResponse, thirdPartyUserId, thirdPartyId, email, true); - AuthRecipeUserInfo getUserInfoFromId = ThirdParty.getUser(process.getProcess(), signUpResponse.user.getSupertokensUserId()); + AuthRecipeUserInfo getUserInfoFromId = ThirdParty.getUser(process.getProcess(), + signUpResponse.user.getSupertokensUserId()); assertEquals(getUserInfoFromId.getSupertokensUserId(), signUpResponse.user.getSupertokensUserId()); assertEquals(getUserInfoFromId.timeJoined, signUpResponse.user.timeJoined); assertEquals(getUserInfoFromId.loginMethods[0].email, signUpResponse.user.loginMethods[0].email); - assertEquals(getUserInfoFromId.loginMethods[0].thirdParty.userId, signUpResponse.user.loginMethods[0].thirdParty.userId); - assertEquals(getUserInfoFromId.loginMethods[0].thirdParty.id, signUpResponse.user.loginMethods[0].thirdParty.id); + assertEquals(getUserInfoFromId.loginMethods[0].thirdParty.userId, + signUpResponse.user.loginMethods[0].thirdParty.userId); + assertEquals(getUserInfoFromId.loginMethods[0].thirdParty.id, + signUpResponse.user.loginMethods[0].thirdParty.id); AuthRecipeUserInfo getUserInfoFromThirdParty = ThirdParty.getUser(process.getProcess(), signUpResponse.user.loginMethods[0].thirdParty.id, diff --git a/src/test/java/io/supertokens/test/thirdparty/api/EmailVerificationTest.java b/src/test/java/io/supertokens/test/thirdparty/api/EmailVerificationTest.java index 8a4330ca2..d0bf0a10e 100644 --- a/src/test/java/io/supertokens/test/thirdparty/api/EmailVerificationTest.java +++ b/src/test/java/io/supertokens/test/thirdparty/api/EmailVerificationTest.java @@ -127,7 +127,8 @@ public void testEmailVerificationOnSignInUp_v4_0() throws Exception { fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertTrue(e.getMessage().contains("Http error. Status Code: 400. Message: Field name 'isVerified' is invalid in JSON input")); + assertTrue(e.getMessage().contains( + "Http error. Status Code: 400. Message: Field name 'isVerified' is invalid in JSON input")); } } @@ -238,7 +239,8 @@ public void testWithAccountLinking() throws Exception { AuthRecipeUserInfo user1 = createEmailPasswordUser(process.getProcess(), "test@example.com", "password"); Thread.sleep(50); - AuthRecipeUserInfo user2 = createThirdPartyUser(process.getProcess(), "google", "google-user", "test@example.com"); + AuthRecipeUserInfo user2 = createThirdPartyUser(process.getProcess(), "google", "google-user", + "test@example.com"); AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()); AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user1.getSupertokensUserId()); @@ -259,7 +261,8 @@ public void testWithAccountLinking() throws Exception { "http://localhost:3567/recipe/signinup", signUpRequestBody, 1000, 1000, null, SemVer.v4_0.get(), "thirdparty"); - assertTrue(EmailVerification.isEmailVerified(process.getProcess(), user2.getSupertokensUserId(), "test@example.com")); + assertTrue(EmailVerification.isEmailVerified(process.getProcess(), user2.getSupertokensUserId(), + "test@example.com")); } } } diff --git a/src/test/java/io/supertokens/test/thirdparty/api/MultitenantAPITest.java b/src/test/java/io/supertokens/test/thirdparty/api/MultitenantAPITest.java index 53a2b9235..e2e037fc6 100644 --- a/src/test/java/io/supertokens/test/thirdparty/api/MultitenantAPITest.java +++ b/src/test/java/io/supertokens/test/thirdparty/api/MultitenantAPITest.java @@ -161,7 +161,8 @@ private void createTenants() t3 = new TenantIdentifier(null, "a1", "t2"); } - public JsonObject signInUp(TenantIdentifier tenantIdentifier, String thirdPartyId, String thirdPartyUserId, String email) + public JsonObject signInUp(TenantIdentifier tenantIdentifier, String thirdPartyId, String thirdPartyUserId, + String email) throws HttpResponseException, IOException { JsonObject emailObject = new JsonObject(); emailObject.addProperty("id", email); @@ -193,7 +194,8 @@ private JsonObject getUserUsingId(TenantIdentifier tenantIdentifier, String user return userResponse.getAsJsonObject("user"); } - private JsonObject getUserUsingThirdPartyUserId(TenantIdentifier tenantIdentifier, String thirdPartyId, String thirdPartyUserId) + private JsonObject getUserUsingThirdPartyUserId(TenantIdentifier tenantIdentifier, String thirdPartyId, + String thirdPartyUserId) throws HttpResponseException, IOException { HashMap map = new HashMap<>(); map.put("thirdPartyId", thirdPartyId); @@ -243,7 +245,8 @@ public void testSameThirdPartyUserCanLoginAcrossTenants() throws Exception { } @Test - public void testGetUserUsingIdReturnsUserFromTheRightTenantWhileQueryingFromAnyTenantInTheSameApp() throws Exception { + public void testGetUserUsingIdReturnsUserFromTheRightTenantWhileQueryingFromAnyTenantInTheSameApp() + throws Exception { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } diff --git a/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartyGetUserAPITest2_7.java b/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartyGetUserAPITest2_7.java index 9aab47c5a..55ed44bac 100644 --- a/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartyGetUserAPITest2_7.java +++ b/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartyGetUserAPITest2_7.java @@ -65,7 +65,7 @@ public void beforeEach() { @Test public void testBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -122,7 +122,7 @@ public void testBadInput() throws Exception { @Test public void testGoodInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -175,7 +175,7 @@ public void testGoodInput() throws Exception { @Test public void testAllTypesOfOutput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -222,7 +222,8 @@ public void testGetUserForUsersOfOtherRecipeIds() throws Exception { AuthRecipeUserInfo user1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "password"); Passwordless.CreateCodeResponse user2code = Passwordless.createCode(process.getProcess(), "test@example.com", null, null, null); - AuthRecipeUserInfo user2 = Passwordless.consumeCode(process.getProcess(), user2code.deviceId, user2code.deviceIdHash, user2code.userInputCode, null).user; + AuthRecipeUserInfo user2 = Passwordless.consumeCode(process.getProcess(), user2code.deviceId, + user2code.deviceIdHash, user2code.userInputCode, null).user; { HashMap map = new HashMap<>(); diff --git a/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest2_7.java b/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest2_7.java index dd4e0587f..f0dd90e90 100644 --- a/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest2_7.java +++ b/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest2_7.java @@ -63,7 +63,7 @@ public void beforeEach() { // failure condition: test fails if signinup response does not match api spec @Test public void testGoodInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -95,7 +95,7 @@ public void testGoodInput() throws Exception { // failure condition: test fails if signin causes a new user to be created @Test public void testEmailNormalisation() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -126,7 +126,7 @@ public void testEmailNormalisation() throws Exception { // simple bad input @Test public void testBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -167,7 +167,7 @@ public void testBadInput() throws Exception { } catch (io.supertokens.test.httpRequest.HttpResponseException e) { assertTrue(e.statusCode == 400 && e.getMessage().equals("Http error. Status Code: 400. Message: Field name 'thirdPartyId' is " - + "invalid " + "in " + "JSON input")); + + "invalid " + "in " + "JSON input")); } } { @@ -197,7 +197,7 @@ public void testBadInput() throws Exception { // email sub object's fields are missing @Test public void testBadInputInEmailSubObject() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -223,7 +223,7 @@ public void testBadInputInEmailSubObject() throws Exception { } catch (io.supertokens.test.httpRequest.HttpResponseException e) { assertTrue(e.statusCode == 400 && e.getMessage().equals("Http error. Status Code: 400. Message: Field name 'id' is " - + "invalid " + "in " + "JSON input")); + + "invalid " + "in " + "JSON input")); } } { @@ -238,7 +238,7 @@ public void testBadInputInEmailSubObject() throws Exception { } catch (io.supertokens.test.httpRequest.HttpResponseException e) { assertTrue(e.statusCode == 400 && e.getMessage().equals("Http error. Status Code: 400. Message: Field name 'isVerified' is " - + "invalid " + "in " + "JSON input")); + + "invalid " + "in " + "JSON input")); } } process.kill(); @@ -246,7 +246,7 @@ public void testBadInputInEmailSubObject() throws Exception { } public static void checkSignInUpResponse(JsonObject response, String thirdPartyId, String thirdPartyUserId, - String email, boolean createdNewUser) { + String email, boolean createdNewUser) { assertEquals("OK", response.get("status").getAsString()); assertEquals(3, response.entrySet().size()); assertEquals(createdNewUser, response.get("createdNewUser").getAsBoolean()); diff --git a/src/test/java/io/supertokens/test/totp/TOTPRecipeTest.java b/src/test/java/io/supertokens/test/totp/TOTPRecipeTest.java index 8177878ef..37a690957 100644 --- a/src/test/java/io/supertokens/test/totp/TOTPRecipeTest.java +++ b/src/test/java/io/supertokens/test/totp/TOTPRecipeTest.java @@ -351,9 +351,11 @@ public void rateLimitCooldownTest() throws Exception { InvalidTotpException invalidTotpException = assertThrows(InvalidTotpException.class, () -> Totp.verifyCode(main, "user", "invalid0")); assertEquals(1, invalidTotpException.currentAttempts); - invalidTotpException = assertThrows(InvalidTotpException.class, () -> Totp.verifyCode(main, "user", "invalid0")); + invalidTotpException = assertThrows(InvalidTotpException.class, + () -> Totp.verifyCode(main, "user", "invalid0")); assertEquals(2, invalidTotpException.currentAttempts); - invalidTotpException = assertThrows(InvalidTotpException.class, () -> Totp.verifyCode(main, "user", "invalid0")); + invalidTotpException = assertThrows(InvalidTotpException.class, + () -> Totp.verifyCode(main, "user", "invalid0")); assertEquals(3, invalidTotpException.currentAttempts); // This triggered rate limiting again. So even valid codes will fail for @@ -368,9 +370,11 @@ public void rateLimitCooldownTest() throws Exception { invalidTotpException = assertThrows(InvalidTotpException.class, () -> Totp.verifyCode(main, "user", "invalid0")); assertEquals(1, invalidTotpException.currentAttempts); - invalidTotpException = assertThrows(InvalidTotpException.class, () -> Totp.verifyCode(main, "user", "invalid0")); + invalidTotpException = assertThrows(InvalidTotpException.class, + () -> Totp.verifyCode(main, "user", "invalid0")); assertEquals(2, invalidTotpException.currentAttempts); - invalidTotpException = assertThrows(InvalidTotpException.class, () -> Totp.verifyCode(main, "user", "invalid0")); + invalidTotpException = assertThrows(InvalidTotpException.class, + () -> Totp.verifyCode(main, "user", "invalid0")); assertEquals(3, invalidTotpException.currentAttempts); Thread.sleep(1100); @@ -590,7 +594,8 @@ public void getDevicesTest() throws Exception { TOTPDevice[] devices = Totp.getDevices(main, "user"); assert (devices.length == 2); - assert (devices[0].equals(device1) && devices[1].equals(device2)) || (devices[1].equals(device1) && devices[0].equals(device2)); + assert (devices[0].equals(device1) && devices[1].equals(device2)) || + (devices[1].equals(device1) && devices[0].equals(device2)); } @Test diff --git a/src/test/java/io/supertokens/test/totp/TOTPStorageTest.java b/src/test/java/io/supertokens/test/totp/TOTPStorageTest.java index 8bb8f0936..5f590347a 100644 --- a/src/test/java/io/supertokens/test/totp/TOTPStorageTest.java +++ b/src/test/java/io/supertokens/test/totp/TOTPStorageTest.java @@ -125,7 +125,8 @@ public void createDeviceTests() throws Exception { TOTPDevice device1 = new TOTPDevice("user", "d1", "secret", 30, 1, false, System.currentTimeMillis()); TOTPDevice device2 = new TOTPDevice("user", "d2", "secret", 30, 1, true, System.currentTimeMillis()); - TOTPDevice device2Duplicate = new TOTPDevice("user", "d2", "new-secret", 30, 1, false, System.currentTimeMillis()); + TOTPDevice device2Duplicate = new TOTPDevice("user", "d2", "new-secret", 30, 1, false, + System.currentTimeMillis()); storage.createDevice(new AppIdentifier(null, null), device1); @@ -335,7 +336,8 @@ public void updateDeviceNameTests() throws Exception { // Try to create a new device and rename it to the same name as an existing // device: - TOTPDevice newDevice = new TOTPDevice("user", "new-device", "secretKey", 30, 1, false, System.currentTimeMillis()); + TOTPDevice newDevice = new TOTPDevice("user", "new-device", "secretKey", 30, 1, false, + System.currentTimeMillis()); storage.createDevice(new AppIdentifier(null, null), newDevice); assertThrows(DeviceAlreadyExistsException.class, @@ -413,7 +415,8 @@ public void insertUsedCodeTest() throws Exception { // Try to insert code after user has atleast one device (i.e. TOTP enabled) { - TOTPDevice newDevice = new TOTPDevice("user", "new-device", "secretKey", 30, 1, false, System.currentTimeMillis()); + TOTPDevice newDevice = new TOTPDevice("user", "new-device", "secretKey", 30, 1, false, + System.currentTimeMillis()); storage.createDevice(new AppIdentifier(null, null), newDevice); insertUsedCodesUtil( storage, diff --git a/src/test/java/io/supertokens/test/totp/TotpLicenseTest.java b/src/test/java/io/supertokens/test/totp/TotpLicenseTest.java index 9dfda6763..77b36c51c 100644 --- a/src/test/java/io/supertokens/test/totp/TotpLicenseTest.java +++ b/src/test/java/io/supertokens/test/totp/TotpLicenseTest.java @@ -42,7 +42,9 @@ import static org.junit.Assert.assertThrows; public class TotpLicenseTest { - public final static String OPAQUE_KEY_WITH_MFA_FEATURE = "Qk8olVa=v-9PU=snnUFMF4ihMCx4zVBOO6Jd7Nrg6Cg5YyFliEj252ADgpwEpDLfFowA0U5OyVo3XL=U4FMft2HDHCDGg9hWD4iwQQiyjMRi6Mu03CVbAxIkNGaXtJ53"; + public final static String OPAQUE_KEY_WITH_MFA_FEATURE = "Qk8olVa=v-9PU" + + "=snnUFMF4ihMCx4zVBOO6Jd7Nrg6Cg5YyFliEj252ADgpwEpDLfFowA0U5OyVo3XL" + + "=U4FMft2HDHCDGg9hWD4iwQQiyjMRi6Mu03CVbAxIkNGaXtJ53"; @Rule public TestRule watchman = Utils.getOnFailure(); diff --git a/src/test/java/io/supertokens/test/totp/api/CreateTotpDeviceAPITest.java b/src/test/java/io/supertokens/test/totp/api/CreateTotpDeviceAPITest.java index 99d6ecbdb..6ec6b482a 100644 --- a/src/test/java/io/supertokens/test/totp/api/CreateTotpDeviceAPITest.java +++ b/src/test/java/io/supertokens/test/totp/api/CreateTotpDeviceAPITest.java @@ -95,7 +95,7 @@ public void testApi() throws Exception { { Exception e = createDeviceRequest(process, body); checkFieldMissingErrorResponse(e, "userId"); - + body.addProperty("deviceName", ""); body.addProperty("userId", ""); @@ -158,7 +158,7 @@ public void testApi() throws Exception { // verify d1 { - TOTPDevice device = Totp.getDevices(process.getProcess(), "user-id" )[0]; + TOTPDevice device = Totp.getDevices(process.getProcess(), "user-id")[0]; String validTotp = TOTPRecipeTest.generateTotpCode(process.getProcess(), device); Totp.verifyDevice(process.getProcess(), "user-id", "d1", validTotp); } diff --git a/src/test/java/io/supertokens/test/totp/api/GetTotpDevicesAPITest.java b/src/test/java/io/supertokens/test/totp/api/GetTotpDevicesAPITest.java index e48ba2b29..f193a4445 100644 --- a/src/test/java/io/supertokens/test/totp/api/GetTotpDevicesAPITest.java +++ b/src/test/java/io/supertokens/test/totp/api/GetTotpDevicesAPITest.java @@ -39,7 +39,7 @@ public void beforeEach() { } private Exception getDevicesRequestException(TestingProcessManager.TestingProcess process, - HashMap params) { + HashMap params) { return assertThrows( io.supertokens.test.httpRequest.HttpResponseException.class, @@ -72,12 +72,13 @@ private void checkResponseErrorContains(Exception ex, String msg) { @Test public void testApi() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); - FeatureFlagTestContent.getInstance(process.main).setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.MFA }); + FeatureFlagTestContent.getInstance(process.main) + .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; diff --git a/src/test/java/io/supertokens/test/totp/api/ImportTotpDeviceAPITest.java b/src/test/java/io/supertokens/test/totp/api/ImportTotpDeviceAPITest.java index 8ac5a3c2d..a5d263d9a 100644 --- a/src/test/java/io/supertokens/test/totp/api/ImportTotpDeviceAPITest.java +++ b/src/test/java/io/supertokens/test/totp/api/ImportTotpDeviceAPITest.java @@ -97,7 +97,7 @@ public void testApi() throws Exception { { Exception e = importDeviceRequest(process, body); checkFieldMissingErrorResponse(e, "userId"); - + body.addProperty("deviceName", ""); body.addProperty("userId", ""); @@ -127,7 +127,7 @@ public void testApi() throws Exception { body.addProperty("deviceName", "d1"); e = importDeviceRequest(process, body); checkResponseErrorContains(e, "secretKey cannot be empty"); - + body.addProperty("secretKey", secret); e = importDeviceRequest(process, body); checkResponseErrorContains(e, "skew must be >= 0"); diff --git a/src/test/java/io/supertokens/test/totp/api/MultitenantAPITest.java b/src/test/java/io/supertokens/test/totp/api/MultitenantAPITest.java index d37b52e11..a5ac1b1f6 100644 --- a/src/test/java/io/supertokens/test/totp/api/MultitenantAPITest.java +++ b/src/test/java/io/supertokens/test/totp/api/MultitenantAPITest.java @@ -260,7 +260,7 @@ public void testCreateDeviceWorksFromAllTenants() throws Exception { TenantIdentifier[] tenants = new TenantIdentifier[]{t1, t2, t3}; for (TenantIdentifier tenantId : tenants) { - createDevice(tenantId, "user"+userCount); + createDevice(tenantId, "user" + userCount); userCount++; } @@ -306,7 +306,8 @@ public void testSameCodeUsedOnDifferentTenantsIsAllowed() throws Exception { JsonObject deviceResponse = createDevice(t1, userId); String secretKey = deviceResponse.get("secret").getAsString(); - TOTPDevice device = new TOTPDevice("user" + userCount, "d1", secretKey, 2, 1, true, System.currentTimeMillis()); + TOTPDevice device = new TOTPDevice("user" + userCount, "d1", secretKey, 2, 1, true, + System.currentTimeMillis()); String validTotp = TOTPRecipeTest.generateTotpCode(process.getProcess(), device); verifyDevice(tenant1, userId, validTotp); diff --git a/src/test/java/io/supertokens/test/totp/api/TotpUserIdMappingTest.java b/src/test/java/io/supertokens/test/totp/api/TotpUserIdMappingTest.java index cdb7d23ae..95afebb9d 100644 --- a/src/test/java/io/supertokens/test/totp/api/TotpUserIdMappingTest.java +++ b/src/test/java/io/supertokens/test/totp/api/TotpUserIdMappingTest.java @@ -39,7 +39,7 @@ public void beforeEach() { @Test public void testExternalUserIdTranslation() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -48,7 +48,8 @@ public void testExternalUserIdTranslation() throws Exception { return; } - FeatureFlagTestContent.getInstance(process.main).setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.MFA }); + FeatureFlagTestContent.getInstance(process.main) + .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); JsonObject body = new JsonObject(); diff --git a/src/test/java/io/supertokens/test/totp/api/UpdateTotpDeviceAPITest.java b/src/test/java/io/supertokens/test/totp/api/UpdateTotpDeviceAPITest.java index 27c5f9fea..3c6e0beb0 100644 --- a/src/test/java/io/supertokens/test/totp/api/UpdateTotpDeviceAPITest.java +++ b/src/test/java/io/supertokens/test/totp/api/UpdateTotpDeviceAPITest.java @@ -67,7 +67,7 @@ private void checkResponseErrorContains(Exception ex, String msg) { @Test public void testApi() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -76,7 +76,8 @@ public void testApi() throws Exception { return; } - FeatureFlagTestContent.getInstance(process.main).setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.MFA }); + FeatureFlagTestContent.getInstance(process.main) + .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); // Setup user and devices: JsonObject createDeviceReq = new JsonObject(); diff --git a/src/test/java/io/supertokens/test/totp/api/VerifyTotpAPITest.java b/src/test/java/io/supertokens/test/totp/api/VerifyTotpAPITest.java index 45a01596d..8c5fdcb22 100644 --- a/src/test/java/io/supertokens/test/totp/api/VerifyTotpAPITest.java +++ b/src/test/java/io/supertokens/test/totp/api/VerifyTotpAPITest.java @@ -90,7 +90,7 @@ private void checkResponseErrorContains(Exception ex, String msg) { @Test public void testApi() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; // Trigger rate limiting on 1 wrong attempts: Utils.setValueInConfig("totp_max_attempts", "2"); diff --git a/src/test/java/io/supertokens/test/totp/api/VerifyTotpDeviceAPITest.java b/src/test/java/io/supertokens/test/totp/api/VerifyTotpDeviceAPITest.java index 70a50bc97..067d847b4 100644 --- a/src/test/java/io/supertokens/test/totp/api/VerifyTotpDeviceAPITest.java +++ b/src/test/java/io/supertokens/test/totp/api/VerifyTotpDeviceAPITest.java @@ -87,7 +87,7 @@ private void checkResponseErrorContains(Exception ex, String msg) { @Test public void testApi() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; // Trigger rate limiting on 1 wrong attempts: Utils.setValueInConfig("totp_max_attempts", "1"); @@ -101,7 +101,8 @@ public void testApi() throws Exception { return; } - FeatureFlagTestContent.getInstance(process.main).setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.MFA }); + FeatureFlagTestContent.getInstance(process.main) + .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); // Setup user and devices: JsonObject createDeviceReq = new JsonObject(); @@ -123,7 +124,8 @@ public void testApi() throws Exception { assertEquals(createDeviceRes.get("status").getAsString(), "OK"); String secretKey = createDeviceRes.get("secret").getAsString(); - TOTPDevice device = new TOTPDevice("user-id", "deviceName", secretKey, 30, 0, false, System.currentTimeMillis()); + TOTPDevice device = new TOTPDevice("user-id", "deviceName", secretKey, 30, 0, false, + System.currentTimeMillis()); // Start the actual tests for update device API: diff --git a/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingStorageTest.java b/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingStorageTest.java index ca7e6ce1b..a02126822 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingStorageTest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingStorageTest.java @@ -106,7 +106,8 @@ public void testCreatingUserIdMapping() throws Exception { externalUserIdInfo); // check that the mapping exists - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), + UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + userInfo.getSupertokensUserId(), true); assertEquals(userInfo.getSupertokensUserId(), userIdMapping.superTokensUserId); assertEquals(externalUserId, userIdMapping.externalUserId); @@ -132,13 +133,15 @@ public void testDuplicateUserIdMapping() throws Exception { AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPassword"); String externalUserId = "external-test"; - storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), externalUserId, null); + storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), externalUserId, + null); { // duplicate exception with both supertokensUserId and externalUserId Exception error = null; try { - storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), externalUserId, null); + storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), + externalUserId, null); } catch (Exception e) { error = e; } @@ -155,7 +158,8 @@ public void testDuplicateUserIdMapping() throws Exception { // duplicate exception with superTokensUserId Exception error = null; try { - storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), "newExternalId", null); + storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), + "newExternalId", null); } catch (Exception e) { error = e; } @@ -175,7 +179,8 @@ public void testDuplicateUserIdMapping() throws Exception { AuthRecipeUserInfo newUser = EmailPassword.signUp(process.main, "test2@example.com", "testPass123"); Exception error = null; try { - storage.createUserIdMapping(new AppIdentifier(null, null), newUser.getSupertokensUserId(), externalUserId, null); + storage.createUserIdMapping(new AppIdentifier(null, null), newUser.getSupertokensUserId(), + externalUserId, null); } catch (Exception e) { error = e; } @@ -210,7 +215,8 @@ public void testCreatingAMappingWithAnUnknownStUserIdAndAPreexistingExternalUser String externalUserId = "externalUserId"; // create a userId mapping - storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), externalUserId, null); + storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), externalUserId, + null); // create a new mapping with unknown superTokensUserId and existing externalUserId Exception error = null; @@ -290,7 +296,8 @@ public void testRetrievingUserIdMapping() throws Exception { // check that the mapping exists with supertokensUserId { - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), + UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + userInfo.getSupertokensUserId(), true); assertNotNull(userIdMapping); @@ -336,7 +343,8 @@ public void testRetrievingUserIdMapping() throws Exception { AuthRecipeUserInfo newUserInfo = EmailPassword.signUp(process.main, "test2@example.com", "testPass123"); String externalUserId2 = userInfo.getSupertokensUserId(); - storage.createUserIdMapping(new AppIdentifier(null, null), newUserInfo.getSupertokensUserId(), externalUserId2, null); + storage.createUserIdMapping(new AppIdentifier(null, null), newUserInfo.getSupertokensUserId(), + externalUserId2, null); UserIdMapping[] userIdMappings = storage.getUserIdMapping(new AppIdentifier(null, null), externalUserId2); @@ -573,7 +581,8 @@ public void createUsersMapTheirIdsCheckRetrieveUseIdMappingsWithListOfUserIds() // create users equal to the User Pagination limit for (int i = 1; i <= AuthRecipe.USER_PAGINATION_LIMIT; i++) { - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test" + i + "@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test" + i + "@example.com", + "testPass123"); superTokensUserIdList.add(userInfo.getSupertokensUserId()); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalId" + i; @@ -629,7 +638,8 @@ public void testCallingGetUserIdMappingForSuperTokensIdsWhenNoMappingExists() th ArrayList superTokensUserIdList = new ArrayList<>(); for (int i = 1; i <= 10; i++) { - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test" + i + "@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test" + i + "@example.com", + "testPass123"); superTokensUserIdList.add(userInfo.getSupertokensUserId()); } @@ -657,7 +667,8 @@ public void create10UsersAndMap5UsersIds() throws Exception { // create users equal to the User Pagination limit for (int i = 1; i <= 10; i++) { - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test" + i + "@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test" + i + "@example.com", + "testPass123"); superTokensUserIdList.add(userInfo.getSupertokensUserId()); if (i <= 5) { @@ -666,7 +677,8 @@ public void create10UsersAndMap5UsersIds() throws Exception { // create userIdMapping for the last 5 users String externalUserId = "externalId" + i; userIdList.add(externalUserId); - storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), externalUserId, null); + storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), + externalUserId, null); } } diff --git a/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingTest.java b/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingTest.java index cfc9e6db2..014c1c6e9 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingTest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingTest.java @@ -113,7 +113,8 @@ public void testDuplicateUserIdMapping() throws Exception { // duplicate exception with both supertokensUserId and externalUserId Exception error = null; try { - UserIdMapping.createUserIdMapping(process.main, userInfo.getSupertokensUserId(), externalUserId, null, false); + UserIdMapping.createUserIdMapping(process.main, userInfo.getSupertokensUserId(), externalUserId, null, + false); } catch (Exception e) { error = e; } @@ -130,7 +131,8 @@ public void testDuplicateUserIdMapping() throws Exception { // duplicate exception with superTokensUserId Exception error = null; try { - UserIdMapping.createUserIdMapping(process.main, userInfo.getSupertokensUserId(), "newExternalId", null, false); + UserIdMapping.createUserIdMapping(process.main, userInfo.getSupertokensUserId(), "newExternalId", null, + false); } catch (Exception e) { error = e; } @@ -150,7 +152,8 @@ public void testDuplicateUserIdMapping() throws Exception { AuthRecipeUserInfo newUser = EmailPassword.signUp(process.main, "test2@example.com", "testPass123"); Exception error = null; try { - UserIdMapping.createUserIdMapping(process.main, newUser.getSupertokensUserId(), externalUserId, null, false); + UserIdMapping.createUserIdMapping(process.main, newUser.getSupertokensUserId(), externalUserId, null, + false); } catch (Exception e) { error = e; } @@ -187,7 +190,8 @@ public void testCreatingUserIdMapping() throws Exception { String externalUserIdInfo = "external-info"; // create a userId mapping - UserIdMapping.createUserIdMapping(process.getProcess(), userInfo.getSupertokensUserId(), externalUserId, externalUserIdInfo, false); + UserIdMapping.createUserIdMapping(process.getProcess(), userInfo.getSupertokensUserId(), externalUserId, + externalUserIdInfo, false); // check that the mapping exists io.supertokens.pluginInterface.useridmapping.UserIdMapping userIdMapping = storage.getUserIdMapping( @@ -791,7 +795,8 @@ public void checkThatCreateUserIdMappingHasAllNonAuthRecipeChecks() throws Excep return; } - FeatureFlagTestContent.getInstance(process.main).setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.MFA }); + FeatureFlagTestContent.getInstance(process.main) + .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); // this list contains the package names for recipes which dont use UserIdMapping ArrayList nonAuthRecipesWhichDontNeedUserIdMapping = new ArrayList<>( @@ -812,7 +817,8 @@ public void checkThatCreateUserIdMappingHasAllNonAuthRecipeChecks() throws Excep String userId = user.getSupertokensUserId(); // create entry in nonAuth table - StorageLayer.getStorage(process.main).addInfoToNonAuthRecipesBasedOnUserId(TenantIdentifier.BASE_TENANT, className, userId); + StorageLayer.getStorage(process.main) + .addInfoToNonAuthRecipesBasedOnUserId(TenantIdentifier.BASE_TENANT, className, userId); // try to create the mapping with superTokensId String errorMessage = null; try { @@ -851,7 +857,8 @@ public void checkThatAddInfoToNonAuthRecipesBasedOnUserIdThrowsAnErrorWithUnknow Exception error = null; try { - StorageLayer.getStorage(process.main).addInfoToNonAuthRecipesBasedOnUserId(TenantIdentifier.BASE_TENANT, "unknownRecipe", "testUserId"); + StorageLayer.getStorage(process.main) + .addInfoToNonAuthRecipesBasedOnUserId(TenantIdentifier.BASE_TENANT, "unknownRecipe", "testUserId"); } catch (IllegalStateException e) { error = e; } @@ -893,12 +900,14 @@ public void checkThatDeleteUserIdMappingHasAllNonAuthRecipeChecks() throws Excep UserIdMapping.createUserIdMapping(process.main, user.getSupertokensUserId(), externalId, null, false); // create entry in nonAuth table with externalId - StorageLayer.getStorage(process.main).addInfoToNonAuthRecipesBasedOnUserId(TenantIdentifier.BASE_TENANT, className, externalId); + StorageLayer.getStorage(process.main) + .addInfoToNonAuthRecipesBasedOnUserId(TenantIdentifier.BASE_TENANT, className, externalId); // try to delete UserIdMapping String errorMessage = null; try { - UserIdMapping.deleteUserIdMapping(process.main, user.getSupertokensUserId(), UserIdType.SUPERTOKENS, false); + UserIdMapping.deleteUserIdMapping(process.main, user.getSupertokensUserId(), UserIdType.SUPERTOKENS, + false); } catch (ServletException e) { errorMessage = e.getRootCause().getMessage(); } @@ -942,7 +951,8 @@ public void checkThatWeDontAllowDBStateA5FromBeingCreatedWhenForceIsFalse() thro // try and map user_2 to user_1s superTokensUserId String errorMessage = null; try { - UserIdMapping.createUserIdMapping(process.main, user_2.getSupertokensUserId(), user_1.getSupertokensUserId(), null, false); + UserIdMapping.createUserIdMapping(process.main, user_2.getSupertokensUserId(), + user_1.getSupertokensUserId(), null, false); } catch (ServletException e) { errorMessage = e.getRootCause().getMessage(); } @@ -970,12 +980,14 @@ public void testThatWeDontAllowDBStateA6WithoutForce() throws Exception { AuthRecipeUserInfo user_2 = EmailPassword.signUp(process.main, "test123@example.com", "testPass123"); // create a mapping between User_1 and User_2 with force - UserIdMapping.createUserIdMapping(process.main, user_1.getSupertokensUserId(), user_2.getSupertokensUserId(), null, true); + UserIdMapping.createUserIdMapping(process.main, user_1.getSupertokensUserId(), user_2.getSupertokensUserId(), + null, true); // try and create a mapping between User_2 and User_1 without force String errorMessage = null; try { - UserIdMapping.createUserIdMapping(process.main, user_2.getSupertokensUserId(), user_1.getSupertokensUserId(), null, false); + UserIdMapping.createUserIdMapping(process.main, user_2.getSupertokensUserId(), + user_1.getSupertokensUserId(), null, false); } catch (ServletException e) { errorMessage = e.getRootCause().getMessage(); } @@ -1006,7 +1018,8 @@ public void testDeleteMappingWithUser_1AndUserIdTypeAsAny() throws Exception { AuthRecipeUserInfo user_2 = EmailPassword.signUp(process.main, "test123@exmaple.com", "testPass123"); // create a mapping between User_2 and User_1 with force - UserIdMapping.createUserIdMapping(process.main, user_2.getSupertokensUserId(), user_1.getSupertokensUserId(), null, true); + UserIdMapping.createUserIdMapping(process.main, user_2.getSupertokensUserId(), user_1.getSupertokensUserId(), + null, true); // check that mapping exists { @@ -1018,7 +1031,8 @@ public void testDeleteMappingWithUser_1AndUserIdTypeAsAny() throws Exception { } // delete mapping with User_1s Id and UserIdType set to ANY, it should delete the mapping - assertTrue(UserIdMapping.deleteUserIdMapping(process.main, user_1.getSupertokensUserId(), UserIdType.ANY, false)); + assertTrue( + UserIdMapping.deleteUserIdMapping(process.main, user_1.getSupertokensUserId(), UserIdType.ANY, false)); // check that mapping is deleted { @@ -1050,7 +1064,8 @@ public void testDeleteMappingWithUser_1AndUserIdTypeAsSUPERTOKENS() throws Excep AuthRecipeUserInfo user_2 = EmailPassword.signUp(process.main, "test123@exmaple.com", "testPass123"); // create a mapping between User_2 and User_1 with force - UserIdMapping.createUserIdMapping(process.main, user_2.getSupertokensUserId(), user_1.getSupertokensUserId(), null, true); + UserIdMapping.createUserIdMapping(process.main, user_2.getSupertokensUserId(), user_1.getSupertokensUserId(), + null, true); // check that mapping exists { @@ -1062,7 +1077,9 @@ public void testDeleteMappingWithUser_1AndUserIdTypeAsSUPERTOKENS() throws Excep } // delete mapping with User_1s Id and UserIdType set to ANY, it should delete the mapping - assertTrue(UserIdMapping.deleteUserIdMapping(process.main, user_1.getSupertokensUserId(), UserIdType.SUPERTOKENS, false)); + assertTrue( + UserIdMapping.deleteUserIdMapping(process.main, user_1.getSupertokensUserId(), UserIdType.SUPERTOKENS, + false)); // check that mapping is deleted { diff --git a/src/test/java/io/supertokens/test/userIdMapping/api/CreateUserIdMappingAPITest.java b/src/test/java/io/supertokens/test/userIdMapping/api/CreateUserIdMappingAPITest.java index 8cc8d4e16..cc268b7f6 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/api/CreateUserIdMappingAPITest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/api/CreateUserIdMappingAPITest.java @@ -366,7 +366,8 @@ public void testCreatingUserIdMappingWithExternalUserIdInfoAsNull() throws Excep UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), + UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + userInfo.getSupertokensUserId(), true); assertNotNull(userIdMapping); diff --git a/src/test/java/io/supertokens/test/userIdMapping/api/GetUserIdMappingAPITest.java b/src/test/java/io/supertokens/test/userIdMapping/api/GetUserIdMappingAPITest.java index 4544013c8..8ec16e875 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/api/GetUserIdMappingAPITest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/api/GetUserIdMappingAPITest.java @@ -54,7 +54,7 @@ public void beforeEach() { @Test public void testBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -132,7 +132,7 @@ public void testBadInput() throws Exception { @Test public void testRetrievingUserIdMappingWithUnknownUserId() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -186,7 +186,7 @@ public void testRetrievingUserIdMappingWithUnknownUserId() throws Exception { @Test public void testRetrieveUserIdMapping() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -280,7 +280,7 @@ public void testRetrieveUserIdMapping() throws Exception { @Test public void testRetrievingUserIdMappingWithoutSendingUserIdType() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -335,7 +335,7 @@ public void testRetrievingUserIdMappingWithoutSendingUserIdType() throws Excepti @Test public void testRetrieveUserIdMappingWithExternalUserIdInfoAsNull() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/userIdMapping/api/MultitenantAPITest.java b/src/test/java/io/supertokens/test/userIdMapping/api/MultitenantAPITest.java index 118ecb737..0b57e6f3c 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/api/MultitenantAPITest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/api/MultitenantAPITest.java @@ -222,6 +222,7 @@ private JsonObject getUserIdMapping(TenantIdentifier tenantIdentifier, String us throws HttpResponseException, IOException { return getUserIdMapping(tenantIdentifier, userId, userIdType, SemVer.v3_0); } + private JsonObject getUserIdMapping(TenantIdentifier tenantIdentifier, String userId, String userIdType, SemVer version) throws HttpResponseException, IOException { @@ -230,7 +231,8 @@ private JsonObject getUserIdMapping(TenantIdentifier tenantIdentifier, String us QUERY_PARAM.put("userIdType", userIdType); JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", - HttpRequestForTesting.getMultitenantUrl(tenantIdentifier, "/recipe/userid/map"), QUERY_PARAM, 1000, 1000, null, + HttpRequestForTesting.getMultitenantUrl(tenantIdentifier, "/recipe/userid/map"), QUERY_PARAM, 1000, + 1000, null, version.get(), "useridmapping"); assertEquals("OK", response.get("status").getAsString()); return response; @@ -243,7 +245,8 @@ private void getUnknownUserIdMapping(TenantIdentifier tenantIdentifier, String u QUERY_PARAM.put("userIdType", userIdType); JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", - HttpRequestForTesting.getMultitenantUrl(tenantIdentifier, "/recipe/userid/map"), QUERY_PARAM, 1000, 1000, null, + HttpRequestForTesting.getMultitenantUrl(tenantIdentifier, "/recipe/userid/map"), QUERY_PARAM, 1000, + 1000, null, SemVer.v3_0.get(), "useridmapping"); assertEquals("UNKNOWN_MAPPING_ERROR", response.get("status").getAsString()); } @@ -278,7 +281,7 @@ public void testUserIdMappingWorksCorrectlyAcrossTenants() throws Exception { user3.addProperty("externalUserId", "euserid3"); - for (TenantIdentifier createTenant: new TenantIdentifier[]{t1}) { + for (TenantIdentifier createTenant : new TenantIdentifier[]{t1}) { successfulCreateUserIdMapping(createTenant, user1.get("id").getAsString(), "euserid1"); successfulCreateUserIdMapping(createTenant, user2.get("id").getAsString(), "euserid2"); successfulCreateUserIdMapping(createTenant, user3.get("id").getAsString(), "euserid3"); @@ -298,13 +301,15 @@ public void testUserIdMappingWorksCorrectlyAcrossTenants() throws Exception { mapping.get("externalUserId").getAsString()); } { - JsonObject mapping = getUserIdMapping(queryTenant, user.get("externalUserId").getAsString(), "EXTERNAL"); + JsonObject mapping = getUserIdMapping(queryTenant, user.get("externalUserId").getAsString(), + "EXTERNAL"); assertEquals(user.get("id").getAsString(), mapping.get("superTokensUserId").getAsString()); assertEquals(user.get("externalUserId").getAsString(), mapping.get("externalUserId").getAsString()); } { - JsonObject mapping = getUserIdMapping(queryTenant, user.get("externalUserId").getAsString(), "ANY"); + JsonObject mapping = getUserIdMapping(queryTenant, user.get("externalUserId").getAsString(), + "ANY"); assertEquals(user.get("id").getAsString(), mapping.get("superTokensUserId").getAsString()); assertEquals(user.get("externalUserId").getAsString(), mapping.get("externalUserId").getAsString()); @@ -395,10 +400,10 @@ public void testSameExternalIdAcrossUserPoolJustReturnsOneOfThem() throws Except JsonObject user1 = emailPasswordSignUp(t1, "user@example.com", "password1"); JsonObject user2 = emailPasswordSignUp(t2, "user@example.com", "password2"); - ((UserIdMappingStorage)StorageLayer.getStorage(t1, process.getProcess())).createUserIdMapping( + ((UserIdMappingStorage) StorageLayer.getStorage(t1, process.getProcess())).createUserIdMapping( t1.toAppIdentifier(), user1.get("id").getAsString(), "euserid", null); - ((UserIdMappingStorage)StorageLayer.getStorage(t2, process.getProcess())).createUserIdMapping( + ((UserIdMappingStorage) StorageLayer.getStorage(t2, process.getProcess())).createUserIdMapping( t2.toAppIdentifier(), user2.get("id").getAsString(), "euserid", null); { @@ -437,10 +442,10 @@ public void testSameExternalIdAcrossUserPoolJustReturnsOneOfThem_v5() throws Exc JsonObject user1 = emailPasswordSignUp(t1, "user@example.com", "password1"); JsonObject user2 = emailPasswordSignUp(t2, "user@example.com", "password2"); - ((UserIdMappingStorage)StorageLayer.getStorage(t1, process.getProcess())).createUserIdMapping( + ((UserIdMappingStorage) StorageLayer.getStorage(t1, process.getProcess())).createUserIdMapping( t1.toAppIdentifier(), user1.get("id").getAsString(), "euserid", null); - ((UserIdMappingStorage)StorageLayer.getStorage(t2, process.getProcess())).createUserIdMapping( + ((UserIdMappingStorage) StorageLayer.getStorage(t2, process.getProcess())).createUserIdMapping( t2.toAppIdentifier(), user2.get("id").getAsString(), "euserid", null); { @@ -497,7 +502,9 @@ public void testUserIdFromDifferentAppIsAllowedForUserIdMapping() throws Excepti fail(); } catch (HttpResponseException e) { assertEquals(400, e.statusCode); - assertEquals("Http error. Status Code: 400. Message: Cannot create a userId mapping where the externalId is also a SuperTokens userID", e.getMessage()); + assertEquals( + "Http error. Status Code: 400. Message: Cannot create a userId mapping where the externalId is also a SuperTokens userID", + e.getMessage()); } } } diff --git a/src/test/java/io/supertokens/test/userIdMapping/api/RemoveUserIdMappingAPITest.java b/src/test/java/io/supertokens/test/userIdMapping/api/RemoveUserIdMappingAPITest.java index 225ba319f..0d71306b4 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/api/RemoveUserIdMappingAPITest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/api/RemoveUserIdMappingAPITest.java @@ -55,7 +55,7 @@ public void beforeEach() { @Test public void testBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -163,7 +163,7 @@ public void testBadInput() throws Exception { @Test public void testDeletingUserIdMappingsWithUnknownUserIds() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -220,7 +220,7 @@ public void testDeletingUserIdMappingsWithUnknownUserIds() throws Exception { @Test public void testDeletingUserIdMapping() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -231,7 +231,8 @@ public void testDeletingUserIdMapping() throws Exception { // create a userId mapping AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); - UserIdMapping userIdMapping = new UserIdMapping(userInfo.getSupertokensUserId(), "externalUserId", "externalUserIdInfo"); + UserIdMapping userIdMapping = new UserIdMapping(userInfo.getSupertokensUserId(), "externalUserId", + "externalUserIdInfo"); createUserIdMappingAndCheckThatItExists(process.main, userIdMapping); // delete userId mapping with userIdType as SUPERTOKENS @@ -322,7 +323,7 @@ public void testDeletingUserIdMapping() throws Exception { @Test public void testDeletingAUserIdMappingWithoutSendingUserIdType() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -333,7 +334,8 @@ public void testDeletingAUserIdMappingWithoutSendingUserIdType() throws Exceptio // create a userId mapping AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); - UserIdMapping userIdMapping = new UserIdMapping(userInfo.getSupertokensUserId(), "externalUserId", "externalUserIdInfo"); + UserIdMapping userIdMapping = new UserIdMapping(userInfo.getSupertokensUserId(), "externalUserId", + "externalUserIdInfo"); createUserIdMappingAndCheckThatItExists(process.main, userIdMapping); { @@ -380,7 +382,7 @@ public void testDeletingAUserIdMappingWithoutSendingUserIdType() throws Exceptio @Test public void deleteUserIdMappingWithAndWithoutForce() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/userIdMapping/api/UpdateExternalUserIdInfoTest.java b/src/test/java/io/supertokens/test/userIdMapping/api/UpdateExternalUserIdInfoTest.java index fe3f930cd..eff927912 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/api/UpdateExternalUserIdInfoTest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/api/UpdateExternalUserIdInfoTest.java @@ -53,7 +53,7 @@ public void beforeEach() { @Test public void testBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -188,7 +188,7 @@ public void testBadInput() throws Exception { @Test public void testUpdatingExternalUserIdInfoWithUnknownUserId() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -258,7 +258,7 @@ public void testUpdatingExternalUserIdInfoWithUnknownUserId() throws Exception { @Test public void testUpdatingExternalUserIdInfoWithSuperTokensUserId() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -270,7 +270,8 @@ public void testUpdatingExternalUserIdInfoWithSuperTokensUserId() throws Excepti // create userId mapping with externalUserIdInfo String externalUserIdInfo = "externalUserIdInfo"; AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); - UserIdMapping userIdMapping = new io.supertokens.pluginInterface.useridmapping.UserIdMapping(userInfo.getSupertokensUserId(), + UserIdMapping userIdMapping = new io.supertokens.pluginInterface.useridmapping.UserIdMapping( + userInfo.getSupertokensUserId(), "externalUserIdInfo", externalUserIdInfo); Utils.createUserIdMappingAndCheckThatItExists(process.main, userIdMapping); @@ -329,7 +330,7 @@ public void testUpdatingExternalUserIdInfoWithSuperTokensUserId() throws Excepti @Test public void testUpdatingExternalUserIdInfoWithExternalUserId() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -341,7 +342,8 @@ public void testUpdatingExternalUserIdInfoWithExternalUserId() throws Exception // create userId mapping with externalUserIdInfo String externalUserIdInfo = "externalUserIdInfo"; AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); - UserIdMapping userIdMapping = new io.supertokens.pluginInterface.useridmapping.UserIdMapping(userInfo.getSupertokensUserId(), + UserIdMapping userIdMapping = new io.supertokens.pluginInterface.useridmapping.UserIdMapping( + userInfo.getSupertokensUserId(), "externalUserIdInfo", externalUserIdInfo); Utils.createUserIdMappingAndCheckThatItExists(process.main, userIdMapping); @@ -400,7 +402,7 @@ public void testUpdatingExternalUserIdInfoWithExternalUserId() throws Exception @Test public void testDeletingExternalUserIdInfo() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -412,7 +414,8 @@ public void testDeletingExternalUserIdInfo() throws Exception { // create userId mapping with externalUserIdInfo String externalUserIdInfo = "externalUserIdInfo"; AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); - UserIdMapping userIdMapping = new io.supertokens.pluginInterface.useridmapping.UserIdMapping(userInfo.getSupertokensUserId(), + UserIdMapping userIdMapping = new io.supertokens.pluginInterface.useridmapping.UserIdMapping( + userInfo.getSupertokensUserId(), "externalUserIdInfo", externalUserIdInfo); Utils.createUserIdMappingAndCheckThatItExists(process.main, userIdMapping); diff --git a/src/test/java/io/supertokens/test/userIdMapping/recipe/ThirdPartyAPITest.java b/src/test/java/io/supertokens/test/userIdMapping/recipe/ThirdPartyAPITest.java index 0f3d7d5c6..e566c10b6 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/recipe/ThirdPartyAPITest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/recipe/ThirdPartyAPITest.java @@ -55,7 +55,7 @@ public void beforeEach() { @Test public void testSignInAPI() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -115,7 +115,7 @@ public void testSignInAPI() throws Exception { @Test public void testGetUsersByEmailAPI() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -157,7 +157,7 @@ public void testGetUsersByEmailAPI() throws Exception { @Test public void testGetUserById() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -198,7 +198,7 @@ public void testGetUserById() throws Exception { @Test public void testGetUserByThirdPartyId() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/userMetadata/UserMetadataTest.java b/src/test/java/io/supertokens/test/userMetadata/UserMetadataTest.java index 6035590b2..b19cec6eb 100644 --- a/src/test/java/io/supertokens/test/userMetadata/UserMetadataTest.java +++ b/src/test/java/io/supertokens/test/userMetadata/UserMetadataTest.java @@ -281,7 +281,7 @@ public void testUserMetadataEmptyRowLocking() throws Exception { try { sqlStorage.setUserMetadata_Transaction(new AppIdentifier(null, null), con, userId, - updatedMetadata); + updatedMetadata); } catch (TenantOrAppNotFoundException e) { throw new StorageTransactionLogicException(e); } diff --git a/src/test/java/io/supertokens/test/userMetadata/api/GetUserMetadataAPITest2_13.java b/src/test/java/io/supertokens/test/userMetadata/api/GetUserMetadataAPITest2_13.java index fea9cac5a..1166e95ab 100644 --- a/src/test/java/io/supertokens/test/userMetadata/api/GetUserMetadataAPITest2_13.java +++ b/src/test/java/io/supertokens/test/userMetadata/api/GetUserMetadataAPITest2_13.java @@ -54,7 +54,7 @@ public void beforeEach() { @Test public void notExistingTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -83,7 +83,7 @@ public void notExistingTest() throws Exception { @Test public void existingMetadataTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -123,7 +123,7 @@ public void existingMetadataTest() throws Exception { @Test public void deletedMetadataTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -164,7 +164,7 @@ public void deletedMetadataTest() throws Exception { @Test public void noIdTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/userMetadata/api/RemoveUserMetadataAPITest2_13.java b/src/test/java/io/supertokens/test/userMetadata/api/RemoveUserMetadataAPITest2_13.java index 73135e299..f8a041f44 100644 --- a/src/test/java/io/supertokens/test/userMetadata/api/RemoveUserMetadataAPITest2_13.java +++ b/src/test/java/io/supertokens/test/userMetadata/api/RemoveUserMetadataAPITest2_13.java @@ -52,7 +52,7 @@ public void beforeEach() { @Test public void notExistingTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -82,7 +82,7 @@ public void notExistingTest() throws Exception { @Test public void existingMetadataTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -123,7 +123,7 @@ public void existingMetadataTest() throws Exception { @Test public void deletedMetadataTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -168,7 +168,7 @@ public void deletedMetadataTest() throws Exception { @Test public void noIdTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/userMetadata/api/SetUserMetadataAPITest2_13.java b/src/test/java/io/supertokens/test/userMetadata/api/SetUserMetadataAPITest2_13.java index 7d38504ae..5254ee87e 100644 --- a/src/test/java/io/supertokens/test/userMetadata/api/SetUserMetadataAPITest2_13.java +++ b/src/test/java/io/supertokens/test/userMetadata/api/SetUserMetadataAPITest2_13.java @@ -54,7 +54,7 @@ public void beforeEach() { @Test public void createMetadataTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -96,7 +96,7 @@ public void createMetadataTest() throws Exception { @Test public void updateMetadataTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -159,7 +159,7 @@ public void updateMetadataTest() throws Exception { @Test public void emptyRequestTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -190,7 +190,7 @@ public void emptyRequestTest() throws Exception { @Test public void noIdTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -226,7 +226,7 @@ public void noIdTest() throws Exception { @Test public void noMetadataTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/userRoles/UserRolesStorageTest.java b/src/test/java/io/supertokens/test/userRoles/UserRolesStorageTest.java index 5c8437e0b..ff35f5060 100644 --- a/src/test/java/io/supertokens/test/userRoles/UserRolesStorageTest.java +++ b/src/test/java/io/supertokens/test/userRoles/UserRolesStorageTest.java @@ -226,7 +226,8 @@ public void testCreatingAndAddingAPermissionToARoleInTransactionAndDeletingRole( } // delete the newly created role try { - boolean wasRoleDeleted = storage.deleteAllUserRoleAssociationsForRole(new AppIdentifier(null, null), role); + boolean wasRoleDeleted = storage.deleteAllUserRoleAssociationsForRole(new AppIdentifier(null, null), + role); wasRoleDeleted = storage.deleteRole(new AppIdentifier(null, null), role) || wasRoleDeleted; r2_success.set(true); } catch (StorageQueryException e) { @@ -474,7 +475,7 @@ public void testAssociatingAnUnknownRoleWithUser() throws Exception { try { UserRoles.addRoleToUser( process.getProcess(), new TenantIdentifier(null, null, null), - StorageLayer.getBaseStorage(process.getProcess()), "userId", "unknownRole"); + StorageLayer.getBaseStorage(process.getProcess()), "userId", "unknownRole"); } catch (Exception e) { error = e; } diff --git a/src/test/java/io/supertokens/test/userRoles/UserRolesTest.java b/src/test/java/io/supertokens/test/userRoles/UserRolesTest.java index 726001688..d5b8df41f 100644 --- a/src/test/java/io/supertokens/test/userRoles/UserRolesTest.java +++ b/src/test/java/io/supertokens/test/userRoles/UserRolesTest.java @@ -1026,7 +1026,8 @@ public void createAnAuthUserAssignRolesAndDeleteUser() throws Exception { assertEquals(0, retrievedRoles.length); // check that the mapping for user role doesnt exist - String[] roleUserMapping = storage.getRolesForUser(new TenantIdentifier(null, null, null), userInfo.getSupertokensUserId()); + String[] roleUserMapping = storage.getRolesForUser(new TenantIdentifier(null, null, null), + userInfo.getSupertokensUserId()); assertEquals(0, roleUserMapping.length); } diff --git a/src/test/java/io/supertokens/test/userRoles/api/GetPermissionsForRoleAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/GetPermissionsForRoleAPITest.java index ae7a49eec..341e0c7b7 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/GetPermissionsForRoleAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/GetPermissionsForRoleAPITest.java @@ -53,7 +53,7 @@ public void beforeEach() { @Test public void badInputTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -112,7 +112,7 @@ public void badInputTest() throws Exception { @Test public void testRetrievingThePermissionsForARole() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -123,7 +123,7 @@ public void testRetrievingThePermissionsForARole() throws Exception { // create a role with permissions String role = "role"; - String[] permissions = new String[] { "permission1", "permission2", "permission3" }; + String[] permissions = new String[]{"permission1", "permission2", "permission3"}; UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); HashMap QUERY_PARAM = new HashMap<>(); @@ -148,7 +148,7 @@ public void testRetrievingThePermissionsForARole() throws Exception { @Test public void testRetrievingThePermissionsForAnUnknownRole() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/userRoles/api/GetRolesAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/GetRolesAPITest.java index dbbb9f59c..3d94b6fea 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/GetRolesAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/GetRolesAPITest.java @@ -50,7 +50,7 @@ public void beforeEach() { @Test public void testGettingRoles() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -60,7 +60,7 @@ public void testGettingRoles() throws Exception { } // create multiple roles - String[] roles = new String[] { "role1", "role2", "role3" }; + String[] roles = new String[]{"role1", "role2", "role3"}; for (String role : roles) { UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); } diff --git a/src/test/java/io/supertokens/test/userRoles/api/GetRolesForPermissionAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/GetRolesForPermissionAPITest.java index 90f0c3ca8..b1cf21624 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/GetRolesForPermissionAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/GetRolesForPermissionAPITest.java @@ -54,7 +54,7 @@ public void beforeEach() { @Test public void badInputTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -112,7 +112,7 @@ public void badInputTest() throws Exception { @Test public void testRetrievingRolesForAPermission() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -122,15 +122,15 @@ public void testRetrievingRolesForAPermission() throws Exception { } // create two roles, assign [permission1] to role1 and [permission1, permission2] to role2 - String[] roles = new String[] { "role1", "role2" }; + String[] roles = new String[]{"role1", "role2"}; String permission1 = "permission1"; String permission2 = "permission2"; // create role1 with permission [permission1] - UserRoles.createNewRoleOrModifyItsPermissions(process.main, roles[0], new String[] { permission1 }); + UserRoles.createNewRoleOrModifyItsPermissions(process.main, roles[0], new String[]{permission1}); // create role2 with permissions [permission1, permission2] UserRoles.createNewRoleOrModifyItsPermissions(process.main, roles[1], - new String[] { permission1, permission2 }); + new String[]{permission1, permission2}); { // retrieve roles for permission1 diff --git a/src/test/java/io/supertokens/test/userRoles/api/GetUserRolesAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/GetUserRolesAPITest.java index 5602010f1..73d9cf17f 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/GetUserRolesAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/GetUserRolesAPITest.java @@ -56,7 +56,7 @@ public void beforeEach() { @Test public void badInputTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -100,7 +100,7 @@ public void badInputTest() throws Exception { @Test public void testGettingRolesForAUser() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -111,7 +111,7 @@ public void testGettingRolesForAUser() throws Exception { // create and add multiple roles to a user, get roles for user { - String[] roles = new String[] { "role1", "role2", "role3" }; + String[] roles = new String[]{"role1", "role2", "role3"}; String userId = "userId"; for (String role : roles) { diff --git a/src/test/java/io/supertokens/test/userRoles/api/GetUsersForRoleAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/GetUsersForRoleAPITest.java index b81fc8ac7..cd5837c99 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/GetUsersForRoleAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/GetUsersForRoleAPITest.java @@ -54,7 +54,7 @@ public void beforeEach() { @Test public void badInputTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -97,7 +97,7 @@ public void badInputTest() throws Exception { @Test public void testRetrievingUsersWhoHaveRole() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -110,7 +110,7 @@ public void testRetrievingUsersWhoHaveRole() throws Exception { UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); // add role to users - String[] userIds = new String[] { "user1", "user2", "user3" }; + String[] userIds = new String[]{"user1", "user2", "user3"}; for (String userId : userIds) { UserRoles.addRoleToUser(process.main, userId, role); } @@ -134,7 +134,7 @@ public void testRetrievingUsersWhoHaveRole() throws Exception { @Test public void testRetrievingUsersWithUnknownRole() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/userRoles/api/RemovePermissionsForRoleAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/RemovePermissionsForRoleAPITest.java index a3bc00ecd..816b9a841 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/RemovePermissionsForRoleAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/RemovePermissionsForRoleAPITest.java @@ -55,7 +55,7 @@ public void beforeEach() { @Test public void testBadInput() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -79,7 +79,7 @@ public void testBadInput() throws Exception { { // role is missing - String[] permissions = new String[] { "testPermission" }; + String[] permissions = new String[]{"testPermission"}; String permissionsString = "{ permissions : " + Arrays.toString(permissions) + " }"; JsonObject request = new JsonParser().parse(permissionsString).getAsJsonObject(); @@ -97,7 +97,7 @@ public void testBadInput() throws Exception { { // role is a number - String[] permissions = new String[] { "testPermission" }; + String[] permissions = new String[]{"testPermission"}; String permissionsString = "{ permissions : " + Arrays.toString(permissions) + " }"; JsonObject request = new JsonParser().parse(permissionsString).getAsJsonObject(); request.addProperty("role", 1); @@ -165,7 +165,7 @@ public void testBadInput() throws Exception { @Test public void deletePermissionsFromRoleTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -175,13 +175,13 @@ public void deletePermissionsFromRoleTest() throws Exception { } // create a role with permissions - String[] permissions = new String[] { "permission1", "permission2", "permission3" }; + String[] permissions = new String[]{"permission1", "permission2", "permission3"}; String role = "role"; UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); // call api to remove some permissions - String[] permissionsToRemove = new String[] { "permission1", "permission2" }; + String[] permissionsToRemove = new String[]{"permission1", "permission2"}; String permissionsString = "{ permissions : " + Arrays.toString(permissionsToRemove) + " }"; JsonObject requestBody = new JsonParser().parse(permissionsString).getAsJsonObject(); @@ -205,7 +205,7 @@ public void deletePermissionsFromRoleTest() throws Exception { @Test public void deleteAllPermissionsFromRoleTest() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -215,7 +215,7 @@ public void deleteAllPermissionsFromRoleTest() throws Exception { } // create a role with permissions - String[] permissions = new String[] { "permission1", "permission2", "permission3" }; + String[] permissions = new String[]{"permission1", "permission2", "permission3"}; String role = "role"; UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); @@ -242,7 +242,7 @@ public void deleteAllPermissionsFromRoleTest() throws Exception { @Test public void deletePermissionsFromAnUnknownRole() throws Exception { - String[] args = { "../" }; + String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -252,7 +252,7 @@ public void deletePermissionsFromAnUnknownRole() throws Exception { } // call api to remove some permissions from an unknownRole - String[] permissionsToRemove = new String[] { "testPermission" }; + String[] permissionsToRemove = new String[]{"testPermission"}; String permissionsString = "{ permissions : " + Arrays.toString(permissionsToRemove) + " }"; JsonObject requestBody = new JsonParser().parse(permissionsString).getAsJsonObject(); diff --git a/test-data/README.md b/test-data/README.md index 79bc71d6d..bfe1949ff 100644 --- a/test-data/README.md +++ b/test-data/README.md @@ -3,8 +3,8 @@ This folder contains test cases for the test: `io.supertokens.test.multitenant.api.TestTenantCreationBehaviour. testCrossVersionCreateAndUpdateCases`. -The create / update tenant APIs have different inputs between CDI version 3.0-4.0, 5.0 and v2 API has been introduced -in 5.1. We created a playground to test how the input / output fares cross versions. Code for that is included in +The create / update tenant APIs have different inputs between CDI version 3.0-4.0, 5.0 and v2 API has been introduced +in 5.1. We created a playground to test how the input / output fares cross versions. Code for that is included in this folder. All the json files here constitute all possible test cases for the test mentioned above. diff --git a/test-data/playground/README.md b/test-data/playground/README.md index 58beeaccd..67370d10f 100644 --- a/test-data/playground/README.md +++ b/test-data/playground/README.md @@ -17,7 +17,8 @@ You may also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ -See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. +See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more +information. ### `npm run build` @@ -33,38 +34,50 @@ See the section about [deployment](https://facebook.github.io/create-react-app/d **Note: this is a one-way operation. Once you `eject`, you can't go back!** -If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. +If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will +remove the single build dependency from your project. -Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. +Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right +into your project so you have full control over them. All of the commands except `eject` will still work, but they will +point to the copied scripts so you can tweak them. At this point you're on your own. -You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. +You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you +shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't +customize it when you are ready for it. ## Learn More -You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). +You can learn more in +the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting -This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) +This section has moved +here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size -This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) +This section has moved +here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App -This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) +This section has moved +here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration -This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) +This section has moved +here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment -This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) +This section has moved +here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `npm run build` fails to minify -This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) +This section has moved +here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) diff --git a/test-data/playground/components/Tenant.jsx b/test-data/playground/components/Tenant.jsx index 28bb80782..3b654229e 100644 --- a/test-data/playground/components/Tenant.jsx +++ b/test-data/playground/components/Tenant.jsx @@ -1,315 +1,338 @@ -import React from 'react'; -import { useState } from "react"; +import React, {useState} from 'react'; import './index.css'; export default function App(props) { - const [tenantState, setTenantState] = useState({ - emailPasswordEnabled: null, - passwordlessEnabled: null, - thirdPartyEnabled: null, - firstFactors: null, - requiredSecondaryFactors: null, - }); + const [tenantState, setTenantState] = useState({ + emailPasswordEnabled: null, + passwordlessEnabled: null, + thirdPartyEnabled: null, + firstFactors: null, + requiredSecondaryFactors: null, + }); - const [errorMsg, setErrorMsg] = useState(""); + const [errorMsg, setErrorMsg] = useState(""); - const [cdi4body, setCdi4Body] = useState('{\n "tenantId": "public"\n}') - const [cdi5body, setCdi5Body] = useState('{\n "tenantId": "public"\n}') - const [v2body, setV2Body] = useState('{\n "tenantId": "public"\n}') + const [cdi4body, setCdi4Body] = useState('{\n "tenantId": "public"\n}') + const [cdi5body, setCdi5Body] = useState('{\n "tenantId": "public"\n}') + const [v2body, setV2Body] = useState('{\n "tenantId": "public"\n}') - const create_4 = (body) => { - let {tenantId} = body; - let newTenantState; - if (tenantId === "public") { - newTenantState = { - emailPasswordEnabled: true, - passwordlessEnabled: true, - thirdPartyEnabled: true, - firstFactors: null, - requiredSecondaryFactors: null, - } - } else { - newTenantState = { - emailPasswordEnabled: false, - passwordlessEnabled: false, - thirdPartyEnabled: false, - firstFactors: [], - requiredSecondaryFactors: null, - } - } + const create_4 = (body) => { + let {tenantId} = body; + let newTenantState; + if (tenantId === "public") { + newTenantState = { + emailPasswordEnabled: true, + passwordlessEnabled: true, + thirdPartyEnabled: true, + firstFactors: null, + requiredSecondaryFactors: null, + } + } else { + newTenantState = { + emailPasswordEnabled: false, + passwordlessEnabled: false, + thirdPartyEnabled: false, + firstFactors: [], + requiredSecondaryFactors: null, + } + } - if (body.emailPasswordEnabled !== undefined) { - newTenantState.emailPasswordEnabled = body.emailPasswordEnabled; - } - if (body.passwordlessEnabled !== undefined) { - newTenantState.passwordlessEnabled = body.passwordlessEnabled; - } - if (body.thirdPartyEnabled !== undefined) { - newTenantState.thirdPartyEnabled = body.thirdPartyEnabled; - } + if (body.emailPasswordEnabled !== undefined) { + newTenantState.emailPasswordEnabled = body.emailPasswordEnabled; + } + if (body.passwordlessEnabled !== undefined) { + newTenantState.passwordlessEnabled = body.passwordlessEnabled; + } + if (body.thirdPartyEnabled !== undefined) { + newTenantState.thirdPartyEnabled = body.thirdPartyEnabled; + } - if (newTenantState.emailPasswordEnabled === true && newTenantState.passwordlessEnabled === true && newTenantState.thirdPartyEnabled === true) { - newTenantState.firstFactors = null; - } else { - newTenantState.firstFactors = []; - if (newTenantState.emailPasswordEnabled === true) { - newTenantState.firstFactors.push("emailpassword"); - } - if (newTenantState.passwordlessEnabled === true) { - newTenantState.firstFactors.push("otp-phone"); - newTenantState.firstFactors.push("otp-email"); - newTenantState.firstFactors.push("link-phone"); - newTenantState.firstFactors.push("link-email"); - } - if (newTenantState.thirdPartyEnabled === true) { - newTenantState.firstFactors.push("thirdparty"); - } + if (newTenantState.emailPasswordEnabled === true && newTenantState.passwordlessEnabled === true && newTenantState.thirdPartyEnabled === true) { + newTenantState.firstFactors = null; + } else { + newTenantState.firstFactors = []; + if (newTenantState.emailPasswordEnabled === true) { + newTenantState.firstFactors.push("emailpassword"); + } + if (newTenantState.passwordlessEnabled === true) { + newTenantState.firstFactors.push("otp-phone"); + newTenantState.firstFactors.push("otp-email"); + newTenantState.firstFactors.push("link-phone"); + newTenantState.firstFactors.push("link-email"); + } + if (newTenantState.thirdPartyEnabled === true) { + newTenantState.firstFactors.push("thirdparty"); + } + } + + setTenantState(newTenantState) } - setTenantState(newTenantState) - } + const update_4 = (body) => { + let newTenantState = {...tenantState} - const update_4 = (body) => { - let newTenantState = {...tenantState} + let firstFactors = ["emailpassword", "otp-phone", "otp-email", "link-phone", "link-email", "thirdparty"]; - let firstFactors = ["emailpassword", "otp-phone", "otp-email", "link-phone", "link-email", "thirdparty"]; + if (body.emailPasswordEnabled === true) { + newTenantState.emailPasswordEnabled = true; + if (newTenantState.firstFactors !== null) { + if (!newTenantState.firstFactors.includes("emailpassword")) { + newTenantState.firstFactors.push("emailpassword"); + } + } + } + if (body.passwordlessEnabled === true) { + newTenantState.passwordlessEnabled = true; + if (newTenantState.firstFactors !== null) { + if (!newTenantState.firstFactors.includes("otp-phone") && !newTenantState.firstFactors.includes("otp-email") && !newTenantState.firstFactors.includes("link-phone") && !newTenantState.firstFactors.includes("link-email")) { + newTenantState.firstFactors.push("otp-phone"); + newTenantState.firstFactors.push("otp-email"); + newTenantState.firstFactors.push("link-phone"); + newTenantState.firstFactors.push("link-email"); + } + } + } + if (body.thirdPartyEnabled === true) { + newTenantState.thirdPartyEnabled = true; + } - if (body.emailPasswordEnabled === true) { - newTenantState.emailPasswordEnabled = true; - if (newTenantState.firstFactors !== null) { - if (!newTenantState.firstFactors.includes("emailpassword")) { - newTenantState.firstFactors.push("emailpassword"); + if (body.emailPasswordEnabled === false || newTenantState.emailPasswordEnabled === false) { + firstFactors = firstFactors.filter(factor => factor !== "emailpassword"); } - } - } - if (body.passwordlessEnabled === true) { - newTenantState.passwordlessEnabled = true; - if (newTenantState.firstFactors !== null) { - if (!newTenantState.firstFactors.includes("otp-phone") && !newTenantState.firstFactors.includes("otp-email") && !newTenantState.firstFactors.includes("link-phone") && !newTenantState.firstFactors.includes("link-email")) { - newTenantState.firstFactors.push("otp-phone"); - newTenantState.firstFactors.push("otp-email"); - newTenantState.firstFactors.push("link-phone"); - newTenantState.firstFactors.push("link-email"); + if (body.passwordlessEnabled === false || newTenantState.passwordlessEnabled === false) { + firstFactors = firstFactors.filter(factor => factor !== "otp-phone" && factor !== "otp-email" && factor !== "link-phone" && factor !== "link-email"); + } + if (body.thirdPartyEnabled === false || newTenantState.thirdPartyEnabled === false) { + firstFactors = firstFactors.filter(factor => factor !== "thirdparty"); } - } - } - if (body.thirdPartyEnabled === true) { - newTenantState.thirdPartyEnabled = true; - } - if (body.emailPasswordEnabled === false || newTenantState.emailPasswordEnabled === false) { - firstFactors = firstFactors.filter(factor => factor !== "emailpassword"); - } - if (body.passwordlessEnabled === false || newTenantState.passwordlessEnabled === false) { - firstFactors = firstFactors.filter(factor => factor !== "otp-phone" && factor !== "otp-email" && factor !== "link-phone" && factor !== "link-email"); - } - if (body.thirdPartyEnabled === false || newTenantState.thirdPartyEnabled === false) { - firstFactors = firstFactors.filter(factor => factor !== "thirdparty"); - } + if (newTenantState.firstFactors === null) { + if (newTenantState.emailPasswordEnabled === false || newTenantState.passwordlessEnabled === false || newTenantState.thirdPartyEnabled === false) { + newTenantState.firstFactors = firstFactors; + } else { + newTenantState.firstFactors = null; + } + } else { + if (newTenantState.emailPasswordEnabled === false || newTenantState.passwordlessEnabled === false || newTenantState.thirdPartyEnabled === false) { + newTenantState.firstFactors = firstFactors.filter(factor => newTenantState.firstFactors.includes(factor)); + } else { + newTenantState.firstFactors = null; + } + } - if (newTenantState.firstFactors === null) { - if (newTenantState.emailPasswordEnabled === false || newTenantState.passwordlessEnabled === false || newTenantState.thirdPartyEnabled === false) { - newTenantState.firstFactors = firstFactors; - } else { - newTenantState.firstFactors = null; - } - } else { - if (newTenantState.emailPasswordEnabled === false || newTenantState.passwordlessEnabled === false || newTenantState.thirdPartyEnabled === false) { - newTenantState.firstFactors = firstFactors.filter(factor => newTenantState.firstFactors.includes(factor)); - } else { - newTenantState.firstFactors = null; - } + setTenantState(newTenantState) } - - setTenantState(newTenantState) - } - const create_5 = (body) => { - let newTenantState; - let {tenantId} = body; + const create_5 = (body) => { + let newTenantState; + let {tenantId} = body; - if (tenantId === "public") { - newTenantState = { - emailPasswordEnabled: true, - passwordlessEnabled: true, - thirdPartyEnabled: true, - firstFactors: null, - requiredSecondaryFactors: null, - } - } else { - newTenantState = { - emailPasswordEnabled: false, - passwordlessEnabled: false, - thirdPartyEnabled: false, - firstFactors: null, - requiredSecondaryFactors: null, - } - } + if (tenantId === "public") { + newTenantState = { + emailPasswordEnabled: true, + passwordlessEnabled: true, + thirdPartyEnabled: true, + firstFactors: null, + requiredSecondaryFactors: null, + } + } else { + newTenantState = { + emailPasswordEnabled: false, + passwordlessEnabled: false, + thirdPartyEnabled: false, + firstFactors: null, + requiredSecondaryFactors: null, + } + } - if (body.emailPasswordEnabled !== undefined) { - newTenantState.emailPasswordEnabled = body.emailPasswordEnabled; - } - if (body.passwordlessEnabled !== undefined) { - newTenantState.passwordlessEnabled = body.passwordlessEnabled; - } - if (body.thirdPartyEnabled !== undefined) { - newTenantState.thirdPartyEnabled = body.thirdPartyEnabled; - } - if (body.firstFactors !== undefined) { - newTenantState.firstFactors = body.firstFactors; + if (body.emailPasswordEnabled !== undefined) { + newTenantState.emailPasswordEnabled = body.emailPasswordEnabled; + } + if (body.passwordlessEnabled !== undefined) { + newTenantState.passwordlessEnabled = body.passwordlessEnabled; + } + if (body.thirdPartyEnabled !== undefined) { + newTenantState.thirdPartyEnabled = body.thirdPartyEnabled; + } + if (body.firstFactors !== undefined) { + newTenantState.firstFactors = body.firstFactors; + } + if (body.requiredSecondaryFactors !== undefined) { + newTenantState.requiredSecondaryFactors = body.requiredSecondaryFactors; + } + + setTenantState(newTenantState) } - if (body.requiredSecondaryFactors !== undefined) { - newTenantState.requiredSecondaryFactors = body.requiredSecondaryFactors; + + const update_5 = (body) => { } - setTenantState(newTenantState) - } + const create_v2 = (body) => { + let newTenantState; + let {tenantId} = body; - const update_5 = (body) => { - } + if (tenantId === "public") { + newTenantState = { + emailPasswordEnabled: null, + passwordlessEnabled: null, + thirdPartyEnabled: null, + firstFactors: null, + requiredSecondaryFactors: null, + } + } else { + newTenantState = { + emailPasswordEnabled: null, + passwordlessEnabled: null, + thirdPartyEnabled: null, + firstFactors: [], + requiredSecondaryFactors: null, + } + } - const create_v2 = (body) => { - let newTenantState; - let {tenantId} = body; + if (body.firstFactors !== undefined) { + newTenantState.firstFactors = body.firstFactors; + } + if (body.requiredSecondaryFactors !== undefined) { + newTenantState.requiredSecondaryFactors = body.requiredSecondaryFactors; + } - if (tenantId === "public") { - newTenantState = { - emailPasswordEnabled: null, - passwordlessEnabled: null, - thirdPartyEnabled: null, - firstFactors: null, - requiredSecondaryFactors: null, - } - } else { - newTenantState = { - emailPasswordEnabled: null, - passwordlessEnabled: null, - thirdPartyEnabled: null, - firstFactors: [], - requiredSecondaryFactors: null, - } + setTenantState(newTenantState) } - if (body.firstFactors !== undefined) { - newTenantState.firstFactors = body.firstFactors; - } - if (body.requiredSecondaryFactors !== undefined) { - newTenantState.requiredSecondaryFactors = body.requiredSecondaryFactors; + const update_v2 = (body) => { } - setTenantState(newTenantState) - } - - const update_v2 = (body) => { - } - - const get_4 = () => { - return { - emailPasswordEnabled: - tenantState.emailPasswordEnabled !== false && - ( - (tenantState.firstFactors === null) || - (tenantState.firstFactors !== null && tenantState.firstFactors.includes("emailpassword")) - ), - thirdPartyEnabled: - tenantState.thirdPartyEnabled !== false && - ( - (tenantState.firstFactors === null) || - (tenantState.firstFactors !== null && tenantState.firstFactors.includes("thirdparty")) - ), - passwordlessEnabled: - tenantState.passwordlessEnabled !== false && - ( - (tenantState.firstFactors === null) || - (tenantState.firstFactors !== null && ( - tenantState.firstFactors.includes("otp-phone") || - tenantState.firstFactors.includes("otp-email") || - tenantState.firstFactors.includes("link-phone") || - tenantState.firstFactors.includes("link-email") - )) - ), - }; - } + const get_4 = () => { + return { + emailPasswordEnabled: + tenantState.emailPasswordEnabled !== false && + ( + (tenantState.firstFactors === null) || + (tenantState.firstFactors !== null && tenantState.firstFactors.includes("emailpassword")) + ), + thirdPartyEnabled: + tenantState.thirdPartyEnabled !== false && + ( + (tenantState.firstFactors === null) || + (tenantState.firstFactors !== null && tenantState.firstFactors.includes("thirdparty")) + ), + passwordlessEnabled: + tenantState.passwordlessEnabled !== false && + ( + (tenantState.firstFactors === null) || + (tenantState.firstFactors !== null && ( + tenantState.firstFactors.includes("otp-phone") || + tenantState.firstFactors.includes("otp-email") || + tenantState.firstFactors.includes("link-phone") || + tenantState.firstFactors.includes("link-email") + )) + ), + }; + } - const get_5 = () => { - return { - emailPasswordEnabled: - tenantState.emailPasswordEnabled === true || - (tenantState.emailPasswordEnabled === null && tenantState.firstFactors === null) || - (tenantState.firstFactors !== null && tenantState.firstFactors.includes("emailpassword")) || - (tenantState.requiredSecondaryFactors !== null && tenantState.requiredSecondaryFactors.includes("emailpassword")), - thirdPartyEnabled: - tenantState.thirdPartyEnabled === true || - (tenantState.thirdPartyEnabled === null && tenantState.firstFactors === null) || - (tenantState.firstFactors !== null && tenantState.firstFactors.includes("thirdparty")) || - (tenantState.requiredSecondaryFactors !== null && tenantState.requiredSecondaryFactors.includes("thirdparty")), - passwordlessEnabled: - tenantState.passwordlessEnabled === true || - (tenantState.passwordlessEnabled === null && tenantState.firstFactors === null) || - (tenantState.firstFactors !== null && ( - tenantState.firstFactors.includes("otp-phone") || - tenantState.firstFactors.includes("otp-email") || - tenantState.firstFactors.includes("link-phone") || - tenantState.firstFactors.includes("link-email") - )) || - (tenantState.requiredSecondaryFactors !== null && ( - tenantState.requiredSecondaryFactors.includes("otp-phone") || - tenantState.requiredSecondaryFactors.includes("otp-email") || - tenantState.requiredSecondaryFactors.includes("link-phone") || - tenantState.requiredSecondaryFactors.includes("link-email") - )), - firstFactors: tenantState.firstFactors !== null && tenantState.firstFactors.length === 0 ? null : tenantState.firstFactors, - requiredSecondaryFactors: tenantState.requiredSecondaryFactors, - }; - } + const get_5 = () => { + return { + emailPasswordEnabled: + tenantState.emailPasswordEnabled === true || + (tenantState.emailPasswordEnabled === null && tenantState.firstFactors === null) || + (tenantState.firstFactors !== null && tenantState.firstFactors.includes("emailpassword")) || + (tenantState.requiredSecondaryFactors !== null && tenantState.requiredSecondaryFactors.includes("emailpassword")), + thirdPartyEnabled: + tenantState.thirdPartyEnabled === true || + (tenantState.thirdPartyEnabled === null && tenantState.firstFactors === null) || + (tenantState.firstFactors !== null && tenantState.firstFactors.includes("thirdparty")) || + (tenantState.requiredSecondaryFactors !== null && tenantState.requiredSecondaryFactors.includes("thirdparty")), + passwordlessEnabled: + tenantState.passwordlessEnabled === true || + (tenantState.passwordlessEnabled === null && tenantState.firstFactors === null) || + (tenantState.firstFactors !== null && ( + tenantState.firstFactors.includes("otp-phone") || + tenantState.firstFactors.includes("otp-email") || + tenantState.firstFactors.includes("link-phone") || + tenantState.firstFactors.includes("link-email") + )) || + (tenantState.requiredSecondaryFactors !== null && ( + tenantState.requiredSecondaryFactors.includes("otp-phone") || + tenantState.requiredSecondaryFactors.includes("otp-email") || + tenantState.requiredSecondaryFactors.includes("link-phone") || + tenantState.requiredSecondaryFactors.includes("link-email") + )), + firstFactors: tenantState.firstFactors !== null && tenantState.firstFactors.length === 0 ? null : tenantState.firstFactors, + requiredSecondaryFactors: tenantState.requiredSecondaryFactors, + }; + } - const get_v2 = () => { - return { - firstFactors: tenantState.firstFactors, - requiredSecondaryFactors: tenantState.requiredSecondaryFactors, - }; - } + const get_v2 = () => { + return { + firstFactors: tenantState.firstFactors, + requiredSecondaryFactors: tenantState.requiredSecondaryFactors, + }; + } - return ( -
-

DB State

-
{JSON.stringify(tenantState, null, 2)}
+ return ( +
+

DB State

+
{JSON.stringify(tenantState, null, 2)}
-
-
-

Get in 4.0

-
{JSON.stringify(get_4(), null, 2)}
-
-
-

Get in 5.0

-
{JSON.stringify(get_5(), null, 2)}
-
-
-

Get in v2

-
{JSON.stringify(get_v2(), null, 2)}
-
-
+
+
+

Get in 4.0

+
{JSON.stringify(get_4(), null, 2)}
+
+
+

Get in 5.0

+
{JSON.stringify(get_5(), null, 2)}
+
+
+

Get in v2

+
{JSON.stringify(get_v2(), null, 2)}
+
+
-
-
- - - -
-
- - - -
-
- - - -
-
+
+
+ + + +
+
+ + + +
+
+ + + +
+
-
{errorMsg}
-
- ); +
{errorMsg}
+
+ ); } diff --git a/test-data/playground/public/index.html b/test-data/playground/public/index.html index aa069f27c..193dd6746 100644 --- a/test-data/playground/public/index.html +++ b/test-data/playground/public/index.html @@ -1,20 +1,20 @@ - - - - - + + + + + - + - + React App - - - -
- - + To begin the development, run `npm start` or `yarn start`. + To create a production bundle, use `npm run build` or `yarn build`. +--> + diff --git a/test-data/playground/src/App.css b/test-data/playground/src/App.css index 74b5e0534..78b8850cf 100644 --- a/test-data/playground/src/App.css +++ b/test-data/playground/src/App.css @@ -1,38 +1,38 @@ .App { - text-align: center; + text-align: center; } .App-logo { - height: 40vmin; - pointer-events: none; + height: 40vmin; + pointer-events: none; } @media (prefers-reduced-motion: no-preference) { - .App-logo { - animation: App-logo-spin infinite 20s linear; - } + .App-logo { + animation: App-logo-spin infinite 20s linear; + } } .App-header { - background-color: #282c34; - min-height: 100vh; - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - font-size: calc(10px + 2vmin); - color: white; + background-color: #282c34; + min-height: 100vh; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + font-size: calc(10px + 2vmin); + color: white; } .App-link { - color: #61dafb; + color: #61dafb; } @keyframes App-logo-spin { - from { - transform: rotate(0deg); - } - to { - transform: rotate(360deg); - } + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } } diff --git a/test-data/playground/src/App.js b/test-data/playground/src/App.js index fe9f4512f..ef6557b51 100644 --- a/test-data/playground/src/App.js +++ b/test-data/playground/src/App.js @@ -1,816 +1,808 @@ -import React from "react"; -import { useState } from "react"; +import React, {useState} from "react"; import "./index.css"; import { - backendCdi4Behaviour, - cdi4CoreBehaviour, - create_4, - create_4_migrate, - frontendCdi4Behaviour, - get_4, - update_4, + backendCdi4Behaviour, + cdi4CoreBehaviour, + create_4, + create_4_migrate, + frontendCdi4Behaviour, + get_4, + update_4, } from "./cdi4"; +import {backendCdi5Behaviour, cdi5CoreBehaviour, create_5, frontendCdi5Behaviour, get_5, update_5,} from "./cdi5"; import { - backendCdi5Behaviour, - cdi5CoreBehaviour, - create_5, - frontendCdi5Behaviour, - get_5, - update_5, -} from "./cdi5"; -import { - backendCdi51Behaviour, - cdi51CoreBehaviour, - create_v2, - frontendCdi51Behaviour, - get_v2, - update_v2, + backendCdi51Behaviour, + cdi51CoreBehaviour, + create_v2, + frontendCdi51Behaviour, + get_v2, + update_v2, } from "./cdi51"; -import { runTests } from "./tests"; +import {runTests} from "./tests"; export default function App(props) { - const [tenantState, setTenantState] = useState({ - tenantId: "undefined", - emailPasswordEnabled: false, - passwordlessEnabled: false, - thirdPartyEnabled: false, - firstFactors: [], - requiredSecondaryFactors: null, - }); + const [tenantState, setTenantState] = useState({ + tenantId: "undefined", + emailPasswordEnabled: false, + passwordlessEnabled: false, + thirdPartyEnabled: false, + firstFactors: [], + requiredSecondaryFactors: null, + }); - const [errorMsg, setErrorMsg] = useState(""); + const [errorMsg, setErrorMsg] = useState(""); - const [cdi4body, setCdi4Body] = useState('{\n "tenantId": "public"\n}'); - const [cdi5body, setCdi5Body] = useState('{\n "tenantId": "public"\n}'); - const [v2body, setV2Body] = useState('{\n "tenantId": "public"\n}'); + const [cdi4body, setCdi4Body] = useState('{\n "tenantId": "public"\n}'); + const [cdi5body, setCdi5Body] = useState('{\n "tenantId": "public"\n}'); + const [v2body, setV2Body] = useState('{\n "tenantId": "public"\n}'); - return ( -
-

DB State

-
{JSON.stringify(tenantState, null, 2)}
+ return ( +
+

DB State

+
{JSON.stringify(tenantState, null, 2)}
-
-
-

Get in 4.0

-
{JSON.stringify(get_4(tenantState), null, 2)}
-
-
-

Get in 5.0

-
{JSON.stringify(get_5(tenantState), null, 2)}
-
-
-

Get in v2

-
{JSON.stringify(get_v2(tenantState), null, 2)}
-
-
+
+
+

Get in 4.0

+
{JSON.stringify(get_4(tenantState), null, 2)}
+
+
+

Get in 5.0

+
{JSON.stringify(get_5(tenantState), null, 2)}
+
+
+

Get in v2

+
{JSON.stringify(get_v2(tenantState), null, 2)}
+
+
-
-
-

Core behaviour

-
{cdi4CoreBehaviour(tenantState)}
-
+
+
+

Core behaviour

+
{cdi4CoreBehaviour(tenantState)}
+
-
-

Core behaviour

-
{cdi5CoreBehaviour(tenantState)}
-
+
+

Core behaviour

+
{cdi5CoreBehaviour(tenantState)}
+
-
-

Core behaviour

-
{cdi51CoreBehaviour(tenantState)}
-
-
+
+

Core behaviour

+
{cdi51CoreBehaviour(tenantState)}
+
+
-
-
-

Backend behaviour

-
{backendCdi4Behaviour(tenantState)}
-
+
+
+

Backend behaviour

+
{backendCdi4Behaviour(tenantState)}
+
-
-

Backend behaviour

-
{backendCdi5Behaviour(tenantState)}
-
+
+

Backend behaviour

+
{backendCdi5Behaviour(tenantState)}
+
-
-

Backend behaviour

-
{backendCdi51Behaviour(tenantState)}
-
-
+
+

Backend behaviour

+
{backendCdi51Behaviour(tenantState)}
+
+
-
-
-

Frontend behaviour

-
{frontendCdi4Behaviour(tenantState)}
-
+
+
+

Frontend behaviour

+
{frontendCdi4Behaviour(tenantState)}
+
-
-

Frontend behaviour

-
{frontendCdi5Behaviour(tenantState)}
-
+
+

Frontend behaviour

+
{frontendCdi5Behaviour(tenantState)}
+
-
-

Frontend behaviour

-
{frontendCdi51Behaviour(tenantState)}
-
-
+
+

Frontend behaviour

+
{frontendCdi51Behaviour(tenantState)}
+
+
-
-

Create / Update

-
+
+

Create / Update

+
-
-
+
+
- - - + + + -
-

Shortcuts:

+
+

Shortcuts:

-

- Tenant: - { - e.preventDefault(); - { - let state = JSON.parse(cdi4body); - state.tenantId = "public"; - setCdi4Body(JSON.stringify(state, null, 2)); - } - { - let state = JSON.parse(cdi5body); - state.tenantId = "public"; - setCdi5Body(JSON.stringify(state, null, 2)); - } - { - let state = JSON.parse(v2body); - state.tenantId = "public"; - setV2Body(JSON.stringify(state, null, 2)); - } - }} - > +

+ Tenant: + { + e.preventDefault(); + { + let state = JSON.parse(cdi4body); + state.tenantId = "public"; + setCdi4Body(JSON.stringify(state, null, 2)); + } + { + let state = JSON.parse(cdi5body); + state.tenantId = "public"; + setCdi5Body(JSON.stringify(state, null, 2)); + } + { + let state = JSON.parse(v2body); + state.tenantId = "public"; + setV2Body(JSON.stringify(state, null, 2)); + } + }} + > public -   - { - e.preventDefault(); - { - let state = JSON.parse(cdi4body); - state.tenantId = "t1"; - setCdi4Body(JSON.stringify(state, null, 2)); - } - { - let state = JSON.parse(cdi5body); - state.tenantId = "t1"; - setCdi5Body(JSON.stringify(state, null, 2)); - } - { - let state = JSON.parse(v2body); - state.tenantId = "t1"; - setV2Body(JSON.stringify(state, null, 2)); - } - }} - > +   + { + e.preventDefault(); + { + let state = JSON.parse(cdi4body); + state.tenantId = "t1"; + setCdi4Body(JSON.stringify(state, null, 2)); + } + { + let state = JSON.parse(cdi5body); + state.tenantId = "t1"; + setCdi5Body(JSON.stringify(state, null, 2)); + } + { + let state = JSON.parse(v2body); + state.tenantId = "t1"; + setV2Body(JSON.stringify(state, null, 2)); + } + }} + > t1 -

-

- emailPasswordEnabled: - { - e.preventDefault(); - let state = JSON.parse(cdi4body); - state.emailPasswordEnabled = undefined; - setCdi4Body(JSON.stringify(state, null, 2)); - }} - > +

+

+ emailPasswordEnabled: + { + e.preventDefault(); + let state = JSON.parse(cdi4body); + state.emailPasswordEnabled = undefined; + setCdi4Body(JSON.stringify(state, null, 2)); + }} + > unset -   - { - e.preventDefault(); - let state = JSON.parse(cdi4body); - state.emailPasswordEnabled = true; - setCdi4Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi4body); + state.emailPasswordEnabled = true; + setCdi4Body(JSON.stringify(state, null, 2)); + }} + > true -   - { - e.preventDefault(); - let state = JSON.parse(cdi4body); - state.emailPasswordEnabled = false; - setCdi4Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi4body); + state.emailPasswordEnabled = false; + setCdi4Body(JSON.stringify(state, null, 2)); + }} + > false -

-

- passwordlessEnabled: - { - e.preventDefault(); - let state = JSON.parse(cdi4body); - state.passwordlessEnabled = undefined; - setCdi4Body(JSON.stringify(state, null, 2)); - }} - > +

+

+ passwordlessEnabled: + { + e.preventDefault(); + let state = JSON.parse(cdi4body); + state.passwordlessEnabled = undefined; + setCdi4Body(JSON.stringify(state, null, 2)); + }} + > unset -   - { - e.preventDefault(); - let state = JSON.parse(cdi4body); - state.passwordlessEnabled = true; - setCdi4Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi4body); + state.passwordlessEnabled = true; + setCdi4Body(JSON.stringify(state, null, 2)); + }} + > true -   - { - e.preventDefault(); - let state = JSON.parse(cdi4body); - state.passwordlessEnabled = false; - setCdi4Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi4body); + state.passwordlessEnabled = false; + setCdi4Body(JSON.stringify(state, null, 2)); + }} + > false -

-

- thirdPartyEnabled: - { - e.preventDefault(); - let state = JSON.parse(cdi4body); - state.thirdPartyEnabled = undefined; - setCdi4Body(JSON.stringify(state, null, 2)); - }} - > +

+

+ thirdPartyEnabled: + { + e.preventDefault(); + let state = JSON.parse(cdi4body); + state.thirdPartyEnabled = undefined; + setCdi4Body(JSON.stringify(state, null, 2)); + }} + > unset -   - { - e.preventDefault(); - let state = JSON.parse(cdi4body); - state.thirdPartyEnabled = true; - setCdi4Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi4body); + state.thirdPartyEnabled = true; + setCdi4Body(JSON.stringify(state, null, 2)); + }} + > true -   - { - e.preventDefault(); - let state = JSON.parse(cdi4body); - state.thirdPartyEnabled = false; - setCdi4Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi4body); + state.thirdPartyEnabled = false; + setCdi4Body(JSON.stringify(state, null, 2)); + }} + > false -

-
-
-
+

+
+
+
- - + + -
-

Shortcuts:

+
+

Shortcuts:

-

- Tenant: - { - e.preventDefault(); - { - let state = JSON.parse(cdi4body); - state.tenantId = "public"; - setCdi4Body(JSON.stringify(state, null, 2)); - } - { - let state = JSON.parse(cdi5body); - state.tenantId = "public"; - setCdi5Body(JSON.stringify(state, null, 2)); - } - { - let state = JSON.parse(v2body); - state.tenantId = "public"; - setV2Body(JSON.stringify(state, null, 2)); - } - }} - > +

+ Tenant: + { + e.preventDefault(); + { + let state = JSON.parse(cdi4body); + state.tenantId = "public"; + setCdi4Body(JSON.stringify(state, null, 2)); + } + { + let state = JSON.parse(cdi5body); + state.tenantId = "public"; + setCdi5Body(JSON.stringify(state, null, 2)); + } + { + let state = JSON.parse(v2body); + state.tenantId = "public"; + setV2Body(JSON.stringify(state, null, 2)); + } + }} + > public -   - { - e.preventDefault(); - { - let state = JSON.parse(cdi4body); - state.tenantId = "t1"; - setCdi4Body(JSON.stringify(state, null, 2)); - } - { - let state = JSON.parse(cdi5body); - state.tenantId = "t1"; - setCdi5Body(JSON.stringify(state, null, 2)); - } - { - let state = JSON.parse(v2body); - state.tenantId = "t1"; - setV2Body(JSON.stringify(state, null, 2)); - } - }} - > +   + { + e.preventDefault(); + { + let state = JSON.parse(cdi4body); + state.tenantId = "t1"; + setCdi4Body(JSON.stringify(state, null, 2)); + } + { + let state = JSON.parse(cdi5body); + state.tenantId = "t1"; + setCdi5Body(JSON.stringify(state, null, 2)); + } + { + let state = JSON.parse(v2body); + state.tenantId = "t1"; + setV2Body(JSON.stringify(state, null, 2)); + } + }} + > t1 -

-

- emailPasswordEnabled: - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.emailPasswordEnabled = undefined; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > +

+

+ emailPasswordEnabled: + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.emailPasswordEnabled = undefined; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > unset -   - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.emailPasswordEnabled = true; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.emailPasswordEnabled = true; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > true -   - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.emailPasswordEnabled = false; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.emailPasswordEnabled = false; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > false -

-

- passwordlessEnabled: - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.passwordlessEnabled = undefined; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > +

+

+ passwordlessEnabled: + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.passwordlessEnabled = undefined; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > unset -   - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.passwordlessEnabled = true; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.passwordlessEnabled = true; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > true -   - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.passwordlessEnabled = false; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.passwordlessEnabled = false; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > false -

-

- thirdPartyEnabled: - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.thirdPartyEnabled = undefined; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > +

+

+ thirdPartyEnabled: + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.thirdPartyEnabled = undefined; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > unset -   - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.thirdPartyEnabled = true; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.thirdPartyEnabled = true; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > true -   - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.thirdPartyEnabled = false; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.thirdPartyEnabled = false; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > false -

-

- firstFactors: - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.firstFactors = undefined; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > +

+

+ firstFactors: + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.firstFactors = undefined; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > unset -   - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.firstFactors = null; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.firstFactors = null; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > null -   - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.firstFactors = ["emailpassword"]; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.firstFactors = ["emailpassword"]; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > [emailpassword] -

-

- requiredSecondaryFactors: - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.requiredSecondaryFactors = undefined; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > +

+

+ requiredSecondaryFactors: + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.requiredSecondaryFactors = undefined; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > unset -   - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.requiredSecondaryFactors = null; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.requiredSecondaryFactors = null; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > null -   - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.requiredSecondaryFactors = ["otp-phone"]; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.requiredSecondaryFactors = ["otp-phone"]; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > [otp-phone] - { - e.preventDefault(); - let state = JSON.parse(cdi5body); - state.requiredSecondaryFactors = ["emailpassword"]; - setCdi5Body(JSON.stringify(state, null, 2)); - }} - > + { + e.preventDefault(); + let state = JSON.parse(cdi5body); + state.requiredSecondaryFactors = ["emailpassword"]; + setCdi5Body(JSON.stringify(state, null, 2)); + }} + > [emailpassword] -

-
-
-
+

+
+
+
- - + + -
-

Shortcuts:

+
+

Shortcuts:

-

- Tenant: - { - e.preventDefault(); - { - let state = JSON.parse(cdi4body); - state.tenantId = "public"; - setCdi4Body(JSON.stringify(state, null, 2)); - } - { - let state = JSON.parse(cdi5body); - state.tenantId = "public"; - setCdi5Body(JSON.stringify(state, null, 2)); - } - { - let state = JSON.parse(v2body); - state.tenantId = "public"; - setV2Body(JSON.stringify(state, null, 2)); - } - }} - > +

+ Tenant: + { + e.preventDefault(); + { + let state = JSON.parse(cdi4body); + state.tenantId = "public"; + setCdi4Body(JSON.stringify(state, null, 2)); + } + { + let state = JSON.parse(cdi5body); + state.tenantId = "public"; + setCdi5Body(JSON.stringify(state, null, 2)); + } + { + let state = JSON.parse(v2body); + state.tenantId = "public"; + setV2Body(JSON.stringify(state, null, 2)); + } + }} + > public -   - { - { - let state = JSON.parse(cdi4body); - state.tenantId = "t1"; - setCdi4Body(JSON.stringify(state, null, 2)); - } - { - let state = JSON.parse(cdi5body); - state.tenantId = "t1"; - setCdi5Body(JSON.stringify(state, null, 2)); - } - { - let state = JSON.parse(v2body); - state.tenantId = "t1"; - setV2Body(JSON.stringify(state, null, 2)); - } - }} - > +   + { + { + let state = JSON.parse(cdi4body); + state.tenantId = "t1"; + setCdi4Body(JSON.stringify(state, null, 2)); + } + { + let state = JSON.parse(cdi5body); + state.tenantId = "t1"; + setCdi5Body(JSON.stringify(state, null, 2)); + } + { + let state = JSON.parse(v2body); + state.tenantId = "t1"; + setV2Body(JSON.stringify(state, null, 2)); + } + }} + > t1 -

-

- firstFactors: - { - e.preventDefault(); - let state = JSON.parse(v2body); - state.firstFactors = undefined; - setV2Body(JSON.stringify(state, null, 2)); - }} - > +

+

+ firstFactors: + { + e.preventDefault(); + let state = JSON.parse(v2body); + state.firstFactors = undefined; + setV2Body(JSON.stringify(state, null, 2)); + }} + > unset -   - { - e.preventDefault(); - let state = JSON.parse(v2body); - state.firstFactors = null; - setV2Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(v2body); + state.firstFactors = null; + setV2Body(JSON.stringify(state, null, 2)); + }} + > null - { - e.preventDefault(); - let state = JSON.parse(v2body); - state.firstFactors = []; - setV2Body(JSON.stringify(state, null, 2)); - }} - > + { + e.preventDefault(); + let state = JSON.parse(v2body); + state.firstFactors = []; + setV2Body(JSON.stringify(state, null, 2)); + }} + > [] -   - { - e.preventDefault(); - let state = JSON.parse(v2body); - state.firstFactors = ["emailpassword"]; - setV2Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(v2body); + state.firstFactors = ["emailpassword"]; + setV2Body(JSON.stringify(state, null, 2)); + }} + > [emailpassword] -

-

- requiredSecondaryFactors: - { - e.preventDefault(); - let state = JSON.parse(v2body); - state.requiredSecondaryFactors = undefined; - setV2Body(JSON.stringify(state, null, 2)); - }} - > +

+

+ requiredSecondaryFactors: + { + e.preventDefault(); + let state = JSON.parse(v2body); + state.requiredSecondaryFactors = undefined; + setV2Body(JSON.stringify(state, null, 2)); + }} + > unset -   - { - e.preventDefault(); - let state = JSON.parse(v2body); - state.requiredSecondaryFactors = null; - setV2Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(v2body); + state.requiredSecondaryFactors = null; + setV2Body(JSON.stringify(state, null, 2)); + }} + > null -   - { - e.preventDefault(); - let state = JSON.parse(v2body); - state.requiredSecondaryFactors = ["otp-phone"]; - setV2Body(JSON.stringify(state, null, 2)); - }} - > +   + { + e.preventDefault(); + let state = JSON.parse(v2body); + state.requiredSecondaryFactors = ["otp-phone"]; + setV2Body(JSON.stringify(state, null, 2)); + }} + > [otp-phone] -

-
-
-
+

+
+
+
-
-

Open console before running tests

- -
-
{errorMsg}
-
- ); +
+

Open console before running tests

+ +
+
{errorMsg}
+
+ ); } diff --git a/test-data/playground/src/App.test.js b/test-data/playground/src/App.test.js index 1f03afeec..ba45315f5 100644 --- a/test-data/playground/src/App.test.js +++ b/test-data/playground/src/App.test.js @@ -1,8 +1,8 @@ -import { render, screen } from '@testing-library/react'; +import {render, screen} from '@testing-library/react'; import App from './App'; test('renders learn react link', () => { - render(); - const linkElement = screen.getByText(/learn react/i); - expect(linkElement).toBeInTheDocument(); + render(); + const linkElement = screen.getByText(/learn react/i); + expect(linkElement).toBeInTheDocument(); }); diff --git a/test-data/playground/src/cdi4.js b/test-data/playground/src/cdi4.js index da079246c..b06cef03f 100644 --- a/test-data/playground/src/cdi4.js +++ b/test-data/playground/src/cdi4.js @@ -1,250 +1,250 @@ let allFirstFactors = [ - "emailpassword", - "otp-phone", - "otp-email", - "link-phone", - "link-email", - "thirdparty", + "emailpassword", + "otp-phone", + "otp-email", + "link-phone", + "link-email", + "thirdparty", ]; export const update_4 = (body, currentState) => { - let newTenantState = { ...currentState }; - - let firstFactors = currentState.firstFactors; - if (body.emailPasswordEnabled === true) { - newTenantState.emailPasswordEnabled = true; - if (firstFactors !== null) { - if (!firstFactors.includes("emailpassword")) { - firstFactors.push("emailpassword"); - } - } - } - if (body.passwordlessEnabled === true) { - newTenantState.passwordlessEnabled = true; - if (newTenantState.firstFactors !== null) { - if ( - !firstFactors.includes("otp-phone") && - !firstFactors.includes("otp-email") && - !firstFactors.includes("link-phone") && - !firstFactors.includes("link-email") - ) { - firstFactors.push("otp-phone"); - firstFactors.push("otp-email"); - firstFactors.push("link-phone"); - firstFactors.push("link-email"); - } - } - } - if (body.thirdPartyEnabled === true) { - newTenantState.thirdPartyEnabled = true; - if (firstFactors !== null) { - if (!firstFactors.includes("thirdparty")) { - firstFactors.push("thirdparty"); - } - } - } - - if ( - body.emailPasswordEnabled === false || - body.passwordlessEnabled === false || - body.thirdPartyEnabled === false || - newTenantState.emailPasswordEnabled === false || - newTenantState.passwordlessEnabled === false || - newTenantState.thirdPartyEnabled === false - ) { - if (firstFactors === null) { - firstFactors = [...allFirstFactors]; - } - } - - if ( - body.emailPasswordEnabled === false || - newTenantState.emailPasswordEnabled === false - ) { - firstFactors = firstFactors.filter((factor) => factor !== "emailpassword"); - } - if ( - body.passwordlessEnabled === false || - newTenantState.passwordlessEnabled === false - ) { - firstFactors = firstFactors.filter( - (factor) => - factor !== "otp-phone" && - factor !== "otp-email" && - factor !== "link-phone" && - factor !== "link-email" - ); - } - if ( - body.thirdPartyEnabled === false || - newTenantState.thirdPartyEnabled === false - ) { - firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); - } - - // if (firstFactors !== null && firstFactors.length === 0) { - // newTenantState.requiredSecondaryFactors = null; - // } - - newTenantState.firstFactors = firstFactors; - - return newTenantState; + let newTenantState = {...currentState}; + + let firstFactors = currentState.firstFactors; + if (body.emailPasswordEnabled === true) { + newTenantState.emailPasswordEnabled = true; + if (firstFactors !== null) { + if (!firstFactors.includes("emailpassword")) { + firstFactors.push("emailpassword"); + } + } + } + if (body.passwordlessEnabled === true) { + newTenantState.passwordlessEnabled = true; + if (newTenantState.firstFactors !== null) { + if ( + !firstFactors.includes("otp-phone") && + !firstFactors.includes("otp-email") && + !firstFactors.includes("link-phone") && + !firstFactors.includes("link-email") + ) { + firstFactors.push("otp-phone"); + firstFactors.push("otp-email"); + firstFactors.push("link-phone"); + firstFactors.push("link-email"); + } + } + } + if (body.thirdPartyEnabled === true) { + newTenantState.thirdPartyEnabled = true; + if (firstFactors !== null) { + if (!firstFactors.includes("thirdparty")) { + firstFactors.push("thirdparty"); + } + } + } + + if ( + body.emailPasswordEnabled === false || + body.passwordlessEnabled === false || + body.thirdPartyEnabled === false || + newTenantState.emailPasswordEnabled === false || + newTenantState.passwordlessEnabled === false || + newTenantState.thirdPartyEnabled === false + ) { + if (firstFactors === null) { + firstFactors = [...allFirstFactors]; + } + } + + if ( + body.emailPasswordEnabled === false || + newTenantState.emailPasswordEnabled === false + ) { + firstFactors = firstFactors.filter((factor) => factor !== "emailpassword"); + } + if ( + body.passwordlessEnabled === false || + newTenantState.passwordlessEnabled === false + ) { + firstFactors = firstFactors.filter( + (factor) => + factor !== "otp-phone" && + factor !== "otp-email" && + factor !== "link-phone" && + factor !== "link-email" + ); + } + if ( + body.thirdPartyEnabled === false || + newTenantState.thirdPartyEnabled === false + ) { + firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); + } + + // if (firstFactors !== null && firstFactors.length === 0) { + // newTenantState.requiredSecondaryFactors = null; + // } + + newTenantState.firstFactors = firstFactors; + + return newTenantState; }; export const create_4 = (body) => { - let { tenantId } = body; - let newTenantState; - if (tenantId === "public") { - newTenantState = { - tenantId, - emailPasswordEnabled: true, - passwordlessEnabled: true, - thirdPartyEnabled: true, - firstFactors: null, - requiredSecondaryFactors: null, - }; - } else { - newTenantState = { - tenantId, - emailPasswordEnabled: false, - passwordlessEnabled: false, - thirdPartyEnabled: false, - firstFactors: [], - requiredSecondaryFactors: null, - }; - } + let {tenantId} = body; + let newTenantState; + if (tenantId === "public") { + newTenantState = { + tenantId, + emailPasswordEnabled: true, + passwordlessEnabled: true, + thirdPartyEnabled: true, + firstFactors: null, + requiredSecondaryFactors: null, + }; + } else { + newTenantState = { + tenantId, + emailPasswordEnabled: false, + passwordlessEnabled: false, + thirdPartyEnabled: false, + firstFactors: [], + requiredSecondaryFactors: null, + }; + } - return update_4(body, newTenantState); + return update_4(body, newTenantState); }; export const create_4_migrate = (body) => { - let { tenantId } = body; - let newTenantState; - if (tenantId === "public") { - newTenantState = { - tenantId, - emailPasswordEnabled: true, - passwordlessEnabled: true, - thirdPartyEnabled: true, - firstFactors: null, - requiredSecondaryFactors: null, - }; - } else { + let {tenantId} = body; + let newTenantState; + if (tenantId === "public") { + newTenantState = { + tenantId, + emailPasswordEnabled: true, + passwordlessEnabled: true, + thirdPartyEnabled: true, + firstFactors: null, + requiredSecondaryFactors: null, + }; + } else { + newTenantState = { + tenantId, + emailPasswordEnabled: false, + passwordlessEnabled: false, + thirdPartyEnabled: false, + firstFactors: null, + requiredSecondaryFactors: null, + }; + } + newTenantState = { - tenantId, - emailPasswordEnabled: false, - passwordlessEnabled: false, - thirdPartyEnabled: false, - firstFactors: null, - requiredSecondaryFactors: null, + ...newTenantState, + ...body, }; - } - - newTenantState = { - ...newTenantState, - ...body, - }; - return newTenantState; + return newTenantState; }; export const get_4 = (tenantState) => { - return { - emailPasswordEnabled: - tenantState.emailPasswordEnabled && - (tenantState.firstFactors === null || - tenantState.firstFactors.includes("emailpassword")), - thirdPartyEnabled: - tenantState.thirdPartyEnabled && - (tenantState.firstFactors === null || - tenantState.firstFactors.includes("thirdparty")), - passwordlessEnabled: - tenantState.passwordlessEnabled && - (tenantState.firstFactors === null || - tenantState.firstFactors.includes("otp-phone") || - tenantState.firstFactors.includes("otp-email") || - tenantState.firstFactors.includes("link-phone") || - tenantState.firstFactors.includes("link-email")), - }; + return { + emailPasswordEnabled: + tenantState.emailPasswordEnabled && + (tenantState.firstFactors === null || + tenantState.firstFactors.includes("emailpassword")), + thirdPartyEnabled: + tenantState.thirdPartyEnabled && + (tenantState.firstFactors === null || + tenantState.firstFactors.includes("thirdparty")), + passwordlessEnabled: + tenantState.passwordlessEnabled && + (tenantState.firstFactors === null || + tenantState.firstFactors.includes("otp-phone") || + tenantState.firstFactors.includes("otp-email") || + tenantState.firstFactors.includes("link-phone") || + tenantState.firstFactors.includes("link-email")), + }; }; export const cdi4CoreBehaviour = (tenantState) => { - let state = get_4(tenantState); - let res = ""; - - if (state.emailPasswordEnabled === false) { - res += "emailpassword APIs are blocked\n"; - } else { - res += "emailpassword APIs are allowed\n"; - } - - if (state.passwordlessEnabled === false) { - res += "passwordless APIs are blocked\n"; - } else { - res += "passwordless APIs are allowed\n"; - } - - if (state.thirdPartyEnabled === false) { - res += "thirdParty APIs are blocked\n"; - } else { - res += "thirdParty APIs are allowed\n"; - } - - return res; + let state = get_4(tenantState); + let res = ""; + + if (state.emailPasswordEnabled === false) { + res += "emailpassword APIs are blocked\n"; + } else { + res += "emailpassword APIs are allowed\n"; + } + + if (state.passwordlessEnabled === false) { + res += "passwordless APIs are blocked\n"; + } else { + res += "passwordless APIs are allowed\n"; + } + + if (state.thirdPartyEnabled === false) { + res += "thirdParty APIs are blocked\n"; + } else { + res += "thirdParty APIs are allowed\n"; + } + + return res; }; export const backendCdi4Behaviour = (tenantState) => { - let state = get_4(tenantState); + let state = get_4(tenantState); - let res = ""; + let res = ""; - res += "enabled booleans in tenant: ✓\n"; - res += "initialised recipes: "; - res += "✗\n"; + res += "enabled booleans in tenant: ✓\n"; + res += "initialised recipes: "; + res += "✗\n"; - res += "\n"; - res += "loginMethodsGET output: "; - res += JSON.stringify(state, null, 2); - return res; + res += "\n"; + res += "loginMethodsGET output: "; + res += JSON.stringify(state, null, 2); + return res; }; export const getCdi4FrontendLoginMethods = (tenantState) => { - let state = get_4(tenantState); - - let loginMethods = ""; - if (state.emailPasswordEnabled) { - loginMethods += " emailpassword"; - } - if (state.passwordlessEnabled) { - loginMethods += " otp-phone otp-email link-phone link-email"; - } - if (state.thirdPartyEnabled) { - loginMethods += " thirdparty"; - } - - if ( - state.emailPasswordEnabled === false && - state.passwordlessEnabled === false && - state.thirdPartyEnabled === false - ) { - loginMethods = " none"; - } - - return loginMethods; + let state = get_4(tenantState); + + let loginMethods = ""; + if (state.emailPasswordEnabled) { + loginMethods += " emailpassword"; + } + if (state.passwordlessEnabled) { + loginMethods += " otp-phone otp-email link-phone link-email"; + } + if (state.thirdPartyEnabled) { + loginMethods += " thirdparty"; + } + + if ( + state.emailPasswordEnabled === false && + state.passwordlessEnabled === false && + state.thirdPartyEnabled === false + ) { + loginMethods = " none"; + } + + return loginMethods; }; export const frontendCdi4Behaviour = (tenantState) => { - let res = ""; + let res = ""; - res += "loginMethodsGET: "; - res += "✓\n"; + res += "loginMethodsGET: "; + res += "✓\n"; - res += "initialised recipes: "; - res += "✓\n"; + res += "initialised recipes: "; + res += "✓\n"; - res += "\n"; + res += "\n"; - res += "ui shows:" + getCdi4FrontendLoginMethods(tenantState) + "\n"; + res += "ui shows:" + getCdi4FrontendLoginMethods(tenantState) + "\n"; - return res; + return res; }; diff --git a/test-data/playground/src/cdi5.js b/test-data/playground/src/cdi5.js index 37da49d8f..885f9feb3 100644 --- a/test-data/playground/src/cdi5.js +++ b/test-data/playground/src/cdi5.js @@ -1,464 +1,464 @@ let allFirstFactors = [ - "emailpassword", - "otp-phone", - "otp-email", - "link-phone", - "link-email", - "thirdparty", + "emailpassword", + "otp-phone", + "otp-email", + "link-phone", + "link-email", + "thirdparty", ]; export const update_5 = (body, currentState) => { - debugger; - let newTenantState = { ...currentState }; - if (Object.keys(body).length === 0) { - return newTenantState; - } - - let firstFactors = currentState.firstFactors; - let requiredSecondaryFactors = currentState.requiredSecondaryFactors; - - if ( - body.emailPasswordEnabled === true || - body.passwordlessEnabled === true || - body.thirdPartyEnabled === true - ) { - if (firstFactors !== null && firstFactors.length === 0) { - firstFactors = null; - newTenantState.emailPasswordEnabled = false; - newTenantState.passwordlessEnabled = false; - newTenantState.thirdPartyEnabled = false; + debugger; + let newTenantState = {...currentState}; + if (Object.keys(body).length === 0) { + return newTenantState; } - } - - if ( - firstFactors === null && - body.requiredSecondaryFactors !== undefined && - body.requiredSecondaryFactors !== null - ) { - const updFirstFactors = () => { - firstFactors = [...allFirstFactors]; - if ((currentState.emailPasswordEnabled === false && body.emailPasswordEnabled !== true) || body.emailPasswordEnabled === false) { - firstFactors = firstFactors.filter( - (factor) => factor !== "emailpassword" - ); - } - if ((currentState.passwordlessEnabled === false && body.passwordlessEnabled !== true) || body.passwordlessEnabled === false) { - firstFactors = firstFactors.filter((factor) => factor !== "otp-phone"); - firstFactors = firstFactors.filter((factor) => factor !== "otp-email"); - firstFactors = firstFactors.filter((factor) => factor !== "link-phone"); - firstFactors = firstFactors.filter((factor) => factor !== "link-email"); - } - if ((currentState.thirdPartyEnabled === false && body.thirdPartyEnabled !== true) || body.thirdPartyEnabled === false) { - firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); - } - - if (firstFactors.length === 6) { - firstFactors = null; - } - }; - currentState = get_5(currentState); + let firstFactors = currentState.firstFactors; + let requiredSecondaryFactors = currentState.requiredSecondaryFactors; if ( - currentState.emailPasswordEnabled === false && - body.requiredSecondaryFactors.includes("emailpassword") && body.emailPasswordEnabled !== true + body.emailPasswordEnabled === true || + body.passwordlessEnabled === true || + body.thirdPartyEnabled === true ) { - updFirstFactors(); + if (firstFactors !== null && firstFactors.length === 0) { + firstFactors = null; + newTenantState.emailPasswordEnabled = false; + newTenantState.passwordlessEnabled = false; + newTenantState.thirdPartyEnabled = false; + } } if ( - currentState.passwordlessEnabled === false && - (body.requiredSecondaryFactors.includes("otp-phone") || - body.requiredSecondaryFactors.includes("otp-email") || - body.requiredSecondaryFactors.includes("link-phone") || - body.requiredSecondaryFactors.includes("link-email")) && - body.passwordlessEnabled !== true + firstFactors === null && + body.requiredSecondaryFactors !== undefined && + body.requiredSecondaryFactors !== null ) { - updFirstFactors(); + const updFirstFactors = () => { + firstFactors = [...allFirstFactors]; + if ((currentState.emailPasswordEnabled === false && body.emailPasswordEnabled !== true) || body.emailPasswordEnabled === false) { + firstFactors = firstFactors.filter( + (factor) => factor !== "emailpassword" + ); + } + if ((currentState.passwordlessEnabled === false && body.passwordlessEnabled !== true) || body.passwordlessEnabled === false) { + firstFactors = firstFactors.filter((factor) => factor !== "otp-phone"); + firstFactors = firstFactors.filter((factor) => factor !== "otp-email"); + firstFactors = firstFactors.filter((factor) => factor !== "link-phone"); + firstFactors = firstFactors.filter((factor) => factor !== "link-email"); + } + if ((currentState.thirdPartyEnabled === false && body.thirdPartyEnabled !== true) || body.thirdPartyEnabled === false) { + firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); + } + + if (firstFactors.length === 6) { + firstFactors = null; + } + }; + + currentState = get_5(currentState); + + if ( + currentState.emailPasswordEnabled === false && + body.requiredSecondaryFactors.includes("emailpassword") && body.emailPasswordEnabled !== true + ) { + updFirstFactors(); + } + + if ( + currentState.passwordlessEnabled === false && + (body.requiredSecondaryFactors.includes("otp-phone") || + body.requiredSecondaryFactors.includes("otp-email") || + body.requiredSecondaryFactors.includes("link-phone") || + body.requiredSecondaryFactors.includes("link-email")) && + body.passwordlessEnabled !== true + ) { + updFirstFactors(); + } + + if ( + currentState.thirdPartyEnabled === false && + body.requiredSecondaryFactors.includes("thirdparty") && body.thirdPartyEnabled !== true + ) { + updFirstFactors(); + } } - if ( - currentState.thirdPartyEnabled === false && - body.requiredSecondaryFactors.includes("thirdparty") && body.thirdPartyEnabled !== true - ) { - updFirstFactors(); - } - } - - if (body.emailPasswordEnabled === true) { - newTenantState.emailPasswordEnabled = true; - } - if (body.passwordlessEnabled === true) { - newTenantState.passwordlessEnabled = true; - } - if (body.thirdPartyEnabled === true) { - newTenantState.thirdPartyEnabled = true; - } - - if (body.firstFactors !== undefined) { - firstFactors = body.firstFactors; - if (firstFactors !== null) { - if (firstFactors.includes("emailpassword")) { + if (body.emailPasswordEnabled === true) { newTenantState.emailPasswordEnabled = true; - } - if ( - firstFactors.includes("otp-phone") || - firstFactors.includes("otp-email") || - firstFactors.includes("link-phone") || - firstFactors.includes("link-email") - ) { - newTenantState.passwordlessEnabled = true; - } - if (firstFactors.includes("thirdparty")) { - newTenantState.thirdPartyEnabled = true; - } } - } - - if (body.requiredSecondaryFactors !== undefined) { - requiredSecondaryFactors = body.requiredSecondaryFactors; - if (requiredSecondaryFactors !== null) { - if (requiredSecondaryFactors.includes("emailpassword")) { - newTenantState.emailPasswordEnabled = true; - } - if ( - requiredSecondaryFactors.includes("otp-phone") || - requiredSecondaryFactors.includes("otp-email") || - requiredSecondaryFactors.includes("link-phone") || - requiredSecondaryFactors.includes("link-email") - ) { + if (body.passwordlessEnabled === true) { newTenantState.passwordlessEnabled = true; - } - if (requiredSecondaryFactors.includes("thirdparty")) { + } + if (body.thirdPartyEnabled === true) { newTenantState.thirdPartyEnabled = true; - } } - } - if (body.emailPasswordEnabled === false) { - if (firstFactors !== null) { - firstFactors = firstFactors.filter( - (factor) => factor !== "emailpassword" - ); + if (body.firstFactors !== undefined) { + firstFactors = body.firstFactors; + if (firstFactors !== null) { + if (firstFactors.includes("emailpassword")) { + newTenantState.emailPasswordEnabled = true; + } + if ( + firstFactors.includes("otp-phone") || + firstFactors.includes("otp-email") || + firstFactors.includes("link-phone") || + firstFactors.includes("link-email") + ) { + newTenantState.passwordlessEnabled = true; + } + if (firstFactors.includes("thirdparty")) { + newTenantState.thirdPartyEnabled = true; + } + } } - if (requiredSecondaryFactors !== null) { - requiredSecondaryFactors = requiredSecondaryFactors.filter( - (factor) => factor !== "emailpassword" - ); + if (body.requiredSecondaryFactors !== undefined) { + requiredSecondaryFactors = body.requiredSecondaryFactors; + if (requiredSecondaryFactors !== null) { + if (requiredSecondaryFactors.includes("emailpassword")) { + newTenantState.emailPasswordEnabled = true; + } + if ( + requiredSecondaryFactors.includes("otp-phone") || + requiredSecondaryFactors.includes("otp-email") || + requiredSecondaryFactors.includes("link-phone") || + requiredSecondaryFactors.includes("link-email") + ) { + newTenantState.passwordlessEnabled = true; + } + if (requiredSecondaryFactors.includes("thirdparty")) { + newTenantState.thirdPartyEnabled = true; + } + } } - newTenantState.emailPasswordEnabled = false; - } - if (body.passwordlessEnabled === false) { - if (firstFactors !== null) { - firstFactors = firstFactors.filter((factor) => factor !== "otp-phone"); - firstFactors = firstFactors.filter((factor) => factor !== "otp-email"); - firstFactors = firstFactors.filter((factor) => factor !== "link-phone"); - firstFactors = firstFactors.filter((factor) => factor !== "link-email"); - } + if (body.emailPasswordEnabled === false) { + if (firstFactors !== null) { + firstFactors = firstFactors.filter( + (factor) => factor !== "emailpassword" + ); + } - if (requiredSecondaryFactors !== null) { - requiredSecondaryFactors = requiredSecondaryFactors.filter( - (factor) => factor !== "otp-phone" - ); - requiredSecondaryFactors = requiredSecondaryFactors.filter( - (factor) => factor !== "otp-email" - ); - requiredSecondaryFactors = requiredSecondaryFactors.filter( - (factor) => factor !== "link-phone" - ); - requiredSecondaryFactors = requiredSecondaryFactors.filter( - (factor) => factor !== "link-email" - ); - } + if (requiredSecondaryFactors !== null) { + requiredSecondaryFactors = requiredSecondaryFactors.filter( + (factor) => factor !== "emailpassword" + ); + } - newTenantState.passwordlessEnabled = false; - } - if (body.thirdPartyEnabled === false) { - if (firstFactors !== null) { - firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); + newTenantState.emailPasswordEnabled = false; + } + if (body.passwordlessEnabled === false) { + if (firstFactors !== null) { + firstFactors = firstFactors.filter((factor) => factor !== "otp-phone"); + firstFactors = firstFactors.filter((factor) => factor !== "otp-email"); + firstFactors = firstFactors.filter((factor) => factor !== "link-phone"); + firstFactors = firstFactors.filter((factor) => factor !== "link-email"); + } + + if (requiredSecondaryFactors !== null) { + requiredSecondaryFactors = requiredSecondaryFactors.filter( + (factor) => factor !== "otp-phone" + ); + requiredSecondaryFactors = requiredSecondaryFactors.filter( + (factor) => factor !== "otp-email" + ); + requiredSecondaryFactors = requiredSecondaryFactors.filter( + (factor) => factor !== "link-phone" + ); + requiredSecondaryFactors = requiredSecondaryFactors.filter( + (factor) => factor !== "link-email" + ); + } + + newTenantState.passwordlessEnabled = false; + } + if (body.thirdPartyEnabled === false) { + if (firstFactors !== null) { + firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); + } + + if (requiredSecondaryFactors !== null) { + requiredSecondaryFactors = requiredSecondaryFactors.filter( + (factor) => factor !== "thirdparty" + ); + } + newTenantState.thirdPartyEnabled = false; } - if (requiredSecondaryFactors !== null) { - requiredSecondaryFactors = requiredSecondaryFactors.filter( - (factor) => factor !== "thirdparty" - ); + if ( + requiredSecondaryFactors !== null && + requiredSecondaryFactors.length === 0 + ) { + requiredSecondaryFactors = null; } - newTenantState.thirdPartyEnabled = false; - } - - if ( - requiredSecondaryFactors !== null && - requiredSecondaryFactors.length === 0 - ) { - requiredSecondaryFactors = null; - } - - // if (firstFactors !== null && firstFactors.length === 0) { - // if (body.requiredSecondaryFactors === undefined) { - // requiredSecondaryFactors = null; - // } - // } - - // if (newTenantState.emailPasswordEnabled === false && newTenantState.passwordlessEnabled === false && newTenantState.thirdPartyEnabled === false) { - // if (body.requiredSecondaryFactors === undefined) { - // requiredSecondaryFactors = null; - // } - // } - - newTenantState.firstFactors = firstFactors; - newTenantState.requiredSecondaryFactors = requiredSecondaryFactors; - - if (newTenantState.firstFactors !== null) { - for (const factor of newTenantState.firstFactors) { - if (factor === "emailpassword") { - newTenantState.emailPasswordEnabled = true; - } - if ( - factor === "otp-phone" || - factor === "otp-email" || - factor === "link-phone" || - factor === "link-email" - ) { - newTenantState.passwordlessEnabled = true; - } - if (factor === "thirdparty") { - newTenantState.thirdPartyEnabled = true; - } + + // if (firstFactors !== null && firstFactors.length === 0) { + // if (body.requiredSecondaryFactors === undefined) { + // requiredSecondaryFactors = null; + // } + // } + + // if (newTenantState.emailPasswordEnabled === false && newTenantState.passwordlessEnabled === false && newTenantState.thirdPartyEnabled === false) { + // if (body.requiredSecondaryFactors === undefined) { + // requiredSecondaryFactors = null; + // } + // } + + newTenantState.firstFactors = firstFactors; + newTenantState.requiredSecondaryFactors = requiredSecondaryFactors; + + if (newTenantState.firstFactors !== null) { + for (const factor of newTenantState.firstFactors) { + if (factor === "emailpassword") { + newTenantState.emailPasswordEnabled = true; + } + if ( + factor === "otp-phone" || + factor === "otp-email" || + factor === "link-phone" || + factor === "link-email" + ) { + newTenantState.passwordlessEnabled = true; + } + if (factor === "thirdparty") { + newTenantState.thirdPartyEnabled = true; + } + } } - } - if (newTenantState.requiredSecondaryFactors !== null) { - for (const factor of newTenantState.requiredSecondaryFactors) { - if (factor === "emailpassword") { - newTenantState.emailPasswordEnabled = true; - } - if ( - factor === "otp-phone" || - factor === "otp-email" || - factor === "link-phone" || - factor === "link-email" - ) { - newTenantState.passwordlessEnabled = true; - } - if (factor === "thirdparty") { - newTenantState.thirdPartyEnabled = true; - } + if (newTenantState.requiredSecondaryFactors !== null) { + for (const factor of newTenantState.requiredSecondaryFactors) { + if (factor === "emailpassword") { + newTenantState.emailPasswordEnabled = true; + } + if ( + factor === "otp-phone" || + factor === "otp-email" || + factor === "link-phone" || + factor === "link-email" + ) { + newTenantState.passwordlessEnabled = true; + } + if (factor === "thirdparty") { + newTenantState.thirdPartyEnabled = true; + } + } } - } - return newTenantState; + return newTenantState; }; export const create_5 = (body) => { - let newTenantState; - let { tenantId } = body; - - if (tenantId === "public") { - newTenantState = { - tenantId, - emailPasswordEnabled: true, - passwordlessEnabled: true, - thirdPartyEnabled: true, - firstFactors: null, - requiredSecondaryFactors: null, - }; - } else { - newTenantState = { - tenantId, - emailPasswordEnabled: false, - passwordlessEnabled: false, - thirdPartyEnabled: false, - firstFactors: null, - requiredSecondaryFactors: null, - }; - } - - const { emailPasswordEnabled, passwordlessEnabled, thirdPartyEnabled } = body; - newTenantState = update_5( - { emailPasswordEnabled, passwordlessEnabled, thirdPartyEnabled }, - newTenantState - ); - const { firstFactors, requiredSecondaryFactors } = body; - newTenantState = update_5( - { firstFactors, requiredSecondaryFactors }, - newTenantState - ); - - return newTenantState; + let newTenantState; + let {tenantId} = body; + + if (tenantId === "public") { + newTenantState = { + tenantId, + emailPasswordEnabled: true, + passwordlessEnabled: true, + thirdPartyEnabled: true, + firstFactors: null, + requiredSecondaryFactors: null, + }; + } else { + newTenantState = { + tenantId, + emailPasswordEnabled: false, + passwordlessEnabled: false, + thirdPartyEnabled: false, + firstFactors: null, + requiredSecondaryFactors: null, + }; + } + + const {emailPasswordEnabled, passwordlessEnabled, thirdPartyEnabled} = body; + newTenantState = update_5( + {emailPasswordEnabled, passwordlessEnabled, thirdPartyEnabled}, + newTenantState + ); + const {firstFactors, requiredSecondaryFactors} = body; + newTenantState = update_5( + {firstFactors, requiredSecondaryFactors}, + newTenantState + ); + + return newTenantState; }; export const get_5 = (tenantState) => { - return { - emailPasswordEnabled: - tenantState.emailPasswordEnabled && - (tenantState.firstFactors === null || - tenantState.firstFactors.length > 0), - thirdPartyEnabled: - tenantState.thirdPartyEnabled && - (tenantState.firstFactors === null || - tenantState.firstFactors.length > 0), - passwordlessEnabled: - tenantState.passwordlessEnabled && - (tenantState.firstFactors === null || - tenantState.firstFactors.length > 0), - firstFactors: - tenantState.firstFactors !== null && tenantState.firstFactors.length === 0 - ? null - : tenantState.firstFactors, - requiredSecondaryFactors: tenantState.requiredSecondaryFactors, - }; + return { + emailPasswordEnabled: + tenantState.emailPasswordEnabled && + (tenantState.firstFactors === null || + tenantState.firstFactors.length > 0), + thirdPartyEnabled: + tenantState.thirdPartyEnabled && + (tenantState.firstFactors === null || + tenantState.firstFactors.length > 0), + passwordlessEnabled: + tenantState.passwordlessEnabled && + (tenantState.firstFactors === null || + tenantState.firstFactors.length > 0), + firstFactors: + tenantState.firstFactors !== null && tenantState.firstFactors.length === 0 + ? null + : tenantState.firstFactors, + requiredSecondaryFactors: tenantState.requiredSecondaryFactors, + }; }; export const cdi5CoreBehaviour = (tenantState) => { - let state = get_5(tenantState); - let res = ""; - - if (state.emailPasswordEnabled === false) { - res += "emailpassword APIs are blocked\n"; - } else { - res += "emailpassword APIs are allowed\n"; - } - - if (state.passwordlessEnabled === false) { - res += "passwordless APIs are blocked\n"; - } else { - res += "passwordless APIs are allowed\n"; - } - - if (state.thirdPartyEnabled === false) { - res += "thirdParty APIs are blocked\n"; - } else { - res += "thirdParty APIs are allowed\n"; - } - - return res; -}; - -export const backendCdi5Behaviour = (tenantState) => { - let state = get_5(tenantState); - - let res = ""; - - res += "firstFactors from core: "; - if (state.firstFactors === null) { - res += "✗\n"; - } else { - res += "✓\n"; - } + let state = get_5(tenantState); + let res = ""; - res += "enabled booleans in tenant: ✓\n"; - - res += "mfa init firstFactors: "; - if (state.firstFactors !== null) { - res += "✗\n"; - } else { - res += "✓\n"; - } - - res += "initialised recipes: "; - res += "✓\n"; - - res += "\nloginMethodsGET output: "; - - let out = { ...state }; - if (state.firstFactors === null) { - let firstFactors = [...allFirstFactors]; if (state.emailPasswordEnabled === false) { - firstFactors = firstFactors.filter( - (factor) => factor !== "emailpassword" - ); - } - if (state.passwordlessEnabled === false) { - firstFactors = firstFactors.filter((factor) => factor !== "otp-phone"); - firstFactors = firstFactors.filter((factor) => factor !== "otp-email"); - firstFactors = firstFactors.filter((factor) => factor !== "link-phone"); - firstFactors = firstFactors.filter((factor) => factor !== "link-email"); - } - if (state.thirdPartyEnabled === false) { - firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); - } - out.firstFactors = firstFactors; - } else { - let firstFactors = [...state.firstFactors]; - if (state.emailPasswordEnabled === false) { - firstFactors = firstFactors.filter( - (factor) => factor !== "emailpassword" - ); + res += "emailpassword APIs are blocked\n"; + } else { + res += "emailpassword APIs are allowed\n"; } + if (state.passwordlessEnabled === false) { - firstFactors = firstFactors.filter((factor) => factor !== "otp-phone"); - firstFactors = firstFactors.filter((factor) => factor !== "otp-email"); - firstFactors = firstFactors.filter((factor) => factor !== "link-phone"); - firstFactors = firstFactors.filter((factor) => factor !== "link-email"); + res += "passwordless APIs are blocked\n"; + } else { + res += "passwordless APIs are allowed\n"; } + if (state.thirdPartyEnabled === false) { - firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); + res += "thirdParty APIs are blocked\n"; + } else { + res += "thirdParty APIs are allowed\n"; } - out.firstFactors = firstFactors; - } - delete out.requiredSecondaryFactors; - res += JSON.stringify(out, null, 2).replaceAll('\\"', "'") + "\n"; - return res; + return res; }; -export const getCdi5FrontendLoginMethods = (tenantState) => { - let state = get_5(tenantState); +export const backendCdi5Behaviour = (tenantState) => { + let state = get_5(tenantState); - let firstFactors; - if (state.firstFactors === null) { - firstFactors = [...allFirstFactors]; - if (state.emailPasswordEnabled === false) { - firstFactors = firstFactors.filter( - (factor) => factor !== "emailpassword" - ); - } - if (state.passwordlessEnabled === false) { - firstFactors = firstFactors.filter((factor) => factor !== "otp-phone"); - firstFactors = firstFactors.filter((factor) => factor !== "otp-email"); - firstFactors = firstFactors.filter((factor) => factor !== "link-phone"); - firstFactors = firstFactors.filter((factor) => factor !== "link-email"); - } - if (state.thirdPartyEnabled === false) { - firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); + let res = ""; + + res += "firstFactors from core: "; + if (state.firstFactors === null) { + res += "✗\n"; + } else { + res += "✓\n"; } - } else { - firstFactors = [...state.firstFactors]; - if (state.emailPasswordEnabled === false) { - firstFactors = firstFactors.filter( - (factor) => factor !== "emailpassword" - ); + + res += "enabled booleans in tenant: ✓\n"; + + res += "mfa init firstFactors: "; + if (state.firstFactors !== null) { + res += "✗\n"; + } else { + res += "✓\n"; } - if (state.passwordlessEnabled === false) { - firstFactors = firstFactors.filter((factor) => factor !== "otp-phone"); - firstFactors = firstFactors.filter((factor) => factor !== "otp-email"); - firstFactors = firstFactors.filter((factor) => factor !== "link-phone"); - firstFactors = firstFactors.filter((factor) => factor !== "link-email"); + + res += "initialised recipes: "; + res += "✓\n"; + + res += "\nloginMethodsGET output: "; + + let out = {...state}; + if (state.firstFactors === null) { + let firstFactors = [...allFirstFactors]; + if (state.emailPasswordEnabled === false) { + firstFactors = firstFactors.filter( + (factor) => factor !== "emailpassword" + ); + } + if (state.passwordlessEnabled === false) { + firstFactors = firstFactors.filter((factor) => factor !== "otp-phone"); + firstFactors = firstFactors.filter((factor) => factor !== "otp-email"); + firstFactors = firstFactors.filter((factor) => factor !== "link-phone"); + firstFactors = firstFactors.filter((factor) => factor !== "link-email"); + } + if (state.thirdPartyEnabled === false) { + firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); + } + out.firstFactors = firstFactors; + } else { + let firstFactors = [...state.firstFactors]; + if (state.emailPasswordEnabled === false) { + firstFactors = firstFactors.filter( + (factor) => factor !== "emailpassword" + ); + } + if (state.passwordlessEnabled === false) { + firstFactors = firstFactors.filter((factor) => factor !== "otp-phone"); + firstFactors = firstFactors.filter((factor) => factor !== "otp-email"); + firstFactors = firstFactors.filter((factor) => factor !== "link-phone"); + firstFactors = firstFactors.filter((factor) => factor !== "link-email"); + } + if (state.thirdPartyEnabled === false) { + firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); + } + out.firstFactors = firstFactors; } - if (state.thirdPartyEnabled === false) { - firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); + delete out.requiredSecondaryFactors; + res += JSON.stringify(out, null, 2).replaceAll('\\"', "'") + "\n"; + + return res; +}; + +export const getCdi5FrontendLoginMethods = (tenantState) => { + let state = get_5(tenantState); + + let firstFactors; + if (state.firstFactors === null) { + firstFactors = [...allFirstFactors]; + if (state.emailPasswordEnabled === false) { + firstFactors = firstFactors.filter( + (factor) => factor !== "emailpassword" + ); + } + if (state.passwordlessEnabled === false) { + firstFactors = firstFactors.filter((factor) => factor !== "otp-phone"); + firstFactors = firstFactors.filter((factor) => factor !== "otp-email"); + firstFactors = firstFactors.filter((factor) => factor !== "link-phone"); + firstFactors = firstFactors.filter((factor) => factor !== "link-email"); + } + if (state.thirdPartyEnabled === false) { + firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); + } + } else { + firstFactors = [...state.firstFactors]; + if (state.emailPasswordEnabled === false) { + firstFactors = firstFactors.filter( + (factor) => factor !== "emailpassword" + ); + } + if (state.passwordlessEnabled === false) { + firstFactors = firstFactors.filter((factor) => factor !== "otp-phone"); + firstFactors = firstFactors.filter((factor) => factor !== "otp-email"); + firstFactors = firstFactors.filter((factor) => factor !== "link-phone"); + firstFactors = firstFactors.filter((factor) => factor !== "link-email"); + } + if (state.thirdPartyEnabled === false) { + firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); + } } - } - return firstFactors.length === 0 ? "none" : firstFactors.join(" "); + return firstFactors.length === 0 ? "none" : firstFactors.join(" "); }; export const frontendCdi5Behaviour = (tenantState) => { - let res = ""; + let res = ""; - res += "loginMethodsGET: "; - res += "✓\n"; + res += "loginMethodsGET: "; + res += "✓\n"; - res += "initialised recipes: "; - res += "✓\n"; + res += "initialised recipes: "; + res += "✓\n"; - res += "mfa init firstFactors: "; - res += "✗\n"; + res += "mfa init firstFactors: "; + res += "✗\n"; - res += "\n"; + res += "\n"; - res += "ui shows: " + getCdi5FrontendLoginMethods(tenantState) + "\n"; + res += "ui shows: " + getCdi5FrontendLoginMethods(tenantState) + "\n"; - return res; + return res; }; diff --git a/test-data/playground/src/cdi51.js b/test-data/playground/src/cdi51.js index 182500e76..41c363509 100644 --- a/test-data/playground/src/cdi51.js +++ b/test-data/playground/src/cdi51.js @@ -1,246 +1,246 @@ let allFirstFactors = [ - "emailpassword", - "otp-phone", - "otp-email", - "link-phone", - "link-email", - "thirdparty", + "emailpassword", + "otp-phone", + "otp-email", + "link-phone", + "link-email", + "thirdparty", ]; export const update_v2 = (body, currentState) => { - let newTenantState = { ...currentState, ...get_v2(currentState) }; + let newTenantState = {...currentState, ...get_v2(currentState)}; - if (body.firstFactors === undefined && body.requiredSecondaryFactors === undefined) { - return currentState; // no updates required - } - - if ( - currentState.emailPasswordEnabled === false && - currentState.passwordlessEnabled === false && - currentState.thirdPartyEnabled === false - ) { - newTenantState.firstFactors = []; - } - - newTenantState.emailPasswordEnabled = true; - newTenantState.passwordlessEnabled = true; - newTenantState.thirdPartyEnabled = true; - - if (body.firstFactors !== undefined) { - newTenantState.firstFactors = body.firstFactors; - - if ( - newTenantState.firstFactors === null || - newTenantState.firstFactors.includes("emailpassword") - ) { - newTenantState.emailPasswordEnabled = true; + if (body.firstFactors === undefined && body.requiredSecondaryFactors === undefined) { + return currentState; // no updates required } - if ( - newTenantState.firstFactors === null || - newTenantState.firstFactors.includes("otp-phone") || - newTenantState.firstFactors.includes("otp-email") || - newTenantState.firstFactors.includes("link-phone") || - newTenantState.firstFactors.includes("link-email") - ) { - newTenantState.passwordlessEnabled = true; - } - if ( - newTenantState.firstFactors === null || - newTenantState.firstFactors.includes("thirdparty") - ) { - newTenantState.thirdPartyEnabled = true; - } - } - if (body.requiredSecondaryFactors !== undefined) { - newTenantState.requiredSecondaryFactors = body.requiredSecondaryFactors; if ( - newTenantState.requiredSecondaryFactors !== null && - newTenantState.requiredSecondaryFactors.includes("emailpassword") + currentState.emailPasswordEnabled === false && + currentState.passwordlessEnabled === false && + currentState.thirdPartyEnabled === false ) { - newTenantState.emailPasswordEnabled = true; + newTenantState.firstFactors = []; } - if ( - newTenantState.requiredSecondaryFactors !== null && - (newTenantState.requiredSecondaryFactors.includes("otp-phone") || - newTenantState.requiredSecondaryFactors.includes("otp-email") || - newTenantState.requiredSecondaryFactors.includes("link-phone") || - newTenantState.requiredSecondaryFactors.includes("link-email")) - ) { - newTenantState.passwordlessEnabled = true; + + newTenantState.emailPasswordEnabled = true; + newTenantState.passwordlessEnabled = true; + newTenantState.thirdPartyEnabled = true; + + if (body.firstFactors !== undefined) { + newTenantState.firstFactors = body.firstFactors; + + if ( + newTenantState.firstFactors === null || + newTenantState.firstFactors.includes("emailpassword") + ) { + newTenantState.emailPasswordEnabled = true; + } + if ( + newTenantState.firstFactors === null || + newTenantState.firstFactors.includes("otp-phone") || + newTenantState.firstFactors.includes("otp-email") || + newTenantState.firstFactors.includes("link-phone") || + newTenantState.firstFactors.includes("link-email") + ) { + newTenantState.passwordlessEnabled = true; + } + if ( + newTenantState.firstFactors === null || + newTenantState.firstFactors.includes("thirdparty") + ) { + newTenantState.thirdPartyEnabled = true; + } } - if ( - newTenantState.requiredSecondaryFactors !== null && - newTenantState.requiredSecondaryFactors.includes("thirdparty") - ) { - newTenantState.thirdPartyEnabled = true; + if (body.requiredSecondaryFactors !== undefined) { + newTenantState.requiredSecondaryFactors = body.requiredSecondaryFactors; + + if ( + newTenantState.requiredSecondaryFactors !== null && + newTenantState.requiredSecondaryFactors.includes("emailpassword") + ) { + newTenantState.emailPasswordEnabled = true; + } + if ( + newTenantState.requiredSecondaryFactors !== null && + (newTenantState.requiredSecondaryFactors.includes("otp-phone") || + newTenantState.requiredSecondaryFactors.includes("otp-email") || + newTenantState.requiredSecondaryFactors.includes("link-phone") || + newTenantState.requiredSecondaryFactors.includes("link-email")) + ) { + newTenantState.passwordlessEnabled = true; + } + if ( + newTenantState.requiredSecondaryFactors !== null && + newTenantState.requiredSecondaryFactors.includes("thirdparty") + ) { + newTenantState.thirdPartyEnabled = true; + } } - } - // if (newTenantState.firstFactors !== null && newTenantState.firstFactors.length === 0) { - // if (body.requiredSecondaryFactors === undefined) { - // newTenantState.requiredSecondaryFactors = null; - // } - // } + // if (newTenantState.firstFactors !== null && newTenantState.firstFactors.length === 0) { + // if (body.requiredSecondaryFactors === undefined) { + // newTenantState.requiredSecondaryFactors = null; + // } + // } - return newTenantState; + return newTenantState; }; export const create_v2 = (body) => { - let newTenantState; - let { tenantId } = body; - - if (tenantId === "public") { - newTenantState = { - tenantId, - emailPasswordEnabled: true, - passwordlessEnabled: true, - thirdPartyEnabled: true, - firstFactors: null, - requiredSecondaryFactors: null, - }; - } else { - newTenantState = { - tenantId, - emailPasswordEnabled: true, - passwordlessEnabled: true, - thirdPartyEnabled: true, - firstFactors: [], - requiredSecondaryFactors: null, - }; - } + let newTenantState; + let {tenantId} = body; + + if (tenantId === "public") { + newTenantState = { + tenantId, + emailPasswordEnabled: true, + passwordlessEnabled: true, + thirdPartyEnabled: true, + firstFactors: null, + requiredSecondaryFactors: null, + }; + } else { + newTenantState = { + tenantId, + emailPasswordEnabled: true, + passwordlessEnabled: true, + thirdPartyEnabled: true, + firstFactors: [], + requiredSecondaryFactors: null, + }; + } - if (body.firstFactors !== undefined) { - newTenantState.firstFactors = body.firstFactors; - } - if (body.requiredSecondaryFactors !== undefined) { - newTenantState.requiredSecondaryFactors = body.requiredSecondaryFactors; - } + if (body.firstFactors !== undefined) { + newTenantState.firstFactors = body.firstFactors; + } + if (body.requiredSecondaryFactors !== undefined) { + newTenantState.requiredSecondaryFactors = body.requiredSecondaryFactors; + } - return update_v2(body, newTenantState); + return update_v2(body, newTenantState); }; export const get_v2 = (tenantState) => { - let firstFactors = tenantState.firstFactors; - if (firstFactors === null) { - if ( - tenantState.emailPasswordEnabled === false || - tenantState.passwordlessEnabled === false || - tenantState.thirdPartyEnabled === false - ) { - firstFactors = [...allFirstFactors]; - - if (tenantState.emailPasswordEnabled === false) { - firstFactors = firstFactors.filter( - (factor) => factor !== "emailpassword" - ); - } - if (tenantState.passwordlessEnabled === false) { - firstFactors = firstFactors.filter((factor) => factor !== "otp-phone"); - firstFactors = firstFactors.filter((factor) => factor !== "otp-email"); - firstFactors = firstFactors.filter((factor) => factor !== "link-phone"); - firstFactors = firstFactors.filter((factor) => factor !== "link-email"); - } - if (tenantState.thirdPartyEnabled === false) { - firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); - } + let firstFactors = tenantState.firstFactors; + if (firstFactors === null) { + if ( + tenantState.emailPasswordEnabled === false || + tenantState.passwordlessEnabled === false || + tenantState.thirdPartyEnabled === false + ) { + firstFactors = [...allFirstFactors]; + + if (tenantState.emailPasswordEnabled === false) { + firstFactors = firstFactors.filter( + (factor) => factor !== "emailpassword" + ); + } + if (tenantState.passwordlessEnabled === false) { + firstFactors = firstFactors.filter((factor) => factor !== "otp-phone"); + firstFactors = firstFactors.filter((factor) => factor !== "otp-email"); + firstFactors = firstFactors.filter((factor) => factor !== "link-phone"); + firstFactors = firstFactors.filter((factor) => factor !== "link-email"); + } + if (tenantState.thirdPartyEnabled === false) { + firstFactors = firstFactors.filter((factor) => factor !== "thirdparty"); + } + } } - } - return { - firstFactors: firstFactors, - requiredSecondaryFactors: tenantState.requiredSecondaryFactors, - }; + return { + firstFactors: firstFactors, + requiredSecondaryFactors: tenantState.requiredSecondaryFactors, + }; }; export const cdi51CoreBehaviour = (tenantState) => { - let res = "Core does not block any of the APIs"; - return res; + let res = "Core does not block any of the APIs"; + return res; }; export const backendCdi51Behaviour = (tenantState) => { - let state = get_v2(tenantState); + let state = get_v2(tenantState); - let res = ""; + let res = ""; - res += "firstFactors from core: "; - if (state.firstFactors === null) { - res += "✗\n"; - } else { - res += "✓\n"; - } + res += "firstFactors from core: "; + if (state.firstFactors === null) { + res += "✗\n"; + } else { + res += "✓\n"; + } - res += "enabled booleans in tenant: ✗\n"; + res += "enabled booleans in tenant: ✗\n"; - res += "mfa init firstFactors: "; - if (state.firstFactors !== null) { - res += "✗\n"; - } else { + res += "mfa init firstFactors: "; + if (state.firstFactors !== null) { + res += "✗\n"; + } else { + res += "✓\n"; + } + + res += "initialised recipes: "; res += "✓\n"; - } - - res += "initialised recipes: "; - res += "✓\n"; - - res += "\n"; - - res += "loginMethodsGET output: "; - - let out = { - emailPasswordEnabled: - state.firstFactors === null || - state.firstFactors.includes("emailpassword"), - passwordlessEnabled: - state.firstFactors === null || - state.firstFactors.includes("otp-phone") || - state.firstFactors.includes("otp-email") || - state.firstFactors.includes("link-phone") || - state.firstFactors.includes("link-email"), - thirdPartyEnabled: - state.firstFactors === null || state.firstFactors.includes("thirdparty"), - }; - if (state.firstFactors === null) { - out.firstFactors = [...allFirstFactors]; - } else { - if (state.firstFactors.length === 0) { - out.firstFactors = []; + + res += "\n"; + + res += "loginMethodsGET output: "; + + let out = { + emailPasswordEnabled: + state.firstFactors === null || + state.firstFactors.includes("emailpassword"), + passwordlessEnabled: + state.firstFactors === null || + state.firstFactors.includes("otp-phone") || + state.firstFactors.includes("otp-email") || + state.firstFactors.includes("link-phone") || + state.firstFactors.includes("link-email"), + thirdPartyEnabled: + state.firstFactors === null || state.firstFactors.includes("thirdparty"), + }; + if (state.firstFactors === null) { + out.firstFactors = [...allFirstFactors]; } else { - out.firstFactors = state.firstFactors; + if (state.firstFactors.length === 0) { + out.firstFactors = []; + } else { + out.firstFactors = state.firstFactors; + } } - } - delete out.requiredSecondaryFactors; - res += JSON.stringify(out, null, 2).replaceAll('\\"', "'") + "\n"; + delete out.requiredSecondaryFactors; + res += JSON.stringify(out, null, 2).replaceAll('\\"', "'") + "\n"; - return res; + return res; }; export const getv2FrontendLoginMethods = (tenantState) => { - let state = get_v2(tenantState); + let state = get_v2(tenantState); - let firstFactors; - if (state.firstFactors === null) { - firstFactors = [...allFirstFactors]; - } else { - firstFactors = [...state.firstFactors]; - } + let firstFactors; + if (state.firstFactors === null) { + firstFactors = [...allFirstFactors]; + } else { + firstFactors = [...state.firstFactors]; + } - return firstFactors.length === 0 ? "none" : firstFactors.join(" "); + return firstFactors.length === 0 ? "none" : firstFactors.join(" "); }; export const frontendCdi51Behaviour = (tenantState) => { - let res = ""; + let res = ""; - res += "loginMethodsGET: "; - res += "✓\n"; + res += "loginMethodsGET: "; + res += "✓\n"; - res += "initialised recipes: "; - res += "✓\n"; + res += "initialised recipes: "; + res += "✓\n"; - res += "mfa init firstFactors: "; - res += "✗\n"; + res += "mfa init firstFactors: "; + res += "✗\n"; - res += "\n"; + res += "\n"; - res += "ui shows: " + getv2FrontendLoginMethods(tenantState) + "\n"; + res += "ui shows: " + getv2FrontendLoginMethods(tenantState) + "\n"; - return res; + return res; }; diff --git a/test-data/playground/src/index.css b/test-data/playground/src/index.css index 84b4e2b60..2bec6a020 100644 --- a/test-data/playground/src/index.css +++ b/test-data/playground/src/index.css @@ -1,91 +1,91 @@ body { - margin: 0; - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; - padding: 2rem; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + padding: 2rem; } code { - font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', + font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; } .row { - display: flex; - justify-content: space-between; + display: flex; + justify-content: space-between; } .row > div { - width: 32%; + width: 32%; } textarea { - display: block; - width: 100%; - height: 10rem; + display: block; + width: 100%; + height: 10rem; } button { - background-color: white; - color: black; - border: 2px solid #008CBA; - padding: 0.5rem 1rem; - text-align: center; - text-decoration: none; - display: inline-block; - font-size: 16px; - margin: 4px 2px; - cursor: pointer; - transition-duration: 0.2s; - border-radius: 4px; + background-color: white; + color: black; + border: 2px solid #008CBA; + padding: 0.5rem 1rem; + text-align: center; + text-decoration: none; + display: inline-block; + font-size: 16px; + margin: 4px 2px; + cursor: pointer; + transition-duration: 0.2s; + border-radius: 4px; } button:hover { - border: 2px solid #008CBA; - background-color: #008CBA; /* Blue */ - color: white; + border: 2px solid #008CBA; + background-color: #008CBA; /* Blue */ + color: white; } button:active { - transform: translateY(2px); + transform: translateY(2px); } span.clickable { - cursor: pointer; - color: #008CBA; - display: inline-block; - margin-left: 0.25rem; - padding: 0.1rem 0.25rem; - border: #008CBA 1px solid; - border-radius: 4px; - transition: all 0.2s; - font-size: 0.85rem; + cursor: pointer; + color: #008CBA; + display: inline-block; + margin-left: 0.25rem; + padding: 0.1rem 0.25rem; + border: #008CBA 1px solid; + border-radius: 4px; + transition: all 0.2s; + font-size: 0.85rem; } span.clickable:hover { - background-color: #008CBA; - color: #eee; + background-color: #008CBA; + color: #eee; } span.clickable:active { - transform: translateY(2px); + transform: translateY(2px); } .shortcuts { } .shortcuts p { - font-size: 0.85rem; - margin: 0.25rem 0; + font-size: 0.85rem; + margin: 0.25rem 0; } pre { - white-space: pre-wrap; - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', + white-space: pre-wrap; + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; - font-size: 0.85rem; + font-size: 0.85rem; } diff --git a/test-data/playground/src/index.js b/test-data/playground/src/index.js index d563c0fb1..f4fc0c5bd 100644 --- a/test-data/playground/src/index.js +++ b/test-data/playground/src/index.js @@ -6,9 +6,9 @@ import reportWebVitals from './reportWebVitals'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( - - - + + + ); // If you want to start measuring performance in your app, pass a function diff --git a/test-data/playground/src/logo.svg b/test-data/playground/src/logo.svg index 9dfc1c058..63a2ad5f3 100644 --- a/test-data/playground/src/logo.svg +++ b/test-data/playground/src/logo.svg @@ -1 +1,7 @@ - \ No newline at end of file + + + + + + + \ No newline at end of file diff --git a/test-data/playground/src/reportWebVitals.js b/test-data/playground/src/reportWebVitals.js index 5253d3ad9..14ba227b3 100644 --- a/test-data/playground/src/reportWebVitals.js +++ b/test-data/playground/src/reportWebVitals.js @@ -1,13 +1,13 @@ const reportWebVitals = onPerfEntry => { - if (onPerfEntry && onPerfEntry instanceof Function) { - import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { - getCLS(onPerfEntry); - getFID(onPerfEntry); - getFCP(onPerfEntry); - getLCP(onPerfEntry); - getTTFB(onPerfEntry); - }); - } + if (onPerfEntry && onPerfEntry instanceof Function) { + import('web-vitals').then(({getCLS, getFID, getFCP, getLCP, getTTFB}) => { + getCLS(onPerfEntry); + getFID(onPerfEntry); + getFCP(onPerfEntry); + getLCP(onPerfEntry); + getTTFB(onPerfEntry); + }); + } }; export default reportWebVitals; diff --git a/test-data/playground/src/tests-copy.js b/test-data/playground/src/tests-copy.js index a8b35b2ff..6c9c90c16 100644 --- a/test-data/playground/src/tests-copy.js +++ b/test-data/playground/src/tests-copy.js @@ -4,150 +4,150 @@ // verify ui state is same across all versions at any point in time // repeat everything 2 lakh times -import { create_4, getCdi4FrontendLoginMethods, update_4 } from "./cdi4"; -import { create_5, getCdi5FrontendLoginMethods, update_5 } from "./cdi5"; -import { create_v2, getv2FrontendLoginMethods, update_v2 } from "./cdi51"; +import {create_4, getCdi4FrontendLoginMethods, update_4} from "./cdi4"; +import {create_5, getCdi5FrontendLoginMethods, update_5} from "./cdi5"; +import {create_v2, getv2FrontendLoginMethods, update_v2} from "./cdi51"; function getRandomElement(arr) { - if (arr.length === 0) { - return undefined; // Handle empty array - } - const randomIndex = Math.floor(Math.random() * arr.length); - return arr[randomIndex]; + if (arr.length === 0) { + return undefined; // Handle empty array + } + const randomIndex = Math.floor(Math.random() * arr.length); + return arr[randomIndex]; } function createRandomTenant() { - let v = getRandomElement(["4", "5", "v2"]); - let b = {}; - - b.tenantId = getRandomElement(["public", "t1"]); - - let tenantState; - if (v === "4") { - b.emailPasswordEnabled = getRandomElement([undefined, true, false]); - b.passwordlessEnabled = getRandomElement([undefined, true, false]); - b.thirdPartyEnabled = getRandomElement([undefined, true, false]); - tenantState = create_4(b); - } else if (v === "5") { - b.emailPasswordEnabled = getRandomElement([undefined, true, false]); - b.passwordlessEnabled = getRandomElement([undefined, true, false]); - b.thirdPartyEnabled = getRandomElement([undefined, true, false]); - b.firstFactors = getRandomElement([undefined, null, ["emailpassword"]]); - b.requiredSecondaryFactors = getRandomElement([ - undefined, - null, - ["otp-phone"], - ]); - tenantState = create_5(b); - } else if (v === "v2") { - b.firstFactors = getRandomElement([undefined, null, [], ["emailpassword"]]); - b.requiredSecondaryFactors = getRandomElement([ - undefined, - null, - ["otp-phone"], - ]); - tenantState = create_v2(b); - } - - return { - tenantState, - step: { - v, - b, - }, - }; + let v = getRandomElement(["4", "5", "v2"]); + let b = {}; + + b.tenantId = getRandomElement(["public", "t1"]); + + let tenantState; + if (v === "4") { + b.emailPasswordEnabled = getRandomElement([undefined, true, false]); + b.passwordlessEnabled = getRandomElement([undefined, true, false]); + b.thirdPartyEnabled = getRandomElement([undefined, true, false]); + tenantState = create_4(b); + } else if (v === "5") { + b.emailPasswordEnabled = getRandomElement([undefined, true, false]); + b.passwordlessEnabled = getRandomElement([undefined, true, false]); + b.thirdPartyEnabled = getRandomElement([undefined, true, false]); + b.firstFactors = getRandomElement([undefined, null, ["emailpassword"]]); + b.requiredSecondaryFactors = getRandomElement([ + undefined, + null, + ["otp-phone"], + ]); + tenantState = create_5(b); + } else if (v === "v2") { + b.firstFactors = getRandomElement([undefined, null, [], ["emailpassword"]]); + b.requiredSecondaryFactors = getRandomElement([ + undefined, + null, + ["otp-phone"], + ]); + tenantState = create_v2(b); + } + + return { + tenantState, + step: { + v, + b, + }, + }; } function applyRandomUpdate(tenantState) { - let v = getRandomElement(["4", "5", "v2"]); - let b = {}; - - b.tenantId = getRandomElement(["public", "t1"]); - - if (v === "4") { - b.emailPasswordEnabled = getRandomElement([undefined, true, false]); - b.passwordlessEnabled = getRandomElement([undefined, true, false]); - b.thirdPartyEnabled = getRandomElement([undefined, true, false]); - tenantState = update_4(b, tenantState); - } else if (v === "5") { - b.emailPasswordEnabled = getRandomElement([undefined, true, false]); - b.passwordlessEnabled = getRandomElement([undefined, true, false]); - b.thirdPartyEnabled = getRandomElement([undefined, true, false]); - b.firstFactors = getRandomElement([undefined, null, ["emailpassword"]]); - b.requiredSecondaryFactors = getRandomElement([ - undefined, - null, - ["otp-phone"], - ]); - tenantState = update_5(b, tenantState); - } else if (v === "v2") { - b.firstFactors = getRandomElement([undefined, null, [], ["emailpassword"]]); - b.requiredSecondaryFactors = getRandomElement([ - undefined, - null, - ["otp-phone"], - ]); - tenantState = update_v2(b, tenantState); - } - - return { - tenantState, - step: { - v, - b, - }, - }; + let v = getRandomElement(["4", "5", "v2"]); + let b = {}; + + b.tenantId = getRandomElement(["public", "t1"]); + + if (v === "4") { + b.emailPasswordEnabled = getRandomElement([undefined, true, false]); + b.passwordlessEnabled = getRandomElement([undefined, true, false]); + b.thirdPartyEnabled = getRandomElement([undefined, true, false]); + tenantState = update_4(b, tenantState); + } else if (v === "5") { + b.emailPasswordEnabled = getRandomElement([undefined, true, false]); + b.passwordlessEnabled = getRandomElement([undefined, true, false]); + b.thirdPartyEnabled = getRandomElement([undefined, true, false]); + b.firstFactors = getRandomElement([undefined, null, ["emailpassword"]]); + b.requiredSecondaryFactors = getRandomElement([ + undefined, + null, + ["otp-phone"], + ]); + tenantState = update_5(b, tenantState); + } else if (v === "v2") { + b.firstFactors = getRandomElement([undefined, null, [], ["emailpassword"]]); + b.requiredSecondaryFactors = getRandomElement([ + undefined, + null, + ["otp-phone"], + ]); + tenantState = update_v2(b, tenantState); + } + + return { + tenantState, + step: { + v, + b, + }, + }; } function doTest() { - let steps = []; - let currentState; - { - let { tenantState, step } = createRandomTenant(); - steps.push(step); - currentState = tenantState; - } - - for (let uId = 0; uId < 10; uId++) { - let { tenantState, step } = applyRandomUpdate(currentState); - steps.push(step); - currentState = tenantState; - - let ui4 = getCdi4FrontendLoginMethods(currentState) - .trim() - .split(" ") - .sort() - .join(" "); - let ui5 = getCdi5FrontendLoginMethods(currentState) - .trim() - .split(" ") - .sort() - .join(" "); - let uiv2 = getv2FrontendLoginMethods(currentState) - .trim() - .split(" ") - .sort() - .join(" "); - - if (ui4 !== ui5 || ui5 !== uiv2 || ui4 !== uiv2) { - console.log("Mismatch found"); - console.log("UI in CDI 4", ui4); - console.log("UI in CDI 5", ui5); - console.log("UI in CDI v2", uiv2); - console.log("State", currentState); - console.log("Steps", steps); - throw new Error("Mismatch found"); + let steps = []; + let currentState; + { + let {tenantState, step} = createRandomTenant(); + steps.push(step); + currentState = tenantState; + } + + for (let uId = 0; uId < 10; uId++) { + let {tenantState, step} = applyRandomUpdate(currentState); + steps.push(step); + currentState = tenantState; + + let ui4 = getCdi4FrontendLoginMethods(currentState) + .trim() + .split(" ") + .sort() + .join(" "); + let ui5 = getCdi5FrontendLoginMethods(currentState) + .trim() + .split(" ") + .sort() + .join(" "); + let uiv2 = getv2FrontendLoginMethods(currentState) + .trim() + .split(" ") + .sort() + .join(" "); + + if (ui4 !== ui5 || ui5 !== uiv2 || ui4 !== uiv2) { + console.log("Mismatch found"); + console.log("UI in CDI 4", ui4); + console.log("UI in CDI 5", ui5); + console.log("UI in CDI v2", uiv2); + console.log("State", currentState); + console.log("Steps", steps); + throw new Error("Mismatch found"); + } } - } } export function runTests() { - for (let tId = 0; tId < 2000000; tId++) { - doTest(); + for (let tId = 0; tId < 2000000; tId++) { + doTest(); - if (tId % 1000 === 999) { - console.log(tId + 1, "tests done"); + if (tId % 1000 === 999) { + console.log(tId + 1, "tests done"); + } } - } - console.log("All tests passed!!!!") + console.log("All tests passed!!!!") } diff --git a/test-data/playground/src/tests.js b/test-data/playground/src/tests.js index a42eff315..2a6cecc42 100644 --- a/test-data/playground/src/tests.js +++ b/test-data/playground/src/tests.js @@ -4,241 +4,241 @@ // verify ui state is same across all versions at any point in time // repeat everything 2 lakh times -import { create_4, getCdi4FrontendLoginMethods, get_4, update_4 } from "./cdi4"; -import { create_5, getCdi5FrontendLoginMethods, get_5, update_5 } from "./cdi5"; +import {create_4, getCdi4FrontendLoginMethods, get_4, update_4} from "./cdi4"; +import {create_5, getCdi5FrontendLoginMethods, get_5, update_5} from "./cdi5"; import * as deepcopy from 'deepcopy'; import { - create_v2, - get_v2, - getv2FrontendLoginMethods, - update_v2, + create_v2, + get_v2, + getv2FrontendLoginMethods, + update_v2, } from "./cdi51"; const testCases = { - 4: [ - [{}, { emailPasswordEnabled: true }, { emailPasswordEnabled: false }], - [{}, { passwordlessEnabled: true }, { passwordlessEnabled: false }], - ], - 5: [ - [{}, { emailPasswordEnabled: true }, { emailPasswordEnabled: false }], - [{}, { passwordlessEnabled: true }, { passwordlessEnabled: false }], - [ - {}, - { firstFactors: null }, - { firstFactors: ["emailpassword"] }, - { firstFactors: ["otp-phone"] }, - { firstFactors: ["emailpassword", "otp-phone"] }, - { firstFactors: ["emailpassword", "custom"] }, + 4: [ + [{}, {emailPasswordEnabled: true}, {emailPasswordEnabled: false}], + [{}, {passwordlessEnabled: true}, {passwordlessEnabled: false}], ], - [ - {}, - { requiredSecondaryFactors: null }, - { requiredSecondaryFactors: ["emailpassword"] }, - { requiredSecondaryFactors: ["otp-phone"] }, - { requiredSecondaryFactors: ["emailpassword", "otp-phone"] }, - { requiredSecondaryFactors: ["emailpassword", "custom"] }, + 5: [ + [{}, {emailPasswordEnabled: true}, {emailPasswordEnabled: false}], + [{}, {passwordlessEnabled: true}, {passwordlessEnabled: false}], + [ + {}, + {firstFactors: null}, + {firstFactors: ["emailpassword"]}, + {firstFactors: ["otp-phone"]}, + {firstFactors: ["emailpassword", "otp-phone"]}, + {firstFactors: ["emailpassword", "custom"]}, + ], + [ + {}, + {requiredSecondaryFactors: null}, + {requiredSecondaryFactors: ["emailpassword"]}, + {requiredSecondaryFactors: ["otp-phone"]}, + {requiredSecondaryFactors: ["emailpassword", "otp-phone"]}, + {requiredSecondaryFactors: ["emailpassword", "custom"]}, + ], ], - ], - v2: [ - [ - {}, - { firstFactors: null }, - { firstFactors: [] }, - { firstFactors: ["emailpassword"] }, - { firstFactors: ["otp-phone"] }, - { firstFactors: ["emailpassword", "otp-phone"] }, - { firstFactors: ["emailpassword", "custom"] }, + v2: [ + [ + {}, + {firstFactors: null}, + {firstFactors: []}, + {firstFactors: ["emailpassword"]}, + {firstFactors: ["otp-phone"]}, + {firstFactors: ["emailpassword", "otp-phone"]}, + {firstFactors: ["emailpassword", "custom"]}, + ], + [ + {}, + {requiredSecondaryFactors: null}, + {requiredSecondaryFactors: ["emailpassword"]}, + {requiredSecondaryFactors: ["otp-phone"]}, + {requiredSecondaryFactors: ["emailpassword", "otp-phone"]}, + {requiredSecondaryFactors: ["emailpassword", "custom"]}, + ], ], - [ - {}, - { requiredSecondaryFactors: null }, - { requiredSecondaryFactors: ["emailpassword"] }, - { requiredSecondaryFactors: ["otp-phone"] }, - { requiredSecondaryFactors: ["emailpassword", "otp-phone"] }, - { requiredSecondaryFactors: ["emailpassword", "custom"] }, - ], - ], }; function generateCombinations(arrayOfArrays) { - const results = []; + const results = []; - function combine(current, index) { - if (index === arrayOfArrays.length) { - results.push(Object.assign({}, ...current)); - return; - } + function combine(current, index) { + if (index === arrayOfArrays.length) { + results.push(Object.assign({}, ...current)); + return; + } - for (let obj of arrayOfArrays[index]) { - combine([...current, obj], index + 1); + for (let obj of arrayOfArrays[index]) { + combine([...current, obj], index + 1); + } } - } - combine([], 0); - return results; + combine([], 0); + return results; } function checkIfInvalid(body) { - if (body.emailPasswordEnabled === false) { - if (body.firstFactors !== undefined && body.firstFactors !== null && body.firstFactors.includes("emailpassword")) { - return true; - } - if (body.requiredSecondaryFactors !== undefined && body.requiredSecondaryFactors !== null && body.requiredSecondaryFactors.includes("emailpassword")) { - return true; + if (body.emailPasswordEnabled === false) { + if (body.firstFactors !== undefined && body.firstFactors !== null && body.firstFactors.includes("emailpassword")) { + return true; + } + if (body.requiredSecondaryFactors !== undefined && body.requiredSecondaryFactors !== null && body.requiredSecondaryFactors.includes("emailpassword")) { + return true; + } } - } - if (body.passwordlessEnabled === false) { - if (body.firstFactors !== undefined && body.firstFactors !== null && (body.firstFactors.includes("otp-phone") || body.firstFactors.includes("otp-email") || body.firstFactors.includes("link-phone") || body.firstFactors.includes("link-email"))) { - return true; - } - if (body.requiredSecondaryFactors !== undefined && body.requiredSecondaryFactors !== null && (body.requiredSecondaryFactors.includes("otp-phone") || body.requiredSecondaryFactors.includes("otp-email") || body.requiredSecondaryFactors.includes("link-phone") || body.requiredSecondaryFactors.includes("link-email"))) { - return true; + if (body.passwordlessEnabled === false) { + if (body.firstFactors !== undefined && body.firstFactors !== null && (body.firstFactors.includes("otp-phone") || body.firstFactors.includes("otp-email") || body.firstFactors.includes("link-phone") || body.firstFactors.includes("link-email"))) { + return true; + } + if (body.requiredSecondaryFactors !== undefined && body.requiredSecondaryFactors !== null && (body.requiredSecondaryFactors.includes("otp-phone") || body.requiredSecondaryFactors.includes("otp-email") || body.requiredSecondaryFactors.includes("link-phone") || body.requiredSecondaryFactors.includes("link-email"))) { + return true; + } } - } - if (body.thirdPartyEnabled === false) { - if (body.firstFactors !== undefined && body.firstFactors !== null && body.firstFactors.includes("thirdparty")) { - return true; - } - if (body.requiredSecondaryFactors !== undefined && body.requiredSecondaryFactors !== null && body.requiredSecondaryFactors.includes("thirdparty")) { - return true; + if (body.thirdPartyEnabled === false) { + if (body.firstFactors !== undefined && body.firstFactors !== null && body.firstFactors.includes("thirdparty")) { + return true; + } + if (body.requiredSecondaryFactors !== undefined && body.requiredSecondaryFactors !== null && body.requiredSecondaryFactors.includes("thirdparty")) { + return true; + } } - } - // if (body.firstFactors !== undefined && body.firstFactors !== null && body.firstFactors.length === 0) { - // if (body.requiredSecondaryFactors !== undefined && body.requiredSecondaryFactors !== null) { - // return true; - // } - // } + // if (body.firstFactors !== undefined && body.firstFactors !== null && body.firstFactors.length === 0) { + // if (body.requiredSecondaryFactors !== undefined && body.requiredSecondaryFactors !== null) { + // return true; + // } + // } - return false; + return false; } function doTest() { - let versions = ["4", "5", "v2"]; - let tenantIds = ["public", "t1"]; - let versionCombinations = {}; - for (let v of versions) { - versionCombinations[v] = generateCombinations(testCases[v]); - } - - let cases = []; - - for (const tenantId of tenantIds) { - for (const cv of versions) { - for (const uv of versions) { - const cbodies = versionCombinations[cv]; - const ubodies = versionCombinations[uv]; - for (const cbody of cbodies) { - for (const ubody of ubodies) { - let tenantState; - if (cv === "4") { - tenantState = create_4({ ...deepcopy(cbody), tenantId }); - } else if (cv === "5") { - tenantState = create_5({ ...deepcopy(cbody), tenantId }); - } else if (cv === "v2") { - tenantState = create_v2({ ...deepcopy(cbody), tenantId }); - } - - if (uv === "4") { - tenantState = update_4({...deepcopy(ubody)}, tenantState); - } else if (uv === "5") { - tenantState = update_5({...deepcopy(ubody)}, tenantState); - } else if (uv === "v2") { - tenantState = update_v2({...deepcopy(ubody)}, tenantState); - } + let versions = ["4", "5", "v2"]; + let tenantIds = ["public", "t1"]; + let versionCombinations = {}; + for (let v of versions) { + versionCombinations[v] = generateCombinations(testCases[v]); + } - let invalid = false; - // if (tenantState.firstFactors !== null && tenantState.firstFactors.length === 0) { - // if (tenantState.requiredSecondaryFactors !== null) { - // invalid = true; - // } - // } - - cases.push({ - tenantId, - cv, - uv, - cbody, - ubody, - tenantState, - g4: get_4(tenantState), - g5: get_5(tenantState), - gv2: get_v2(tenantState), - invalidConfig: invalid || checkIfInvalid(cbody) || checkIfInvalid(ubody), - }); - - let ui4 = getCdi4FrontendLoginMethods(tenantState) - .trim() - .split(" ") - .sort() - .join(" "); - let ui5 = getCdi5FrontendLoginMethods(tenantState) - .trim() - .split(" ") - .sort() - .join(" "); - let uiv2 = getv2FrontendLoginMethods(tenantState) - .trim() - .split(" ") - .sort() - .join(" "); - - if (ui4 !== ui5 || ui5 !== uiv2 || ui4 !== uiv2) { - if (ui5 === uiv2) { - let ok = true - for (const f of ui5.split(' ')) { - if (f === 'custom') { - continue; - } - if (!ui4.includes(f)) { - ok = false - } - } - if (ok) { - continue; + let cases = []; + + for (const tenantId of tenantIds) { + for (const cv of versions) { + for (const uv of versions) { + const cbodies = versionCombinations[cv]; + const ubodies = versionCombinations[uv]; + for (const cbody of cbodies) { + for (const ubody of ubodies) { + let tenantState; + if (cv === "4") { + tenantState = create_4({...deepcopy(cbody), tenantId}); + } else if (cv === "5") { + tenantState = create_5({...deepcopy(cbody), tenantId}); + } else if (cv === "v2") { + tenantState = create_v2({...deepcopy(cbody), tenantId}); + } + + if (uv === "4") { + tenantState = update_4({...deepcopy(ubody)}, tenantState); + } else if (uv === "5") { + tenantState = update_5({...deepcopy(ubody)}, tenantState); + } else if (uv === "v2") { + tenantState = update_v2({...deepcopy(ubody)}, tenantState); + } + + let invalid = false; + // if (tenantState.firstFactors !== null && tenantState.firstFactors.length === 0) { + // if (tenantState.requiredSecondaryFactors !== null) { + // invalid = true; + // } + // } + + cases.push({ + tenantId, + cv, + uv, + cbody, + ubody, + tenantState, + g4: get_4(tenantState), + g5: get_5(tenantState), + gv2: get_v2(tenantState), + invalidConfig: invalid || checkIfInvalid(cbody) || checkIfInvalid(ubody), + }); + + let ui4 = getCdi4FrontendLoginMethods(tenantState) + .trim() + .split(" ") + .sort() + .join(" "); + let ui5 = getCdi5FrontendLoginMethods(tenantState) + .trim() + .split(" ") + .sort() + .join(" "); + let uiv2 = getv2FrontendLoginMethods(tenantState) + .trim() + .split(" ") + .sort() + .join(" "); + + if (ui4 !== ui5 || ui5 !== uiv2 || ui4 !== uiv2) { + if (ui5 === uiv2) { + let ok = true + for (const f of ui5.split(' ')) { + if (f === 'custom') { + continue; + } + if (!ui4.includes(f)) { + ok = false + } + } + if (ok) { + continue; + } + } + console.log("Mismatch found"); + console.log("UI in CDI 4", ui4); + console.log("UI in CDI 5", ui5); + console.log("UI in CDI v2", uiv2); + throw new Error("Mismatch found"); + } + } } - } - console.log("Mismatch found"); - console.log("UI in CDI 4", ui4); - console.log("UI in CDI 5", ui5); - console.log("UI in CDI v2", uiv2); - throw new Error("Mismatch found"); } - } } - } } - } - console.log(cases); - downloadArrayAsJsonLines(cases, "cdi-tests"); + console.log(cases); + downloadArrayAsJsonLines(cases, "cdi-tests"); } function downloadArrayAsJsonLines(exportArray, exportName) { - // Convert each object to JSON and join with newlines - const jsonLines = exportArray.map((obj) => JSON.stringify(obj)).join("\n"); + // Convert each object to JSON and join with newlines + const jsonLines = exportArray.map((obj) => JSON.stringify(obj)).join("\n"); - // Create a Blob with the JSON lines - const blob = new Blob([jsonLines], { type: "application/x-jsonlines" }); + // Create a Blob with the JSON lines + const blob = new Blob([jsonLines], {type: "application/x-jsonlines"}); - // Create a download link - const url = URL.createObjectURL(blob); - const downloadLink = document.createElement("a"); - downloadLink.href = url; - downloadLink.download = exportName + ".jsonl"; + // Create a download link + const url = URL.createObjectURL(blob); + const downloadLink = document.createElement("a"); + downloadLink.href = url; + downloadLink.download = exportName + ".jsonl"; - // Append to the document, trigger click, and remove - document.body.appendChild(downloadLink); - downloadLink.click(); - document.body.removeChild(downloadLink); + // Append to the document, trigger click, and remove + document.body.appendChild(downloadLink); + downloadLink.click(); + document.body.removeChild(downloadLink); - // Clean up the URL object - URL.revokeObjectURL(url); + // Clean up the URL object + URL.revokeObjectURL(url); } export function runTests() { - doTest(); + doTest(); } diff --git a/test-data/tenant-cdi-test-cases_6.json b/test-data/tenant-cdi-test-cases_6.json index d87a05538..9b740410b 100644 --- a/test-data/tenant-cdi-test-cases_6.json +++ b/test-data/tenant-cdi-test-cases_6.json @@ -1 +1,68 @@ -{"tenantId":"t1","cv":"v2","uv":"v2","cbody":{"firstFactors":["emailpassword","custom"],"requiredSecondaryFactors":["emailpassword","custom"]},"ubody":{"firstFactors":["emailpassword","custom"],"requiredSecondaryFactors":["emailpassword","custom"]},"tenantState":{"tenantId":"t1","emailPasswordEnabled":true,"passwordlessEnabled":true,"thirdPartyEnabled":true,"firstFactors":["emailpassword","custom"],"requiredSecondaryFactors":["emailpassword","custom"]},"g4":{"emailPasswordEnabled":true,"thirdPartyEnabled":false,"passwordlessEnabled":false},"g5":{"emailPasswordEnabled":true,"thirdPartyEnabled":true,"passwordlessEnabled":true,"firstFactors":["emailpassword","custom"],"requiredSecondaryFactors":["emailpassword","custom"]},"gv2":{"firstFactors":["emailpassword","custom"],"requiredSecondaryFactors":["emailpassword","custom"]},"invalidConfig":false} \ No newline at end of file +{ + "tenantId": "t1", + "cv": "v2", + "uv": "v2", + "cbody": { + "firstFactors": [ + "emailpassword", + "custom" + ], + "requiredSecondaryFactors": [ + "emailpassword", + "custom" + ] + }, + "ubody": { + "firstFactors": [ + "emailpassword", + "custom" + ], + "requiredSecondaryFactors": [ + "emailpassword", + "custom" + ] + }, + "tenantState": { + "tenantId": "t1", + "emailPasswordEnabled": true, + "passwordlessEnabled": true, + "thirdPartyEnabled": true, + "firstFactors": [ + "emailpassword", + "custom" + ], + "requiredSecondaryFactors": [ + "emailpassword", + "custom" + ] + }, + "g4": { + "emailPasswordEnabled": true, + "thirdPartyEnabled": false, + "passwordlessEnabled": false + }, + "g5": { + "emailPasswordEnabled": true, + "thirdPartyEnabled": true, + "passwordlessEnabled": true, + "firstFactors": [ + "emailpassword", + "custom" + ], + "requiredSecondaryFactors": [ + "emailpassword", + "custom" + ] + }, + "gv2": { + "firstFactors": [ + "emailpassword", + "custom" + ], + "requiredSecondaryFactors": [ + "emailpassword", + "custom" + ] + }, + "invalidConfig": false +} \ No newline at end of file