Line data Source code
1 : import { FirebaseError } from 'firebase/app'
2 : import { ref } from 'vue'
3 :
4 : import {
5 : authErrorMessage,
6 : classifyAuthError,
7 : severityForAuthError
8 : } from '@comfyorg/account-core/firebaseAuthError'
9 : import type {
10 : AuthErrorClassification,
11 : AuthErrorCopy
12 : } from '@comfyorg/account-core/firebaseAuthError'
13 :
14 : import { useErrorHandling } from '@/composables/useErrorHandling'
15 : import { st, t } from '@/i18n'
16 : import enMessages from '@/locales/en/main.json' with { type: 'json' }
17 : import { presentSsoRequired } from '@/platform/auth/sso/ssoRequired'
18 : import { isCloud } from '@/platform/distribution/types'
19 : import { useTelemetry } from '@comfyorg/telemetry'
20 : import type { AuthFlowAction } from '@comfyorg/telemetry/types'
21 : import { useToast } from '@/components/ui/toast/toastStore'
22 : import {
23 : clearAllWorkspaceStorage,
24 : prepareWorkflowLogoutTransition
25 : } from '@/platform/workflow/persistence/base/storageIO'
26 : import { useWorkflowService } from '@/platform/workflow/core/services/workflowService'
27 : import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
28 : import { useDialogService } from '@/services/dialogService'
29 : import { SsoRequiredAuthError, useAuthStore } from '@/stores/authStore'
30 : import type { SocialSignInOptions } from '@/stores/authStore'
31 :
32 : /**
33 : * The app's own auth.errors table, read through vue-i18n at resolution time.
34 : * The key set is the app's, so a code added to main.json renders without the
35 : * package having to know it.
36 : */
37 2356 : export const localizedAuthErrorCopy = (): AuthErrorCopy => ({
38 : ...Object.fromEntries(
39 : Object.keys(enMessages.auth.errors).map((key) => [
40 : key,
41 : st(`auth.errors.${key}`, t('auth.errors.generic'))
42 : ])
43 : ),
44 : generic: t('auth.errors.generic'),
45 : signupBlocked: st('auth.errors.signupBlocked', t('auth.errors.generic'))
46 : })
47 :
48 2356 : const isPopupTakenOverByDesktop = (
49 : classification: AuthErrorClassification
50 : ): boolean =>
51 : !!window.__comfyDesktop2 &&
52 : classification.kind === 'popup-dismissed' &&
53 : classification.code === 'auth/popup-blocked'
54 :
55 : /**
56 : * Service for Firebase Auth actions.
57 : * All actions are wrapped with error handling.
58 : * @returns {Object} - Object containing all Firebase Auth actions
59 : */
60 2356 : export const useAuthActions = () => {
61 2397 : const authStore = useAuthStore()
62 2397 : const toast = useToast()
63 2397 : const { wrapWithErrorHandlingAsync, toastErrorHandler } = useErrorHandling()
64 :
65 2397 : const accessError = ref(false)
66 :
67 2397 : const reportAuthFlowError =
68 : (authAction: AuthFlowAction) => (error: unknown) => {
69 0 : useTelemetry()?.trackAuthFailed({
70 : error_code: error instanceof FirebaseError ? error.code : 'unknown',
71 : auth_action: authAction
72 : })
73 0 : reportError(error)
74 : }
75 :
76 : /** Sends an account its SSO organization refused to SSO instead of a failure toast. */
77 2397 : const presentSsoRefusal = (error: SsoRequiredAuthError): boolean => {
78 0 : const presented = presentSsoRequired('customer_create', {
79 : email: authStore.userEmail ?? undefined,
80 : organizationId: error.organizationId
81 : })
82 0 : if (presented) void authStore.logout().catch(toastErrorHandler)
83 0 : return presented
84 : }
85 :
86 2397 : const reportError = (error: unknown) => {
87 1 : if (error instanceof SsoRequiredAuthError && presentSsoRefusal(error)) {
88 0 : return
89 : }
90 1 : const classification = classifyAuthError(error)
91 1 : if (isPopupTakenOverByDesktop(classification)) {
92 0 : toast.info(t('auth.desktopHost.continueInBrowser'), { duration: 6000 })
93 0 : return
94 : }
95 : // Ref: https://firebase.google.com/docs/auth/admin/errors
96 1 : const kind = severityForAuthError(classification)
97 1 : const notify = (description: string) =>
98 : toast[kind](t(`g.${kind}`), { description })
99 1 : if (classification.kind === 'unauthorized-domain') {
100 0 : accessError.value = true
101 0 : notify(
102 : t('toastMessages.unauthorizedDomain', {
103 : domain: window.location.hostname,
104 : email: 'support@comfy.org'
105 : })
106 : )
107 1 : } else if (classification.kind !== 'unknown') {
108 0 : notify(authErrorMessage(classification, localizedAuthErrorCopy()))
109 1 : } else if (error instanceof FirebaseError) {
110 : // classifyAuthError only knows auth/ codes; an app/ or installations/
111 : // FirebaseError still gets the localized copy, never the raw SDK text.
112 0 : toast.error(t('g.error'), {
113 : description: st(`auth.errors.${error.code}`, t('auth.errors.generic'))
114 : })
115 : } else {
116 1 : toastErrorHandler(error)
117 : }
118 : }
119 :
120 : /** `beforeSignOut` runs once unsaved work is settled; false keeps the user signed in. */
121 2397 : const logout = wrapWithErrorHandlingAsync(
122 : async ({
123 : beforeSignOut,
124 : signInPath = '/cloud/login'
125 : }: {
126 : beforeSignOut?: () => Promise<boolean>
127 : signInPath?: string
128 : } = {}): Promise<boolean> => {
129 : if (isCloud) {
130 : const workflowStore = useWorkflowStore()
131 : const modifiedWorkflows = workflowStore.modifiedWorkflows
132 : if (modifiedWorkflows.length > 0) {
133 : const dialogService = useDialogService()
134 : const confirmed = await dialogService.confirm({
135 : title: t('auth.signOut.unsavedChangesTitle'),
136 : message: t('auth.signOut.unsavedChangesMessage'),
137 : type: 'dirtyClose',
138 : denyLabel: t('auth.signOut.signOutAnyway')
139 : })
140 : if (confirmed === null) return false
141 :
142 : if (confirmed) {
143 : const workflowService = useWorkflowService()
144 : for (const workflow of modifiedWorkflows) {
145 : try {
146 : const saved = await workflowService.saveWorkflow(workflow)
147 : if (!saved) return false
148 : } catch {
149 : throw new Error(
150 : t('auth.signOut.saveFailed', { workflow: workflow.path })
151 : )
152 : }
153 : }
154 : }
155 : }
156 : }
157 :
158 0 : if (beforeSignOut && !(await beforeSignOut())) return false
159 :
160 0 : await authStore.logout()
161 : if (isCloud) {
162 : prepareWorkflowLogoutTransition()
163 : clearAllWorkspaceStorage()
164 : }
165 :
166 0 : toast.success(t('auth.signOut.success'), {
167 : description: t('auth.signOut.successDetail'),
168 : duration: 5000
169 : })
170 :
171 : if (isCloud) {
172 : try {
173 : window.location.href = signInPath
174 : } catch {
175 : // needed for local development until we bring in cloud login pages.
176 : window.location.reload()
177 : }
178 : }
179 0 : return true
180 : },
181 : reportError
182 : )
183 :
184 2397 : const sendPasswordReset = wrapWithErrorHandlingAsync(
185 : async (email: string) => {
186 0 : await authStore.sendPasswordReset(email)
187 0 : toast.success(t('auth.login.passwordResetSent'), {
188 : description: t('auth.login.passwordResetSentDetail'),
189 : duration: 5000
190 : })
191 0 : return true
192 : },
193 : reportAuthFlowError('password_reset')
194 : )
195 :
196 2397 : const signInWithGoogle = async (options?: SocialSignInOptions) =>
197 : await wrapWithErrorHandlingAsync(
198 : async () => await authStore.loginWithGoogle(options),
199 : reportAuthFlowError(
200 : options?.isNewUser ? 'google_sign_up' : 'google_sign_in'
201 : )
202 : )()
203 :
204 2397 : const signInWithGithub = async (options?: SocialSignInOptions) =>
205 : await wrapWithErrorHandlingAsync(
206 : async () => await authStore.loginWithGithub(options),
207 : reportAuthFlowError(
208 : options?.isNewUser ? 'github_sign_up' : 'github_sign_in'
209 : )
210 : )()
211 :
212 : const signInWithEmail = wrapWithErrorHandlingAsync(
213 : async (email: string, password: string) => {
214 1 : return await authStore.login(email, password)
215 : },
216 : reportAuthFlowError('email_sign_in')
217 : )
218 :
219 : const signUpWithEmail = wrapWithErrorHandlingAsync(
220 : async (email: string, password: string, turnstileToken?: string) => {
221 0 : return await authStore.register(email, password, turnstileToken)
222 : },
223 : reportAuthFlowError('email_sign_up')
224 : )
225 :
226 2397 : return {
227 : logout,
228 : sendPasswordReset,
229 : signInWithGoogle,
230 : signInWithGithub,
231 : signInWithEmail,
232 : signUpWithEmail,
233 : accessError,
234 : reportError
235 : }
236 : }
|