Line data Source code
1 : import { until } from '@vueuse/core'
2 :
3 : import { useFeatureFlags } from '@/composables/useFeatureFlags'
4 : import {
5 : readsSignedInWebSession,
6 : useCloudWebSessionStore
7 : } from '@/platform/auth/session/cloudWebSessionStore'
8 : import { useApiKeyAuthStore } from '@/stores/apiKeyAuthStore'
9 : import { useAuthStore } from '@/stores/authStore'
10 :
11 : export type CloudSignIn = 'signed_in' | 'signed_out' | 'pending'
12 :
13 2356 : const DIFFERENT_LOGIN_SIGN_OUT_TIMEOUT_MS = 5_000
14 :
15 2356 : const boots = new WeakMap<object, Promise<void>>()
16 :
17 : /** With SSO on, a signed-in session outranks a stored key; the key stays the fallback. */
18 0 : async function storedApiKeyIsTheLogin(): Promise<boolean> {
19 0 : if (useApiKeyAuthStore().getApiKey() === null) return false
20 0 : const { flags } = useFeatureFlags()
21 0 : if (!flags.ssoEnabled || !flags.unifiedWebSessionEnabled) return true
22 0 : return !(await readsSignedInWebSession())
23 : }
24 :
25 0 : async function bootOnce(): Promise<void> {
26 0 : const auth = useAuthStore()
27 0 : if (auth.currentUser === null && (await storedApiKeyIsTheLogin())) return
28 0 : const webSession = useCloudWebSessionStore()
29 0 : if (!webSession.start()) return
30 0 : await webSession.whenReady()
31 0 : const sessionId = webSession.signedInUser?.id
32 0 : if (sessionId && auth.currentUser && auth.currentUser.uid !== sessionId) {
33 0 : await until(() => auth.currentUser === null).toBe(true, {
34 : timeout: DIFFERENT_LOGIN_SIGN_OUT_TIMEOUT_MS
35 : })
36 : }
37 : }
38 :
39 : /** Starts the web session once Firebase has restored, so it sees the remembered login. */
40 0 : export function bootCloudIdentity(): Promise<void> {
41 0 : const webSession = useCloudWebSessionStore()
42 0 : const boot =
43 : boots.get(webSession) ??
44 : bootOnce().catch((error: unknown) => {
45 0 : boots.delete(webSession)
46 0 : throw error
47 : })
48 0 : boots.set(webSession, boot)
49 0 : return boot
50 : }
51 :
52 0 : export async function cloudSignIn(): Promise<CloudSignIn> {
53 0 : const auth = useAuthStore()
54 0 : const hasTokenLogin = async () => (await auth.getAuthHeader()) !== null
55 0 : await bootCloudIdentity()
56 0 : const webSession = useCloudWebSessionStore()
57 0 : await webSession.whenSessionCreated()
58 0 : if (!webSession.isActive()) {
59 0 : return (await hasTokenLogin()) ? 'signed_in' : 'signed_out'
60 : }
61 0 : const { state } = webSession
62 0 : if (state.phase === 'signed_in') return 'signed_in'
63 0 : if (state.phase === 'signed_out' && state.outcome === 'revoked') {
64 0 : return 'signed_out'
65 : }
66 0 : if (await hasTokenLogin()) return 'signed_in'
67 0 : return state.phase === 'retry_wait' ? 'pending' : 'signed_out'
68 : }
|