Compare commits
49 Commits
@nhost/has
...
release-20
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e7762cb2b5 | ||
|
|
e353d99de8 | ||
|
|
c4d289a4d5 | ||
|
|
e2065e22df | ||
|
|
d738884d7d | ||
|
|
b50404566f | ||
|
|
8caf3daa54 | ||
|
|
8a07613cbe | ||
|
|
736862c9cc | ||
|
|
ea99fb31d7 | ||
|
|
70433187cc | ||
|
|
39b10a2e9f | ||
|
|
4b8478004e | ||
|
|
61eb6cdc2d | ||
|
|
14187d381f | ||
|
|
99b78f147e | ||
|
|
2aa81a6cb9 | ||
|
|
a1edaf18ea | ||
|
|
4d835c4b9c | ||
|
|
44a3e6bd41 | ||
|
|
6ee2d1f5bf | ||
|
|
df51c3e64e | ||
|
|
9acae7d1c4 | ||
|
|
f6947a2194 | ||
|
|
31e636a9c8 | ||
|
|
0fdff345ac | ||
|
|
97db63791b | ||
|
|
a0931e282f | ||
|
|
e87505c564 | ||
|
|
c0635ae1c7 | ||
|
|
d2a9a9ae1d | ||
|
|
c97b43f149 | ||
|
|
2026bb7a9c | ||
|
|
1bc1e30f5e | ||
|
|
85526782f2 | ||
|
|
fad7f640de | ||
|
|
5ff4dd6e40 | ||
|
|
0bf28085b7 | ||
|
|
b302dbd27d | ||
|
|
72a365c5fc | ||
|
|
d11363a74c | ||
|
|
1bc2fabe59 | ||
|
|
f8243f9434 | ||
|
|
d9eb90604d | ||
|
|
cef647194d | ||
|
|
efd68c3f92 | ||
|
|
233232b06f | ||
|
|
5e962300f6 | ||
|
|
048b3389e6 |
19
.github/labeler.yml
vendored
19
.github/labeler.yml
vendored
@@ -1,24 +1,25 @@
|
||||
dashboard:
|
||||
- dashboard/**/*
|
||||
- any:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: ['dashboard/**/*']
|
||||
|
||||
documentation:
|
||||
- any:
|
||||
- docs/**/*
|
||||
- any: ['docs/**/*']
|
||||
|
||||
examples:
|
||||
- examples/**/*
|
||||
- any: ['examples/**/*']
|
||||
|
||||
sdk:
|
||||
- packages/**/*
|
||||
- any: ['packages/**/*']
|
||||
|
||||
integrations:
|
||||
- integrations/**/*
|
||||
- any: ['integrations/**/*']
|
||||
|
||||
react:
|
||||
- '{packages,examples,integrations}/*react*/**/*'
|
||||
- any: ['{packages,examples,integrations}/*react*/**/*']
|
||||
|
||||
nextjs:
|
||||
- '{packages,examples}/*next*/**/*'
|
||||
- any: ['{packages,examples}/*next*/**/*']
|
||||
|
||||
vue:
|
||||
- '{packages,examples,integrations}/*vue*/**/*'
|
||||
- any: ['{packages,examples,integrations}/*vue*/**/*']
|
||||
|
||||
16
.github/workflows/ci.yaml
vendored
16
.github/workflows/ci.yaml
vendored
@@ -7,12 +7,14 @@ on:
|
||||
- 'assets/**'
|
||||
- '**.md'
|
||||
- 'LICENSE'
|
||||
- 'docs/**'
|
||||
pull_request:
|
||||
types: [opened, synchronize]
|
||||
paths-ignore:
|
||||
- 'assets/**'
|
||||
- '**.md'
|
||||
- 'LICENSE'
|
||||
- 'docs/**'
|
||||
env:
|
||||
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||
TURBO_TEAM: nhost
|
||||
@@ -27,7 +29,8 @@ env:
|
||||
NHOST_PRO_TEST_PROJECT_NAME: ${{ vars.NHOST_PRO_TEST_PROJECT_NAME }}
|
||||
NHOST_TEST_USER_EMAIL: ${{ secrets.NHOST_TEST_USER_EMAIL }}
|
||||
NHOST_TEST_USER_PASSWORD: ${{ secrets.NHOST_TEST_USER_PASSWORD }}
|
||||
NHOST_TEST_PROJECT_ADMIN_SECRET: ${{ secrets.NHOST_TEST_PROJECT_ADMIN_SECRET }}
|
||||
NHOST_TEST_PROJECT_ADMIN_SECRET: '${{ secrets.NHOST_TEST_PROJECT_ADMIN_SECRET }}'
|
||||
NHOST_TEST_FREE_USER_EMAILS: ${{ secrets.NHOST_TEST_FREE_USER_EMAILS }}
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -169,6 +172,10 @@ jobs:
|
||||
- name: Set Dashboard Preview URL
|
||||
if: steps.fetch-dashboard-preview-url.outputs.preview_url != ''
|
||||
run: echo "NHOST_TEST_DASHBOARD_URL=https://${{ steps.fetch-dashboard-preview-url.outputs.preview_url }}" >> $GITHUB_ENV
|
||||
- name: Run Upgrade project Dashboard e2e tests
|
||||
if: matrix.package.path == 'dashboard'
|
||||
timeout-minutes: 10
|
||||
run: pnpm --filter="${{ matrix.package.name }}" run e2e:upgrade-project
|
||||
# * Run the `ci` script of the current package of the matrix. Dependencies build is cached by Turborepo
|
||||
- name: Run e2e tests
|
||||
timeout-minutes: 20
|
||||
@@ -177,13 +184,16 @@ jobs:
|
||||
- name: Run Local Dashboard e2e tests
|
||||
if: matrix.package.path == 'dashboard'
|
||||
timeout-minutes: 5
|
||||
run: |
|
||||
pnpm --filter="${{ matrix.package.name }}" run e2e-local
|
||||
run: pnpm --filter="${{ matrix.package.name }}" run e2e:local
|
||||
|
||||
- name: Stop Nhost CLI
|
||||
if: matrix.package.path == 'dashboard'
|
||||
working-directory: ./nhost-test-project
|
||||
run: nhost down
|
||||
- name: Stop Nhost CLI for packages
|
||||
if: always() && (matrix.package.path == 'packages/hasura-auth-js' || matrix.package.path == 'packages/hasura-storage-js')
|
||||
working-directory: ./${{ matrix.package.path }}
|
||||
run: nhost down
|
||||
- id: file-name
|
||||
if: ${{ failure() }}
|
||||
name: Transform package name into a valid file name
|
||||
|
||||
28
.github/workflows/deploy-dashboard.yaml
vendored
28
.github/workflows/deploy-dashboard.yaml
vendored
@@ -56,3 +56,31 @@ jobs:
|
||||
vercel pull --environment=production --token=${{ secrets.DASHBOARD_VERCEL_DEPLOY_TOKEN }}
|
||||
vercel build --prod --token=${{ secrets.DASHBOARD_VERCEL_DEPLOY_TOKEN }}
|
||||
vercel deploy --prebuilt --prod --token=${{ secrets.DASHBOARD_VERCEL_DEPLOY_TOKEN }}
|
||||
|
||||
- name: Send Discord notification (success)
|
||||
if: success()
|
||||
uses: tsickert/discord-webhook@v7.0.0
|
||||
with:
|
||||
webhook-url: ${{ secrets.DISCORD_WEBHOOK_PRODUCTION }}
|
||||
embed-title: "Dashboard Deployment"
|
||||
embed-description: |
|
||||
**Status**: success
|
||||
**Triggered by**: ${{ github.actor }}
|
||||
|
||||
**Inputs**:
|
||||
- Git Ref: ${{ inputs.git_ref }}
|
||||
embed-color: '5763719'
|
||||
|
||||
- name: Send Discord notification (failure)
|
||||
if: failure()
|
||||
uses: tsickert/discord-webhook@v7.0.0
|
||||
with:
|
||||
webhook-url: ${{ secrets.DISCORD_WEBHOOK_PRODUCTION }}
|
||||
embed-title: "Dashboard Deployment"
|
||||
embed-description: |
|
||||
**Status**: failure
|
||||
**Triggered by**: ${{ github.actor }}
|
||||
|
||||
**Inputs**:
|
||||
- Git Ref: ${{ inputs.git_ref }}
|
||||
embed-color: '15548997'
|
||||
|
||||
7
.github/workflows/labeler.yaml
vendored
7
.github/workflows/labeler.yaml
vendored
@@ -3,13 +3,12 @@ on:
|
||||
- pull_request_target
|
||||
|
||||
jobs:
|
||||
triage:
|
||||
labeler:
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/labeler@v4
|
||||
- uses: actions/labeler@v5
|
||||
with:
|
||||
repo-token: '${{ secrets.GH_PAT }}'
|
||||
sync-labels: ''
|
||||
repo-token: ${{ secrets.GH_PAT }}
|
||||
|
||||
@@ -2,9 +2,7 @@
|
||||
|
||||
## Requirements
|
||||
|
||||
### Node.js v18
|
||||
|
||||
_⚠️ Node.js v16 is also supported for the time being but support will be dropped in the near future_.
|
||||
### Node.js v20 or later
|
||||
|
||||
### [pnpm](https://pnpm.io/) package manager
|
||||
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
// $schema provides code completion hints to IDEs.
|
||||
"$schema": "https://github.com/IBM/audit-ci/raw/main/docs/schema.json",
|
||||
"moderate": true,
|
||||
"allowlist": ["vue-template-compiler"]
|
||||
"allowlist": ["vue-template-compiler", { "id": "CVE-2025-48068", "path": "next" }]
|
||||
}
|
||||
|
||||
@@ -25,4 +25,6 @@ NEXT_PUBLIC_ZENDESK_USER_EMAIL=
|
||||
|
||||
CODEGEN_GRAPHQL_URL=https://local.graphql.local.nhost.run/v1
|
||||
CODEGEN_HASURA_ADMIN_SECRET=nhost-admin-secret
|
||||
NEXT_PUBLIC_TURNSTILE_SITE_KEY=FIXME
|
||||
NEXT_PUBLIC_TURNSTILE_SITE_KEY=FIXME
|
||||
|
||||
NEXT_PUBLIC_SOC2_REPORT_FILE_ID=
|
||||
@@ -76,6 +76,13 @@ module.exports = {
|
||||
],
|
||||
},
|
||||
],
|
||||
'jsx-a11y/label-has-associated-control': [
|
||||
2,
|
||||
{
|
||||
controlComponents: ['Input'],
|
||||
depth: 3,
|
||||
},
|
||||
],
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
|
||||
@@ -1,5 +1,68 @@
|
||||
# @nhost/dashboard
|
||||
|
||||
## 2.32.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 736862c: fix: update link to base directory docs in git settings
|
||||
- ea99fb3: chore: dashboard: improve messaging when git connected
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- d738884: chore (dashboard): Add link about antivirus integration
|
||||
|
||||
## 2.31.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 39b10a2: feat (dashboard): Add multi-factor authentication
|
||||
- 4b84780: feat (dashboard): Add Webauthn to dashboard
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 61eb6cd: fix (dashboard): Fix update project e2e test
|
||||
- @nhost/react-apollo@18.0.0
|
||||
- @nhost/nextjs@2.2.8
|
||||
|
||||
## 2.30.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- f6947a2: fix: fetch job-backup services logs using Live filter
|
||||
- 44a3e6b: fix: collapsed main navigation sidebar overlaps mobile navbar
|
||||
- 99b78f1: feat: dashboard: add download button for soc2 report
|
||||
- 9acae7d: fix: e2e tests, stop on error when refreshing metadata
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 31e636a: fix (dashboard): Use the correct payload to reset metadata before the e2e tests
|
||||
|
||||
## 2.29.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- c97b43f: fix: update vite to address vulnerability audit
|
||||
- a0931e2: fix: improve logs time range and filter selection
|
||||
- c0635ae: feat (dashboard): Add information about that free organization cannot be upgraded.
|
||||
- e87505c: fix: can downsize postgres storage capacity using local dashboard
|
||||
|
||||
## 2.28.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 8552678: feat: dashboard: add additional events to segment
|
||||
- 0bf2808: chore: refresh metadata before end-to-end tests
|
||||
- 72a365c: fix: correct graphql page roles dropdown's source
|
||||
- cef6471: fix: dashboard: add anonid to user's metadata
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- d9eb906: fix: update vite and nextjs because of vulnerability
|
||||
- 233232b: feat (dashboard): improve Upgrade project dialog
|
||||
- Updated dependencies [d9eb906]
|
||||
- @nhost/nextjs@2.2.7
|
||||
- @nhost/react-apollo@17.0.4
|
||||
|
||||
## 2.27.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -40,3 +40,7 @@ export const TEST_USER_EMAIL = process.env.NHOST_TEST_USER_EMAIL;
|
||||
export const TEST_USER_PASSWORD = process.env.NHOST_TEST_USER_PASSWORD;
|
||||
|
||||
export const TEST_PERSONAL_ORG_SLUG = process.env.NHOST_TEST_PERSONAL_ORG_SLUG;
|
||||
|
||||
const freeUserEmails = process.env.NHOST_TEST_FREE_USER_EMAILS;
|
||||
|
||||
export const TEST_FREE_USER_EMAILS = JSON.parse(freeUserEmails);
|
||||
|
||||
55
dashboard/e2e/setup/refresh-metadata.setup.ts
Normal file
55
dashboard/e2e/setup/refresh-metadata.setup.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
/* eslint-disable no-console */
|
||||
import { TEST_PROJECT_ADMIN_SECRET, TEST_PROJECT_SUBDOMAIN } from '@/e2e/env';
|
||||
import { test as setup } from '@playwright/test';
|
||||
|
||||
setup('refresh metadata', async () => {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`https://${TEST_PROJECT_SUBDOMAIN}.hasura.eu-central-1.staging.nhost.run/v1/metadata`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'x-hasura-admin-secret': TEST_PROJECT_ADMIN_SECRET,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
args: [
|
||||
{
|
||||
type: 'reload_metadata',
|
||||
args: {
|
||||
reload_sources: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
args: {},
|
||||
type: 'get_inconsistent_metadata',
|
||||
},
|
||||
],
|
||||
source: 'default',
|
||||
type: 'bulk',
|
||||
}),
|
||||
},
|
||||
);
|
||||
const body = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
const message = `[${body.code}]:${body.error}`;
|
||||
throw new Error(message);
|
||||
} else {
|
||||
const isConsistent = body[0].is_consistent;
|
||||
if (isConsistent) {
|
||||
console.log('Metadata is consistent.');
|
||||
} else {
|
||||
console.error('Metadata is not consistent.');
|
||||
console.error(body[0].inconsistent_objects);
|
||||
throw new Error('Metadata is not consistent');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Log safe error information
|
||||
console.error(
|
||||
'Failed to refresh metadata:',
|
||||
error instanceof Error ? error.message : 'Unknown error',
|
||||
);
|
||||
throw new Error('Failed to refresh metadata');
|
||||
}
|
||||
});
|
||||
142
dashboard/e2e/upgrade-project/upgrade-project.test.ts
Normal file
142
dashboard/e2e/upgrade-project/upgrade-project.test.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import { expect, test } from '@/e2e/fixtures/auth-hook';
|
||||
import {
|
||||
getCardExpiration,
|
||||
getFreeUserStarterOrgSlug,
|
||||
getNewOrgSlug,
|
||||
getNewProjectName,
|
||||
getNewProjectSlug,
|
||||
getOrgSlugFromUrl,
|
||||
getProjectSlugFromUrl,
|
||||
gotoUrl,
|
||||
loginWithFreeUser,
|
||||
setNewOrgSlug,
|
||||
setNewProjectName,
|
||||
setNewProjectSlug,
|
||||
} from '@/e2e/utils';
|
||||
import { faker } from '@faker-js/faker';
|
||||
import type { Page } from '@playwright/test';
|
||||
|
||||
let page: Page;
|
||||
|
||||
test.beforeAll(async ({ browser }) => {
|
||||
page = await browser.newPage();
|
||||
await loginWithFreeUser(page);
|
||||
});
|
||||
|
||||
test('should create a new project', async () => {
|
||||
await gotoUrl(page, `/orgs/${getFreeUserStarterOrgSlug()}/projects/new`);
|
||||
const projectName = faker.lorem.words(3);
|
||||
|
||||
await page.getByLabel('Project Name').fill(projectName);
|
||||
await page.getByText('Create Project').click();
|
||||
|
||||
expect(page.getByText('Creating the project...')).toBeVisible();
|
||||
expect(page.getByText('Internal info')).toBeVisible();
|
||||
|
||||
await page.waitForSelector('button:has-text("Upgrade project")', {
|
||||
timeout: 120000,
|
||||
});
|
||||
|
||||
const newProjectSlug = getProjectSlugFromUrl(page.url());
|
||||
setNewProjectSlug(newProjectSlug);
|
||||
setNewProjectName(projectName);
|
||||
});
|
||||
|
||||
test('should upgrade the project', async () => {
|
||||
await gotoUrl(
|
||||
page,
|
||||
`/orgs/${getFreeUserStarterOrgSlug()}/projects/${getNewProjectSlug()}`,
|
||||
);
|
||||
const upgradeProject = page.getByText('Upgrade project');
|
||||
expect(upgradeProject).toBeVisible();
|
||||
|
||||
await upgradeProject.click();
|
||||
|
||||
await page.waitForSelector('h2:has-text("Upgrade project")');
|
||||
|
||||
await page.getByRole('button', { name: 'Continue' }).click();
|
||||
await page.waitForSelector('h2:has-text("New Organization")');
|
||||
|
||||
const newOrgName = faker.lorem.words(3);
|
||||
await page.getByLabel('Organization Name').fill(newOrgName);
|
||||
|
||||
await page.getByText('Create organization').click();
|
||||
await page.waitForSelector('button:has-text("Create organization")', {
|
||||
state: 'hidden',
|
||||
});
|
||||
const stripeFrame = page
|
||||
.frameLocator('iframe[name="embedded-checkout"]')
|
||||
.first();
|
||||
stripeFrame.getByText('Subscribe to Nhost');
|
||||
await stripeFrame.getByLabel('Email').fill(faker.internet.email());
|
||||
|
||||
await stripeFrame
|
||||
.getByPlaceholder('1234 1234 1234 1234')
|
||||
.fill('4242424242424242');
|
||||
|
||||
await stripeFrame.getByPlaceholder('MM / YY').fill(getCardExpiration());
|
||||
await stripeFrame.getByPlaceholder('CVC').fill('123');
|
||||
await stripeFrame
|
||||
.getByPlaceholder('Full name on card')
|
||||
.fill('EndyTo EndyTest');
|
||||
await stripeFrame.locator('#billingCountry').scrollIntoViewIfNeeded();
|
||||
// Need to comment out for local testing START
|
||||
await stripeFrame.getByPlaceholder('Address', { exact: true }).click();
|
||||
stripeFrame.locator('span:has-text("Enter address manually")');
|
||||
await stripeFrame.getByText('Enter address manually').click();
|
||||
await stripeFrame
|
||||
.getByPlaceholder('Address line 1', { exact: true })
|
||||
.fill('123 Main Street');
|
||||
await stripeFrame
|
||||
.getByPlaceholder('City', { exact: true })
|
||||
.fill('Springfield');
|
||||
await stripeFrame.getByPlaceholder('ZIP', { exact: true }).fill('62701');
|
||||
await stripeFrame.locator('#enableStripePass').click({ force: true });
|
||||
// local Comment end
|
||||
await stripeFrame
|
||||
.getByTestId('hosted-payment-submit-button')
|
||||
.scrollIntoViewIfNeeded();
|
||||
await stripeFrame
|
||||
.getByTestId('hosted-payment-submit-button')
|
||||
.click({ force: true });
|
||||
|
||||
await page.waitForSelector('h2:has-text("Upgrade project")');
|
||||
await page.waitForSelector(
|
||||
'div:has-text("Organization created successfully.")',
|
||||
);
|
||||
await page.waitForSelector(
|
||||
'div:has-text("Project has been upgraded successfully!")',
|
||||
);
|
||||
|
||||
page.getByRole('button', { name: 'Create project' });
|
||||
|
||||
await page.waitForSelector(`div:has-text("${newOrgName}")`);
|
||||
await page.waitForSelector(`p:has-text("${getNewProjectName()}")`);
|
||||
|
||||
setNewOrgSlug(getOrgSlugFromUrl(page.url()));
|
||||
});
|
||||
|
||||
test('should delete the new organization', async () => {
|
||||
await gotoUrl(page, `/orgs/${getNewOrgSlug()}/projects`);
|
||||
await page.getByRole('link', { name: 'Settings' }).click();
|
||||
|
||||
await page.waitForSelector('h3:has-text("Delete Organization")');
|
||||
await page.getByRole('button', { name: 'Delete' }).click();
|
||||
|
||||
await page.waitForSelector('h2:has-text("Delete Organization")');
|
||||
expect(page.getByTestId('deleteOrgButton')).toBeDisabled();
|
||||
|
||||
await page.getByLabel("I'm sure I want to delete this Organization").click();
|
||||
expect(page.getByTestId('deleteOrgButton')).toBeDisabled();
|
||||
await page.getByLabel('I understand this action cannot be undone').click();
|
||||
expect(page.getByTestId('deleteOrgButton')).not.toBeDisabled();
|
||||
|
||||
await page.getByTestId('deleteOrgButton').click();
|
||||
|
||||
await page.waitForSelector('div:has-text("Deleting the organization")');
|
||||
await page.waitForSelector(
|
||||
'div:has-text("Successfully deleted the organization")',
|
||||
);
|
||||
|
||||
await page.waitForSelector(`div:has-text("Personal Organization")`);
|
||||
});
|
||||
@@ -1,6 +1,12 @@
|
||||
import { TEST_ORGANIZATION_SLUG, TEST_PROJECT_SUBDOMAIN } from '@/e2e/env';
|
||||
import {
|
||||
TEST_FREE_USER_EMAILS,
|
||||
TEST_ORGANIZATION_SLUG,
|
||||
TEST_PROJECT_SUBDOMAIN,
|
||||
TEST_USER_PASSWORD,
|
||||
} from '@/e2e/env';
|
||||
import { faker } from '@faker-js/faker';
|
||||
import type { Page } from '@playwright/test';
|
||||
import { type Page, expect } from '@playwright/test';
|
||||
import { add, format } from 'date-fns-v4';
|
||||
|
||||
/**
|
||||
* Open a project by navigating to the project's overview page.
|
||||
@@ -213,8 +219,96 @@ export async function clickPermissionButton({
|
||||
.click();
|
||||
}
|
||||
|
||||
export async function gotoAuthURL(page) {
|
||||
export async function gotoAuthURL(page: Page) {
|
||||
const authUrl = `/orgs/${TEST_ORGANIZATION_SLUG}/projects/${TEST_PROJECT_SUBDOMAIN}/users`;
|
||||
await page.goto(authUrl);
|
||||
await page.waitForURL(authUrl, { waitUntil: 'networkidle' });
|
||||
}
|
||||
|
||||
export async function gotoUrl(page: Page, url: string) {
|
||||
await page.url;
|
||||
await page.goto(url);
|
||||
await page.waitForURL(url, { waitUntil: 'networkidle' });
|
||||
}
|
||||
|
||||
let newOrgSlug: string;
|
||||
|
||||
export function getNewOrgSlug() {
|
||||
return newOrgSlug;
|
||||
}
|
||||
|
||||
export function setNewOrgSlug(slug: string) {
|
||||
newOrgSlug = slug;
|
||||
}
|
||||
|
||||
let freeUserStarterOrgSlug: string;
|
||||
|
||||
export function getFreeUserStarterOrgSlug() {
|
||||
return freeUserStarterOrgSlug;
|
||||
}
|
||||
|
||||
export function setFreeUserStarterOrgSlug(slug: string) {
|
||||
freeUserStarterOrgSlug = slug;
|
||||
}
|
||||
|
||||
let newProjectSlug: string;
|
||||
|
||||
export function getNewProjectSlug() {
|
||||
return newProjectSlug;
|
||||
}
|
||||
|
||||
export function setNewProjectSlug(slug: string) {
|
||||
newProjectSlug = slug;
|
||||
}
|
||||
|
||||
export function getProjectSlugFromUrl(url: string) {
|
||||
const [, projectSlug] = url.split('/projects/');
|
||||
|
||||
return projectSlug;
|
||||
}
|
||||
|
||||
export function getOrgSlugFromUrl(url: string) {
|
||||
const orgSlug = url.split('/orgs/')[1].replace('/projects', '');
|
||||
return orgSlug;
|
||||
}
|
||||
|
||||
export function getCardExpiration() {
|
||||
const now = add(new Date(), { years: 3 });
|
||||
return format(now, 'MMyy');
|
||||
}
|
||||
|
||||
let newProjectName: string;
|
||||
|
||||
export function getNewProjectName() {
|
||||
return newProjectName;
|
||||
}
|
||||
|
||||
export function setNewProjectName(name: string) {
|
||||
newProjectName = name;
|
||||
}
|
||||
|
||||
function getRandomUserIndex(): number {
|
||||
return Math.floor(Math.random() * 5);
|
||||
}
|
||||
|
||||
export async function loginWithFreeUser(page: Page) {
|
||||
const userIndex = getRandomUserIndex();
|
||||
|
||||
const freeUserEmail = TEST_FREE_USER_EMAILS[userIndex];
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`Selected userIndex: ${userIndex}`);
|
||||
await page.goto('/');
|
||||
await page.waitForURL('/signin');
|
||||
await page.getByRole('link', { name: /continue with email/i }).click();
|
||||
|
||||
await page.waitForURL('/signin/email');
|
||||
await page.getByLabel('Email').fill(freeUserEmail);
|
||||
await page.getByLabel('Password').fill(TEST_USER_PASSWORD);
|
||||
await page.getByRole('button', { name: /sign in/i }).click();
|
||||
expect(
|
||||
await page.getByRole('button', { name: 'Create project' }),
|
||||
).not.toBeVisible();
|
||||
await page.waitForSelector('h2:has-text("Welcome to")', { timeout: 20000 });
|
||||
setFreeUserStarterOrgSlug(getOrgSlugFromUrl(await page.url()));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@nhost/dashboard",
|
||||
"version": "2.27.0",
|
||||
"version": "2.32.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"preinstall": "npx only-allow pnpm",
|
||||
@@ -16,8 +16,10 @@
|
||||
"storybook": "start-storybook -p 6006 -s public",
|
||||
"build-storybook": "build-storybook",
|
||||
"install-browsers": "pnpm playwright install && pnpm playwright install-deps",
|
||||
"e2e": "pnpm install-browsers && pnpm playwright test --config=playwright.config.ts",
|
||||
"e2e-local": "pnpm install-browsers && pnpm playwright test --config=playwright.local.config.ts"
|
||||
"e2e:tests": "pnpm install-browsers && pnpm playwright test --config=playwright.config.ts -x",
|
||||
"e2e": "pnpm e2e:tests --project=main",
|
||||
"e2e:local": "pnpm e2e:tests --project=local",
|
||||
"e2e:upgrade-project": "pnpm e2e:tests --project=upgrade-project"
|
||||
},
|
||||
"dependencies": {
|
||||
"@apollo/client": "^3.9.9",
|
||||
@@ -37,6 +39,7 @@
|
||||
"@heroicons/react": "^1.0.6",
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
"@iarna/toml": "^2.2.5",
|
||||
"@icons-pack/react-simple-icons": "^9.6.0",
|
||||
"@marsidev/react-turnstile": "^1.0.2",
|
||||
"@mui/base": "5.0.0-beta.31",
|
||||
"@mui/material": "^5.15.14",
|
||||
@@ -87,7 +90,7 @@
|
||||
"just-kebab-case": "^4.2.0",
|
||||
"lodash.debounce": "^4.0.8",
|
||||
"lucide-react": "^0.416.0",
|
||||
"next": "^14.2.25",
|
||||
"next": "^14.2.26",
|
||||
"next-nprogress-bar": "^2.3.13",
|
||||
"next-seo": "^6.5.0",
|
||||
"next-themes": "^0.3.0",
|
||||
@@ -194,7 +197,7 @@
|
||||
"tailwindcss": "^3.4.12",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsconfig-paths-webpack-plugin": "^4.1.0",
|
||||
"vite": "^5.4.17",
|
||||
"vite": "^5.4.19",
|
||||
"vite-tsconfig-paths": "^4.3.2",
|
||||
"vitest": "^0.32.4"
|
||||
},
|
||||
|
||||
@@ -17,7 +17,7 @@ export default defineConfig({
|
||||
reporter: 'html',
|
||||
use: {
|
||||
actionTimeout: 0,
|
||||
trace: 'on-first-retry',
|
||||
trace: 'retain-on-failure',
|
||||
baseURL: process.env.NHOST_TEST_DASHBOARD_URL,
|
||||
launchOptions: {
|
||||
slowMo: 500,
|
||||
@@ -34,13 +34,28 @@ export default defineConfig({
|
||||
testMatch: ['**/teardown/*.teardown.ts'],
|
||||
},
|
||||
{
|
||||
name: 'chromium',
|
||||
name: 'main',
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
storageState: 'e2e/.auth/user.json',
|
||||
},
|
||||
dependencies: ['setup'],
|
||||
grepInvert: [/Local Dashboard CLI e2e tests/],
|
||||
testIgnore: ['upgrade-project.test.ts', 'cli-local-dashboard.test.ts'],
|
||||
},
|
||||
{
|
||||
name: 'local',
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
baseURL: '', // Local dashboard URL
|
||||
},
|
||||
testMatch: 'cli-local-dashboard.test.ts',
|
||||
},
|
||||
{
|
||||
name: 'upgrade-project',
|
||||
testMatch: 'upgrade-project.test.ts',
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
timeout: 30 * 1000,
|
||||
expect: {
|
||||
timeout: 5000,
|
||||
},
|
||||
fullyParallel: false,
|
||||
forbidOnly: !!process.env.CI,
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
workers: 1,
|
||||
reporter: 'html',
|
||||
use: {
|
||||
actionTimeout: 0,
|
||||
trace: 'on-first-retry',
|
||||
baseURL: '', // Local dashboard URL
|
||||
launchOptions: {
|
||||
slowMo: 500,
|
||||
},
|
||||
},
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
use: {
|
||||
...devices['Desktop Chrome'],
|
||||
},
|
||||
testMatch: ['**/e2e/cli-local-dashboard/**'],
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -82,7 +82,7 @@ describe('DateTimePicker', () => {
|
||||
const secondsInput = await screen.getByLabelText('Seconds');
|
||||
await user.type(secondsInput, '13');
|
||||
|
||||
user.click(await screen.getByRole('button', { name: 'Select' }));
|
||||
await user.click(await screen.getByRole('button', { name: 'Select' }));
|
||||
|
||||
await waitFor(async () =>
|
||||
expect(
|
||||
|
||||
61
dashboard/src/components/common/MfaOtpForm/MfaOtpForm.tsx
Normal file
61
dashboard/src/components/common/MfaOtpForm/MfaOtpForm.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
import { Button } from '@/components/ui/v3/button';
|
||||
import { Input } from '@/components/ui/v3/input';
|
||||
import { type ChangeEvent, useEffect, useRef, useState } from 'react';
|
||||
|
||||
interface Props {
|
||||
sendMfaOtp: (code: string) => Promise<any>;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
function MfaOtpForm({ sendMfaOtp, loading }: Props) {
|
||||
const [otpValue, setOtpValue] = useState<string>('');
|
||||
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
|
||||
const inputRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (inputRef.current) {
|
||||
inputRef.current.focus();
|
||||
}
|
||||
}, []);
|
||||
|
||||
async function sendMfa(code: string) {
|
||||
if (code.length === 6 && !isSubmitting) {
|
||||
setIsSubmitting(true);
|
||||
const result = await sendMfaOtp(code);
|
||||
if (!result) {
|
||||
setTimeout(() => {
|
||||
inputRef.current?.focus();
|
||||
}, 10);
|
||||
}
|
||||
}
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
|
||||
async function handleChange(event: ChangeEvent<HTMLInputElement>) {
|
||||
const code = event.target.value.replace(/[^0-9]/g, '').slice(0, 6);
|
||||
setOtpValue(code);
|
||||
|
||||
sendMfa(code);
|
||||
}
|
||||
|
||||
const isInputDisabled = loading || isSubmitting;
|
||||
const isButtonDisabled = isInputDisabled || otpValue.length !== 6;
|
||||
|
||||
return (
|
||||
<div className="relative grid w-full grid-flow-row gap-4 bg-transparent">
|
||||
<Input
|
||||
ref={inputRef}
|
||||
value={otpValue}
|
||||
placeholder="Enter TOTP"
|
||||
className="!bg-transparent"
|
||||
disabled={isInputDisabled}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
<Button disabled={isButtonDisabled}>
|
||||
{loading ? 'Verifying...' : 'Verify'}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default MfaOtpForm;
|
||||
1
dashboard/src/components/common/MfaOtpForm/index.ts
Normal file
1
dashboard/src/components/common/MfaOtpForm/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as MfaOtpForm } from './MfaOtpForm';
|
||||
@@ -7,7 +7,6 @@ import { List } from '@/components/ui/v2/List';
|
||||
import { ListItem } from '@/components/ui/v2/ListItem';
|
||||
import { Text } from '@/components/ui/v2/Text';
|
||||
import { useOrgs } from '@/features/orgs/projects/hooks/useOrgs';
|
||||
import {} from '@/utils/__generated__/graphql';
|
||||
import { Divider } from '@mui/material';
|
||||
import debounce from 'lodash.debounce';
|
||||
import Image from 'next/image';
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Box } from '@/components/ui/v2/Box';
|
||||
import { ArrowSquareOutIcon } from '@/components/ui/v2/icons/ArrowSquareOutIcon';
|
||||
import { Link } from '@/components/ui/v2/Link';
|
||||
import { Text } from '@/components/ui/v2/Text';
|
||||
import { TransferProjectDialog } from '@/features/orgs/components/common/TransferProjectDialog';
|
||||
import { TransferOrUpgradeProjectDialog } from '@/features/orgs/components/common/TransferOrUpgradeProjectDialog';
|
||||
import { useState } from 'react';
|
||||
|
||||
import { OpenTransferDialogButton } from '@/components/common/OpenTransferDialogButton';
|
||||
@@ -51,7 +51,7 @@ export default function UpgradeToProBanner({
|
||||
|
||||
<div className="flex flex-col gap-2 space-y-2 lg:flex-row lg:items-center lg:space-x-2 lg:space-y-0">
|
||||
<OpenTransferDialogButton onClick={handleTransferDialogOpen} />
|
||||
<TransferProjectDialog
|
||||
<TransferOrUpgradeProjectDialog
|
||||
open={transferProjectDialogOpen}
|
||||
setOpen={setTransferProjectDialogOpen}
|
||||
/>
|
||||
|
||||
59
dashboard/src/components/form/FormInput/FormInput.tsx
Normal file
59
dashboard/src/components/form/FormInput/FormInput.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import {
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/v3/form';
|
||||
import { Input } from '@/components/ui/v3/input';
|
||||
import type { Control, FieldPath, FieldValues } from 'react-hook-form';
|
||||
|
||||
const inputClasses =
|
||||
'!bg-transparent aria-[invalid=true]:border-red-500 aria-[invalid=true]:focus:border-red-500 aria-[invalid=true]:focus:ring-red-500';
|
||||
|
||||
interface FormInputProps<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
> {
|
||||
control: Control<TFieldValues>;
|
||||
name: TName;
|
||||
label: string;
|
||||
placeholder?: string;
|
||||
className?: string;
|
||||
type?: string;
|
||||
}
|
||||
|
||||
function FormInput<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
>({
|
||||
control,
|
||||
name,
|
||||
label,
|
||||
placeholder,
|
||||
className = '',
|
||||
type = 'text',
|
||||
}: FormInputProps<TFieldValues, TName>) {
|
||||
return (
|
||||
<FormField
|
||||
control={control}
|
||||
name={name}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{label}</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type={type}
|
||||
placeholder={placeholder || label}
|
||||
{...field}
|
||||
className={`${inputClasses} ${className}`}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default FormInput;
|
||||
1
dashboard/src/components/form/FormInput/index.ts
Normal file
1
dashboard/src/components/form/FormInput/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as FormInput } from './FormInput';
|
||||
@@ -41,7 +41,7 @@ export default function MainNav({ container }: MainNavProps) {
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<div
|
||||
className="min- absolute left-0 z-50 flex h-full w-6 justify-center border-r-[1px] bg-background pt-1 hover:bg-accent"
|
||||
className="min- absolute left-0 z-[39] flex h-full w-6 justify-center border-r-[1px] bg-background pt-1 hover:bg-accent"
|
||||
onMouseEnter={() => setOpen(true)}
|
||||
>
|
||||
<Menu className="h-4 w-4" />
|
||||
|
||||
@@ -6,8 +6,8 @@ import {
|
||||
type ReactElement,
|
||||
} from 'react';
|
||||
|
||||
import { CopyToClipboardButton as CopyToClipboardButtonOriginal } from '@/components/presentational/CopyToClipboardButton';
|
||||
import { Box } from '@/components/ui/v2/Box';
|
||||
import { CopyToClipboardButton as CopyToClipboardButtonOriginal } from './CopyToClipboardButton';
|
||||
import { getNodeText } from './getNodeText';
|
||||
|
||||
export interface CodeBlockPropsBase {
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { Button, type ButtonProps } from '@/components/ui/v3/button';
|
||||
import { isNotEmptyValue } from '@/lib/utils';
|
||||
import { copy } from '@/utils/copy';
|
||||
import { clsx } from 'clsx';
|
||||
import { Copy } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import {
|
||||
IconButton,
|
||||
type IconButtonProps,
|
||||
} from '@/components/ui/v2/IconButton';
|
||||
import { CopyIcon } from '@/components/ui/v2/icons/CopyIcon';
|
||||
import { copy } from '@/utils/copy';
|
||||
|
||||
export function CopyToClipboardButton({
|
||||
function CopyToClipboardButton({
|
||||
textToCopy,
|
||||
className,
|
||||
title,
|
||||
@@ -16,7 +13,7 @@ export function CopyToClipboardButton({
|
||||
}: {
|
||||
textToCopy: string;
|
||||
title: string;
|
||||
} & IconButtonProps) {
|
||||
} & ButtonProps) {
|
||||
const [disabled, setDisabled] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -35,12 +32,18 @@ export function CopyToClipboardButton({
|
||||
if (!textToCopy || disabled) {
|
||||
return null;
|
||||
}
|
||||
const hasChildren = isNotEmptyValue(props.children);
|
||||
|
||||
return (
|
||||
<IconButton
|
||||
variant="borderless"
|
||||
color="secondary"
|
||||
className={clsx('group', className)}
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant="outline"
|
||||
className={clsx(
|
||||
'group h-fit w-fit border-0 bg-transparent p-[2px] hover:bg-[#d6eefb] dark:hover:bg-[#1e2942]',
|
||||
className,
|
||||
{ 'gap-3': hasChildren },
|
||||
)}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
|
||||
@@ -49,7 +52,9 @@ export function CopyToClipboardButton({
|
||||
aria-label={textToCopy}
|
||||
{...props}
|
||||
>
|
||||
<CopyIcon className="top-5 h-4 w-4" />
|
||||
</IconButton>
|
||||
{props.children}
|
||||
<Copy className="top-5 h-4 w-4" />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
export default CopyToClipboardButton;
|
||||
@@ -0,0 +1 @@
|
||||
export { default as CopyToClipboardButton } from './CopyToClipboardButton';
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Badge } from '@/components/ui/v3/badge';
|
||||
import useMfaEnabled from '@/features/account/settings/components/AccountMfaSettings/hooks/useMfaEnabled';
|
||||
import DisableMfaButton from './DisableMfaButton/DisableMfaButton';
|
||||
import EnableMfaButton from './EnableMfaButton/EnableMfaButton';
|
||||
|
||||
function MFaEnabledBadge() {
|
||||
return (
|
||||
<Badge variant="outline" className="border-green-400 text-green-400">
|
||||
Enabled
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
function MFaDisabledBadge() {
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text- border-destructive text-destructive"
|
||||
>
|
||||
Disabled
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
function AccountMfaSettings() {
|
||||
const { isMfaEnabled } = useMfaEnabled();
|
||||
return (
|
||||
<div className="rounded-lg border border-[#EAEDF0] bg-white font-['Inter_var'] dark:border-[#2F363D] dark:bg-paper">
|
||||
<div className="flex w-full flex-col items-start gap-6 p-4">
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<h3 className="flex items-center text-[1.125rem] font-semibold leading-[1.75]">
|
||||
<span className="mr-4">Multi-Factor Authentication </span>
|
||||
{isMfaEnabled ? <MFaEnabledBadge /> : <MFaDisabledBadge />}
|
||||
</h3>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full items-center border-t border-[#EAEDF0] px-4 py-2 dark:border-[#2F363D]">
|
||||
{isMfaEnabled ? <DisableMfaButton /> : <EnableMfaButton />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default AccountMfaSettings;
|
||||
@@ -0,0 +1,70 @@
|
||||
import { MfaOtpForm } from '@/components/common/MfaOtpForm';
|
||||
import { Button } from '@/components/ui/v3/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/v3/dialog';
|
||||
import useMfaEnabled from '@/features/account/settings/components/AccountMfaSettings/hooks/useMfaEnabled';
|
||||
import { getToastStyleProps } from '@/utils/constants/settings';
|
||||
import { useConfigMfa } from '@nhost/nextjs';
|
||||
import { useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
|
||||
const defaultErrorMessage =
|
||||
'An error occurred while trying to enable multi-factor authentication. Please try again.';
|
||||
|
||||
function DisableMfaButton() {
|
||||
const { disableMfa, isDisabling } = useConfigMfa();
|
||||
const [open, setOpen] = useState(false);
|
||||
const { loading, refetch } = useMfaEnabled();
|
||||
const buttonDisabled = loading || isDisabling;
|
||||
|
||||
async function onSendMfaOtp(code: string) {
|
||||
const result = await disableMfa(code);
|
||||
if (result.error) {
|
||||
toast.error(
|
||||
result.error.message || defaultErrorMessage,
|
||||
getToastStyleProps(),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
toast.success(
|
||||
'Multi-factor authentication has been disabled.',
|
||||
getToastStyleProps(),
|
||||
);
|
||||
await refetch();
|
||||
setOpen(false);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={buttonDisabled}
|
||||
className="p-y[0.375rem] h-9 gap-2 border-destructive px-2 text-destructive hover:bg-destructive"
|
||||
>
|
||||
Disable multi-factor authentication
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="z-[9999] max-w-[28rem] text-foreground">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Disable multi-factor authentication</DialogTitle>
|
||||
</DialogHeader>
|
||||
<DialogDescription className="hidden">
|
||||
Disable multi-factor authentication
|
||||
</DialogDescription>
|
||||
|
||||
<MfaOtpForm loading={isDisabling} sendMfaOtp={onSendMfaOtp} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default DisableMfaButton;
|
||||
@@ -0,0 +1 @@
|
||||
export { default as DisableMfaButton } from './DisableMfaButton';
|
||||
@@ -0,0 +1,19 @@
|
||||
import { CopyToClipboardButton } from '@/components/presentational/CopyToClipboardButton';
|
||||
|
||||
interface Props {
|
||||
totpSecret: string | null;
|
||||
}
|
||||
|
||||
function CopyMfaTOTPSecret({ totpSecret }: Props) {
|
||||
return (
|
||||
<CopyToClipboardButton
|
||||
className="p-2"
|
||||
textToCopy={totpSecret}
|
||||
title="TOTP secret"
|
||||
>
|
||||
OR Copy TOTP secret
|
||||
</CopyToClipboardButton>
|
||||
);
|
||||
}
|
||||
|
||||
export default CopyMfaTOTPSecret;
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Button } from '@/components/ui/v3/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/v3/dialog';
|
||||
import useMfaEnabled from '@/features/account/settings/components/AccountMfaSettings/hooks/useMfaEnabled';
|
||||
import { useState } from 'react';
|
||||
import MfaQRCodeAndTOTPSecret from './MfaQRCodeAndTOTPSecret';
|
||||
|
||||
function EnableMfaButton() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { isMfaEnabled, loading, refetch } = useMfaEnabled();
|
||||
const buttonDisabled = loading || isMfaEnabled;
|
||||
|
||||
async function handleOnSuccess() {
|
||||
setOpen(false);
|
||||
await refetch();
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={buttonDisabled}
|
||||
className="p-y[0.375rem] h-9 gap-2 border-green-600 px-2 text-green-600 hover:bg-destructive hover:bg-green-600"
|
||||
>
|
||||
Enable multi-factor authentication
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="z-[9999] max-w-[28rem] text-foreground">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Enable multi-factor authentication</DialogTitle>
|
||||
</DialogHeader>
|
||||
<DialogDescription className="hidden">
|
||||
Enable multi-factor authentication
|
||||
</DialogDescription>
|
||||
<MfaQRCodeAndTOTPSecret onSuccess={handleOnSuccess} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default EnableMfaButton;
|
||||
@@ -0,0 +1,74 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import { MfaOtpForm } from '@/components/common/MfaOtpForm';
|
||||
import { Spinner } from '@/components/ui/v3/spinner';
|
||||
import { getToastStyleProps } from '@/utils/constants/settings';
|
||||
import { useConfigMfa } from '@nhost/nextjs';
|
||||
import { useEffect } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import CopyMfaTOTPSecret from './CopyMfaTOTPSecret';
|
||||
|
||||
const defaultErrorMessage =
|
||||
'An error occurred while trying to enable multi-factor authentication. Please try again.';
|
||||
|
||||
interface Props {
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
function MfaQRCodeAndTOTPSecret({ onSuccess }: Props) {
|
||||
const {
|
||||
generateQrCode,
|
||||
qrCodeDataUrl,
|
||||
isGenerated,
|
||||
isGenerating,
|
||||
activateMfa,
|
||||
isActivating,
|
||||
totpSecret,
|
||||
} = useConfigMfa();
|
||||
|
||||
async function onSendMfaOtp(code: string) {
|
||||
const result = await activateMfa(code);
|
||||
if (result.error) {
|
||||
toast.error(
|
||||
result.error.message || defaultErrorMessage,
|
||||
getToastStyleProps(),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
toast.success(
|
||||
'Multi-factor authentication has been enabled.',
|
||||
getToastStyleProps(),
|
||||
);
|
||||
onSuccess();
|
||||
return true;
|
||||
}
|
||||
useEffect(() => {
|
||||
async function generate() {
|
||||
const result = await generateQrCode();
|
||||
if (result.error) {
|
||||
toast.error(result.error.message, getToastStyleProps());
|
||||
}
|
||||
}
|
||||
generate();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col items-center justify-center gap-4">
|
||||
{isGenerating && <Spinner />}
|
||||
{isGenerated && qrCodeDataUrl && (
|
||||
<>
|
||||
<div className="flex flex-col justify-center gap-4">
|
||||
<p className="text-base">
|
||||
Scan the QR Code with your authenticator app
|
||||
</p>
|
||||
<img alt="qrcode" src={qrCodeDataUrl} className="mx-auto w-64" />
|
||||
</div>
|
||||
<CopyMfaTOTPSecret totpSecret={totpSecret} />
|
||||
<MfaOtpForm loading={isActivating} sendMfaOtp={onSendMfaOtp} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default MfaQRCodeAndTOTPSecret;
|
||||
@@ -0,0 +1 @@
|
||||
export { default as EnableMfaButton } from './EnableMfaButton';
|
||||
@@ -0,0 +1,17 @@
|
||||
import { isNotEmptyValue } from '@/lib/utils';
|
||||
import { useGetActiveMfaTypeQuery } from '@/utils/__generated__/graphql';
|
||||
import { useUserId } from '@nhost/nextjs';
|
||||
|
||||
function useMfaEnabled() {
|
||||
const userId = useUserId();
|
||||
const { data, loading, refetch } = useGetActiveMfaTypeQuery({
|
||||
variables: { id: userId },
|
||||
fetchPolicy: 'cache-first',
|
||||
});
|
||||
|
||||
const isMfaEnabled = isNotEmptyValue(data?.user.activeMfaType);
|
||||
|
||||
return { loading, isMfaEnabled, refetch };
|
||||
}
|
||||
|
||||
export default useMfaEnabled;
|
||||
@@ -0,0 +1 @@
|
||||
export { default as AccountMfaSettings } from './components/AccountMfaSettings';
|
||||
@@ -10,9 +10,9 @@ import { CopyIcon } from '@/components/ui/v2/icons/CopyIcon';
|
||||
import { Input } from '@/components/ui/v2/Input';
|
||||
import { Option } from '@/components/ui/v2/Option';
|
||||
import { Text } from '@/components/ui/v2/Text';
|
||||
import useActionWithElevatedPermissions from '@/features/account/settings/hooks/useActionWithElevatedPermissions';
|
||||
import type { DialogFormProps } from '@/types/common';
|
||||
import { GetPersonalAccessTokensDocument } from '@/utils/__generated__/graphql';
|
||||
import { getToastStyleProps } from '@/utils/constants/settings';
|
||||
import { copy } from '@/utils/copy';
|
||||
import { getDateComponents } from '@/utils/getDateComponents';
|
||||
import { useApolloClient } from '@apollo/client';
|
||||
@@ -20,7 +20,6 @@ import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import { useNhostClient } from '@nhost/nextjs';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { FormProvider, useForm } from 'react-hook-form';
|
||||
import { toast } from 'react-hot-toast';
|
||||
import * as Yup from 'yup';
|
||||
|
||||
export const createPATFormValidationSchema = Yup.object({
|
||||
@@ -84,6 +83,25 @@ export default function CreatePATForm({
|
||||
resolver: yupResolver(createPATFormValidationSchema),
|
||||
});
|
||||
|
||||
const createPAT = useActionWithElevatedPermissions({
|
||||
actionFn: async (
|
||||
expiresAt: Date,
|
||||
metadata?: Record<string, string | number>,
|
||||
) => {
|
||||
const result = await nhostClient.auth.createPAT(expiresAt, metadata);
|
||||
return result;
|
||||
},
|
||||
successMessage: 'The personal access token has been created successfully.',
|
||||
onSuccess: ({ data }) => {
|
||||
setPersonalAccessToken(data?.personalAccessToken);
|
||||
apolloClient.refetchQueries({
|
||||
include: [GetPersonalAccessTokensDocument],
|
||||
});
|
||||
|
||||
form.reset();
|
||||
},
|
||||
});
|
||||
|
||||
const { register, formState } = form;
|
||||
|
||||
const isDirty = Object.keys(formState.dirtyFields).length > 0;
|
||||
@@ -93,44 +111,11 @@ export default function CreatePATForm({
|
||||
}, [isDirty, location, onDirtyStateChange]);
|
||||
|
||||
async function handleSubmit(formValues: CreatePATFormValues) {
|
||||
try {
|
||||
const { error, data } = await nhostClient.auth.createPAT(
|
||||
new Date(formValues.expiresAt),
|
||||
{
|
||||
name: formValues.name,
|
||||
application: 'dashboard',
|
||||
userAgent: window.navigator.userAgent,
|
||||
},
|
||||
);
|
||||
|
||||
const toastStyle = getToastStyleProps();
|
||||
|
||||
if (error) {
|
||||
toast.error(error.message, {
|
||||
style: toastStyle.style,
|
||||
...toastStyle.error,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toast.success(
|
||||
'The personal access token has been created successfully.',
|
||||
{
|
||||
style: toastStyle.style,
|
||||
...toastStyle.success,
|
||||
},
|
||||
);
|
||||
|
||||
setPersonalAccessToken(data?.personalAccessToken);
|
||||
|
||||
apolloClient.refetchQueries({
|
||||
include: [GetPersonalAccessTokensDocument],
|
||||
});
|
||||
|
||||
form.reset();
|
||||
} catch {
|
||||
// Note: This error is handled by the toast.
|
||||
}
|
||||
await createPAT(new Date(formValues.expiresAt), {
|
||||
name: formValues.name,
|
||||
application: 'dashboard',
|
||||
userAgent: window.navigator.userAgent,
|
||||
});
|
||||
}
|
||||
|
||||
if (personalAccessToken) {
|
||||
|
||||
@@ -19,7 +19,7 @@ export type DisplayNameSettingFormValues = Yup.InferType<
|
||||
>;
|
||||
|
||||
export default function DisplayNameSetting() {
|
||||
const { id: userID, displayName } = useUserData();
|
||||
const { id: userID, displayName } = useUserData() || {};
|
||||
|
||||
const [updateUserDisplayName] = useUpdateUserDisplayNameMutation();
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Form } from '@/components/form/Form';
|
||||
import { SettingsContainer } from '@/components/layout/SettingsContainer';
|
||||
import { Input } from '@/components/ui/v2/Input';
|
||||
import { execPromiseWithErrorToast } from '@/features/orgs/utils/execPromiseWithErrorToast';
|
||||
import useActionWithElevatedPermissions from '@/features/account/settings/hooks/useActionWithElevatedPermissions';
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import { useNhostClient, useUserData } from '@nhost/nextjs';
|
||||
import { FormProvider, useForm } from 'react-hook-form';
|
||||
@@ -15,7 +15,7 @@ export type EmailSettingFormValues = Yup.InferType<typeof validationSchema>;
|
||||
|
||||
export default function EmailSetting() {
|
||||
const nhost = useNhostClient();
|
||||
const { email } = useUserData();
|
||||
const { email } = useUserData() || {};
|
||||
|
||||
const form = useForm<EmailSettingFormValues>({
|
||||
reValidateMode: 'onSubmit',
|
||||
@@ -26,25 +26,23 @@ export default function EmailSetting() {
|
||||
const { register, formState } = form;
|
||||
const isDirty = Object.keys(formState.dirtyFields).length > 0;
|
||||
|
||||
const changeEmail = useActionWithElevatedPermissions({
|
||||
actionFn: async (newEmail: string) => {
|
||||
const result = await nhost.auth.changeEmail({
|
||||
newEmail,
|
||||
options: {
|
||||
redirectTo: `${window.location.origin}/account`,
|
||||
},
|
||||
});
|
||||
return result;
|
||||
},
|
||||
successMessage:
|
||||
'Please check your inbox. Follow the link to finalize changing your email.',
|
||||
onSuccess: () => form.reset(),
|
||||
});
|
||||
|
||||
async function handleSubmit(formValues: EmailSettingFormValues) {
|
||||
await execPromiseWithErrorToast(
|
||||
async () => {
|
||||
await nhost.auth.changeEmail({
|
||||
newEmail: formValues.email,
|
||||
options: {
|
||||
redirectTo: `${window.location.origin}/account`,
|
||||
},
|
||||
});
|
||||
form.reset({ email: formValues.email });
|
||||
},
|
||||
{
|
||||
loadingMessage: 'Updating your email...',
|
||||
successMessage:
|
||||
'Please check your inbox. Follow the link to finalize changing your email.',
|
||||
errorMessage:
|
||||
'An error occurred while trying to update your email. Please try again.',
|
||||
},
|
||||
);
|
||||
await changeEmail(formValues.email);
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
import { Form } from '@/components/form/Form';
|
||||
import { SettingsContainer } from '@/components/layout/SettingsContainer';
|
||||
import { Input } from '@/components/ui/v2/Input';
|
||||
import { execPromiseWithErrorToast } from '@/features/orgs/utils/execPromiseWithErrorToast';
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import { useChangePassword } from '@nhost/nextjs';
|
||||
import { FormProvider, useForm } from 'react-hook-form';
|
||||
import * as Yup from 'yup';
|
||||
|
||||
const validationSchema = Yup.object({
|
||||
newPassword: Yup.string()
|
||||
.label('New Password')
|
||||
.nullable()
|
||||
.required('This field is required.'),
|
||||
confirmPassword: Yup.string()
|
||||
.label('Confirm Password')
|
||||
.nullable()
|
||||
.required('This field is required.')
|
||||
.test(
|
||||
'passwords-match',
|
||||
'Passwords must match.',
|
||||
(value, ctx) => ctx.parent.newPassword === value,
|
||||
),
|
||||
});
|
||||
|
||||
export type PasswordSettingsFormValues = Yup.InferType<typeof validationSchema>;
|
||||
|
||||
export default function PasswordSettings() {
|
||||
const { changePassword } = useChangePassword();
|
||||
const form = useForm<PasswordSettingsFormValues>({
|
||||
reValidateMode: 'onSubmit',
|
||||
resolver: yupResolver(validationSchema),
|
||||
});
|
||||
|
||||
const { register, formState } = form;
|
||||
const isDirty = Object.keys(formState.dirtyFields).length > 0;
|
||||
|
||||
async function handleSubmit(formValues: PasswordSettingsFormValues) {
|
||||
await execPromiseWithErrorToast(
|
||||
async () => {
|
||||
// TODO fix changePassword should throw an error if something happens
|
||||
await changePassword(formValues.newPassword);
|
||||
form.reset();
|
||||
},
|
||||
{
|
||||
loadingMessage: 'Changing password...',
|
||||
successMessage: 'The password has been changed successfully.',
|
||||
errorMessage:
|
||||
'An error occurred while trying to update the password. Please try again.',
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<FormProvider {...form}>
|
||||
<Form onSubmit={handleSubmit}>
|
||||
<SettingsContainer
|
||||
title="Change Password"
|
||||
description="Update your account password."
|
||||
slotProps={{
|
||||
submitButton: {
|
||||
disabled: !isDirty,
|
||||
loading: formState.isSubmitting,
|
||||
},
|
||||
}}
|
||||
className="grid grid-flow-row lg:grid-cols-5"
|
||||
>
|
||||
<Input
|
||||
{...register('newPassword')}
|
||||
className="col-span-2"
|
||||
type="password"
|
||||
id="new-password"
|
||||
label="New Password"
|
||||
fullWidth
|
||||
helperText={formState.errors.newPassword?.message}
|
||||
error={Boolean(formState.errors.newPassword)}
|
||||
/>
|
||||
|
||||
<Input
|
||||
{...register('confirmPassword')}
|
||||
className="col-span-2 row-start-2"
|
||||
type="password"
|
||||
id="confirm-password"
|
||||
label="Confirm Password"
|
||||
fullWidth
|
||||
helperText={formState.errors.confirmPassword?.message}
|
||||
error={Boolean(formState.errors.confirmPassword)}
|
||||
/>
|
||||
</SettingsContainer>
|
||||
</Form>
|
||||
</FormProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { FormInput } from '@/components/form/FormInput';
|
||||
import { Button } from '@/components/ui/v3/button';
|
||||
import { Form } from '@/components/ui/v3/form';
|
||||
import useChangePasswordForm from '@/features/account/settings/components/PasswordSettings/hooks/useChangePasswordForm';
|
||||
import useOnChangePasswordHandler from '@/features/account/settings/components/PasswordSettings/hooks/useOnChangePasswordHandler';
|
||||
|
||||
export default function PasswordSettings() {
|
||||
const form = useChangePasswordForm();
|
||||
const onSubmit = useOnChangePasswordHandler({
|
||||
onSuccess: () => form.reset(),
|
||||
});
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)}>
|
||||
<div className="rounded-lg border border-[#EAEDF0] bg-white font-['Inter_var'] dark:border-[#2F363D] dark:bg-paper">
|
||||
<div className="flex w-full flex-col items-start gap-4 p-4">
|
||||
<div className="flex w-full flex-col items-start">
|
||||
<h3 className="text-[1.125rem] font-semibold leading-[1.75]">
|
||||
Change Password
|
||||
</h3>
|
||||
<p className="text-[#556378] dark:text-[#A2B3BE]">
|
||||
Update your account password.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex w-[370px] flex-col gap-4">
|
||||
<FormInput
|
||||
control={form.control}
|
||||
name="newPassword"
|
||||
type="password"
|
||||
label="New Password"
|
||||
/>
|
||||
<FormInput
|
||||
control={form.control}
|
||||
name="confirmPassword"
|
||||
type="password"
|
||||
label="Confirm Password"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full items-center justify-end border-t border-[#EAEDF0] px-4 py-2 dark:border-[#2F363D]">
|
||||
<Button type="submit" variant="outline">
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
const validationSchema = z
|
||||
.object({
|
||||
newPassword: z
|
||||
.string({
|
||||
required_error: 'This field is required.',
|
||||
})
|
||||
.min(1, 'This field is required.'),
|
||||
confirmPassword: z
|
||||
.string({
|
||||
required_error: 'This field is required.',
|
||||
})
|
||||
.min(1, 'This field is required.'),
|
||||
})
|
||||
.refine((data) => data.newPassword === data.confirmPassword, {
|
||||
message: 'Passwords must match.',
|
||||
path: ['confirmPassword'],
|
||||
});
|
||||
|
||||
export type ChangePasswordFormValues = z.infer<typeof validationSchema>;
|
||||
|
||||
function useChangePasswordForm() {
|
||||
const form = useForm<ChangePasswordFormValues>({
|
||||
mode: 'onTouched',
|
||||
reValidateMode: 'onBlur',
|
||||
defaultValues: {
|
||||
newPassword: '',
|
||||
confirmPassword: '',
|
||||
},
|
||||
resolver: zodResolver(validationSchema),
|
||||
});
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
export default useChangePasswordForm;
|
||||
@@ -0,0 +1,27 @@
|
||||
import useActionWithElevatedPermissions from '@/features/account/settings/hooks/useActionWithElevatedPermissions';
|
||||
import { useChangePassword } from '@nhost/nextjs';
|
||||
import { type ChangePasswordFormValues } from './useChangePasswordForm';
|
||||
|
||||
interface Props {
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
function useOnChangePasswordHandler({ onSuccess }: Props) {
|
||||
const { changePassword: actionFn } = useChangePassword();
|
||||
|
||||
const changePassword = useActionWithElevatedPermissions({
|
||||
actionFn,
|
||||
onSuccess,
|
||||
successMessage: 'The password has been changed successfully.',
|
||||
});
|
||||
|
||||
async function onSubmit(values: ChangePasswordFormValues) {
|
||||
const { newPassword } = values;
|
||||
|
||||
await changePassword(newPassword);
|
||||
}
|
||||
|
||||
return onSubmit;
|
||||
}
|
||||
|
||||
export default useOnChangePasswordHandler;
|
||||
@@ -1,2 +1 @@
|
||||
export * from './PasswordSettings';
|
||||
export { default as PasswordSettings } from './PasswordSettings';
|
||||
export { default as PasswordSettings } from './components/PasswordSettings';
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Button } from '@/components/ui/v3/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/v3/dialog';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
|
||||
import SecurityKeyForm from './NewSecurityKeyForm';
|
||||
|
||||
function AddSecurityKeyButton() {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="h-9 gap-2 px-2 py-[0.375rem] hover:bg-[#d6eefb] dark:hover:bg-[#1e2942]"
|
||||
>
|
||||
<Plus className="h-5 w-5" />
|
||||
Add New Security Key
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent
|
||||
className="sr z-[9999] text-foreground sm:max-w-xl"
|
||||
aria-describedby="Add a Security Key"
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add a Security Key</DialogTitle>
|
||||
</DialogHeader>
|
||||
<DialogDescription className="sr-only">
|
||||
Add a Security Key
|
||||
</DialogDescription>
|
||||
<SecurityKeyForm onSuccess={() => setOpen(false)} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default AddSecurityKeyButton;
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Button } from '@/components/ui/v3/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/v3/form';
|
||||
import { Input } from '@/components/ui/v3/input';
|
||||
import useNewSecurityKeyForm from '@/features/account/settings/components/SecurityKeysSettings/hooks/useNewSecurityKeyForm';
|
||||
import useOnAddNewSecurityKeyHandler from '@/features/account/settings/components/SecurityKeysSettings/hooks/useOnAddNewSecurityKeyHandler';
|
||||
|
||||
interface Props {
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
function NewSecurityKeyForm({ onSuccess }: Props) {
|
||||
const form = useNewSecurityKeyForm();
|
||||
const onSubmit = useOnAddNewSecurityKeyHandler({ onSuccess });
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className="grid grid-flow-row gap-4 bg-transparent"
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="nickname"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
placeholder="Name"
|
||||
{...field}
|
||||
className="!bg-transparent"
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="outline"
|
||||
className="w-full !bg-transparent"
|
||||
>
|
||||
Add new security key
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
export default NewSecurityKeyForm;
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Button } from '@/components/ui/v3/button';
|
||||
import useRemoveSecurityKey from '@/features/account/settings/components/SecurityKeysSettings/hooks/useRemoveSecurityKey';
|
||||
import { execPromiseWithErrorToast } from '@/features/orgs/utils/execPromiseWithErrorToast';
|
||||
import { Trash } from 'lucide-react';
|
||||
import { memo } from 'react';
|
||||
|
||||
interface Props {
|
||||
id: string;
|
||||
}
|
||||
|
||||
function RemoveSecurityKeyButton({ id }: Props) {
|
||||
const removeSecurityKey = useRemoveSecurityKey();
|
||||
|
||||
function handleClick() {
|
||||
execPromiseWithErrorToast(async () => removeSecurityKey(id), {
|
||||
loadingMessage: 'Removing security key...',
|
||||
successMessage: 'Security key has been removed successfully.',
|
||||
errorMessage:
|
||||
'An error occurred while trying to remove security key. Please try again.',
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
onClick={handleClick}
|
||||
aria-label={`Remove security key ${id}`}
|
||||
>
|
||||
<Trash />
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
export default memo(RemoveSecurityKeyButton);
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Spinner } from '@/components/ui/v3/spinner';
|
||||
import useGetSecurityKeys from '@/features/account/settings/hooks/useGetSecurityKeys';
|
||||
import { InfoAlert } from '@/features/orgs/components/InfoAlert';
|
||||
import { Fingerprint } from 'lucide-react';
|
||||
import { memo } from 'react';
|
||||
import RemoveSecurityKeyButton from './RemoveSecurityKeyButton';
|
||||
|
||||
type SecurityKeyProps = {
|
||||
id: string;
|
||||
nickname?: string;
|
||||
};
|
||||
|
||||
function SecurityKey({ id, nickname }: SecurityKeyProps) {
|
||||
return (
|
||||
<div className="flex w-full items-center justify-between rounded-lg border border-[#EAEDF0] px-2 py-2 dark:border-[#2F363D]">
|
||||
<div className="flex justify-start gap-3">
|
||||
<Fingerprint />
|
||||
<span>{nickname || id}</span>
|
||||
</div>
|
||||
<RemoveSecurityKeyButton id={id} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const MemoizedSecurityKey = memo(SecurityKey);
|
||||
|
||||
function SecurityKeyList() {
|
||||
const { data, loading } = useGetSecurityKeys();
|
||||
|
||||
return (
|
||||
<div>
|
||||
{loading && <Spinner />}
|
||||
{!loading && data?.authUserSecurityKeys.length === 0 && (
|
||||
<InfoAlert>No security keys have been added yet!</InfoAlert>
|
||||
)}
|
||||
{data?.authUserSecurityKeys.map(({ id, nickname }) => (
|
||||
<MemoizedSecurityKey key={id} id={id} nickname={nickname} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default SecurityKeyList;
|
||||
@@ -0,0 +1,24 @@
|
||||
import AddSecurityKeyButton from './AddSecurityKeyButton';
|
||||
import SecurityKeyList from './SecurityKeyList';
|
||||
|
||||
function SecurityKeysSettings() {
|
||||
return (
|
||||
<div className="rounded-lg border border-[#EAEDF0] bg-white font-display dark:border-[#2F363D] dark:bg-paper">
|
||||
<div className="flex w-full flex-col items-start gap-6 p-4">
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<h3 className="text-[1.125rem] font-semibold leading-[1.75]">
|
||||
Manage your security keys
|
||||
</h3>
|
||||
</div>
|
||||
<div className="flex w-full flex-col gap-4">
|
||||
<SecurityKeyList />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full items-center border-t border-[#EAEDF0] px-4 py-2 dark:border-[#2F363D]">
|
||||
<AddSecurityKeyButton />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default SecurityKeysSettings;
|
||||
@@ -0,0 +1,25 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
const validationSchema = z
|
||||
.object({
|
||||
nickname: z.string().min(1, { message: 'Nickname is required' }),
|
||||
})
|
||||
.required();
|
||||
|
||||
export type NewSecurityKeyFormValues = z.infer<typeof validationSchema>;
|
||||
|
||||
function useNewSecurityKeyForm() {
|
||||
const form = useForm<NewSecurityKeyFormValues>({
|
||||
reValidateMode: 'onSubmit',
|
||||
defaultValues: {
|
||||
nickname: '',
|
||||
},
|
||||
resolver: zodResolver(validationSchema),
|
||||
});
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
export default useNewSecurityKeyForm;
|
||||
@@ -0,0 +1,30 @@
|
||||
import useActionWithElevatedPermissions from '@/features/account/settings/hooks/useActionWithElevatedPermissions';
|
||||
import useGetSecurityKeys from '@/features/account/settings/hooks/useGetSecurityKeys';
|
||||
import { useAddSecurityKey } from '@nhost/nextjs';
|
||||
import { type NewSecurityKeyFormValues } from './useNewSecurityKeyForm';
|
||||
|
||||
interface Props {
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
function useOnAddNewSecurityKeyHandler({ onSuccess }: Props) {
|
||||
const { refetch } = useGetSecurityKeys();
|
||||
const { add: actionFn } = useAddSecurityKey();
|
||||
const addSecurityKey = useActionWithElevatedPermissions({
|
||||
actionFn,
|
||||
onSuccess: async () => {
|
||||
await refetch();
|
||||
onSuccess();
|
||||
},
|
||||
successMessage: 'Security key has been added.',
|
||||
});
|
||||
|
||||
async function onSubmit(values: NewSecurityKeyFormValues) {
|
||||
const { nickname } = values;
|
||||
await addSecurityKey(nickname);
|
||||
}
|
||||
|
||||
return onSubmit;
|
||||
}
|
||||
|
||||
export default useOnAddNewSecurityKeyHandler;
|
||||
@@ -0,0 +1,22 @@
|
||||
import useElevatedPermissions from '@/features/account/settings/hooks/useElevatedPermissions';
|
||||
import useGetSecurityKeys from '@/features/account/settings/hooks/useGetSecurityKeys';
|
||||
import { useRemoveSecurityKeyMutation } from '@/utils/__generated__/graphql';
|
||||
|
||||
function useRemoveSecurityKey() {
|
||||
const [removeSecurityKeyMutation] = useRemoveSecurityKeyMutation();
|
||||
const { elevatePermissions } = useElevatedPermissions();
|
||||
const { refetch: refetchSecurityKeys } = useGetSecurityKeys();
|
||||
|
||||
async function removeSecurityKey(id: string) {
|
||||
const permissionGranted = await elevatePermissions(true);
|
||||
|
||||
if (permissionGranted) {
|
||||
await removeSecurityKeyMutation({ variables: { id } });
|
||||
await refetchSecurityKeys();
|
||||
}
|
||||
}
|
||||
|
||||
return removeSecurityKey;
|
||||
}
|
||||
|
||||
export default useRemoveSecurityKey;
|
||||
@@ -0,0 +1 @@
|
||||
export { default as SecurityKeysSettings } from './components/SecurityKeysSettings';
|
||||
@@ -0,0 +1,5 @@
|
||||
query getActiveMfaType($id: uuid!) {
|
||||
user(id: $id) {
|
||||
activeMfaType
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
query securityKeys($userId: uuid!) {
|
||||
authUserSecurityKeys(where: { userId: { _eq: $userId } }) {
|
||||
id
|
||||
nickname
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
mutation removeSecurityKey($id: uuid!) {
|
||||
deleteAuthUserSecurityKey(id: $id) {
|
||||
id
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import useElevatedPermissions from '@/features/account/settings/hooks/useElevatedPermissions';
|
||||
import useGetSecurityKeys from '@/features/account/settings/hooks/useGetSecurityKeys';
|
||||
import type { AuthErrorPayload } from '@nhost/nextjs';
|
||||
import { toast } from 'react-hot-toast';
|
||||
|
||||
type Action = (...args: any[]) => Promise<ActionResult>;
|
||||
|
||||
type ActionResult = {
|
||||
isError?: boolean;
|
||||
error: AuthErrorPayload;
|
||||
};
|
||||
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
|
||||
|
||||
interface Props<Fn extends Action> {
|
||||
actionFn: Fn;
|
||||
onSuccess?: (result: UnwrapPromise<ReturnType<Fn>>) => void;
|
||||
onError?: () => void;
|
||||
successMessage?: string;
|
||||
}
|
||||
|
||||
function useActionWithElevatedPermissions<F extends Action>({
|
||||
actionFn,
|
||||
onSuccess,
|
||||
onError,
|
||||
successMessage,
|
||||
}: Props<F>) {
|
||||
const { elevated, elevatePermissions } = useElevatedPermissions();
|
||||
const { data } = useGetSecurityKeys();
|
||||
|
||||
async function requestPermissions() {
|
||||
if (elevated || data?.authUserSecurityKeys.length === 0) {
|
||||
return true;
|
||||
}
|
||||
const isPermissionsElevated = await elevatePermissions();
|
||||
return isPermissionsElevated;
|
||||
}
|
||||
|
||||
async function actionWithElevatedPermissions(...args: Parameters<F>) {
|
||||
let isSuccess = false;
|
||||
const permissionGranted = await requestPermissions();
|
||||
|
||||
if (!permissionGranted) {
|
||||
return isSuccess;
|
||||
}
|
||||
|
||||
const response = await actionFn(...args);
|
||||
if (response.error) {
|
||||
toast.error(response.error?.message || 'Something went wrong.');
|
||||
onError?.();
|
||||
} else {
|
||||
toast.success(successMessage || 'Success');
|
||||
onSuccess?.(response as UnwrapPromise<ReturnType<F>>);
|
||||
isSuccess = true;
|
||||
}
|
||||
|
||||
return isSuccess;
|
||||
}
|
||||
return actionWithElevatedPermissions;
|
||||
}
|
||||
|
||||
export default useActionWithElevatedPermissions;
|
||||
@@ -0,0 +1,36 @@
|
||||
import { getToastStyleProps } from '@/utils/constants/settings';
|
||||
import { useElevateSecurityKeyEmail, useUserData } from '@nhost/nextjs';
|
||||
import { toast } from 'react-hot-toast';
|
||||
|
||||
function useElevatedPermissions() {
|
||||
const user = useUserData();
|
||||
|
||||
const { elevated, elevateEmailSecurityKey } = useElevateSecurityKeyEmail();
|
||||
|
||||
async function elevatePermissions(shouldThrowError = false) {
|
||||
if (elevated) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
const response = await elevateEmailSecurityKey(user.email);
|
||||
if (response.isError) {
|
||||
const errorMessage =
|
||||
response.error?.message || 'Permissions were not elevated';
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (shouldThrowError) {
|
||||
throw e;
|
||||
} else {
|
||||
const message = e?.message || 'Could not elevate permissions';
|
||||
toast.error(message, getToastStyleProps());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { elevated, elevatePermissions };
|
||||
}
|
||||
|
||||
export default useElevatedPermissions;
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useSecurityKeysQuery } from '@/utils/__generated__/graphql';
|
||||
import { useUserId } from '@nhost/nextjs';
|
||||
|
||||
function useGetSecurityKeys() {
|
||||
const currentUserId = useUserId();
|
||||
const query = useSecurityKeysQuery({
|
||||
variables: {
|
||||
userId: currentUserId,
|
||||
},
|
||||
});
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
export default useGetSecurityKeys;
|
||||
@@ -0,0 +1,35 @@
|
||||
import { ButtonWithLoading as Button } from '@/components/ui/v3/button';
|
||||
import {
|
||||
useGithubAuthentication,
|
||||
type UseGithubAuthenticationHookProps,
|
||||
} from '@/features/auth/AuthProviders/Github/hooks/useGithubAuthentication';
|
||||
import { SiGithub } from '@icons-pack/react-simple-icons';
|
||||
|
||||
interface Props extends UseGithubAuthenticationHookProps {
|
||||
buttonText?: string;
|
||||
withAnonId?: boolean;
|
||||
redirectTo?: string;
|
||||
}
|
||||
|
||||
function GithubAuthButton({
|
||||
buttonText = 'Continue with GitHub',
|
||||
withAnonId = false,
|
||||
redirectTo,
|
||||
}: Props) {
|
||||
const { mutate: signInWithGithub, isLoading } = useGithubAuthentication({
|
||||
withAnonId,
|
||||
redirectTo,
|
||||
});
|
||||
return (
|
||||
<Button
|
||||
className="gap-2 !bg-white text-sm+ !text-black hover:ring-2 hover:ring-white hover:ring-opacity-50 disabled:!text-black disabled:!text-opacity-60"
|
||||
disabled={isLoading}
|
||||
loading={isLoading}
|
||||
onClick={() => signInWithGithub()}
|
||||
>
|
||||
<SiGithub size={14} /> {buttonText}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
export default GithubAuthButton;
|
||||
@@ -0,0 +1 @@
|
||||
export { default as GithubAuthButton } from './GithubAuthButton';
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './useGithubAuthentication';
|
||||
export { default as useGithubAuthentication } from './useGithubAuthentication';
|
||||
@@ -0,0 +1,39 @@
|
||||
import { getAnonId } from '@/lib/segment';
|
||||
import { isNotEmptyValue } from '@/lib/utils';
|
||||
import { getToastStyleProps } from '@/utils/constants/settings';
|
||||
import { nhost } from '@/utils/nhost';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { toast } from 'react-hot-toast';
|
||||
|
||||
export interface UseGithubAuthenticationHookProps {
|
||||
withAnonId?: boolean;
|
||||
redirectTo?: string;
|
||||
errorText?: string;
|
||||
}
|
||||
|
||||
function useGithubAuthentication({
|
||||
withAnonId = false,
|
||||
redirectTo,
|
||||
errorText,
|
||||
}: UseGithubAuthenticationHookProps) {
|
||||
const githubAuthenticationMutation = useMutation(
|
||||
async () => {
|
||||
const options = {
|
||||
...(isNotEmptyValue(redirectTo) && { redirectTo }),
|
||||
...(withAnonId && { metadata: { anonId: await getAnonId() } }),
|
||||
};
|
||||
return nhost.auth.signIn({
|
||||
provider: 'github',
|
||||
...(isNotEmptyValue(options) && { options }),
|
||||
});
|
||||
},
|
||||
{
|
||||
onError: () => {
|
||||
toast.error(errorText, getToastStyleProps());
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return githubAuthenticationMutation;
|
||||
}
|
||||
export default useGithubAuthentication;
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Button } from '@/components/ui/v3/button';
|
||||
import { useSignInWithSecurityKey } from '@/features/auth/SignIn/SecurityKey/hooks/useSignInWithSecurityKey';
|
||||
import { Fingerprint } from 'lucide-react';
|
||||
import { VerifyEmailDialog } from './VerifyEmailDialog';
|
||||
|
||||
function SignInWithSecurityKey() {
|
||||
const { disabled, signInWithSecurityKey, needsEmailVerification } =
|
||||
useSignInWithSecurityKey();
|
||||
return (
|
||||
<>
|
||||
<VerifyEmailDialog needsEmailVerification={needsEmailVerification} />
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="gap-2 !bg-white text-sm+ !text-black hover:ring-2 hover:ring-white hover:ring-opacity-50 disabled:!text-black disabled:!text-opacity-60"
|
||||
disabled={disabled}
|
||||
onClick={signInWithSecurityKey}
|
||||
>
|
||||
<Fingerprint size={14} />
|
||||
Continue with a security key
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default SignInWithSecurityKey;
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/v3/dialog';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
interface Props {
|
||||
needsEmailVerification: boolean;
|
||||
}
|
||||
|
||||
export function VerifyEmailDialog({ needsEmailVerification }: Props) {
|
||||
const [open, setOpen] = useState(needsEmailVerification);
|
||||
|
||||
useEffect(() => {
|
||||
setOpen(needsEmailVerification);
|
||||
}, [needsEmailVerification, open]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Email verification required</DialogTitle>
|
||||
<DialogDescription>
|
||||
You need to verify your email first. Please check your mailbox and
|
||||
follow the confirmation link to complete the registration.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { default as useSignInWithSecurityKey } from './useSignInWithSecurityKey';
|
||||
@@ -0,0 +1,34 @@
|
||||
import { getToastStyleProps } from '@/utils/constants/settings';
|
||||
import { useSignInSecurityKey } from '@nhost/nextjs';
|
||||
import { useRouter } from 'next/router';
|
||||
import { useState } from 'react';
|
||||
import { toast } from 'react-hot-toast';
|
||||
|
||||
function useSignInWithSecurityKey() {
|
||||
const { signInSecurityKey } = useSignInSecurityKey();
|
||||
const [needsEmailVerification, setNeedsEmailVerification] = useState(false);
|
||||
const [disabled, setDisabled] = useState(false);
|
||||
const { replace } = useRouter();
|
||||
|
||||
async function signInWithSecurityKey() {
|
||||
setDisabled(true);
|
||||
const {
|
||||
isError,
|
||||
isSuccess,
|
||||
needsEmailVerification: _needsEmailVerification,
|
||||
error,
|
||||
} = await signInSecurityKey();
|
||||
if (isError) {
|
||||
toast.error(error?.message, getToastStyleProps());
|
||||
} else if (_needsEmailVerification) {
|
||||
setNeedsEmailVerification(true);
|
||||
} else if (isSuccess) {
|
||||
replace('/');
|
||||
}
|
||||
setDisabled(false);
|
||||
}
|
||||
|
||||
return { disabled, signInWithSecurityKey, needsEmailVerification };
|
||||
}
|
||||
|
||||
export default useSignInWithSecurityKey;
|
||||
1
dashboard/src/features/auth/SignIn/SecurityKey/index.ts
Normal file
1
dashboard/src/features/auth/SignIn/SecurityKey/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as SignInWithSecurityKey } from './components/SignInWithSecurityKey/SignInWithSecurityKey';
|
||||
@@ -0,0 +1,26 @@
|
||||
import { MfaOtpForm } from '@/components/common/MfaOtpForm';
|
||||
import type { SendMfaOtpHandler } from '@nhost/nextjs';
|
||||
import { Smartphone } from 'lucide-react';
|
||||
|
||||
interface Props {
|
||||
sendMfaOtp: SendMfaOtpHandler;
|
||||
loading: boolean;
|
||||
}
|
||||
|
||||
function MfaSignInOtpForm({ sendMfaOtp, loading }: Props) {
|
||||
return (
|
||||
<div className="ws-full relative grid grid-flow-row gap-4 bg-transparent">
|
||||
<div className="flex w-full flex-col items-center justify-center gap-3">
|
||||
<Smartphone size={32} />
|
||||
<h2 className="text-[1.25rem]">Authentication Code</h2>
|
||||
</div>
|
||||
<MfaOtpForm loading={loading} sendMfaOtp={sendMfaOtp} />
|
||||
<p className="text-center">
|
||||
Open your authenticator app or browser extension to view your
|
||||
authentication code.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default MfaSignInOtpForm;
|
||||
@@ -0,0 +1,16 @@
|
||||
import useOnSignUpWithPasswordHandler from '@/features/auth/SignIn/SignInWithEmailAndPassword/hooks/useOnSignInWithEmailAndPasswordHandler';
|
||||
import MfaSignInOtpForm from './MfaSignInOtpForm';
|
||||
import SignInWithEmailAndPasswordForm from './SignInWithEmailAndPasswordForm';
|
||||
|
||||
function SignInWithEmailAndPassword() {
|
||||
const { onSignIWithEmailAndPassword, sendMfaOtp, isLoading, needsMfaOtp } =
|
||||
useOnSignUpWithPasswordHandler();
|
||||
|
||||
return needsMfaOtp ? (
|
||||
<MfaSignInOtpForm sendMfaOtp={sendMfaOtp} loading={isLoading} />
|
||||
) : (
|
||||
<SignInWithEmailAndPasswordForm onSubmit={onSignIWithEmailAndPassword} />
|
||||
);
|
||||
}
|
||||
|
||||
export default SignInWithEmailAndPassword;
|
||||
@@ -0,0 +1,57 @@
|
||||
import { FormInput } from '@/components/form/FormInput';
|
||||
import { Button } from '@/components/ui/v3/button';
|
||||
import { Form } from '@/components/ui/v3/form';
|
||||
import useSignInWithEmailAndPasswordForm, {
|
||||
type SignInWithEmailAndPasswordFormValues,
|
||||
} from '@/features/auth/SignIn/SignInWithEmailAndPassword/hooks/useSignInWithEmailAndPasswordForm';
|
||||
import NextLink from 'next/link';
|
||||
|
||||
interface Props {
|
||||
onSubmit: (values: SignInWithEmailAndPasswordFormValues) => void;
|
||||
}
|
||||
|
||||
function SignInWithEmailAndPassword({ onSubmit }: Props) {
|
||||
const form = useSignInWithEmailAndPasswordForm();
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(onSubmit)}
|
||||
className="grid grid-flow-row gap-4 bg-transparent"
|
||||
>
|
||||
<FormInput
|
||||
control={form.control}
|
||||
label="Email"
|
||||
name="email"
|
||||
type="email"
|
||||
/>
|
||||
<FormInput
|
||||
control={form.control}
|
||||
label="Password"
|
||||
name="password"
|
||||
type="password"
|
||||
/>
|
||||
<NextLink
|
||||
href="/password/new"
|
||||
className="justify-self-start font-semibold"
|
||||
>
|
||||
Forgot password?
|
||||
</NextLink>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="outline"
|
||||
className="w-full !bg-white !text-black disabled:!text-black disabled:!text-opacity-60"
|
||||
>
|
||||
Sign In
|
||||
</Button>
|
||||
<p color="secondary" className="text-center">
|
||||
<span className="text-[#A2B3BE]">or </span>
|
||||
<NextLink className="font-semibold" href="/signin">
|
||||
sign in with GitHub
|
||||
</NextLink>
|
||||
</p>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
export default SignInWithEmailAndPassword;
|
||||
@@ -0,0 +1,50 @@
|
||||
import { getToastStyleProps } from '@/utils/constants/settings';
|
||||
import {
|
||||
useSendVerificationEmail,
|
||||
useSignInEmailPassword,
|
||||
} from '@nhost/nextjs';
|
||||
import { useRouter } from 'next/router';
|
||||
import toast from 'react-hot-toast';
|
||||
import type { SignInWithEmailAndPasswordFormValues } from './useSignInWithEmailAndPasswordForm';
|
||||
|
||||
function useOnSignInWithEmailAndPasswordHandler() {
|
||||
const router = useRouter();
|
||||
const { signInEmailPassword, needsMfaOtp, sendMfaOtp, isLoading } =
|
||||
useSignInEmailPassword();
|
||||
|
||||
const { sendEmail } = useSendVerificationEmail();
|
||||
|
||||
async function onSignIWithEmailAndPassword({
|
||||
email,
|
||||
password,
|
||||
}: SignInWithEmailAndPasswordFormValues) {
|
||||
try {
|
||||
const { needsEmailVerification, error } = await signInEmailPassword(
|
||||
email,
|
||||
password,
|
||||
);
|
||||
if (error) {
|
||||
toast.error(
|
||||
error?.message ||
|
||||
'An error occurred while signing in. Please try again.',
|
||||
getToastStyleProps(),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (needsEmailVerification) {
|
||||
await sendEmail(email);
|
||||
router.push(`/email/verify?email=${encodeURIComponent(email)}`);
|
||||
}
|
||||
} catch {
|
||||
toast.error(
|
||||
'An error occurred while signing in. Please try again.',
|
||||
getToastStyleProps(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { onSignIWithEmailAndPassword, needsMfaOtp, sendMfaOtp, isLoading };
|
||||
}
|
||||
|
||||
export default useOnSignInWithEmailAndPasswordHandler;
|
||||
@@ -0,0 +1,30 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
const validationSchema = z
|
||||
.object({
|
||||
email: z.string().email({ message: 'Invalid email address' }),
|
||||
password: z.string().min(1, { message: 'Password is required' }),
|
||||
})
|
||||
.required();
|
||||
|
||||
export type SignInWithEmailAndPasswordFormValues = z.infer<
|
||||
typeof validationSchema
|
||||
>;
|
||||
|
||||
function useSignInWithEmailAndPasswordForm() {
|
||||
const form = useForm<SignInWithEmailAndPasswordFormValues>({
|
||||
mode: 'onTouched',
|
||||
reValidateMode: 'onBlur',
|
||||
defaultValues: {
|
||||
email: '',
|
||||
password: '',
|
||||
},
|
||||
resolver: zodResolver(validationSchema),
|
||||
});
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
export default useSignInWithEmailAndPasswordForm;
|
||||
@@ -0,0 +1 @@
|
||||
export { default as SignInWithEmailAndPassword } from './components/SignInWithEmailAndPassword';
|
||||
@@ -0,0 +1,15 @@
|
||||
import { GithubAuthButton } from '@/features/auth/AuthProviders/Github/components/GithubAuthButton';
|
||||
import { useHostName } from '@/features/orgs/projects/common/hooks/useHostName';
|
||||
|
||||
function SignInWithGithub() {
|
||||
const redirectTo = useHostName();
|
||||
return (
|
||||
<GithubAuthButton
|
||||
redirectTo={redirectTo}
|
||||
buttonText="Continue with GitHub"
|
||||
errorText="An error occurred while trying to sign in using GitHub. Please try again later."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default SignInWithGithub;
|
||||
@@ -0,0 +1 @@
|
||||
export { default as SignInWithGithub } from './SignInWithGithub';
|
||||
39
dashboard/src/features/auth/SignUp/SignUpTabs/SignUpTabs.tsx
Normal file
39
dashboard/src/features/auth/SignUp/SignUpTabs/SignUpTabs.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
import {
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from '@/components/ui/v3/tabs';
|
||||
import { useState } from 'react';
|
||||
import { SignUpWithEmailAndPasswordForm } from './SignUpWithEmailAndPassword';
|
||||
import { SignUpWithSecurityKeyForm } from './SignUpWithSecurityKey';
|
||||
|
||||
function SignUpTabs() {
|
||||
const [tab, setTab] = useState<string>('password');
|
||||
return (
|
||||
<Tabs value={tab} onValueChange={setTab} className="w-full">
|
||||
<TabsList className="w-full">
|
||||
<TabsTrigger value="password" className="w-full">
|
||||
Sign Up with a Password
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="security-key" className="w-full">
|
||||
Sign Up with a Security key
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<div className="pt-7">
|
||||
{tab === 'password' && (
|
||||
<TabsContent value="password">
|
||||
<SignUpWithEmailAndPasswordForm />
|
||||
</TabsContent>
|
||||
)}
|
||||
{tab === 'security-key' && (
|
||||
<TabsContent value="security-key">
|
||||
<SignUpWithSecurityKeyForm />
|
||||
</TabsContent>
|
||||
)}
|
||||
</div>
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
|
||||
export default SignUpTabs;
|
||||
@@ -0,0 +1,81 @@
|
||||
import { FormInput } from '@/components/form/FormInput';
|
||||
import { Button } from '@/components/ui/v3/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/v3/form';
|
||||
import useOnSignUpWithPasswordHandler from '@/features/auth/SignUp/SignUpTabs/SignUpWithEmailAndPassword/hooks/useOnSignUpWithPasswordHandler';
|
||||
import useSignUpWithEmailAndPasswordForm from '@/features/auth/SignUp/SignUpTabs/SignUpWithEmailAndPassword/hooks/useSignUpWithEmailAndPasswordForm';
|
||||
import { Turnstile } from '@marsidev/react-turnstile';
|
||||
|
||||
function SignUpWithEmailAndPasswordForm() {
|
||||
const form = useSignUpWithEmailAndPasswordForm();
|
||||
const onSignUpWithPassword = useOnSignUpWithPasswordHandler();
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(onSignUpWithPassword)}
|
||||
className="grid grid-flow-row gap-4 bg-transparent"
|
||||
>
|
||||
<FormInput control={form.control} label="Name" name="displayName" />
|
||||
<FormInput
|
||||
control={form.control}
|
||||
label="Email"
|
||||
name="email"
|
||||
type="email"
|
||||
/>
|
||||
<FormInput
|
||||
control={form.control}
|
||||
label="Password"
|
||||
name="password"
|
||||
type="password"
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="turnstileToken"
|
||||
render={() => (
|
||||
<FormItem>
|
||||
<FormLabel>Verification</FormLabel>
|
||||
<FormControl>
|
||||
<Turnstile
|
||||
siteKey={process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY}
|
||||
options={{ theme: 'dark', size: 'flexible' }}
|
||||
onSuccess={(token) => {
|
||||
form.setValue('turnstileToken', token, {
|
||||
shouldValidate: true,
|
||||
});
|
||||
}}
|
||||
onError={() => {
|
||||
form.setValue('turnstileToken', '', {
|
||||
shouldValidate: true,
|
||||
});
|
||||
}}
|
||||
onExpire={() => {
|
||||
form.setValue('turnstileToken', '', {
|
||||
shouldValidate: true,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="outline"
|
||||
className="w-full !bg-transparent"
|
||||
>
|
||||
Sign Up
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
export default SignUpWithEmailAndPasswordForm;
|
||||
@@ -0,0 +1,56 @@
|
||||
import { getAnonId } from '@/lib/segment';
|
||||
import { getToastStyleProps } from '@/utils/constants/settings';
|
||||
import { useSignUpEmailPassword } from '@nhost/nextjs';
|
||||
import { useRouter } from 'next/router';
|
||||
import toast from 'react-hot-toast';
|
||||
import type { SignUpWithEmailAndPasswordFormValues } from './useSignUpWithEmailAndPasswordForm';
|
||||
|
||||
function useOnSignUpWithPasswordHandler() {
|
||||
const { signUpEmailPassword } = useSignUpEmailPassword();
|
||||
const router = useRouter();
|
||||
|
||||
async function onSignUpWithPassword({
|
||||
email,
|
||||
password,
|
||||
displayName,
|
||||
turnstileToken,
|
||||
}: SignUpWithEmailAndPasswordFormValues) {
|
||||
try {
|
||||
const { needsEmailVerification, error } = await signUpEmailPassword(
|
||||
email,
|
||||
password,
|
||||
{
|
||||
displayName,
|
||||
metadata: { anonId: await getAnonId() },
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'x-cf-turnstile-response': turnstileToken,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (error) {
|
||||
toast.error(
|
||||
error.message ||
|
||||
'An error occurred while signing up. Please try again.',
|
||||
getToastStyleProps(),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (needsEmailVerification) {
|
||||
router.push(`/email/verify?email=${encodeURIComponent(email)}`);
|
||||
}
|
||||
} catch {
|
||||
toast.error(
|
||||
'An error occurred while signing up. Please try again.',
|
||||
getToastStyleProps(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return onSignUpWithPassword;
|
||||
}
|
||||
|
||||
export default useOnSignUpWithPasswordHandler;
|
||||
@@ -0,0 +1,43 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
const validationSchema = z
|
||||
.object({
|
||||
email: z.string().email({ message: 'Invalid email address' }),
|
||||
password: z.string().min(1, { message: 'Password is required' }),
|
||||
displayName: z
|
||||
.string()
|
||||
.regex(
|
||||
/^[\p{L}\p{N}\p{S} ,.'-]+$/u,
|
||||
'Use only letters, numbers, symbols and basic punctuation',
|
||||
)
|
||||
.min(1, { message: 'Name is required' })
|
||||
.max(32, { message: 'Name must be 32 characters or less' }),
|
||||
turnstileToken: z
|
||||
.string()
|
||||
.min(1, { message: 'Please complete the CAPTCHA' }),
|
||||
})
|
||||
.required();
|
||||
|
||||
export type SignUpWithEmailAndPasswordFormValues = z.infer<
|
||||
typeof validationSchema
|
||||
>;
|
||||
|
||||
function useSignUpWithEmailAndPasswordForm() {
|
||||
const form = useForm<SignUpWithEmailAndPasswordFormValues>({
|
||||
mode: 'onTouched',
|
||||
reValidateMode: 'onBlur',
|
||||
defaultValues: {
|
||||
email: '',
|
||||
password: '',
|
||||
displayName: '',
|
||||
turnstileToken: '',
|
||||
},
|
||||
resolver: zodResolver(validationSchema),
|
||||
});
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
export default useSignUpWithEmailAndPasswordForm;
|
||||
@@ -0,0 +1 @@
|
||||
export { default as SignUpWithEmailAndPasswordForm } from './components/SignUpWithEmailAndPasswordForm';
|
||||
@@ -0,0 +1,75 @@
|
||||
import { FormInput } from '@/components/form/FormInput';
|
||||
import { Button } from '@/components/ui/v3/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/v3/form';
|
||||
import useSignupWithSecurityKeyForm from '@/features/auth/SignUp/SignUpTabs/SignUpWithSecurityKey/hooks/useSignupWithSecurityKeyForm';
|
||||
import useSignupWithSecurityKeyHandler from '@/features/auth/SignUp/SignUpTabs/SignUpWithSecurityKey/hooks/useSignupWithSecurityKeyHandler';
|
||||
import { Turnstile } from '@marsidev/react-turnstile';
|
||||
|
||||
function SignUpWithSecurityKeyForm() {
|
||||
const form = useSignupWithSecurityKeyForm();
|
||||
const onSignUpWithSecurityKey = useSignupWithSecurityKeyHandler();
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(onSignUpWithSecurityKey)}
|
||||
className="grid grid-flow-row gap-4 bg-transparent"
|
||||
>
|
||||
<FormInput control={form.control} label="Name" name="displayName" />
|
||||
<FormInput
|
||||
control={form.control}
|
||||
label="Email"
|
||||
name="email"
|
||||
type="email"
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="turnstileToken"
|
||||
render={() => (
|
||||
<FormItem>
|
||||
<FormLabel>Verification</FormLabel>
|
||||
<FormControl>
|
||||
<Turnstile
|
||||
siteKey={process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY}
|
||||
options={{ theme: 'dark', size: 'flexible' }}
|
||||
onSuccess={(token) => {
|
||||
form.setValue('turnstileToken', token, {
|
||||
shouldValidate: true,
|
||||
});
|
||||
}}
|
||||
onError={() => {
|
||||
form.setValue('turnstileToken', '', {
|
||||
shouldValidate: true,
|
||||
});
|
||||
}}
|
||||
onExpire={() => {
|
||||
form.setValue('turnstileToken', '', {
|
||||
shouldValidate: true,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="outline"
|
||||
className="w-full !bg-transparent"
|
||||
>
|
||||
Sign Up
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
export default SignUpWithSecurityKeyForm;
|
||||
@@ -0,0 +1,42 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
const validationSchema = z
|
||||
.object({
|
||||
email: z
|
||||
.string()
|
||||
.email({ message: 'Invalid email address' })
|
||||
.min(1, { message: 'Email is required' }),
|
||||
displayName: z
|
||||
.string()
|
||||
.regex(
|
||||
/^[\p{L}\p{N}\p{S} ,.'-]+$/u,
|
||||
'Use only letters, numbers, symbols and basic punctuation',
|
||||
)
|
||||
.min(1, { message: 'Name is required' })
|
||||
.max(32, { message: 'Name must be 32 characters or less' }),
|
||||
turnstileToken: z
|
||||
.string()
|
||||
.min(1, { message: 'Please complete the CAPTCHA' }),
|
||||
})
|
||||
.required();
|
||||
|
||||
export type SignUpWithSecurityKeyFormValues = z.infer<typeof validationSchema>;
|
||||
|
||||
function useSignUpWithSecurityKey() {
|
||||
const form = useForm<SignUpWithSecurityKeyFormValues>({
|
||||
mode: 'onTouched',
|
||||
reValidateMode: 'onBlur',
|
||||
defaultValues: {
|
||||
email: '',
|
||||
displayName: '',
|
||||
turnstileToken: '',
|
||||
},
|
||||
resolver: zodResolver(validationSchema),
|
||||
});
|
||||
|
||||
return form;
|
||||
}
|
||||
|
||||
export default useSignUpWithSecurityKey;
|
||||
@@ -0,0 +1,54 @@
|
||||
import { getAnonId } from '@/lib/segment';
|
||||
import { getToastStyleProps } from '@/utils/constants/settings';
|
||||
import { useSignUpEmailSecurityKeyEmail } from '@nhost/nextjs';
|
||||
import { useRouter } from 'next/router';
|
||||
import toast from 'react-hot-toast';
|
||||
import type { SignUpWithSecurityKeyFormValues } from './useSignupWithSecurityKeyForm';
|
||||
|
||||
function useOnSignUpWithSecurityKeyHandler() {
|
||||
const { signUpEmailSecurityKey } = useSignUpEmailSecurityKeyEmail();
|
||||
const router = useRouter();
|
||||
|
||||
async function onSignUpWithSecurityKey({
|
||||
email,
|
||||
displayName,
|
||||
turnstileToken,
|
||||
}: SignUpWithSecurityKeyFormValues) {
|
||||
try {
|
||||
const { needsEmailVerification, error } = await signUpEmailSecurityKey(
|
||||
email,
|
||||
{
|
||||
displayName,
|
||||
metadata: { anonId: await getAnonId() },
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'x-cf-turnstile-response': turnstileToken,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (error) {
|
||||
toast.error(
|
||||
error.message ||
|
||||
'An error occurred while signing up. Please try again.',
|
||||
getToastStyleProps(),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (needsEmailVerification) {
|
||||
router.push(`/email/verify?email=${encodeURIComponent(email)}`);
|
||||
}
|
||||
} catch {
|
||||
toast.error(
|
||||
'An error occurred while signing up. Please try again.',
|
||||
getToastStyleProps(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return onSignUpWithSecurityKey;
|
||||
}
|
||||
|
||||
export default useOnSignUpWithSecurityKeyHandler;
|
||||
@@ -0,0 +1 @@
|
||||
export { default as SignUpWithSecurityKeyForm } from './components/SignUpWithSecurityKeyForm';
|
||||
1
dashboard/src/features/auth/SignUp/SignUpTabs/index.ts
Normal file
1
dashboard/src/features/auth/SignUp/SignUpTabs/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default as SignUpTabs } from './SignUpTabs';
|
||||
@@ -0,0 +1,13 @@
|
||||
import { GithubAuthButton } from '@/features/auth/AuthProviders/Github/components/GithubAuthButton';
|
||||
|
||||
function SignUpWithGithub() {
|
||||
return (
|
||||
<GithubAuthButton
|
||||
withAnonId
|
||||
buttonText="Sign Up with GitHub"
|
||||
errorText="An error occurred while trying to sign up using GitHub. Please try again."
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default SignUpWithGithub;
|
||||
@@ -0,0 +1 @@
|
||||
export { default as SignUpWithGithub } from './SignUpWithGithub';
|
||||
@@ -26,7 +26,7 @@ function InfoAlert({
|
||||
<Alert className={alertClassNames}>
|
||||
{icon && <div>{icon}</div>}
|
||||
<div>
|
||||
{title && <AlertTitle>{title}</AlertTitle>}
|
||||
{title && <AlertTitle className="font-semibold">{title}</AlertTitle>}
|
||||
{children && (
|
||||
<AlertDescription className={descClassNames}>
|
||||
{children}
|
||||
|
||||
@@ -14,13 +14,15 @@ export default function StripeEmbeddedForm({
|
||||
clientSecret: string;
|
||||
}) {
|
||||
return (
|
||||
<EmbeddedCheckoutProvider
|
||||
stripe={stripePromise}
|
||||
options={{
|
||||
clientSecret,
|
||||
}}
|
||||
>
|
||||
<EmbeddedCheckout />
|
||||
</EmbeddedCheckoutProvider>
|
||||
<div className="h-[80vh] overflow-y-scroll">
|
||||
<EmbeddedCheckoutProvider
|
||||
stripe={stripePromise}
|
||||
options={{
|
||||
clientSecret,
|
||||
}}
|
||||
>
|
||||
<EmbeddedCheckout />
|
||||
</EmbeddedCheckoutProvider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useUI } from '@/components/common/UIProvider';
|
||||
import { SettingsContainer } from '@/components/layout/SettingsContainer';
|
||||
import { TransferProjectDialog } from '@/features/orgs/components/common/TransferProjectDialog';
|
||||
import { TransferOrUpgradeProjectDialog } from '@/features/orgs/components/common/TransferOrUpgradeProjectDialog';
|
||||
import { useIsPlatform } from '@/features/orgs/projects/common/hooks/useIsPlatform';
|
||||
import { useState } from 'react';
|
||||
|
||||
@@ -26,7 +26,7 @@ export default function TransferProject() {
|
||||
}}
|
||||
/>
|
||||
|
||||
<TransferProjectDialog open={open} setOpen={setOpen} />
|
||||
<TransferOrUpgradeProjectDialog open={open} setOpen={setOpen} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useUI } from '@/components/common/UIProvider';
|
||||
import { ActivityIndicator } from '@/components/ui/v2/ActivityIndicator';
|
||||
import { ArrowSquareOutIcon } from '@/components/ui/v2/icons/ArrowSquareOutIcon';
|
||||
import { Link } from '@/components/ui/v2/Link';
|
||||
import { Button } from '@/components/ui/v3/button';
|
||||
import {
|
||||
Dialog,
|
||||
@@ -21,6 +20,8 @@ import {
|
||||
FormMessage,
|
||||
} from '@/components/ui/v3/form';
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/v3/radio-group';
|
||||
import { InfoAlert } from '@/features/orgs/components/InfoAlert';
|
||||
import TextLink from '@/features/orgs/projects/common/components/TextLink/TextLink';
|
||||
import { planDescriptions } from '@/features/orgs/projects/common/utils/planDescriptions';
|
||||
import { useCurrentOrg } from '@/features/orgs/projects/hooks/useCurrentOrg';
|
||||
import { execPromiseWithErrorToast } from '@/features/orgs/utils/execPromiseWithErrorToast';
|
||||
@@ -35,6 +36,14 @@ import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
function NewOrgButton() {
|
||||
return (
|
||||
<strong className="inline-flex items-center justify-center gap-2 px-1">
|
||||
<span>+ New Organization</span>
|
||||
</strong>
|
||||
);
|
||||
}
|
||||
|
||||
const changeOrgPlanForm = z.object({
|
||||
plan: z.string(),
|
||||
});
|
||||
@@ -48,6 +57,8 @@ export default function SubscriptionPlan() {
|
||||
const [fetchOrganizationCustomePortalLink, { loading }] =
|
||||
useBillingOrganizationCustomePortalLazyQuery();
|
||||
|
||||
const isFreeOrg = org?.plan.isFree;
|
||||
|
||||
const form = useForm<z.infer<typeof changeOrgPlanForm>>({
|
||||
resolver: zodResolver(changeOrgPlanForm),
|
||||
defaultValues: {
|
||||
@@ -125,7 +136,7 @@ export default function SubscriptionPlan() {
|
||||
<div className="flex w-full flex-col gap-1 border-b p-4">
|
||||
<h4 className="font-medium">Subscription plan</h4>
|
||||
</div>
|
||||
<div className="flex w-full flex-col justify-between gap-8 border-b p-4 md:flex-row">
|
||||
<div className="flex w-full flex-col justify-between gap-8 p-4 md:flex-row">
|
||||
<div className="flex basis-1/2 flex-col gap-4">
|
||||
<span className="font-medium">Organization name</span>
|
||||
<span className="font-medium">{org?.name}</span>
|
||||
@@ -152,31 +163,26 @@ export default function SubscriptionPlan() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex w-full flex-col-reverse items-end justify-between gap-2 p-4 md:flex-row md:items-center md:gap-0">
|
||||
{isFreeOrg && (
|
||||
<div className="flex w-full flex-col justify-between gap-8 p-4 md:flex-row">
|
||||
<InfoAlert title="Personal Organizations can not be upgraded.">
|
||||
You may create a new organization with premium features by
|
||||
clicking on the <NewOrgButton /> button in the left sidebar.
|
||||
</InfoAlert>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex w-full flex-col-reverse items-end justify-between gap-2 border-t p-4 md:flex-row md:items-center md:gap-0">
|
||||
<div>
|
||||
<span>For a complete list of features, visit our </span>
|
||||
<Link
|
||||
href="https://nhost.io/pricing"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
underline="hover"
|
||||
className="font-medium"
|
||||
>
|
||||
<TextLink href="https://nhost.io/pricing">
|
||||
pricing
|
||||
<ArrowSquareOutIcon className="mb-[2px] ml-1 h-4 w-4" />
|
||||
</Link>
|
||||
</TextLink>
|
||||
<span> You can also visit our </span>
|
||||
<Link
|
||||
href="https://docs.nhost.io/platform/cloud/billing"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
underline="hover"
|
||||
className="font-medium"
|
||||
>
|
||||
<TextLink href="https://docs.nhost.io/platform/cloud/billing">
|
||||
documentation
|
||||
<ArrowSquareOutIcon className="mb-[2px] ml-1 h-4 w-4" />
|
||||
</Link>
|
||||
</TextLink>
|
||||
<span> for billing information</span>
|
||||
</div>
|
||||
<div className="flex w-full flex-row items-center justify-end gap-2">
|
||||
@@ -245,7 +251,7 @@ export default function SubscriptionPlan() {
|
||||
</div>
|
||||
|
||||
<div className="mt-0 flex h-full items-center text-xl font-semibold">
|
||||
{plan.isFree ? 'Free' : `${plan.price}/mo`}
|
||||
{isFreeOrg ? 'Free' : `${plan.price}/mo`}
|
||||
</div>
|
||||
</FormLabel>
|
||||
</FormItem>
|
||||
@@ -264,16 +270,10 @@ export default function SubscriptionPlan() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Link
|
||||
href="mailto:hello@nhost.io"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
underline="hover"
|
||||
className="font-medium"
|
||||
>
|
||||
<TextLink href="mailto:hello@nhost.io">
|
||||
Contact us
|
||||
<ArrowSquareOutIcon className="ml-1 h-4 w-4" />
|
||||
</Link>
|
||||
</TextLink>
|
||||
</div>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
|
||||
@@ -1,24 +1,30 @@
|
||||
import { ActivityIndicator } from '@/components/ui/v2/ActivityIndicator';
|
||||
import { DialogDescription } from '@/components/ui/v3/dialog';
|
||||
import { useFinishOrgCreation } from '@/features/orgs/hooks/useFinishOrgCreation';
|
||||
import { type FinishOrgCreationOnCompletedCb } from '@/features/orgs/hooks/useFinishOrgCreation/useFinishOrgCreation';
|
||||
import { CheckoutStatus } from '@/utils/__generated__/graphql';
|
||||
import { memo } from 'react';
|
||||
|
||||
interface Props {
|
||||
loading: boolean;
|
||||
status: CheckoutStatus | null;
|
||||
onCompleted: FinishOrgCreationOnCompletedCb;
|
||||
onError?: () => void;
|
||||
successMessage: string;
|
||||
loadingMessage: string;
|
||||
errorMessage: string;
|
||||
pendingMessage: string;
|
||||
withDialogDescription?: boolean;
|
||||
}
|
||||
|
||||
function FinishOrgCreationProcess({
|
||||
loading,
|
||||
status,
|
||||
onCompleted,
|
||||
onError,
|
||||
successMessage,
|
||||
loadingMessage,
|
||||
errorMessage,
|
||||
pendingMessage,
|
||||
withDialogDescription,
|
||||
}: Props) {
|
||||
const [loading, status] = useFinishOrgCreation({ onCompleted, onError });
|
||||
let message: string | undefined;
|
||||
|
||||
switch (status) {
|
||||
@@ -38,13 +44,15 @@ function FinishOrgCreationProcess({
|
||||
message = loadingMessage;
|
||||
}
|
||||
|
||||
const Component = withDialogDescription ? DialogDescription : 'span';
|
||||
|
||||
return (
|
||||
<div className="relative flex flex-auto overflow-x-hidden">
|
||||
<div className="flex h-full w-full flex-col items-center justify-center space-y-2">
|
||||
{(loading || status === CheckoutStatus.Completed) && (
|
||||
<ActivityIndicator circularProgressProps={{ className: 'w-6 h-6' }} />
|
||||
)}
|
||||
<span>{message}</span>
|
||||
<Component>{message}</Component>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { FinishOrgCreationProcess } from '@/features/orgs/components/common/FinishOrgCreationProcess';
|
||||
import { useFinishOrgCreation } from '@/features/orgs/hooks/useFinishOrgCreation';
|
||||
import { type FinishOrgCreationOnCompletedCb } from '@/features/orgs/hooks/useFinishOrgCreation/useFinishOrgCreation';
|
||||
|
||||
interface Props {
|
||||
@@ -8,15 +7,15 @@ interface Props {
|
||||
}
|
||||
|
||||
function FinishOrgCreation({ onCompleted, onError }: Props) {
|
||||
const [loading, status] = useFinishOrgCreation({ onCompleted, onError });
|
||||
return (
|
||||
<FinishOrgCreationProcess
|
||||
loading={loading}
|
||||
status={status}
|
||||
loadingMessage="Processing new organization request"
|
||||
onCompleted={onCompleted}
|
||||
onError={onError}
|
||||
loadingMessage="Creating new organization"
|
||||
successMessage="Organization created successfully."
|
||||
pendingMessage="Organization creation is pending..."
|
||||
errorMessage="Error occurred while creating the organization. Please try again."
|
||||
withDialogDescription
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -22,12 +22,17 @@ import {
|
||||
import { setupServer } from 'msw/node';
|
||||
import { useState } from 'react';
|
||||
import { afterAll, beforeAll, vi } from 'vitest';
|
||||
import TransferProjectDialog from './TransferProjectDialog';
|
||||
import TransferorUpgradeProjectDialog from './TransferOrUpgradeProjectDialog';
|
||||
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation(mockMatchMediaValue),
|
||||
});
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useRouter: vi.fn(),
|
||||
useOrgs: vi.fn(),
|
||||
push: vi.fn(),
|
||||
}));
|
||||
|
||||
mockPointerEvent();
|
||||
|
||||
@@ -44,7 +49,7 @@ const getUseRouterObject = (session_id?: string) => ({
|
||||
appSubdomain: 'test-project',
|
||||
session_id,
|
||||
},
|
||||
push: vi.fn(),
|
||||
push: mocks.push,
|
||||
replace: vi.fn(),
|
||||
reload: vi.fn(),
|
||||
back: vi.fn(),
|
||||
@@ -58,11 +63,6 @@ const getUseRouterObject = (session_id?: string) => ({
|
||||
isFallback: false,
|
||||
});
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useRouter: vi.fn(),
|
||||
useOrgs: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/orgs/projects/hooks/useOrgs', async () => {
|
||||
const actualUseOrgs = await vi.importActual<any>(
|
||||
'@/features/orgs/projects/hooks/useOrgs',
|
||||
@@ -78,17 +78,42 @@ const postOrganizationRequestResolver = createGraphqlMockResolver(
|
||||
'mutation',
|
||||
);
|
||||
|
||||
const billingTransferAppRequestResolver = createGraphqlMockResolver(
|
||||
'billingTransferApp',
|
||||
'mutation',
|
||||
);
|
||||
|
||||
vi.mock('next/router', () => ({
|
||||
useRouter: mocks.useRouter,
|
||||
}));
|
||||
|
||||
async function asyncFireEvent(element: Document | Element | Window | Node) {
|
||||
await waitFor(() => {
|
||||
fireEvent(
|
||||
element,
|
||||
new MouseEvent('click', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function DialogWrapper({
|
||||
defaultOpen = true,
|
||||
isUpgrade = false,
|
||||
}: {
|
||||
defaultOpen?: boolean;
|
||||
isUpgrade?: boolean;
|
||||
}) {
|
||||
const [open, setOpen] = useState(defaultOpen);
|
||||
return <TransferProjectDialog open={open} setOpen={setOpen} />;
|
||||
return (
|
||||
<TransferorUpgradeProjectDialog
|
||||
open={open}
|
||||
setOpen={setOpen}
|
||||
isUpgrade={isUpgrade}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const server = setupServer(tokenQuery);
|
||||
@@ -102,11 +127,12 @@ beforeAll(() => {
|
||||
afterEach(() => {
|
||||
queryClient.clear();
|
||||
mocks.useRouter.mockRestore();
|
||||
mocks.push.mockRestore();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
server.close();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
test('opens create org dialog when selecting "create new org" and closes transfer dialog', async () => {
|
||||
@@ -141,13 +167,7 @@ test('opens create org dialog when selecting "create new org" and closes transfe
|
||||
const submitButton = await screen.findByText('Continue');
|
||||
expect(submitButton).toHaveTextContent('Continue');
|
||||
|
||||
fireEvent(
|
||||
submitButton,
|
||||
new MouseEvent('click', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
asyncFireEvent(submitButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(submitButton).not.toBeInTheDocument();
|
||||
@@ -156,13 +176,48 @@ test('opens create org dialog when selecting "create new org" and closes transfe
|
||||
const newOrgTitle = await screen.findByText('New Organization');
|
||||
expect(newOrgTitle).toBeInTheDocument();
|
||||
const closeButton = await screen.findByText('Close');
|
||||
fireEvent(
|
||||
closeButton,
|
||||
new MouseEvent('click', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
asyncFireEvent(closeButton);
|
||||
await waitFor(() => {
|
||||
expect(newOrgTitle).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
const submitButtonAfterClosingNewOrgDialog =
|
||||
await screen.findByText('Continue');
|
||||
await waitFor(() => {
|
||||
expect(submitButtonAfterClosingNewOrgDialog).toHaveTextContent('Continue');
|
||||
});
|
||||
});
|
||||
test('when upgrading a project by clicking on the Continue button the create new org modal is opened and the initial dialog is closed', async () => {
|
||||
mocks.useRouter.mockImplementation(() => getUseRouterObject());
|
||||
|
||||
server.use(getProjectQuery);
|
||||
server.use(getOrganization);
|
||||
mocks.useOrgs.mockImplementation(() => ({
|
||||
orgs: mockOrganizations,
|
||||
currentOrg: mockOrganization,
|
||||
loading: false,
|
||||
refetch: vi.fn(),
|
||||
}));
|
||||
server.use(prefetchNewAppQuery);
|
||||
|
||||
render(<DialogWrapper isUpgrade />);
|
||||
|
||||
expect(await screen.findByText('Upgrade project')).toBeInTheDocument();
|
||||
|
||||
const submitButton = await screen.findByText('Continue');
|
||||
expect(submitButton).toHaveTextContent('Continue');
|
||||
|
||||
asyncFireEvent(submitButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(submitButton).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
const newOrgTitle = await screen.findByText('New Organization');
|
||||
expect(newOrgTitle).toBeInTheDocument();
|
||||
const closeButton = await screen.findByText('Close');
|
||||
|
||||
asyncFireEvent(closeButton);
|
||||
await waitFor(() => {
|
||||
expect(newOrgTitle).not.toBeInTheDocument();
|
||||
});
|
||||
@@ -182,7 +237,9 @@ test(`transfer dialog opens automatically when there is a session_id and selects
|
||||
orgs: mockOrganizations,
|
||||
currentOrg: mockOrganization,
|
||||
loading: false,
|
||||
refetch: vi.fn(),
|
||||
refetch: async () => ({
|
||||
data: { organizations: mockOrganizationsWithNewOrg },
|
||||
}),
|
||||
}));
|
||||
server.use(prefetchNewAppQuery);
|
||||
server.use(postOrganizationRequestResolver.handler);
|
||||
@@ -196,13 +253,7 @@ test(`transfer dialog opens automatically when there is a session_id and selects
|
||||
|
||||
const closeButton = await screen.findByText('Close');
|
||||
|
||||
fireEvent(
|
||||
closeButton,
|
||||
new MouseEvent('click', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
asyncFireEvent(closeButton);
|
||||
|
||||
await waitFor(() => {});
|
||||
expect(closeButton).toBeInTheDocument();
|
||||
@@ -220,15 +271,84 @@ test(`transfer dialog opens automatically when there is a session_id and selects
|
||||
orgs: mockOrganizationsWithNewOrg,
|
||||
currentOrg: mockOrganization,
|
||||
loading: false,
|
||||
refetch: vi.fn(),
|
||||
refetch: async () => ({
|
||||
data: { organizations: mockOrganizationsWithNewOrg },
|
||||
}),
|
||||
}));
|
||||
|
||||
await waitFor(async () => {
|
||||
expect(
|
||||
await screen.queryByRole('combobox', {
|
||||
name: /Organization/i,
|
||||
}),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const organizationCombobox = await screen.findByRole('combobox', {
|
||||
name: /Organization/i,
|
||||
});
|
||||
|
||||
expect(organizationCombobox).toHaveTextContent(newOrg.name);
|
||||
|
||||
const submitButton = await screen.findByText('Transfer');
|
||||
expect(submitButton).not.toBeDisabled();
|
||||
});
|
||||
test(`upgrade project dialog opens automatically when there is a session_id and transfers the project to ${newOrg.name}`, async () => {
|
||||
mocks.useRouter.mockImplementation(() => getUseRouterObject('session_id'));
|
||||
server.use(getProjectQuery);
|
||||
server.use(getOrganization);
|
||||
|
||||
mocks.useOrgs.mockImplementation(() => ({
|
||||
orgs: mockOrganizations,
|
||||
currentOrg: mockOrganization,
|
||||
loading: false,
|
||||
refetch: async () => ({
|
||||
data: { organizations: mockOrganizationsWithNewOrg },
|
||||
}),
|
||||
}));
|
||||
server.use(prefetchNewAppQuery);
|
||||
server.use(postOrganizationRequestResolver.handler);
|
||||
server.use(billingTransferAppRequestResolver.handler);
|
||||
|
||||
render(<DialogWrapper defaultOpen={false} isUpgrade />);
|
||||
const processingNewOrgText = await screen.findByText(
|
||||
'Creating new organization',
|
||||
);
|
||||
|
||||
expect(processingNewOrgText).toBeInTheDocument();
|
||||
|
||||
const closeButton = await screen.findByText('Close');
|
||||
|
||||
asyncFireEvent(closeButton);
|
||||
|
||||
await waitFor(() => {});
|
||||
expect(closeButton).toBeInTheDocument();
|
||||
|
||||
postOrganizationRequestResolver.resolve({
|
||||
billingPostOrganizationRequest: {
|
||||
Status: 'COMPLETED',
|
||||
Slug: newOrg.slug,
|
||||
ClientSecret: null,
|
||||
__typename: 'PostOrganizationRequestResponse',
|
||||
},
|
||||
});
|
||||
|
||||
mocks.useOrgs.mockImplementation(() => ({
|
||||
orgs: mockOrganizationsWithNewOrg,
|
||||
currentOrg: mockOrganization,
|
||||
loading: false,
|
||||
refetch: async () => ({
|
||||
data: { organizations: mockOrganizationsWithNewOrg },
|
||||
}),
|
||||
}));
|
||||
await waitFor(async () => {
|
||||
expect(await screen.findByText('Upgrading project...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
billingTransferAppRequestResolver.resolve({
|
||||
billingTransferApp: true,
|
||||
});
|
||||
|
||||
await waitFor(async () => {});
|
||||
|
||||
expect(mocks.push).toHaveBeenCalledWith('/orgs/new-org/projects');
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
import { LoadingScreen } from '@/components/presentational/LoadingScreen';
|
||||
import { Dialog, DialogContent } from '@/components/ui/v3/dialog';
|
||||
import CreateOrgDialog from '@/features/orgs/components/CreateOrgFormDialog/CreateOrgFormDialog';
|
||||
import { useOrgs } from '@/features/orgs/projects/hooks/useOrgs';
|
||||
import { useProject } from '@/features/orgs/projects/hooks/useProject';
|
||||
import { useRouter } from 'next/router';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import TransferProjectDialogContent from './TransferProjectDialogContent';
|
||||
import UpgradeProjectDialogContent from './UpgradeProjectDialogContent';
|
||||
|
||||
interface TransferProjectDialogProps {
|
||||
open: boolean;
|
||||
setOpen: (value: boolean) => void;
|
||||
isUpgrade?: boolean;
|
||||
}
|
||||
|
||||
export default function TransferOrUpgradeProjectDialog({
|
||||
open,
|
||||
setOpen,
|
||||
isUpgrade,
|
||||
}: TransferProjectDialogProps) {
|
||||
const { asPath, query, isReady: isRouterReady } = useRouter();
|
||||
const { session_id } = query;
|
||||
const { loading: projectLoading } = useProject();
|
||||
const { loading: orgsLoading } = useOrgs();
|
||||
|
||||
const [showCreateOrgModal, setShowCreateOrgModal] = useState(false);
|
||||
const [preventClose, setPreventClose] = useState(false);
|
||||
const [selectedOrgId, setSelectedOrgId] = useState<string>();
|
||||
|
||||
useEffect(() => {
|
||||
if (session_id && isRouterReady) {
|
||||
setOpen(true);
|
||||
setPreventClose(true);
|
||||
}
|
||||
}, [session_id, setOpen, isRouterReady]);
|
||||
|
||||
const path = asPath.split('?')[0];
|
||||
const redirectUrl = `${window.location.origin}${path}`;
|
||||
|
||||
const handleCreateDialogOpenStateChange = (newState: boolean) => {
|
||||
setShowCreateOrgModal(newState);
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
const handleFinishOrgCreationCompleted = useCallback(async () => {
|
||||
setPreventClose(false);
|
||||
}, []);
|
||||
|
||||
const handleTransferProjectDialogOpenChange = (newValue: boolean) => {
|
||||
if (preventClose) {
|
||||
return;
|
||||
}
|
||||
if (!newValue) {
|
||||
setSelectedOrgId(undefined);
|
||||
}
|
||||
|
||||
setOpen(newValue);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleCreateNewOrg = () => {
|
||||
setShowCreateOrgModal(true);
|
||||
setOpen(false);
|
||||
};
|
||||
const handleOnCreateOrgError = useCallback(() => setPreventClose(false), []);
|
||||
|
||||
if (projectLoading || orgsLoading) {
|
||||
return <LoadingScreen />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={handleTransferProjectDialogOpenChange}>
|
||||
<DialogContent className="z-[9999] text-foreground sm:max-w-xl">
|
||||
{isUpgrade ? (
|
||||
<UpgradeProjectDialogContent
|
||||
onCancel={handleCancel}
|
||||
onCreateNewOrg={handleCreateNewOrg}
|
||||
onCreateOrgError={handleOnCreateOrgError}
|
||||
/>
|
||||
) : (
|
||||
<TransferProjectDialogContent
|
||||
onFinishOrgCreationCompleted={handleFinishOrgCreationCompleted}
|
||||
onFinishOrgError={() => setPreventClose(false)}
|
||||
onCreateNewOrg={handleCreateNewOrg}
|
||||
onCancel={handleCancel}
|
||||
selectedOrganizationId={selectedOrgId}
|
||||
onOrganizationChange={setSelectedOrgId}
|
||||
/>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<CreateOrgDialog
|
||||
hideNewOrgButton
|
||||
isOpen={showCreateOrgModal}
|
||||
onOpenStateChange={handleCreateDialogOpenStateChange}
|
||||
redirectUrl={redirectUrl}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import {
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/v3/dialog';
|
||||
import { type FinishOrgCreationOnCompletedCb } from '@/features/orgs/hooks/useFinishOrgCreation/useFinishOrgCreation';
|
||||
import { useOrgs } from '@/features/orgs/projects/hooks/useOrgs';
|
||||
import { isNotEmptyValue } from '@/lib/utils';
|
||||
import { useRouter } from 'next/router';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import FinishOrgCreation from './FinishOrgCreation';
|
||||
import TransferProjectForm, {
|
||||
type TransferProjectFormProps,
|
||||
} from './TransferProjectForm';
|
||||
|
||||
interface Props extends TransferProjectFormProps {
|
||||
onFinishOrgCreationCompleted: () => void;
|
||||
onFinishOrgError: () => void;
|
||||
}
|
||||
|
||||
function TransferProjectDialogContent({
|
||||
onCreateNewOrg,
|
||||
onCancel,
|
||||
onFinishOrgCreationCompleted,
|
||||
onFinishOrgError,
|
||||
selectedOrganizationId,
|
||||
onOrganizationChange,
|
||||
}: Props) {
|
||||
const { query, replace, pathname } = useRouter();
|
||||
const { session_id, ...remainingQuery } = query;
|
||||
const { refetch: refetchOrgs } = useOrgs();
|
||||
const [showContent, setShowContent] = useState(true);
|
||||
|
||||
const removeSessionIdFromQuery = useCallback(() => {
|
||||
replace({ pathname, query: remainingQuery }, undefined, {
|
||||
shallow: true,
|
||||
});
|
||||
}, [replace, remainingQuery, pathname]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isNotEmptyValue(session_id)) {
|
||||
setShowContent(false);
|
||||
}
|
||||
}, [session_id]);
|
||||
|
||||
const handleOnCompleted: FinishOrgCreationOnCompletedCb = useCallback(
|
||||
async ({ Slug }) => {
|
||||
removeSessionIdFromQuery();
|
||||
const {
|
||||
data: { organizations },
|
||||
} = await refetchOrgs();
|
||||
|
||||
const newOrg = organizations.find((org) => org.slug === Slug);
|
||||
|
||||
setShowContent(true);
|
||||
onOrganizationChange(newOrg.id);
|
||||
onFinishOrgCreationCompleted();
|
||||
},
|
||||
[
|
||||
onFinishOrgCreationCompleted,
|
||||
refetchOrgs,
|
||||
removeSessionIdFromQuery,
|
||||
onOrganizationChange,
|
||||
],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<DialogHeader className="flex gap-2">
|
||||
<DialogTitle>
|
||||
Move the current project to a different organization.
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
{showContent ? (
|
||||
<>
|
||||
<DialogDescription>
|
||||
To transfer a project between organizations, you must be an{' '}
|
||||
<span className="font-bold">ADMIN</span> in both.
|
||||
<br />
|
||||
When transferred to a new organization, the project will adopt that
|
||||
organization’s plan.
|
||||
</DialogDescription>
|
||||
<TransferProjectForm
|
||||
onCreateNewOrg={onCreateNewOrg}
|
||||
selectedOrganizationId={selectedOrganizationId}
|
||||
onCancel={onCancel}
|
||||
onOrganizationChange={onOrganizationChange}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<FinishOrgCreation
|
||||
onCompleted={handleOnCompleted}
|
||||
onError={onFinishOrgError}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default TransferProjectDialogContent;
|
||||
@@ -0,0 +1,186 @@
|
||||
import { Badge } from '@/components/ui/v3/badge';
|
||||
import { ButtonWithLoading as Button } from '@/components/ui/v3/button';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/v3/form';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/v3/select';
|
||||
import { useOrgs, type Org } from '@/features/orgs/projects/hooks/useOrgs';
|
||||
import { useProject } from '@/features/orgs/projects/hooks/useProject';
|
||||
import { execPromiseWithErrorToast } from '@/features/orgs/utils/execPromiseWithErrorToast';
|
||||
import { cn, isNotEmptyValue } from '@/lib/utils';
|
||||
import {
|
||||
Organization_Members_Role_Enum,
|
||||
useBillingTransferAppMutation,
|
||||
} from '@/utils/__generated__/graphql';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useUserId } from '@nhost/nextjs';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { useRouter } from 'next/router';
|
||||
import { useEffect } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
|
||||
const CREATE_NEW_ORG = 'createNewOrg';
|
||||
|
||||
const transferProjectFormSchema = z.object({
|
||||
organization: z.string(),
|
||||
});
|
||||
|
||||
export interface TransferProjectFormProps {
|
||||
onCreateNewOrg: () => void;
|
||||
onCancel: () => void;
|
||||
selectedOrganizationId?: string;
|
||||
onOrganizationChange(value: string): void;
|
||||
}
|
||||
|
||||
function TransferProjectForm({
|
||||
onCreateNewOrg,
|
||||
selectedOrganizationId,
|
||||
onCancel,
|
||||
onOrganizationChange,
|
||||
}: TransferProjectFormProps) {
|
||||
const { push } = useRouter();
|
||||
const { orgs, currentOrg } = useOrgs();
|
||||
const { project } = useProject();
|
||||
const currentUserId = useUserId();
|
||||
const [transferProject] = useBillingTransferAppMutation();
|
||||
|
||||
const form = useForm<z.infer<typeof transferProjectFormSchema>>({
|
||||
resolver: zodResolver(transferProjectFormSchema),
|
||||
defaultValues: {
|
||||
organization: '',
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (isNotEmptyValue(selectedOrganizationId)) {
|
||||
form.setValue('organization', selectedOrganizationId, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}
|
||||
}, [selectedOrganizationId, form]);
|
||||
|
||||
const isUserAdminOfOrg = (org: Org, userId: string) =>
|
||||
org.members.some(
|
||||
(member) =>
|
||||
member.role === Organization_Members_Role_Enum.Admin &&
|
||||
member.user.id === userId,
|
||||
);
|
||||
|
||||
const createNewFormSelected = form.watch('organization') === CREATE_NEW_ORG;
|
||||
const submitButtonText = createNewFormSelected ? 'Continue' : 'Transfer';
|
||||
|
||||
const onSubmit = async (
|
||||
values: z.infer<typeof transferProjectFormSchema>,
|
||||
) => {
|
||||
const { organization } = values;
|
||||
|
||||
if (organization === CREATE_NEW_ORG) {
|
||||
onCreateNewOrg();
|
||||
} else {
|
||||
await execPromiseWithErrorToast(
|
||||
async () => {
|
||||
await transferProject({
|
||||
variables: {
|
||||
appID: project?.id,
|
||||
organizationID: organization,
|
||||
},
|
||||
});
|
||||
|
||||
const targetOrg = orgs.find((o) => o.id === organization);
|
||||
await push(`/orgs/${targetOrg.slug}/projects`);
|
||||
},
|
||||
{
|
||||
loadingMessage: 'Transferring project...',
|
||||
successMessage: 'Project transferred successfully!',
|
||||
errorMessage: 'Error transferring project. Please try again.',
|
||||
},
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="organization"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Organization</FormLabel>
|
||||
<Select onValueChange={onOrganizationChange} value={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Organization" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{orgs.map((org) => (
|
||||
<SelectItem
|
||||
key={org.id}
|
||||
value={org.id}
|
||||
disabled={
|
||||
org.plan.isFree || // disable the personal org
|
||||
org.id === currentOrg.id || // disable the current org as it can't be a destination org
|
||||
!isUserAdminOfOrg(org, currentUserId) // disable orgs that the current user is not admin of
|
||||
}
|
||||
>
|
||||
{org.name}
|
||||
<Badge
|
||||
variant={org.plan.isFree ? 'outline' : 'default'}
|
||||
className={cn(
|
||||
org.plan.isFree ? 'bg-muted' : '',
|
||||
'hover:none ml-2 h-5 px-[6px] text-[10px]',
|
||||
)}
|
||||
>
|
||||
{org.plan.name}
|
||||
</Badge>
|
||||
</SelectItem>
|
||||
))}
|
||||
<SelectItem key={CREATE_NEW_ORG} value={CREATE_NEW_ORG}>
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Plus className="h-4 w-4 font-bold" strokeWidth={3} />{' '}
|
||||
<span>New Organization</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex justify-end space-x-2">
|
||||
<Button
|
||||
variant="secondary"
|
||||
type="button"
|
||||
disabled={form.formState.isSubmitting}
|
||||
onClick={onCancel}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={form.formState.isSubmitting || !form.formState.isDirty}
|
||||
loading={form.formState.isSubmitting}
|
||||
>
|
||||
{submitButtonText}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
export default TransferProjectForm;
|
||||
@@ -0,0 +1,116 @@
|
||||
import { Button } from '@/components/ui/v3/button';
|
||||
import {
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/v3/dialog';
|
||||
import { type FinishOrgCreationOnCompletedCb } from '@/features/orgs/hooks/useFinishOrgCreation/useFinishOrgCreation';
|
||||
import { useOrgs } from '@/features/orgs/projects/hooks/useOrgs';
|
||||
import { useProject } from '@/features/orgs/projects/hooks/useProject';
|
||||
import { execPromiseWithErrorToast } from '@/features/orgs/utils/execPromiseWithErrorToast';
|
||||
import { analytics } from '@/lib/segment';
|
||||
import { isEmptyValue } from '@/lib/utils';
|
||||
import { useBillingTransferAppMutation } from '@/utils/__generated__/graphql';
|
||||
import { useRouter } from 'next/router';
|
||||
import { memo } from 'react';
|
||||
import FinishOrgCreation from './FinishOrgCreation';
|
||||
|
||||
interface Props {
|
||||
onCreateOrgError: () => void;
|
||||
onCancel: () => void;
|
||||
onCreateNewOrg: () => void;
|
||||
}
|
||||
|
||||
function UpgradeProjectDialogContent({
|
||||
onCreateNewOrg,
|
||||
onCancel,
|
||||
onCreateOrgError,
|
||||
}: Props) {
|
||||
const [transferProjectMutation] = useBillingTransferAppMutation();
|
||||
const { project } = useProject();
|
||||
const { refetch: refetchOrgs } = useOrgs();
|
||||
const { push, query } = useRouter();
|
||||
const { session_id } = query;
|
||||
|
||||
const showContent = isEmptyValue(session_id);
|
||||
async function transferProject(newOrgSlug: string) {
|
||||
const { data } = await refetchOrgs();
|
||||
const newOrg = data.organizations.find((org) => org.slug === newOrgSlug);
|
||||
await execPromiseWithErrorToast(
|
||||
async () => {
|
||||
await transferProjectMutation({
|
||||
variables: {
|
||||
appID: project?.id,
|
||||
organizationID: newOrg?.id,
|
||||
},
|
||||
});
|
||||
|
||||
analytics.track('Project Upgraded', {
|
||||
projectId: project?.id,
|
||||
projectName: project?.name,
|
||||
projectSubdomain: project?.subdomain,
|
||||
newOrganizationId: newOrg?.id,
|
||||
newOrganizationName: newOrg?.name,
|
||||
newOrganizationSlug: newOrg?.slug,
|
||||
newOrganizationPlan: newOrg?.plan?.name,
|
||||
newOrganizationPlanId: newOrg?.plan?.id,
|
||||
});
|
||||
|
||||
await push(`/orgs/${newOrg?.slug}/projects`);
|
||||
},
|
||||
{
|
||||
loadingMessage: 'Upgrading project...',
|
||||
successMessage: 'Project has been upgraded successfully!',
|
||||
errorMessage: 'Error upgrading project. Please try again.',
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const handleOnCompleted: FinishOrgCreationOnCompletedCb = async (data) => {
|
||||
await transferProject(data.Slug);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<DialogHeader className="flex gap-2">
|
||||
<DialogTitle>Upgrade project</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{showContent ? (
|
||||
<>
|
||||
<DialogDescription className="text-base">
|
||||
<span className="mb-4 block">
|
||||
To access premium features from a paid plan, a project must belong
|
||||
to an organization on that plan.
|
||||
</span>
|
||||
<span className="mb-4 block">
|
||||
Continue to create a new organization with a subscription plan.
|
||||
Your project will be automatically transferred to the new
|
||||
organization, unlocking all paid features.
|
||||
</span>
|
||||
<span className="block">
|
||||
Alternatively, you can transfer your project to an existing paid
|
||||
organization in your project's settings.
|
||||
</span>
|
||||
</DialogDescription>
|
||||
<DialogFooter>
|
||||
<Button variant="secondary" type="button" onClick={onCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" onClick={onCreateNewOrg}>
|
||||
Continue
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
) : (
|
||||
<FinishOrgCreation
|
||||
onCompleted={handleOnCompleted}
|
||||
onError={onCreateOrgError}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default memo(UpgradeProjectDialogContent);
|
||||
@@ -0,0 +1 @@
|
||||
export { default as TransferOrUpgradeProjectDialog } from './TransferOrUpgradeProjectDialog';
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user