Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
168 changes: 168 additions & 0 deletions src/components/dialog/content/setting/UserPanel.test.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,42 @@
import { fromPartial } from '@total-typescript/shoehorn'
import userEvent from '@testing-library/user-event'
import { render, screen } from '@testing-library/vue'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { computed, defineComponent } from 'vue'
import { createI18n } from 'vue-i18n'
import { createMemoryHistory, createRouter } from 'vue-router'

import type { FirebaseIdentity } from '@comfyorg/account-core/firebase'
import type { WebSessionCommandResult } from '@comfyorg/account-core/webSession'
import type { WebSessionIdentityState } from '@comfyorg/account-core/webSessionIdentity'

import { useCurrentUser } from '@/composables/auth/useCurrentUser'
import enMessages from '@/locales/en/main.json' with { type: 'json' }
import { useCloudWebSessionStore } from '@/platform/auth/session/cloudWebSessionStore'
import { useToastStore } from '@/platform/updates/common/toastStore'
import type { ComfyWorkflow } from '@/platform/workflow/management/stores/workflowStore'
import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
import { api } from '@/scripts/api'
import { useDialogService } from '@/services/dialogService'
import { useAuthStore } from '@/stores/authStore'

import UserPanel from './UserPanel.vue'

vi.mock(import('@/composables/auth/useCurrentUser'))
vi.mock(import('@/services/dialogService'))
vi.mock(import('@/platform/distribution/types'), () => ({
DISTRIBUTION: 'cloud' as const,
isCloud: true,
isDesktop: false,
isNightly: false
}))
vi.mock(import('@/platform/auth/firebaseIdentity'), () => ({
firebaseIdentity: fromPartial<FirebaseIdentity>({
onUserChanged: () => () => {},
onTokenChanged: () => () => {},
currentUser: () => null
})
}))

const i18n = createI18n({
legacy: false,
Expand Down Expand Up @@ -100,3 +124,147 @@ describe('UserPanel update password', () => {
expect(location.assign).not.toHaveBeenCalled()
})
})

describe('UserPanel sign out of all devices', () => {
const signOutEverywhere = { name: 'Sign out of all devices' }

beforeEach(() => {
vi.spyOn(api, 'reconnectSocket').mockResolvedValue()
vi.spyOn(useAuthStore(), 'logout').mockResolvedValue()
vi.stubGlobal('location', { href: '/' })
})

function withUnsavedWorkflow() {
const workflow = fromPartial<ComfyWorkflow>({
path: 'a.json',
isModified: true
})
Object.assign(useWorkflowStore(), { modifiedWorkflows: [workflow] })
}

const signedInSession: WebSessionIdentityState = {
phase: 'signed_in',
session: {
user: {
id: 'user-a',
email: 'user-a@example.com',
emailVerified: true,
signInProvider: 'google.com'
},
csrfToken: 'csrf-user-a',
expiresAt: Date.now() + 86_400_000,
absoluteExpiresAt: Date.now() + 604_800_000
}
}

function onWebSession(revokeAll: WebSessionCommandResult) {
const webSession = useCloudWebSessionStore()
webSession.state = signedInSession
return vi
.spyOn(webSession, 'revokeAllSessions')
.mockResolvedValue(revokeAll)
}

it.for<{
name: string
session: WebSessionIdentityState
firebaseLogin: boolean
}>([
{
name: 'the web session is off',
session: { phase: 'idle' },
firebaseLogin: true
},
{
name: 'the web session is signed out',
session: { phase: 'signed_out', outcome: 'signed_out' },
firebaseLogin: true
},
{
name: 'the tab has no Firebase login to prove identity',
session: signedInSession,
firebaseLogin: false
}
])('renders nothing when $name', async ({ session, firebaseLogin }) => {
signInAsEmailUser({ hasFirebaseLogin: firebaseLogin })
useCloudWebSessionStore().state = session
await renderPanel()

expect(screen.getByRole('button', { name: 'Log Out' })).toBeVisible()
expect(screen.queryByRole('button', signOutEverywhere)).toBeNull()
})

it('revokes every session once, then signs this tab out', async () => {
signInAsEmailUser({ hasFirebaseLogin: true })
const revokeAll = onWebSession({ status: 'ok' })
await renderPanel()

await userEvent.click(screen.getByRole('button', signOutEverywhere))

expect(revokeAll).toHaveBeenCalledOnce()
expect(useAuthStore().logout).toHaveBeenCalledOnce()
expect(revokeAll.mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(useAuthStore().logout).mock.invocationCallOrder[0]
)
expect(useToastStore().messagesToAdd).toContainEqual(
expect.objectContaining({
severity: 'success',
summary: 'Signed out of all devices'
})
)
})

it('asks about unsaved work before revoking anything', async () => {
signInAsEmailUser({ hasFirebaseLogin: true })
withUnsavedWorkflow()
vi.mocked(useDialogService().confirm).mockResolvedValue(false)
const revokeAll = onWebSession({ status: 'ok' })
await renderPanel()

await userEvent.click(screen.getByRole('button', signOutEverywhere))

expect(useDialogService().confirm).toHaveBeenCalledWith(
expect.objectContaining({ title: 'Unsaved Changes' })
)
expect(
vi.mocked(useDialogService().confirm).mock.invocationCallOrder[0]
).toBeLessThan(revokeAll.mock.invocationCallOrder[0])
expect(useAuthStore().logout).toHaveBeenCalledOnce()
})

it('sends no revoke and stays signed in when the unsaved-work prompt is cancelled', async () => {
signInAsEmailUser({ hasFirebaseLogin: true })
withUnsavedWorkflow()
vi.mocked(useDialogService().confirm).mockResolvedValue(null)
const revokeAll = onWebSession({ status: 'ok' })
await renderPanel()

await userEvent.click(screen.getByRole('button', signOutEverywhere))

expect(revokeAll).not.toHaveBeenCalled()
expect(useAuthStore().logout).not.toHaveBeenCalled()
expect(useToastStore().messagesToAdd).toEqual([])
})

it('keeps the user signed in and shows why when the revoke fails', async () => {
signInAsEmailUser({ hasFirebaseLogin: true })
onWebSession({
status: 'error',
code: 'SESSION_UNAVAILABLE',
retryable: true
})
await renderPanel()

await userEvent.click(screen.getByRole('button', signOutEverywhere))

expect(useAuthStore().logout).not.toHaveBeenCalled()
expect(useToastStore().messagesToAdd).toEqual([
expect.objectContaining({
severity: 'error',
summary: "Couldn't sign out of all devices",
detail: enMessages.auth.webSession.token.unavailable
})
])
expect(screen.getByRole('button', signOutEverywhere)).toBeEnabled()
})
})
13 changes: 8 additions & 5 deletions src/components/dialog/content/setting/UserPanel.vue
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,13 @@

<Spinner v-if="loading" class="mt-4 size-8" />
<div v-else class="mt-4 flex flex-col gap-2">
<Button class="w-32" variant="secondary" @click="handleSignOut">
<i class="pi pi-sign-out" />
{{ $t('auth.signOut.signOut') }}
</Button>
<div class="flex flex-wrap items-center gap-2">
<Button class="w-32" variant="secondary" @click="handleSignOut">
<i class="pi pi-sign-out" />
{{ $t('auth.signOut.signOut') }}
</Button>
<SignOutEverywhereButton />
</div>
<i18n-t
v-if="!isApiKeyLogin"
keypath="auth.deleteAccount.contactSupport"
Expand Down Expand Up @@ -97,6 +100,7 @@ import UserAvatar from '@/components/common/UserAvatar.vue'
import Button from '@/components/ui/button/Button.vue'
import Spinner from '@/components/ui/spinner/Spinner.vue'
import { useCurrentUser } from '@/composables/auth/useCurrentUser'
import SignOutEverywhereButton from '@/platform/auth/session/components/SignOutEverywhereButton.vue'
import { useDialogService } from '@/services/dialogService'

const { t } = useI18n()
Expand All @@ -116,7 +120,6 @@ const {
handleSignOut,
handleSignIn
} = useCurrentUser()

async function onUpdatePassword() {
if (!needsFirebaseSignIn.value) {
await dialogService.showUpdatePasswordDialog()
Expand Down
44 changes: 44 additions & 0 deletions src/composables/auth/useAuthActions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,50 @@ describe('useAuthActions.logout', () => {
)
})

it.for([
{ name: 'the prompt is dismissed', answer: null, runsHook: false },
{ name: 'a workflow save is cancelled', answer: true, runsHook: false },
{ name: 'the user signs out anyway', answer: false, runsHook: true }
])(
'beforeSignOut runs only once unsaved work is settled: $name',
async ({ answer, runsHook }) => {
Object.assign(mockWorkflowStore, {
modifiedWorkflows: [makeWorkflow('a.json')]
})
vi.mocked(useDialogService().confirm).mockResolvedValueOnce(answer)
vi.mocked(useWorkflowService().saveWorkflow).mockResolvedValueOnce(false)
const beforeSignOut = vi.fn(async () => true)
const { logout } = useAuthActions()

await logout({ beforeSignOut })

expect(beforeSignOut).toHaveBeenCalledTimes(runsHook ? 1 : 0)
expect(mockAuthStore.logout).toHaveBeenCalledTimes(runsHook ? 1 : 0)
}
)

it('signs out after beforeSignOut allows it', async () => {
const beforeSignOut = vi.fn(async () => true)
const { logout } = useAuthActions()

await logout({ beforeSignOut })

expect(mockAuthStore.logout).toHaveBeenCalledOnce()
expect(beforeSignOut.mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(mockAuthStore.logout).mock.invocationCallOrder[0]
)
})

it('keeps the user signed in when beforeSignOut refuses', async () => {
const { logout } = useAuthActions()

await logout({ beforeSignOut: async () => false })

expect(mockAuthStore.logout).not.toHaveBeenCalled()
expect(mockClearAllWorkspaceStorage).not.toHaveBeenCalled()
expect(mockToastStore.add).not.toHaveBeenCalled()
})

it('passes denyLabel "Sign out anyway" to the dialog', async () => {
Object.assign(mockWorkflowStore, {
modifiedWorkflows: [makeWorkflow('a.json')]
Expand Down
96 changes: 52 additions & 44 deletions src/composables/auth/useAuthActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,58 +106,66 @@ export const useAuthActions = () => {
}
}

const logout = wrapWithErrorHandlingAsync(async () => {
if (isCloud) {
const workflowStore = useWorkflowStore()
const modifiedWorkflows = workflowStore.modifiedWorkflows
if (modifiedWorkflows.length > 0) {
const dialogService = useDialogService()
const confirmed = await dialogService.confirm({
title: t('auth.signOut.unsavedChangesTitle'),
message: t('auth.signOut.unsavedChangesMessage'),
type: 'dirtyClose',
denyLabel: t('auth.signOut.signOutAnyway')
})
if (confirmed === null) return

if (confirmed) {
const workflowService = useWorkflowService()
for (const workflow of modifiedWorkflows) {
try {
const saved = await workflowService.saveWorkflow(workflow)
if (!saved) return
} catch {
throw new Error(
t('auth.signOut.saveFailed', { workflow: workflow.path })
)
/** `beforeSignOut` runs once unsaved work is settled; false keeps the user signed in. */
const logout = wrapWithErrorHandlingAsync(
async ({
beforeSignOut
}: { beforeSignOut?: () => Promise<boolean> } = {}) => {
if (isCloud) {
const workflowStore = useWorkflowStore()
const modifiedWorkflows = workflowStore.modifiedWorkflows
if (modifiedWorkflows.length > 0) {
const dialogService = useDialogService()
const confirmed = await dialogService.confirm({
title: t('auth.signOut.unsavedChangesTitle'),
message: t('auth.signOut.unsavedChangesMessage'),
type: 'dirtyClose',
denyLabel: t('auth.signOut.signOutAnyway')
})
if (confirmed === null) return

if (confirmed) {
const workflowService = useWorkflowService()
for (const workflow of modifiedWorkflows) {
try {
const saved = await workflowService.saveWorkflow(workflow)
if (!saved) return
} catch {
throw new Error(
t('auth.signOut.saveFailed', { workflow: workflow.path })
)
}
}
}
}
}
}

await authStore.logout()
if (isCloud) {
prepareWorkflowLogoutTransition()
clearAllWorkspaceStorage()
}
if (beforeSignOut && !(await beforeSignOut())) return

toastStore.add({
severity: 'success',
summary: t('auth.signOut.success'),
detail: t('auth.signOut.successDetail'),
life: 5000
})
await authStore.logout()
if (isCloud) {
prepareWorkflowLogoutTransition()
clearAllWorkspaceStorage()
}

if (isCloud) {
try {
window.location.href = '/cloud/login'
} catch {
// needed for local development until we bring in cloud login pages.
window.location.reload()
toastStore.add({
severity: 'success',
summary: t('auth.signOut.success'),
detail: t('auth.signOut.successDetail'),
life: 5000
})

if (isCloud) {
try {
window.location.href = '/cloud/login'
} catch {
// needed for local development until we bring in cloud login pages.
window.location.reload()
}
}
}
}, reportError)
},
reportError
)

const sendPasswordReset = wrapWithErrorHandlingAsync(
async (email: string) => {
Expand Down
6 changes: 6 additions & 0 deletions src/locales/en/main.json
Original file line number Diff line number Diff line change
Expand Up @@ -2722,6 +2722,12 @@
"signOutAnyway": "Sign out anyway",
"saveFailed": "Sign-out cancelled because saving \"{workflow}\" failed."
},
"signOutEverywhere": {
"action": "Sign out of all devices",
"success": "Signed out of all devices",
"successDetail": "Every device signed in to your account has been signed out.",
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
"failed": "Couldn't sign out of all devices"
},
"accountChanged": {
"title": "Account changed",
"detail": "Another tab or Comfy site signed in as {email}, so this page was reset."
Expand Down
Loading
Loading