diff --git a/electron/src/backend/Controller.ts b/electron/src/backend/Controller.ts index 6f15b476e..3d9bb7e78 100644 --- a/electron/src/backend/Controller.ts +++ b/electron/src/backend/Controller.ts @@ -154,9 +154,10 @@ class Controller { this.clients.emit('device', cli.data.device?.uid) } - registration = async (code: string) => { + registration = async (code: string, done?: unknown) => { await cli.set('registration', code) this.clients.emit('device', cli.data.device?.uid) + if (typeof done === 'function') done(cli.data.device?.uid ?? '') } restore = async (deviceId: string) => { diff --git a/electron/src/backend/server.test.ts b/electron/src/backend/server.test.ts index bd8d6f4fc..2a27c06e6 100644 --- a/electron/src/backend/server.test.ts +++ b/electron/src/backend/server.test.ts @@ -19,7 +19,7 @@ jest.mock('./index', () => ({ __esModule: true, default: {} })) jest.mock('./Logger', () => ({ __esModule: true, default: { info: jest.fn(), warn: jest.fn(), error: jest.fn() } })) jest.mock('./cliInterface', () => ({ __esModule: true, - default: { readUser: jest.fn(), signOut: jest.fn(), isSignedOut: () => true, data: {}, EVENTS: {} }, + default: { readUser: jest.fn(), signOut: jest.fn(), set: jest.fn(), isSignedOut: () => true, data: {}, EVENTS: {} }, })) jest.mock('./LAN', () => ({ __esModule: true, default: { EVENTS: {} } })) jest.mock('./systemInfo', () => ({ __esModule: true, default: async () => ({ id: 'device-1' }) })) @@ -163,6 +163,31 @@ describe('backend/server broadcasts', () => { expect(signOut).toHaveBeenCalledTimes(1) }) + it('answers an unregister with the device left registered, and still broadcasts it', async () => { + Object.assign(user, credentials) + const window = await open() + expect(await authenticate(window, credentials)).toBe('authenticated') + const data = cli.data as { device?: { uid: string } } + const set = cli.set as jest.Mock + + data.device = { uid: 'device-1' } + set.mockImplementationOnce(async () => (data.device = undefined)) + const broadcast = next(window, 'device') + expect(await window.emitWithAck('registration', 'DELETE')).toBe('') + await broadcast + + data.device = { uid: 'device-1' } + set.mockImplementationOnce(async () => {}) + expect(await window.emitWithAck('registration', 'DELETE')).toBe('device-1') + }) + + it('leaves a signed-out window unanswered when it asks to unregister', async () => { + const window = await open() + const set = (cli.set as jest.Mock).mockClear() + await expect(window.timeout(200).emitWithAck('registration', 'DELETE')).rejects.toThrow() + expect(set).not.toHaveBeenCalled() + }) + it('lets a signed-in window release the agent, then drops every window signed in as its owner', async () => { const signOut = (cli.signOut as jest.Mock).mockClear() Object.assign(user, { ...credentials, signedIn: true }) diff --git a/frontend/src/components/DeleteAccountDialog.test.tsx b/frontend/src/components/DeleteAccountDialog.test.tsx new file mode 100644 index 000000000..3e57b16f8 --- /dev/null +++ b/frontend/src/components/DeleteAccountDialog.test.tsx @@ -0,0 +1,257 @@ +import React, { act } from 'react' +import { createRoot, Root } from 'react-dom/client' +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' + +const api = vi.hoisted(() => ({ graphQLRequestAccountDeletion: vi.fn(), graphQLDeleteAccount: vi.fn() })) +const dispatch = vi.hoisted(() => ({ + backend: { unregisterThisDevice: vi.fn() }, + feedback: { set: vi.fn(), sendFeedback: vi.fn() }, + auth: { signOut: vi.fn() }, +})) +vi.mock('../services/graphQLMutation', () => api) +vi.mock('../store', () => ({})) +vi.mock('../helpers/sleep', () => ({ + default: () => Promise.resolve(), + withTimeout: (promise: Promise) => promise, +})) +vi.mock('./TargetPlatform', () => ({ TargetPlatform: () => null })) +vi.mock('react-redux', () => { + const state = { user: { id: 'ME', email: 'me@example.com', created: new Date(0) }, connections: { all: [] } } + return { + useDispatch: () => dispatch, + useStore: () => ({ getState: () => state }), + useSelector: (select: (state: any) => any) => select(state), + } +}) +vi.mock('react-i18next', () => ({ + initReactI18next: { type: '3rdParty', init: () => {} }, + useTranslation: () => ({ + t: (_: string, fallback: string | Record, values?: Record) => { + const options = typeof fallback === 'string' ? values : fallback + const text = typeof fallback === 'string' ? fallback : fallback.defaultValue + return text.replace(/{{(\w+)}}/g, (_m: string, name: string) => String(options?.[name] ?? '')) + }, + }), +})) + +import { ThemeProvider } from '@mui/material' +import { createTheme } from '@mui/material/styles' +import { jssTheme } from '../styling/theme' +import { DeleteAccountDialog } from './DeleteAccountDialog' +import { OwnedDevices } from '../hooks/useOwnedDevices' + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + +const theme = createTheme(jssTheme(false)) +const owned = (thisDeviceOwned: boolean): OwnedDevices => ({ + total: 2, + thisDeviceOwned, + devices: [ + { id: 'ON', name: 'Online Pi', state: 'active', platform: 0 }, + { id: 'OFF', name: 'Offline NAS', state: 'inactive', platform: 0 }, + ], +}) + +let root: Root +let container: HTMLDivElement + +const flush = () => act(async () => {}) +const dialog = () => document.querySelector('[role=dialog]') as HTMLElement +const button = (label: string) => { + const found = [...dialog().querySelectorAll('button')].find(b => b.textContent === label) + if (!found) throw new Error(`no "${label}" in: ${dialog().textContent}`) + return found +} +const click = async (label: string) => { + await act(async () => button(label).click()) + await flush() +} +const check = (index = 0) => + act(async () => (dialog().querySelectorAll('input[type=checkbox]')[index] as HTMLInputElement).click()) +const typeCode = async (code: string) => { + const input = dialog().querySelector('input[autocomplete=one-time-code]') as HTMLInputElement + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, code) + input.dispatchEvent(new Event('input', { bubbles: true })) + }) +} +const render = async (devices: OwnedDevices | null = owned(true), props: object = {}) => { + await act(async () => + root.render( + + + + ) + ) + await flush() +} +const toFeedback = async () => { + await check() + await click('Continue') +} +const toConfirm = async () => { + await click('Continue') + await click('Email me a code') +} +const submit = async (code = 'ABC234') => { + await typeCode(code) + await click('Delete account permanently') +} + +beforeEach(() => { + vi.resetAllMocks() + api.graphQLRequestAccountDeletion.mockResolvedValue({ ok: true }) + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) +}) +afterEach(() => { + act(() => root.unmount()) + container.remove() +}) + +describe('DeleteAccountDialog', () => { + it('holds Continue until the person accepts that Remote.It stays on their devices', async () => { + await render() + expect([...dialog().querySelectorAll('li')].map(item => item.textContent)).toEqual([ + 'Online PiOnline', + 'Offline NASOffline', + ]) + expect(dialog().textContent).toContain('You own 2 devices') + expect(dialog().textContent).toContain('This device is unregistered automatically') + expect(button('Continue').disabled).toBe(true) + await check() + expect(button('Continue').disabled).toBe(false) + }) + + it('holds Continue until the devices are known, so this device is never skipped', async () => { + await render(null) + await check() + expect(dialog().textContent).toContain('Loading your devices…') + expect(button('Continue').disabled).toBe(true) + + await render(null, { devicesFailed: true }) + expect(dialog().textContent).toContain("Your devices couldn't be loaded") + expect(button('Continue').disabled).toBe(true) + }) + + it('mentions the organization only to someone who has one', async () => { + await render(owned(false)) + await toFeedback() + await click('Continue') + expect(dialog().textContent).not.toContain('Your organization and its roles are deleted') + + await render(owned(false), { hasOrganization: true }) + expect(dialog().textContent).toContain('Your organization and its roles are deleted') + }) + + it('unregisters this device before the account is deleted, then signs out without a survey ticket', async () => { + dispatch.backend.unregisterThisDevice.mockResolvedValue(true) + api.graphQLDeleteAccount.mockResolvedValue({ ok: true }) + await render() + await toFeedback() + await toConfirm() + await submit('abc234') + + expect(api.graphQLDeleteAccount).toHaveBeenCalledWith('ABC234') + expect(dispatch.backend.unregisterThisDevice.mock.invocationCallOrder[0]).toBeLessThan( + api.graphQLDeleteAccount.mock.invocationCallOrder[0] + ) + expect(dispatch.feedback.set).not.toHaveBeenCalled() + expect(dispatch.auth.signOut).toHaveBeenCalled() + expect(dialog().textContent).toContain('Your account has been deleted') + }) + + it('never deletes the account when this device could not be unregistered', async () => { + dispatch.backend.unregisterThisDevice.mockResolvedValue(false) + await render() + await toFeedback() + await toConfirm() + await submit() + + expect(api.graphQLDeleteAccount).not.toHaveBeenCalled() + expect(dialog().textContent).toContain("This device couldn't be unregistered") + expect(button('Delete account permanently').disabled).toBe(false) + }) + + it('leaves a device registered to someone else alone', async () => { + api.graphQLDeleteAccount.mockResolvedValue({ ok: true }) + await render(owned(false)) + await toFeedback() + await toConfirm() + await submit() + + expect(dispatch.backend.unregisterThisDevice).not.toHaveBeenCalled() + expect(api.graphQLDeleteAccount).toHaveBeenCalled() + }) + + it('asks for a new code after the fifth wrong one', async () => { + api.graphQLDeleteAccount.mockResolvedValue({ ok: false, code: 'NOT_AUTHORIZED', message: 'Not Authorized' }) + await render(owned(false)) + await toFeedback() + await toConfirm() + for (let attempt = 1; attempt <= 4; attempt++) { + await submit() + expect(dialog().textContent).toContain('That code is incorrect or has expired.') + } + await submit() + + expect(api.graphQLDeleteAccount).toHaveBeenCalledTimes(5) + expect(dialog().textContent).toContain('Too many incorrect codes') + expect(button('Email me a code')).toBeTruthy() + }) + + it('shows a refusal in place and needs a new code, since the server spent the old one', async () => { + api.graphQLDeleteAccount.mockResolvedValue({ + ok: false, + code: 'INVALID_ARGUMENT', + message: 'Invalid Arguments: your subscription is still active — cancel it first', + args: ['your subscription is still active — cancel it first'], + }) + await render(owned(false)) + await toFeedback() + await toConfirm() + await submit() + + expect(dialog().textContent).toContain('Your subscription is still active — cancel it first') + expect(dialog().textContent).not.toContain('Invalid Arguments') + expect(button('Email me a code')).toBeTruthy() + expect(dispatch.auth.signOut).not.toHaveBeenCalled() + }) + + it('keeps the code after a network failure, so the person can retry it', async () => { + api.graphQLDeleteAccount.mockResolvedValueOnce({ ok: false }).mockResolvedValueOnce({ ok: true }) + await render(owned(false)) + await toFeedback() + await toConfirm() + await submit() + + expect(dialog().textContent).toContain('Something went wrong. Please try again.') + await click('Delete account permanently') + expect(api.graphQLDeleteAccount).toHaveBeenLastCalledWith('ABC234') + expect(dispatch.auth.signOut).toHaveBeenCalled() + }) + + it('sends the survey only when the person filled it in', async () => { + api.graphQLDeleteAccount.mockResolvedValue({ ok: true }) + await render(owned(false)) + await toFeedback() + await check() + await toConfirm() + await submit() + + expect(dispatch.feedback.set).toHaveBeenCalledWith( + expect.objectContaining({ + subject: 'Account deleted: me@example.com', + data: expect.objectContaining({ reasons: ['My device isn’t supported'] }), + }) + ) + expect(dispatch.feedback.sendFeedback).toHaveBeenCalled() + }) +}) diff --git a/frontend/src/components/DeleteAccountDialog.tsx b/frontend/src/components/DeleteAccountDialog.tsx new file mode 100644 index 000000000..95f7dd76a --- /dev/null +++ b/frontend/src/components/DeleteAccountDialog.tsx @@ -0,0 +1,430 @@ +import React, { useState } from 'react' +import { useTranslation } from 'react-i18next' +import { useDispatch, useSelector, useStore } from 'react-redux' +import { + Box, + Button, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + List, + ListItem, + ListItemIcon, + ListItemText, + TextField, + Typography, +} from '@mui/material' +import { Dispatch, State } from '../store' +import { graphQLDeleteAccount, graphQLRequestAccountDeletion } from '../services/graphQLMutation' +import { GraphQLInlineResult } from '../services/graphQL' +import { OwnedDevices } from '../hooks/useOwnedDevices' +import { OwnedDevicesList } from './OwnedDevicesList' +import { ListItemCheckbox } from './ListItemCheckbox' +import { Notice } from './Notice' +import { Icon } from './Icon' +import { spacing } from '../styling' +import sleep, { withTimeout } from '../helpers/sleep' + +const CODE_LENGTH = 6 +const MAX_ATTEMPTS = 5 +const SIGN_OUT_DELAY = 3000 +const FEEDBACK_TIMEOUT = 10000 + +type Step = 'devices' | 'feedback' | 'confirm' | 'done' +type Busy = 'sending' | 'unregistering' | 'deleting' + +type Props = { + open: boolean + owned?: OwnedDevices + devicesFailed?: boolean + hasOrganization?: boolean + onShowInstructions: () => void + onClose: () => void +} + +export const DeleteAccountDialog: React.FC = ({ + open, + owned, + devicesFailed, + hasOrganization, + onShowInstructions, + onClose, +}) => { + const { t } = useTranslation() + const dispatch = useDispatch() + const store = useStore() + const user = useSelector((state: State) => state.user) + const [step, setStep] = useState('devices') + const [acknowledged, setAcknowledged] = useState(false) + const [reasons, setReasons] = useState([]) + const [body, setBody] = useState('') + const [contact, setContact] = useState(true) + const [codeSent, setCodeSent] = useState(false) + const [code, setCode] = useState('') + const [failures, setFailures] = useState(0) + const [busy, setBusy] = useState() + const [error, setError] = useState() + + const locked = !!busy || step === 'done' + const ready = !busy && (!codeSent || code.length === CODE_LENGTH) + + const REASONS = [ + t('deleteAccountSection.reasonUnsupportedDevice', 'My device isn’t supported'), + t('deleteAccountSection.reasonInstallDifficult', 'Installation was too difficult'), + t('deleteAccountSection.reasonConnectionQuality', 'Connection quality or performance issues'), + t('deleteAccountSection.reasonCouldntGetOnline', 'Couldn’t get my device online'), + t('deleteAccountSection.reasonCouldntConnect', 'Couldn’t connect'), + t('deleteAccountSection.reasonCost', 'Cost of service'), + t('deleteAccountSection.reasonAnotherAccount', 'Have another account'), + t('deleteAccountSection.reasonTooHard', 'Too hard to use'), + t('deleteAccountSection.reasonNotExpected', 'Not what I thought it was'), + t('deleteAccountSection.reasonNotUsing', 'Not using it anymore'), + t('deleteAccountSection.reasonUsingSomethingElse', 'Using something else'), + ] + + const refusal = ({ message, args }: GraphQLInlineResult) => { + const reason = Array.isArray(args) ? args.join(' ') : message + return reason + ? reason.charAt(0).toUpperCase() + reason.slice(1) + : t('deleteAccountDialog.genericError', 'Something went wrong. Please try again.') + } + + const goTo = (next: Step) => { + setError(undefined) + setStep(next) + } + + const toggleReason = (reason: string) => + setReasons(reasons.includes(reason) ? reasons.filter(r => r !== reason) : [...reasons, reason]) + + const sendCode = async () => { + setError(undefined) + setBusy('sending') + const result = await graphQLRequestAccountDeletion() + setBusy(undefined) + if (!result.ok) return setError(refusal(result)) + setCodeSent(true) + setCode('') + setFailures(0) + } + + const sendFeedback = async () => { + if (!reasons.length && !body.trim()) return + dispatch.feedback.set({ + subject: `Account deleted: ${user.email}`, + body, + data: { + email: user.email, + userId: user.id, + reasons, + contactMe: contact ? 'Yes' : 'No', + createdDate: user.created?.toLocaleString(navigator.language, { + month: 'short', + day: 'numeric', + year: 'numeric', + }), + lastConnections: store.getState().connections.all.slice(0, 5), + }, + snackbar: t('deleteAccountDialog.doneTitle', 'Your account has been deleted'), + }) + await dispatch.feedback.sendFeedback() + } + + const deleteAccount = async () => { + setError(undefined) + + if (owned?.thisDeviceOwned) { + setBusy('unregistering') + if (!(await dispatch.backend.unregisterThisDevice())) { + setBusy(undefined) + return setError( + t( + 'deleteAccountDialog.unregisterFailed', + "This device couldn't be unregistered, so your account was not deleted. Try again, or unregister this device from its device page first." + ) + ) + } + } + + setBusy('deleting') + const result = await graphQLDeleteAccount(code) + setBusy(undefined) + + if (result.code === 'NOT_AUTHORIZED') { + const attempts = failures + 1 + setFailures(attempts) + setCode('') + if (attempts < MAX_ATTEMPTS) + return setError(t('deleteAccountDialog.invalidCode', 'That code is incorrect or has expired.')) + setCodeSent(false) + return setError( + t('deleteAccountDialog.tooManyAttempts', 'Too many incorrect codes. Request a new code to try again.') + ) + } + + if (!result.ok) { + if (result.code) setCodeSent(false) + return setError(refusal(result)) + } + + setStep('done') + await Promise.all([withTimeout(sendFeedback(), FEEDBACK_TIMEOUT), sleep(SIGN_OUT_DELAY)]) + dispatch.auth.signOut() + } + + const busyLabel = { + sending: t('deleteAccountDialog.sending', 'Sending…'), + unregistering: t('deleteAccountDialog.unregistering', 'Unregistering this device…'), + deleting: t('deleteAccountDialog.deleting', 'Deleting…'), + } + + const consequences = [ + { + icon: 'hdd', + text: t('deleteAccountDialog.consequenceDevices', 'The devices you own are removed from your account'), + }, + hasOrganization && { + icon: 'industry-alt', + text: t('deleteAccountDialog.consequenceOrganization', 'Your organization and its roles are deleted'), + }, + { + icon: 'user-friends', + text: t( + 'deleteAccountDialog.consequenceShares', + 'Devices shared with you and your memberships in other organizations are removed' + ), + }, + { icon: 'sign-out', text: t('deleteAccountDialog.consequenceSignIn', 'Your sign-in and access keys stop working') }, + ].filter(Boolean) as { icon: string; text: string }[] + + const actions = (left: React.ReactNode, primary: React.ReactNode) => ( + + {left} + + {primary} + + ) + + return ( + + {step === 'devices' && ( + <> + + {t('deleteAccountDialog.devicesTitle', 'Remote.It will keep running on your devices')} + + + + {t( + 'deleteAccountDialog.devicesBody', + "Deleting your account removes your devices from it, but it doesn't uninstall Remote.It. The software keeps running on every device it's installed on until you remove it." + )} + + {!owned && ( + + {devicesFailed + ? t('deleteAccountDialog.devicesFailed', "Your devices couldn't be loaded. Close this and try again.") + : t('deleteAccountDialog.devicesLoading', 'Loading your devices…')} + + )} + {owned && ( + + t('deleteAccountDialog.devicesOwned', { count, defaultValue: 'You own {{count}} devices' }) + } + /> + )} + + + + + {actions( + , + + )} + + )} + + {step === 'feedback' && ( + <> + + + 🥺 + + {t('deleteAccountDialog.feedbackTitle', 'Why are you leaving?')} + + {t('deleteAccountSection.confirmSorry', 'We are sorry to see you go!')} +
+ {t( + 'deleteAccountDialog.feedbackOptional', + "Optional — telling us why it didn't work out helps us improve." + )} +
+
+ + + {REASONS.map(reason => ( + toggleReason(reason)} + /> + ))} + + setBody(e.target.value)} + /> + + + {actions( + , + + )} + + )} + + {step === 'confirm' && ( + <> + {t('deleteAccountDialog.confirmTitle', 'Delete your account')} + + + {consequences.map(({ icon, text }) => ( + + + + + + + ))} + + + {t('deleteAccountDialog.permanent', "This happens immediately and can't be undone.")} + + {codeSent ? ( + <> + + {t('deleteAccountDialog.codeSent', { + email: user.email, + defaultValue: 'Enter the code we sent to {{email}}. It expires in 10 minutes.', + })} + + + setCode( + e.target.value + .replace(/[^A-Za-z0-9]/g, '') + .toUpperCase() + .slice(0, CODE_LENGTH) + ) + } + onKeyDown={e => e.key === 'Enter' && ready && deleteAccount()} + inputProps={{ + 'aria-label': t('deleteAccountDialog.codeLabel', 'Confirmation code'), + maxLength: CODE_LENGTH, + autoComplete: 'one-time-code', + style: { textAlign: 'center', fontSize: '1.5rem', letterSpacing: '0.5rem' }, + }} + /> + + + ) : ( + + {t('deleteAccountDialog.codeIntro', { + email: user.email, + defaultValue: "To confirm, we'll email a code to {{email}}.", + })} + + )} + {error && ( + + {error} + + )} + + {actions( + , + + )} + + )} + + {step === 'done' && ( + + + + + {t('deleteAccountDialog.doneTitle', 'Your account has been deleted')} + + + {t('deleteAccountDialog.doneBody', 'Thank you for using Remote.It. Signing you out…')} + + + + )} +
+ ) +} diff --git a/frontend/src/components/DeleteAccountSection.tsx b/frontend/src/components/DeleteAccountSection.tsx index 0b6b5e349..a9febb41d 100644 --- a/frontend/src/components/DeleteAccountSection.tsx +++ b/frontend/src/components/DeleteAccountSection.tsx @@ -1,171 +1,89 @@ -import React from 'react' -import { State } from '../store' -import { useSelector } from 'react-redux' -import { Typography, Box, Button, TextField, List } from '@mui/material' +import React, { useState } from 'react' +import { useHistory } from 'react-router-dom' +import { useDispatch, useSelector } from 'react-redux' import { useTranslation } from 'react-i18next' -import { ListItemCheckbox } from '../components/ListItemCheckbox' -import { useDispatch } from 'react-redux' -import { Dispatch } from '../store' -import { Gutters } from '../components/Gutters' -import { Confirm } from '../components/Confirm' -import { Notice } from '../components/Notice' -import { spacing } from '../styling' +import { Typography, Button, Stack } from '@mui/material' +import { Dispatch, State } from '../store' +import { PERSONAL_PLAN_ID } from '../models/plans' +import { getOwnOrganization } from '../models/organization' +import { selectRemoteitLicense } from '../selectors/organizations' +import { useOwnedDevices } from '../hooks/useOwnedDevices' +import { RemoveRemoteitDialog } from './RemoveRemoteitDialog' +import { DeleteAccountDialog } from './DeleteAccountDialog' +import { Gutters } from './Gutters' +import { Notice } from './Notice' +import { Link } from './Link' -interface DeleteAccountSectionProps { - user?: IUser - paidPlan?: boolean - deleteAccount?: boolean -} - -export const DeleteAccountSection: React.FC = ({ - user, - paidPlan = false, - deleteAccount, -}) => { - const connections = useSelector((state: State) => state.connections.all).slice(0, 5) - const [confirm, setConfirm] = React.useState(false) - const [contact, setContact] = React.useState(true) - const [reasons, setReasons] = React.useState([]) - const [body, setBody] = React.useState('') - const dispatch = useDispatch() +export const DeleteAccountSection: React.FC = () => { const { t } = useTranslation() + const history = useHistory() + const dispatch = useDispatch() + const userId = useSelector((state: State) => state.user.id) + const license = useSelector((state: State) => selectRemoteitLicense(state, state.user.id)) + const members = useSelector((state: State) => getOwnOrganization(state).members) + const hasOrganization = useSelector((state: State) => !!getOwnOrganization(state).id) + const [dialog, setDialog] = useState<'remove' | 'delete'>() + const [opened, setOpened] = useState(0) + const { owned, failed } = useOwnedDevices(!!dialog) + const paidPlan = !!license && license.plan.id !== PERSONAL_PLAN_ID + const otherMembers = members.filter(member => member.user.id !== userId).length - const REASONS = [ - t('deleteAccountSection.reasonUnsupportedDevice', 'My device isn’t supported'), - t('deleteAccountSection.reasonInstallDifficult', 'Installation was too difficult'), - t('deleteAccountSection.reasonConnectionQuality', 'Connection quality or performance issues'), - t('deleteAccountSection.reasonCouldntGetOnline', 'Couldn’t get my device online'), - t('deleteAccountSection.reasonCouldntConnect', 'Couldn’t connect'), - t('deleteAccountSection.reasonCost', 'Cost of service'), - t('deleteAccountSection.reasonAnotherAccount', 'Have another account'), - t('deleteAccountSection.reasonTooHard', 'Too hard to use'), - t('deleteAccountSection.reasonNotExpected', 'Not what I thought it was'), - t('deleteAccountSection.reasonNotUsing', 'Not using it anymore'), - t('deleteAccountSection.reasonUsingSomethingElse', 'Using something else'), - ] - - const handleDelete = () => setConfirm(true) - const handleReason = (reason: string) => { - if (reasons.includes(reason)) setReasons(reasons.filter(r => r !== reason)) - else setReasons([...reasons, reason]) + const openDelete = () => { + setOpened(opened + 1) + setDialog('delete') } - const handleConfirm = () => { - dispatch.feedback.set({ - subject: `Account deletion request for ${user?.email}`, - body, - data: { - email: user?.email, - userId: user?.id, - reasons, - contactMe: contact ? 'Yes' : 'No', - createdDate: user?.created?.toLocaleString(navigator.language, { - month: 'short', - day: 'numeric', - year: 'numeric', - }), - lastConnections: connections, - }, - snackbar: t('deleteAccountSection.snackbar', 'Your account delete request has been sent.'), - }) - dispatch.feedback.sendFeedback() - dispatch.ui.set({ deleteAccount: true }) - setConfirm(false) + const close = () => setDialog(undefined) + const manageMembers = async (event: React.MouseEvent) => { + event.preventDefault() + await dispatch.accounts.select(userId) + history.push('/organization/members') } + return ( - {paidPlan ? ( + {paidPlan && ( {t('deleteAccountSection.paidPlanNotice', 'You have a paid subscription plan.')}{' '} - {t('deleteAccountSection.paidPlanDowngrade', 'Please downgrade to Personal to request an account deletion.')} + + {t('deleteAccountSection.paidPlanCancel', 'Cancel it before deleting your account.')} + + + )} + {otherMembers > 0 && ( + + {t('deleteAccountSection.membersNotice', { + count: otherMembers, + defaultValue: 'Your organization has {{count}} other members.', + })}{' '} + + {t('deleteAccountSection.membersRemove', 'Transfer ownership or remove them before deleting your account.')} + - ) : ( - <> - - {t( - 'deleteAccountSection.description', - 'If you no longer want/need your Remote.It account, you can request an account deletion. Once your delete request is processed, all your account information is removed permanently.' - )} - - - - setConfirm(false)} - title={ - <> - - {/* Pleading Emoji */} - 🥺 - - {t('deleteAccountSection.confirmTitle', 'Why do you want to delete your account?')} - - {t('deleteAccountSection.confirmSorry', 'We are sorry to see you go!')} -
- {t('deleteAccountSection.confirmHelp', "Please help us improve by telling us why it didn't work out.")} -
- - } - action={t('common.delete', 'Delete')} - disabled={body.length < 2 && reasons.length < 1} - > - - {REASONS.map((reason, i) => ( - { - handleReason(reason) - }} - /> - ))} - - setBody(e.target.value)} - /> - setContact(checked)} - /> - - {t( - 'deleteAccountSection.permanentWarning', - 'I understand that this is permanent and that accounts and related devices can not be recovered.' - )} - -
-
- - {t('deleteAccountSection.turnaround', 'Deletion requests take 3 to 5 business days to complete.')} - - )} + + {t( + 'deleteAccountSection.description', + "Deleting your account is immediate and permanent. It doesn't uninstall Remote.It from your devices, so remove it from each device first." + )} + + + + + + + setDialog('remove')} + onClose={close} + />
) } diff --git a/frontend/src/components/OwnedDevicesList.tsx b/frontend/src/components/OwnedDevicesList.tsx new file mode 100644 index 000000000..a1d44312a --- /dev/null +++ b/frontend/src/components/OwnedDevicesList.tsx @@ -0,0 +1,45 @@ +import React from 'react' +import { useTranslation } from 'react-i18next' +import { Box, List, ListItem, ListItemIcon, ListItemText, Typography } from '@mui/material' +import { OwnedDevices } from '../hooks/useOwnedDevices' +import { TargetPlatform } from './TargetPlatform' +import { StatusChip } from './StatusChip' +import { Notice } from './Notice' + +type Props = { owned: OwnedDevices; title: (count: number) => string } + +export const OwnedDevicesList: React.FC = ({ owned, title }) => { + const { t } = useTranslation() + const more = owned.total - owned.devices.length + + return ( + <> + {owned.devices.length > 0 && ( + + {title(owned.total)} + + {owned.devices.map(device => ( + + + + + + + + ))} + + {more > 0 && ( + + {t('ownedDevicesList.more', { count: more, defaultValue: 'and {{count}} more' })} + + )} + + )} + {owned.thisDeviceOwned && ( + + {t('ownedDevicesList.thisDevice', 'This device is unregistered automatically when you delete your account.')} + + )} + + ) +} diff --git a/frontend/src/components/RemoveRemoteitDialog.tsx b/frontend/src/components/RemoveRemoteitDialog.tsx new file mode 100644 index 000000000..8ad1d6705 --- /dev/null +++ b/frontend/src/components/RemoveRemoteitDialog.tsx @@ -0,0 +1,82 @@ +import React from 'react' +import { useTranslation } from 'react-i18next' +import { Stack, Typography } from '@mui/material' +import { OwnedDevices } from '../hooks/useOwnedDevices' +import { OwnedDevicesList } from './OwnedDevicesList' +import { CopyCodeBlock } from './CopyCodeBlock' +import { Confirm } from './Confirm' +import { Notice } from './Notice' +import { Link } from './Link' + +const UNINSTALL_SUPPORT_URL = 'https://support.remote.it/hc/en-us/articles/360054866351' + +type Props = { + open: boolean + owned?: OwnedDevices + onClose: () => void +} + +export const RemoveRemoteitDialog: React.FC = ({ open, owned, onClose }) => { + const { t } = useTranslation() + const desktopApps = [ + { + label: t('removeRemoteitDialog.desktopMacLinux', 'Desktop app on macOS or Linux'), + steps: t( + 'removeRemoteitDialog.desktopMacLinuxSteps', + 'Open Settings, then Application, expand Advanced, and select Uninstall.' + ), + }, + { + label: t('removeRemoteitDialog.desktopWindows', 'Desktop app on Windows'), + steps: t('removeRemoteitDialog.desktopWindowsSteps', 'Uninstall Remote.It from Windows Settings, under Apps.'), + }, + ] + + return ( + + + {t( + 'removeRemoteitDialog.intro', + "Deleting your account doesn't uninstall Remote.It. Remove it from each device you own before you delete your account." + )} + + + {t( + 'removeRemoteitDialog.localAccess', + 'Uninstall from the device itself or over your local network. Removing Remote.It through a Remote.It connection ends that connection right away.' + )} + + + + + + {desktopApps.map(({ label, steps }) => ( + + {label} + {' — '} + {steps} + + ))} + + + {t('removeRemoteitDialog.otherDevices', 'Instructions for other devices')} + + + {owned && ( + t('removeRemoteitDialog.yourDevices', { count, defaultValue: 'Your devices ({{count}})' })} + /> + )} + + ) +} diff --git a/frontend/src/hooks/useOwnedDevices.test.tsx b/frontend/src/hooks/useOwnedDevices.test.tsx new file mode 100644 index 000000000..457073bc0 --- /dev/null +++ b/frontend/src/hooks/useOwnedDevices.test.tsx @@ -0,0 +1,92 @@ +import React, { act } from 'react' +import { createRoot } from 'react-dom/client' +import { describe, it, expect, vi } from 'vitest' + +const { graphQLFetchOwnedDevices, state } = vi.hoisted(() => ({ + graphQLFetchOwnedDevices: vi.fn(), + state: { auth: { user: { id: 'ME' } }, backend: { thisId: '' } }, +})) +vi.mock('../services/graphQLDevice', () => ({ graphQLFetchOwnedDevices })) +vi.mock('../store', () => ({})) +vi.mock('react-redux', () => ({ useSelector: (select: (s: any) => any) => select(state) })) + +import { parseOwnedDevices, useOwnedDevices, OWNED_DEVICES_SHOWN, OwnedDevices } from './useOwnedDevices' + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) + +const device = (id: string, state = 'active') => ({ id, name: id, state, platform: 0 }) + +describe('parseOwnedDevices', () => { + it('takes this device out of the list and the count when the person owns it', () => { + const login = { + account: { devices: { total: 3, items: [device('A'), device('THIS'), device('B', 'inactive')] } }, + device: [{ id: 'THIS', owner: { id: 'ME' } }], + } + expect(parseOwnedDevices(login, 'ME', 'THIS')).toEqual({ + devices: [device('A'), device('B', 'inactive')], + total: 2, + thisDeviceOwned: true, + }) + }) + + it('leaves the count alone when this device belongs to someone else', () => { + const login = { + account: { devices: { total: 2, items: [device('A'), device('B')] } }, + device: [{ id: 'THIS', owner: { id: 'SOMEONE' } }], + } + expect(parseOwnedDevices(login, 'ME', 'THIS')).toMatchObject({ total: 2, thisDeviceOwned: false }) + }) + + it('shows at most the first page whether or not this device was in it', () => { + const items = Array.from({ length: OWNED_DEVICES_SHOWN + 1 }, (_, i) => device(`D${i}`)) + const parsed = parseOwnedDevices({ account: { devices: { total: 40, items } } }, 'ME') + expect(parsed.devices).toHaveLength(OWNED_DEVICES_SHOWN) + expect(parsed).toMatchObject({ total: 40, thisDeviceOwned: false }) + }) + + it('treats a missing response as no devices', () => { + expect(parseOwnedDevices(undefined, 'ME', 'THIS')).toEqual({ devices: [], total: 0, thisDeviceOwned: false }) + }) +}) + +describe('useOwnedDevices', () => { + it('refetches on each open and when this device turns up or changes, but not when it is unregistered', async () => { + const response = (thisId: string) => ({ + data: { + data: { + login: { account: { devices: { total: 1, items: [] } }, device: [{ id: thisId, owner: { id: 'ME' } }] }, + }, + }, + }) + graphQLFetchOwnedDevices.mockImplementation(async (_: string, __: number, thisId: string) => response(thisId)) + let latest: OwnedDevices | undefined + let open = true + const Probe = () => { + latest = useOwnedDevices(open).owned + return null + } + const root = createRoot(document.createElement('div')) + const render = () => act(async () => root.render()) + + await render() + expect(graphQLFetchOwnedDevices).toHaveBeenLastCalledWith('ME', OWNED_DEVICES_SHOWN + 1, '') + + state.backend.thisId = 'THIS' + await render() + expect(graphQLFetchOwnedDevices).toHaveBeenLastCalledWith('ME', OWNED_DEVICES_SHOWN + 1, 'THIS') + expect(latest?.thisDeviceOwned).toBe(true) + + state.backend.thisId = '' + await render() + expect(graphQLFetchOwnedDevices).toHaveBeenCalledTimes(2) + expect(latest?.thisDeviceOwned).toBe(true) + + open = false + await render() + expect(latest?.thisDeviceOwned).toBe(true) + open = true + await render() + expect(graphQLFetchOwnedDevices).toHaveBeenCalledTimes(3) + act(() => root.unmount()) + }) +}) diff --git a/frontend/src/hooks/useOwnedDevices.ts b/frontend/src/hooks/useOwnedDevices.ts new file mode 100644 index 000000000..76002b7be --- /dev/null +++ b/frontend/src/hooks/useOwnedDevices.ts @@ -0,0 +1,53 @@ +import { useEffect, useRef, useState } from 'react' +import { useSelector } from 'react-redux' +import { State } from '../store' +import { getUserId } from '../selectors/state' +import { graphQLFetchOwnedDevices } from '../services/graphQLDevice' + +export const OWNED_DEVICES_SHOWN = 10 + +export type OwnedDevice = { id: string; name: string; state: string; platform: number } + +export type OwnedDevices = { devices: OwnedDevice[]; total: number; thisDeviceOwned: boolean } + +export function parseOwnedDevices(login: any, userId: string, thisId?: string): OwnedDevices { + const items: OwnedDevice[] = login?.account?.devices?.items || [] + const thisDeviceOwned = !!login?.device?.some((device: { owner?: { id: string } }) => device.owner?.id === userId) + return { + devices: items.filter(device => device.id !== thisId).slice(0, OWNED_DEVICES_SHOWN), + total: (login?.account?.devices?.total || 0) - (thisDeviceOwned ? 1 : 0), + thisDeviceOwned, + } +} + +export function useOwnedDevices(enabled: boolean) { + const userId = useSelector(getUserId) + const thisId = useSelector((state: State) => state.backend.thisId) + const [owned, setOwned] = useState() + const [failed, setFailed] = useState(false) + const fetchedFor = useRef() + const fresh = useRef(false) + + useEffect(() => { + if (!enabled || !userId) { + fresh.current = false + return + } + if (fresh.current && owned && (!thisId || thisId === fetchedFor.current)) return + let current = true + fresh.current = true + fetchedFor.current = thisId + setOwned(undefined) + setFailed(false) + graphQLFetchOwnedDevices(userId, OWNED_DEVICES_SHOWN + 1, thisId).then(result => { + if (!current) return + if (result === 'ERROR') return setFailed(true) + setOwned(parseOwnedDevices(result.data?.data?.login, userId, thisId)) + }) + return () => { + current = false + } + }, [enabled, userId, thisId]) + + return { owned, failed } +} diff --git a/frontend/src/i18n/locales/de/app.json b/frontend/src/i18n/locales/de/app.json index 0034a3557..c60f64520 100644 --- a/frontend/src/i18n/locales/de/app.json +++ b/frontend/src/i18n/locales/de/app.json @@ -455,6 +455,7 @@ "common": { "actionCannotBeUndone": "Diese Aktion kann nicht rückgängig gemacht werden.", "areYouSure": "Sind Sie sicher?", + "back": "Zurück", "cancel": "Abbrechen", "cannotBeUndone": "Diese Aktion kann nicht rückgängig gemacht werden.", "clear": "Löschen", @@ -684,17 +685,50 @@ "title": "Zugriffsschlüssel löschen", "warning": "Diese Aktion ist endgültig und kann nicht rückgängig gemacht werden." }, + "deleteAccountDialog": { + "acknowledge": "Mir ist bewusst, dass Remote.It auf meinen Geräten installiert bleibt und weiterläuft und durch das Löschen meines Kontos nicht entfernt wird.", + "codeIntro": "Zur Bestätigung senden wir einen Code per E-Mail an {{email}}.", + "codeLabel": "Bestätigungscode", + "codePlaceholder": "Code", + "codeSent": "Geben Sie den Code ein, den wir an {{email}} gesendet haben. Er ist 10 Minuten gültig.", + "confirmTitle": "Konto löschen", + "consequenceDevices": "Ihre Geräte werden aus Ihrem Konto entfernt", + "consequenceOrganization": "Ihre Organisation und ihre Rollen werden gelöscht", + "consequenceShares": "Für Sie freigegebene Geräte und Ihre Mitgliedschaften in anderen Organisationen werden entfernt", + "consequenceSignIn": "Ihre Anmeldung und Ihre Zugriffsschlüssel funktionieren nicht mehr", + "deleteButton": "Konto endgültig löschen", + "deleting": "Wird gelöscht…", + "devicesBody": "Beim Löschen Ihres Kontos werden Ihre Geräte daraus entfernt, Remote.It wird aber nicht deinstalliert. Die Software läuft auf jedem Gerät weiter, auf dem sie installiert ist, bis Sie sie entfernen.", + "devicesFailed": "Ihre Geräte konnten nicht geladen werden. Schließen Sie dieses Fenster und versuchen Sie es erneut.", + "devicesLoading": "Ihre Geräte werden geladen…", + "devicesOwned_one": "Sie besitzen {{count}} Gerät", + "devicesOwned_other": "Sie besitzen {{count}} Geräte", + "devicesTitle": "Remote.It läuft auf Ihren Geräten weiter", + "doneBody": "Danke, dass Sie Remote.It genutzt haben. Sie werden abgemeldet…", + "doneTitle": "Ihr Konto wurde gelöscht", + "feedbackOptional": "Optional – wenn Sie uns sagen, warum es nicht gepasst hat, hilft uns das, besser zu werden.", + "feedbackTitle": "Warum verlassen Sie uns?", + "genericError": "Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.", + "invalidCode": "Dieser Code ist falsch oder abgelaufen.", + "permanent": "Das geschieht sofort und kann nicht rückgängig gemacht werden.", + "resendCode": "Neuen Code senden", + "sendCode": "Code per E-Mail senden", + "sending": "Wird gesendet…", + "tooManyAttempts": "Zu viele falsche Codes. Fordern Sie einen neuen Code an, um es erneut zu versuchen.", + "unregisterFailed": "Die Registrierung dieses Geräts konnte nicht aufgehoben werden, daher wurde Ihr Konto nicht gelöscht. Versuchen Sie es erneut oder heben Sie die Registrierung zuerst auf der Seite des Geräts auf.", + "unregistering": "Registrierung dieses Geräts wird aufgehoben…" + }, "deleteAccountSection": { - "confirmHelp": "Bitte helfen Sie uns, uns zu verbessern, indem Sie uns mitteilen, warum es nicht funktioniert hat.", "confirmSorry": "Schade, dass Sie uns verlassen!", - "confirmTitle": "Warum möchten Sie Ihr Konto löschen?", "contactMeLabel": "Ich bin damit einverstanden, dass mich jemand bezüglich meines Feedbacks kontaktiert.", "deleteButton": "Mein Konto löschen", - "description": "Wenn Sie Ihr Remote.It-Konto nicht mehr benötigen, können Sie eine Kontolöschung beantragen. Sobald Ihre Löschanfrage bearbeitet wurde, werden alle Ihre Kontoinformationen dauerhaft entfernt.", + "description": "Das Löschen Ihres Kontos erfolgt sofort und endgültig. Remote.It wird dabei nicht von Ihren Geräten deinstalliert – entfernen Sie es daher zuerst von jedem Gerät.", + "membersNotice_one": "Ihre Organisation hat {{count}} weiteres Mitglied.", + "membersNotice_other": "Ihre Organisation hat {{count}} weitere Mitglieder.", + "membersRemove": "Übertragen Sie die Inhaberschaft oder entfernen Sie die Mitglieder, bevor Sie Ihr Konto löschen.", "otherReasonLabel": "Anderer Grund", - "paidPlanDowngrade": "Bitte stufen Sie auf Personal herab, um eine Kontolöschung zu beantragen.", + "paidPlanCancel": "Kündigen Sie es, bevor Sie Ihr Konto löschen.", "paidPlanNotice": "Sie haben ein kostenpflichtiges Abonnement.", - "permanentWarning": "Ich verstehe, dass dies endgültig ist und Konten sowie zugehörige Geräte nicht wiederhergestellt werden können.", "reasonAnotherAccount": "Habe ein anderes Konto", "reasonConnectionQuality": "Probleme mit der Verbindungsqualität oder Leistung", "reasonCost": "Kosten des Dienstes", @@ -706,8 +740,7 @@ "reasonTooHard": "Zu schwer zu bedienen", "reasonUnsupportedDevice": "Mein Gerät wird nicht unterstützt", "reasonUsingSomethingElse": "Nutze etwas anderes", - "snackbar": "Ihre Anfrage zur Kontolöschung wurde gesendet.", - "turnaround": "Löschanfragen benötigen 3 bis 5 Werktage zur Bearbeitung." + "removeButton": "So entfernen Sie Remote.It" }, "deleteDevice": { "deletingDevices": "Geräte werden gelöscht.", @@ -1597,6 +1630,11 @@ "removeMembersWarning": "Dadurch werden alle Ihre Mitglieder und ihr Zugriff auf Ihre Geräte entfernt.", "settings": "Einstellungen" }, + "ownedDevicesList": { + "more_one": "und {{count}} weiteres", + "more_other": "und {{count}} weitere", + "thisDevice": "Die Registrierung dieses Geräts wird automatisch aufgehoben, wenn Sie Ihr Konto löschen." + }, "partnerStatsDetailPanel": { "activated": "Aktiviert", "activeLast30Days": "Aktiv (letzte 30 Tage)", @@ -1866,6 +1904,20 @@ "guideTitle": "Gerät hinzufügen", "managePermissionRequired": "Sie benötigen die Berechtigung „Verwalten“, um ein Gerät zu dieser Organisation hinzuzufügen." }, + "removeRemoteitDialog": { + "debian": "Raspberry Pi, Ubuntu und andere Debian-basierte Linux-Systeme", + "desktopMacLinux": "Desktop-App unter macOS oder Linux", + "desktopMacLinuxSteps": "Öffnen Sie die Einstellungen, dann „Anwendung“, klappen Sie „Erweitert“ auf und wählen Sie „Deinstallieren“.", + "desktopWindows": "Desktop-App unter Windows", + "desktopWindowsSteps": "Deinstallieren Sie Remote.It in den Windows-Einstellungen unter „Apps“.", + "intro": "Beim Löschen Ihres Kontos wird Remote.It nicht deinstalliert. Entfernen Sie es von jedem Ihrer Geräte, bevor Sie Ihr Konto löschen.", + "localAccess": "Deinstallieren Sie direkt am Gerät oder über Ihr lokales Netzwerk. Wenn Sie Remote.It über eine Remote.It-Verbindung entfernen, wird diese Verbindung sofort getrennt.", + "openwrt": "OpenWrt", + "otherDevices": "Anleitungen für andere Geräte", + "title": "Remote.It von Ihren Geräten entfernen", + "yourDevices_one": "Ihre Geräte ({{count}})", + "yourDevices_other": "Ihre Geräte ({{count}})" + }, "rentANodeForm": { "addDns": "Öffentliche DNS-Adresse hinzufügen", "addIpv6": "Öffentliche IPv6-Adresse hinzufügen", diff --git a/frontend/src/i18n/locales/en/app.json b/frontend/src/i18n/locales/en/app.json index ef7ec2e8c..0a97bb91b 100644 --- a/frontend/src/i18n/locales/en/app.json +++ b/frontend/src/i18n/locales/en/app.json @@ -455,6 +455,7 @@ "common": { "actionCannotBeUndone": "This action cannot be undone.", "areYouSure": "Are you sure?", + "back": "Back", "cancel": "Cancel", "cannotBeUndone": "This action cannot be undone.", "clear": "Clear", @@ -684,17 +685,50 @@ "title": "Delete Access Key", "warning": "This action is permanent and cannot be undone." }, + "deleteAccountDialog": { + "acknowledge": "I understand that Remote.It stays installed and running on my devices, and deleting my account won't remove it.", + "codeIntro": "To confirm, we'll email a code to {{email}}.", + "codeLabel": "Confirmation code", + "codePlaceholder": "Code", + "codeSent": "Enter the code we sent to {{email}}. It expires in 10 minutes.", + "confirmTitle": "Delete your account", + "consequenceDevices": "The devices you own are removed from your account", + "consequenceOrganization": "Your organization and its roles are deleted", + "consequenceShares": "Devices shared with you and your memberships in other organizations are removed", + "consequenceSignIn": "Your sign-in and access keys stop working", + "deleteButton": "Delete account permanently", + "deleting": "Deleting…", + "devicesBody": "Deleting your account removes your devices from it, but it doesn't uninstall Remote.It. The software keeps running on every device it's installed on until you remove it.", + "devicesFailed": "Your devices couldn't be loaded. Close this and try again.", + "devicesLoading": "Loading your devices…", + "devicesOwned_one": "You own {{count}} device", + "devicesOwned_other": "You own {{count}} devices", + "devicesTitle": "Remote.It will keep running on your devices", + "doneBody": "Thank you for using Remote.It. Signing you out…", + "doneTitle": "Your account has been deleted", + "feedbackOptional": "Optional — telling us why it didn't work out helps us improve.", + "feedbackTitle": "Why are you leaving?", + "genericError": "Something went wrong. Please try again.", + "invalidCode": "That code is incorrect or has expired.", + "permanent": "This happens immediately and can't be undone.", + "resendCode": "Send a new code", + "sendCode": "Email me a code", + "sending": "Sending…", + "tooManyAttempts": "Too many incorrect codes. Request a new code to try again.", + "unregisterFailed": "This device couldn't be unregistered, so your account was not deleted. Try again, or unregister this device from its device page first.", + "unregistering": "Unregistering this device…" + }, "deleteAccountSection": { - "confirmHelp": "Please help us improve by telling us why it didn't work out.", "confirmSorry": "We are sorry to see you go!", - "confirmTitle": "Why do you want to delete your account?", "contactMeLabel": "I'm open to having someone contact me about my feedback.", "deleteButton": "Delete my account", - "description": "If you no longer want/need your Remote.It account, you can request an account deletion. Once your delete request is processed, all your account information is removed permanently.", + "description": "Deleting your account is immediate and permanent. It doesn't uninstall Remote.It from your devices, so remove it from each device first.", + "membersNotice_one": "Your organization has {{count}} other member.", + "membersNotice_other": "Your organization has {{count}} other members.", + "membersRemove": "Transfer ownership or remove them before deleting your account.", "otherReasonLabel": "Other Reason", - "paidPlanDowngrade": "Please downgrade to Personal to request an account deletion.", + "paidPlanCancel": "Cancel it before deleting your account.", "paidPlanNotice": "You have a paid subscription plan.", - "permanentWarning": "I understand that this is permanent and that accounts and related devices can not be recovered.", "reasonAnotherAccount": "Have another account", "reasonConnectionQuality": "Connection quality or performance issues", "reasonCost": "Cost of service", @@ -706,8 +740,7 @@ "reasonTooHard": "Too hard to use", "reasonUnsupportedDevice": "My device isn’t supported", "reasonUsingSomethingElse": "Using something else", - "snackbar": "Your account delete request has been sent.", - "turnaround": "Deletion requests take 3 to 5 business days to complete." + "removeButton": "How to remove Remote.It" }, "deleteDevice": { "deletingDevices": "deleting devices.", @@ -1597,6 +1630,11 @@ "removeMembersWarning": "This will remove all your members and their access to your devices.", "settings": "Settings" }, + "ownedDevicesList": { + "more_one": "and {{count}} more", + "more_other": "and {{count}} more", + "thisDevice": "This device is unregistered automatically when you delete your account." + }, "partnerStatsDetailPanel": { "activated": "Activated", "activeLast30Days": "Active (Last 30 Days)", @@ -1866,6 +1904,20 @@ "guideTitle": "Add a device", "managePermissionRequired": "Manage permission required to add a device to this organization." }, + "removeRemoteitDialog": { + "debian": "Raspberry Pi, Ubuntu and other Debian Linux", + "desktopMacLinux": "Desktop app on macOS or Linux", + "desktopMacLinuxSteps": "Open Settings, then Application, expand Advanced, and select Uninstall.", + "desktopWindows": "Desktop app on Windows", + "desktopWindowsSteps": "Uninstall Remote.It from Windows Settings, under Apps.", + "intro": "Deleting your account doesn't uninstall Remote.It. Remove it from each device you own before you delete your account.", + "localAccess": "Uninstall from the device itself or over your local network. Removing Remote.It through a Remote.It connection ends that connection right away.", + "openwrt": "OpenWrt", + "otherDevices": "Instructions for other devices", + "title": "Remove Remote.It from your devices", + "yourDevices_one": "Your devices ({{count}})", + "yourDevices_other": "Your devices ({{count}})" + }, "rentANodeForm": { "addDns": "Add a public DNS address", "addIpv6": "Add a public IPv6 address", diff --git a/frontend/src/i18n/locales/es/app.json b/frontend/src/i18n/locales/es/app.json index 8b6936ed6..faf07f533 100644 --- a/frontend/src/i18n/locales/es/app.json +++ b/frontend/src/i18n/locales/es/app.json @@ -459,6 +459,7 @@ "common": { "actionCannotBeUndone": "Esta acción no se puede deshacer.", "areYouSure": "¿Estás seguro?", + "back": "Atrás", "cancel": "Cancelar", "cannotBeUndone": "Esta acción no se puede deshacer.", "clear": "Borrar", @@ -688,17 +689,52 @@ "title": "Eliminar clave de acceso", "warning": "Esta acción es permanente y no se puede deshacer." }, + "deleteAccountDialog": { + "acknowledge": "Entiendo que Remote.It seguirá instalado y en ejecución en mis dispositivos, y que eliminar mi cuenta no lo desinstala.", + "codeIntro": "Para confirmar, enviaremos un código por correo a {{email}}.", + "codeLabel": "Código de confirmación", + "codePlaceholder": "Código", + "codeSent": "Introduce el código que enviamos a {{email}}. Caduca en 10 minutos.", + "confirmTitle": "Eliminar tu cuenta", + "consequenceDevices": "Los dispositivos de tu propiedad se quitan de tu cuenta", + "consequenceOrganization": "Tu organización y sus roles se eliminan", + "consequenceShares": "Se quitan los dispositivos compartidos contigo y tus membresías en otras organizaciones", + "consequenceSignIn": "Tu inicio de sesión y tus claves de acceso dejan de funcionar", + "deleteButton": "Eliminar la cuenta definitivamente", + "deleting": "Eliminando…", + "devicesBody": "Al eliminar tu cuenta, tus dispositivos se quitan de ella, pero Remote.It no se desinstala. El software sigue funcionando en cada dispositivo donde está instalado hasta que lo quites.", + "devicesFailed": "No se pudieron cargar tus dispositivos. Cierra esto e inténtalo de nuevo.", + "devicesLoading": "Cargando tus dispositivos…", + "devicesOwned_one": "Tienes {{count}} dispositivo", + "devicesOwned_many": "Tienes {{count}} dispositivos", + "devicesOwned_other": "Tienes {{count}} dispositivos", + "devicesTitle": "Remote.It seguirá funcionando en tus dispositivos", + "doneBody": "Gracias por usar Remote.It. Cerrando sesión…", + "doneTitle": "Tu cuenta se ha eliminado", + "feedbackOptional": "Opcional: contarnos por qué no funcionó nos ayuda a mejorar.", + "feedbackTitle": "¿Por qué te vas?", + "genericError": "Algo salió mal. Inténtalo de nuevo.", + "invalidCode": "El código es incorrecto o ha caducado.", + "permanent": "Esto ocurre de inmediato y no se puede deshacer.", + "resendCode": "Enviar un código nuevo", + "sendCode": "Enviarme un código", + "sending": "Enviando…", + "tooManyAttempts": "Demasiados códigos incorrectos. Solicita un código nuevo para volver a intentarlo.", + "unregisterFailed": "No se pudo anular el registro de este dispositivo, así que tu cuenta no se eliminó. Inténtalo de nuevo o anula primero el registro desde la página del dispositivo.", + "unregistering": "Anulando el registro de este dispositivo…" + }, "deleteAccountSection": { - "confirmHelp": "Ayúdanos a mejorar contándonos por qué no funcionó.", "confirmSorry": "¡Lamentamos que te vayas!", - "confirmTitle": "¿Por qué quieres eliminar tu cuenta?", "contactMeLabel": "Acepto que alguien se ponga en contacto conmigo sobre mis comentarios.", "deleteButton": "Eliminar mi cuenta", - "description": "Si ya no quieres o necesitas tu cuenta de Remote.It, puedes solicitar su eliminación. Una vez procesada la solicitud, toda la información de tu cuenta se eliminará de forma permanente.", + "description": "Eliminar tu cuenta es inmediato y permanente. No desinstala Remote.It de tus dispositivos, así que quítalo primero de cada uno.", + "membersNotice_one": "Tu organización tiene {{count}} miembro más.", + "membersNotice_many": "Tu organización tiene {{count}} miembros más.", + "membersNotice_other": "Tu organización tiene {{count}} miembros más.", + "membersRemove": "Transfiere la propiedad o quítalos antes de eliminar tu cuenta.", "otherReasonLabel": "Otro motivo", - "paidPlanDowngrade": "Cambia a un plan Personal para poder solicitar la eliminación de tu cuenta.", + "paidPlanCancel": "Cancélalo antes de eliminar tu cuenta.", "paidPlanNotice": "Tienes un plan de suscripción pago.", - "permanentWarning": "Entiendo que esto es permanente y que las cuentas y los dispositivos relacionados no se pueden recuperar.", "reasonAnotherAccount": "Tengo otra cuenta", "reasonConnectionQuality": "Problemas de calidad de conexión o rendimiento", "reasonCost": "Costo del servicio", @@ -710,8 +746,7 @@ "reasonTooHard": "Es demasiado difícil de usar", "reasonUnsupportedDevice": "Mi dispositivo no es compatible", "reasonUsingSomethingElse": "Uso otra cosa", - "snackbar": "Se envió tu solicitud de eliminación de cuenta.", - "turnaround": "Las solicitudes de eliminación tardan de 3 a 5 días hábiles en completarse." + "removeButton": "Cómo quitar Remote.It" }, "deleteDevice": { "deletingDevices": "eliminando dispositivos.", @@ -1612,6 +1647,12 @@ "removeMembersWarning": "Esto eliminará a todos tus miembros y su acceso a tus dispositivos.", "settings": "Configuración" }, + "ownedDevicesList": { + "more_one": "y {{count}} más", + "more_many": "y {{count}} más", + "more_other": "y {{count}} más", + "thisDevice": "El registro de este dispositivo se anula automáticamente cuando eliminas tu cuenta." + }, "partnerStatsDetailPanel": { "activated": "Activado", "activeLast30Days": "Activo (últimos 30 días)", @@ -1889,6 +1930,21 @@ "guideTitle": "Añadir un dispositivo", "managePermissionRequired": "Debes tener el permiso \"Gestionar\" para añadir un dispositivo a esta organización." }, + "removeRemoteitDialog": { + "debian": "Raspberry Pi, Ubuntu y otros Linux basados en Debian", + "desktopMacLinux": "App de escritorio en macOS o Linux", + "desktopMacLinuxSteps": "Abre Configuración, luego Aplicación, despliega Avanzado y selecciona Desinstalar.", + "desktopWindows": "App de escritorio en Windows", + "desktopWindowsSteps": "Desinstala Remote.It desde la Configuración de Windows, en Aplicaciones.", + "intro": "Eliminar tu cuenta no desinstala Remote.It. Quítalo de cada dispositivo que tengas antes de eliminar tu cuenta.", + "localAccess": "Desinstálalo desde el propio dispositivo o a través de tu red local. Si quitas Remote.It mediante una conexión de Remote.It, esa conexión se corta de inmediato.", + "openwrt": "OpenWrt", + "otherDevices": "Instrucciones para otros dispositivos", + "title": "Quitar Remote.It de tus dispositivos", + "yourDevices_one": "Tus dispositivos ({{count}})", + "yourDevices_many": "Tus dispositivos ({{count}})", + "yourDevices_other": "Tus dispositivos ({{count}})" + }, "rentANodeForm": { "addDns": "Añadir una dirección DNS pública", "addIpv6": "Añadir una dirección IPv6 pública", diff --git a/frontend/src/i18n/locales/ja/app.json b/frontend/src/i18n/locales/ja/app.json index e4c8b5220..6a3f177a5 100644 --- a/frontend/src/i18n/locales/ja/app.json +++ b/frontend/src/i18n/locales/ja/app.json @@ -451,6 +451,7 @@ "common": { "actionCannotBeUndone": "この操作は元に戻せません。", "areYouSure": "本当によろしいですか?", + "back": "戻る", "cancel": "キャンセル", "cannotBeUndone": "この操作は元に戻せません。", "clear": "クリア", @@ -680,17 +681,48 @@ "title": "アクセスキーを削除", "warning": "この操作は取り消せず、元に戻せません。" }, + "deleteAccountDialog": { + "acknowledge": "Remote.It はデバイスにインストールされたまま動作し続け、アカウントを削除しても削除されないことを理解しました。", + "codeIntro": "確認のため、{{email}} にコードをメールでお送りします。", + "codeLabel": "確認コード", + "codePlaceholder": "コード", + "codeSent": "{{email}} に送信したコードを入力してください。有効期限は10分です。", + "confirmTitle": "アカウントを削除", + "consequenceDevices": "所有しているデバイスがアカウントから削除されます", + "consequenceOrganization": "組織とそのロールが削除されます", + "consequenceShares": "共有されているデバイスと、他の組織のメンバーシップが削除されます", + "consequenceSignIn": "サインインとアクセスキーが使えなくなります", + "deleteButton": "アカウントを完全に削除", + "deleting": "削除中…", + "devicesBody": "アカウントを削除するとデバイスはアカウントから外れますが、Remote.It はアンインストールされません。ソフトウェアは、削除するまでインストールされているすべてのデバイスで動作し続けます。", + "devicesFailed": "デバイスを読み込めませんでした。閉じてからもう一度お試しください。", + "devicesLoading": "デバイスを読み込んでいます…", + "devicesOwned_other": "所有しているデバイス: {{count}}台", + "devicesTitle": "Remote.It はデバイス上で動作し続けます", + "doneBody": "Remote.It をご利用いただきありがとうございました。サインアウトしています…", + "doneTitle": "アカウントを削除しました", + "feedbackOptional": "任意 — うまくいかなかった理由を教えていただけると、改善に役立ちます。", + "feedbackTitle": "退会の理由を教えてください", + "genericError": "問題が発生しました。もう一度お試しください。", + "invalidCode": "コードが正しくないか、有効期限が切れています。", + "permanent": "この操作はすぐに実行され、元に戻せません。", + "resendCode": "新しいコードを送信", + "sendCode": "コードをメールで受け取る", + "sending": "送信中…", + "tooManyAttempts": "誤ったコードの入力が多すぎます。新しいコードをリクエストしてやり直してください。", + "unregisterFailed": "このデバイスの登録を解除できなかったため、アカウントは削除されていません。もう一度お試しいただくか、先にデバイスのページからこのデバイスの登録を解除してください。", + "unregistering": "このデバイスの登録を解除中…" + }, "deleteAccountSection": { - "confirmHelp": "うまくいかなかった理由を教えていただき、改善にご協力ください。", "confirmSorry": "退会されるとのこと、残念です。", - "confirmTitle": "アカウントを削除する理由は何ですか?", "contactMeLabel": "フィードバックについて連絡を受けても構いません。", "deleteButton": "アカウントを削除する", - "description": "Remote.It アカウントが不要になった場合は、アカウントの削除をリクエストできます。削除リクエストが処理されると、アカウント情報はすべて完全に削除されます。", + "description": "アカウントの削除はすぐに実行され、元に戻せません。デバイスから Remote.It はアンインストールされないため、先に各デバイスから削除してください。", + "membersNotice_other": "組織には他に {{count}} 人のメンバーがいます。", + "membersRemove": "アカウントを削除する前に、所有権を移転するかメンバーを削除してください。", "otherReasonLabel": "その他の理由", - "paidPlanDowngrade": "アカウントの削除をリクエストするには、Personalプランにダウングレードしてください。", + "paidPlanCancel": "アカウントを削除する前に解約してください。", "paidPlanNotice": "有料サブスクリプションプランをご利用中です。", - "permanentWarning": "これは永久的な操作であり、アカウントおよび関連するデバイスは復元できないことを理解しています。", "reasonAnotherAccount": "別のアカウントを持っている", "reasonConnectionQuality": "接続品質またはパフォーマンスの問題", "reasonCost": "サービスの費用", @@ -702,8 +734,7 @@ "reasonTooHard": "使いにくい", "reasonUnsupportedDevice": "自分のデバイスがサポートされていない", "reasonUsingSomethingElse": "別のものを使用している", - "snackbar": "アカウント削除のリクエストを送信しました。", - "turnaround": "削除リクエストの完了には3〜5営業日かかります。" + "removeButton": "Remote.It の削除方法" }, "deleteDevice": { "deletingDevices": "デバイスを削除しています。", @@ -1582,6 +1613,10 @@ "removeMembersWarning": "これにより、すべてのメンバーとデバイスへのアクセス権が削除されます。", "settings": "設定" }, + "ownedDevicesList": { + "more_other": "他 {{count}} 台", + "thisDevice": "このデバイスは、アカウントを削除すると自動的に登録解除されます。" + }, "partnerStatsDetailPanel": { "activated": "有効化済み", "activeLast30Days": "アクティブ (過去30日間)", @@ -1843,6 +1878,19 @@ "guideTitle": "デバイスを追加", "managePermissionRequired": "この組織にデバイスを追加するには「管理」権限が必要です。" }, + "removeRemoteitDialog": { + "debian": "Raspberry Pi、Ubuntu、その他の Debian 系 Linux", + "desktopMacLinux": "macOS または Linux のデスクトップアプリ", + "desktopMacLinuxSteps": "設定を開き、「アプリケーション」の「詳細設定」を展開して「アンインストール」を選択します。", + "desktopWindows": "Windows のデスクトップアプリ", + "desktopWindowsSteps": "Windows の設定の「アプリ」から Remote.It をアンインストールします。", + "intro": "アカウントを削除しても Remote.It はアンインストールされません。アカウントを削除する前に、所有している各デバイスから削除してください。", + "localAccess": "デバイス本体またはローカルネットワーク経由でアンインストールしてください。Remote.It の接続を使って Remote.It を削除すると、その接続はすぐに切断されます。", + "openwrt": "OpenWrt", + "otherDevices": "その他のデバイスの手順", + "title": "デバイスから Remote.It を削除する", + "yourDevices_other": "所有デバイス ({{count}})" + }, "rentANodeForm": { "addDns": "公開DNSアドレスを追加", "addIpv6": "公開IPv6アドレスを追加", diff --git a/frontend/src/models/backend.test.ts b/frontend/src/models/backend.test.ts new file mode 100644 index 000000000..b47a56974 --- /dev/null +++ b/frontend/src/models/backend.test.ts @@ -0,0 +1,51 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' + +const { emit, emitWithAck } = vi.hoisted(() => ({ emit: vi.fn(), emitWithAck: vi.fn() })) +vi.mock('../services/Controller', () => ({ emit, default: { emitWithAck } })) +vi.mock('../services/browser', () => ({ default: {}, setLocalStorage: vi.fn(), getOs: vi.fn() })) +vi.mock('../i18n', () => ({ default: { t: (k: string) => k } })) + +import backend from './backend' + +describe('backend.unregisterThisDevice', () => { + const state = { backend: { thisId: 'THIS' }, ui: {} } + let dispatch: any + let effects: any + + beforeEach(() => { + vi.resetAllMocks() + dispatch = { ui: { set: vi.fn() }, backend: { set: vi.fn() }, devices: {} } + effects = (backend as any).effects(dispatch) + }) + + it('resolves true once the agent answers that no device is registered', async () => { + emitWithAck.mockResolvedValue('') + await expect(effects.unregisterThisDevice(undefined, state)).resolves.toBe(true) + expect(emitWithAck).toHaveBeenCalledWith('registration', 60 * 1000, 'DELETE') + }) + + it('resolves false when the agent answers that the device is still registered', async () => { + emitWithAck.mockResolvedValue('THIS') + await expect(effects.unregisterThisDevice(undefined, state)).resolves.toBe(false) + }) + + it('resolves false when no answer comes back', async () => { + emitWithAck.mockResolvedValue(undefined) + await expect(effects.unregisterThisDevice(undefined, state)).resolves.toBe(false) + }) + + it('is not settled by an unrelated device broadcast', async () => { + let answer: (deviceId: string) => void = () => {} + emitWithAck.mockReturnValue(new Promise(resolve => (answer = resolve))) + const unregistering = effects.unregisterThisDevice(undefined, state) + await effects.targetDeviceUpdated('THIS', state) + answer('') + await expect(unregistering).resolves.toBe(true) + }) + + it('has nothing to do without a registered device', async () => { + await expect(effects.unregisterThisDevice(undefined, { backend: { thisId: '' } })).resolves.toBe(true) + expect(emitWithAck).not.toHaveBeenCalled() + expect(emit).not.toHaveBeenCalled() + }) +}) diff --git a/frontend/src/models/backend.ts b/frontend/src/models/backend.ts index cbb5243e5..4aed87bb3 100644 --- a/frontend/src/models/backend.ts +++ b/frontend/src/models/backend.ts @@ -1,11 +1,12 @@ import browser, { setLocalStorage, getOs } from '../services/browser' import { createModel } from '@rematch/core' import { RootModel } from '.' -import { emit } from '../services/Controller' +import Controller, { emit } from '../services/Controller' import sleep from '../helpers/sleep' import i18n from '../i18n' export const NOTICE_VERSION_ID = 'notice-version' +const UNREGISTER_TIMEOUT = 60 * 1000 export type IBackendState = { initialized: boolean @@ -91,6 +92,12 @@ export default createModel()({ }) return result }, + async unregisterThisDevice(_: void, state) { + const { thisId } = state.backend + if (!thisId) return true + dispatch.ui.set({ silent: thisId }) + return (await Controller.emitWithAck('registration', UNREGISTER_TIMEOUT, 'DELETE')) === '' + }, async targetDeviceUpdated(newId: string, state) { const { ui, backend, devices } = dispatch const { thisId } = state.backend diff --git a/frontend/src/models/ui.ts b/frontend/src/models/ui.ts index 5e53859c7..4970d36f9 100644 --- a/frontend/src/models/ui.ts +++ b/frontend/src/models/ui.ts @@ -63,7 +63,6 @@ export type UIState = { fetching: boolean destroying: boolean transferring: boolean - deleteAccount: boolean routingLock?: IRouteType routingMessage?: string sidebarMenu: boolean @@ -151,7 +150,6 @@ export const defaultState: UIState = { fetching: false, destroying: false, transferring: false, - deleteAccount: false, routingLock: undefined, routingMessage: undefined, sidebarMenu: false, diff --git a/frontend/src/pages/ProfilePage.tsx b/frontend/src/pages/ProfilePage.tsx index 411f8dcfa..ca171bf24 100644 --- a/frontend/src/pages/ProfilePage.tsx +++ b/frontend/src/pages/ProfilePage.tsx @@ -2,7 +2,6 @@ import React from 'react' import { LANGUAGES } from '../constants' import { SUPPORTED_LANGUAGES } from '../i18n' import { Dispatch, State } from '../store' -import { isPersonal } from '../models/plans' import { Typography, List } from '@mui/material' import { useTranslation } from 'react-i18next' import { useSelector, useDispatch } from 'react-redux' @@ -19,11 +18,7 @@ import { Link } from '../components/Link' import { spacing } from '../styling' export const ProfilePage: React.FC = () => { - const { paidPlan, user, deleteAccount } = useSelector((state: State) => ({ - user: state.user, - paidPlan: !isPersonal(state), - deleteAccount: state.ui.deleteAccount, - })) + const user = useSelector((state: State) => state.user) const dispatch = useDispatch() const { t } = useTranslation() @@ -87,7 +82,7 @@ export const ProfilePage: React.FC = () => { /> {t('settings.accountDeletion', 'Account deletion')} - + ) } diff --git a/frontend/src/services/Controller.ts b/frontend/src/services/Controller.ts index b9eb94d43..c7212a6e0 100644 --- a/frontend/src/services/Controller.ts +++ b/frontend/src/services/Controller.ts @@ -147,11 +147,11 @@ class Controller extends EventEmitter { return this } - emitWithAck = (event: SocketAction, timeout: number): Promise => + emitWithAck = (event: SocketAction, timeout: number, ...args: unknown[]): Promise => this.socket?.connected ? this.socket .timeout(timeout) - .emitWithAck(event) + .emitWithAck(event, ...args) .catch(() => undefined) : Promise.resolve(undefined) diff --git a/frontend/src/services/graphQL.ts b/frontend/src/services/graphQL.ts index f782f31f4..b863b1970 100644 --- a/frontend/src/services/graphQL.ts +++ b/frontend/src/services/graphQL.ts @@ -21,6 +21,17 @@ export async function graphQLPartialRequest(query: String, variables: ILookup = {}): Promise { + const response = await post({ query, variables }) + if (response === 'ERROR') return { ok: false } + const errors = graphQLGetErrors(response, true) + if (!errors) return { ok: true } + const { message, extensions } = errors[0] as Error & { extensions?: { code?: string; args?: unknown } } + return { ok: false, code: extensions?.code, message, args: extensions?.args } +} + export function graphQLGetErrors( response: AxiosResponse, silent?: boolean, diff --git a/frontend/src/services/graphQLDevice.ts b/frontend/src/services/graphQLDevice.ts index cbf94433e..1f820658c 100644 --- a/frontend/src/services/graphQLDevice.ts +++ b/frontend/src/services/graphQLDevice.ts @@ -312,6 +312,24 @@ export async function graphQLFetchDeviceCount({ size, tag, owner, accountId }: g ) } +export async function graphQLFetchOwnedDevices(accountId: string, size: number, thisId?: string) { + return await graphQLBasicRequest( + ` query OwnedDevices($accountId: String, $size: Int${thisId ? ', $thisId: [String!]!' : ''}) { + login { + id + account(id: $accountId) { + devices(owner: true, size: $size, sort: "state,name") { + total + items { id name state platform } + } + } + ${thisId ? 'device(id: $thisId) { id owner { id } }' : ''} + } + }`, + { accountId, size, thisId: thisId ? [thisId] : undefined } + ) +} + export function graphQLDeviceAdaptor({ gqlDevices, accountId, diff --git a/frontend/src/services/graphQLMutation.ts b/frontend/src/services/graphQLMutation.ts index 23f645ae2..9436a281d 100644 --- a/frontend/src/services/graphQLMutation.ts +++ b/frontend/src/services/graphQLMutation.ts @@ -1,5 +1,5 @@ import { addConnectionProps } from '../models/networks' -import { graphQLBasicRequest } from './graphQL' +import { graphQLBasicRequest, graphQLInlineRequest } from './graphQL' export async function graphQLSetAttributes(attributes: ILookup, serviceId?: String) { return await graphQLBasicRequest( @@ -748,6 +748,19 @@ export async function graphQLAdminUpdateEmail(from: string, to: string) { ) } +export async function graphQLRequestAccountDeletion() { + return await graphQLInlineRequest(` mutation { requestAccountDeletion }`) +} + +export async function graphQLDeleteAccount(code: string) { + return await graphQLInlineRequest( + ` mutation DeleteAccount($code: String!) { + deleteAccount(code: $code) + }`, + { code } + ) +} + export async function graphQLAdminDeleteUser(id: string, force: boolean = false) { return await graphQLBasicRequest( ` mutation AdminDeleteUser($id: String!, $force: Boolean) {