File size: 10,891 Bytes
ad5834b
 
 
 
 
ec00e65
ad5834b
 
2746f0a
 
 
ad5834b
 
 
 
 
 
2746f0a
ad5834b
ec00e65
 
 
 
ad5834b
2746f0a
 
ad5834b
 
2746f0a
 
 
 
 
92af839
2746f0a
 
 
 
 
 
 
 
ec00e65
 
2746f0a
 
ec00e65
 
 
 
 
 
 
 
 
 
c89ea72
ec00e65
 
 
 
ad5834b
c89ea72
 
 
 
 
ad5834b
 
 
ec00e65
 
 
 
 
 
c89ea72
ec00e65
c89ea72
 
ec00e65
 
c89ea72
 
 
 
 
 
 
 
ec00e65
c89ea72
ec00e65
 
c89ea72
 
 
 
 
 
ec00e65
 
c89ea72
ec00e65
 
 
 
c89ea72
 
 
ec00e65
 
 
 
 
 
 
c89ea72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59e6cdc
c89ea72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec00e65
 
c89ea72
ec00e65
 
 
 
c89ea72
ec00e65
c89ea72
 
 
 
ec00e65
c89ea72
8f34ccc
 
 
c89ea72
 
 
bc48d9e
 
 
59e6cdc
 
 
 
 
 
 
 
 
 
 
 
 
 
bc48d9e
59e6cdc
c89ea72
 
 
 
 
59e6cdc
f3d125b
c89ea72
 
 
 
 
 
 
 
 
 
 
 
ec00e65
c89ea72
 
 
f3d125b
c89ea72
 
 
 
 
 
 
ec00e65
 
 
c89ea72
ec00e65
 
 
 
c89ea72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec00e65
 
 
 
 
c89ea72
 
 
 
 
ec00e65
c89ea72
 
 
 
 
 
 
ec00e65
 
 
 
 
 
 
c89ea72
ec00e65
 
 
c89ea72
ec00e65
c89ea72
 
ec00e65
 
 
2746f0a
c89ea72
 
ad5834b
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Everyday Cats – Sign-in</title>
    <style>
      body {
        background: #fffafc;
        color: #222;
        font-family: "Inter", system-ui, sans-serif;
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100vh;
        flex-direction: column;
        text-align: center;
        margin: 0;
      }
      .container {
        max-width: 400px;
        padding: 2rem;
      }
      h1 {
        font-size: 1.8rem;
        margin-bottom: 0.5rem;
      }
      p {
        font-size: 1rem;
        opacity: 0.8;
        margin-bottom: 1.5rem;
      }
      button {
        background: #FFB84D;
        border: none;
        padding: 0.75rem 1.5rem;
        border-radius: 9999px;
        font-size: 1rem;
        font-weight: 600;
        color: white;
        cursor: pointer;
        transition: 0.2s;
        width: 100%;
        max-width: 280px;
      }
      button:hover {
        background: #ffa833;
      }
      button:disabled {
        opacity: 0.6;
        cursor: not-allowed;
      }
      .error {
        color: #d32f2f;
        margin-top: 1rem;
        font-size: 0.9rem;
        word-break: break-word;
      }
      .loading {
        margin-top: 1rem;
        opacity: 0.7;
      }
      .note {
        margin-top: 12px;
        font-size: 0.85rem;
        opacity: 0.85;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <h1 id="title">Welcome to Everyday Cats</h1>
      <p id="message">Sign in with your Google account to continue</p>
      <button id="authButton" onclick="handleAuth()">Sign in with Google</button>
      <p class="loading" id="loading" style="display: none;">Processing...</p>
      <p class="error" id="error"></p>
      <p class="note" id="note">Tip: Serve this page over http(s). Add your test domain to Firebase Auth → Authorized domains.</p>
    </div>

    <!-- Full script: handles popup (desktop) and redirect (mobile/webview) flows -->
    <script type="module">
      import { initializeApp } from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-app.js';
      import {
        getAuth,
        signInWithPopup,
        signInWithRedirect,
        getRedirectResult,
        GoogleAuthProvider,
        onAuthStateChanged
      } from 'https://www.gstatic.com/firebasejs/10.7.1/firebase-auth.js';

      // ---------- Firebase config (keep or replace with your own) ----------
      const firebaseConfig = {
        apiKey: "AIzaSyAJZ5UwyLo4b4L8_G7Nocw0nj7dhyBZ_yU",
        authDomain: "cartpost-db-06.firebaseapp.com",
        projectId: "cartpost-db-06",
        storageBucket: "cartpost-db-06.firebasestorage.app",
        messagingSenderId: "212802992706",
        appId: "1:212802992706:web:2a32a453c42cbc3bdfcbdb",
        measurementId: "G-JYWF6B9MVZ"
      };

      // ---------- Init ----------
      const app = initializeApp(firebaseConfig);
      const auth = getAuth(app);
      const provider = new GoogleAuthProvider();

      // Your app deep-link scheme (used when redirecting to native app)
      const appScheme = "everydaydresscode";

      // UI elements
      const titleEl = document.getElementById('title');
      const messageEl = document.getElementById('message');
      const buttonEl = document.getElementById('authButton');
      const loadingEl = document.getElementById('loading');
      const errorEl = document.getElementById('error');

      // ---------- Helpers ----------
      function isLikelyWebViewOrInApp() {
        const ua = navigator.userAgent || '';
        // common markers for in-app browsers / webviews
        const webviewMarkers = /wv|WebView|FBAN|FBAV|Instagram|KAKAOTALK|Line|MicroMessenger/i;
        // On Android, some webviews don't include "Chrome" in UA
        return webviewMarkers.test(ua) || (/Android/i.test(ua) && !/Chrome/i.test(ua));
      }

      function resetUI() {
        buttonEl.disabled = false;
        loadingEl.style.display = 'none';
      }

      function safeSetError(msg) {
        // ensure we never put an object directly into DOM
        errorEl.textContent = String(msg || 'Authentication failed.');
      }

      // ---------- Handle redirect result (page load after signInWithRedirect) ----------
      getRedirectResult(auth)
        .then(async (result) => {
          alert("rere", result);
          if (result && result.user) {
            // Successful redirect result
            const user = result.user;
            try {
              const token = await user.getIdToken();
              showSuccess(user);
              // small delay to let user see success message
              setTimeout(() => redirectToApp(token, user), 1000);
            } catch (tokenErr) {
              console.error('Token error after redirect:', tokenErr);
              safeSetError('Signed in but failed to retrieve token. See console for details.');
            }
          }
        })
        .catch((err) => {
          console.error('getRedirectResult error:', err.code, err.message);
          // Friendly message but keep details in console
          safeSetError('Authentication after redirect failed. See console for details.');
          resetUI();
        });

      // ---------- Persisted state detection ----------
      onAuthStateChanged(auth, (user) => {
        if (user) {
          // Already signed-in (session persisted)
          showSuccess(user);
        }
      });

      // ---------- Main auth handler (called on button click) ----------
      window.handleAuth = async function() {
        // disable UI while we try
        buttonEl.disabled = true;
        loadingEl.style.display = 'block';
        errorEl.textContent = '';

        try {
          // if (isLikelyWebViewOrInApp()) {
          
          if (true) {
            // Use redirect flow in environments where popup is unreliable
            console.log('Detected webview/in-app: using signInWithRedirect.');
            // signInWithRedirect will redirect the browser away; getRedirectResult will handle the result on return.
           const result = await signInWithRedirect(auth, provider)
              
            
          alert("rere", result);
          if (result && result.user) {
            // Successful redirect result
            const user = result.user;
            try {
              const token = await user.getIdToken();
              showSuccess(user);
              // small delay to let user see success message
              setTimeout(() => redirectToApp(token, user), 1000);
            } catch (tokenErr) {
              console.error('Token error after redirect:', tokenErr);
              safeSetError('Signed in but failed to retrieve token. See console for details.');
            }
          }
        
            
            // After this line the browser navigates away; no further code executes in most cases.
          } else {
            // Desktop / normal browsers: popup flow
            console.log('Using signInWithPopup for desktop browser.');
            const result = await signInWithPopup(auth, provider);
            
            
            if (result && result.user) {
              const user = result.user;
              const token = await user.getIdToken();
              showSuccess(user);
              // Wait briefly so user sees success then redirect to app.
              setTimeout(() => redirectToApp(token, user), 800);
            } else {
              // Defensive fallback, shouldn't normally happen
              console.warn('signInWithPopup returned no user:', result);
              safeSetError('Sign-in did not complete. Check console for details.');
              resetUI();
            }
          }
        } catch (err) {
          // Common Firebase errors: log full details and show human message
          console.error('Auth error:', err.code, err.message, err);
          alert('Auth error:', err.code, err.message, err);
          let msg = 'Authentication failed. See console for details.';
          if (err && err.code === 'auth/popup-closed-by-user') msg = 'Sign-in cancelled. Please try again.';
          else if (err && err.code === 'auth/popup-blocked') msg = 'Pop-up blocked. Allow pop-ups and try again.';
          else if (err && err.code === 'auth/cancelled-popup-request') msg = 'Popup request cancelled (race). Try again.';
          else if (err && err.code === 'auth/unauthorized-domain') msg = 'Unauthorized domain — add this domain in Firebase Console (Auth → Authorized domains).';
          safeSetError(msg);
          resetUI();
        }
      };

      // ---------- UI helpers ----------
      function showSuccess(user) {
        titleEl.textContent = 'Sign-in Complete';
        messageEl.innerHTML = `Welcome, <strong>${user.displayName || user.email}</strong>! Redirecting to app...`;
        buttonEl.textContent = 'Open App';
        buttonEl.onclick = async () => {
          // ensure currentUser exists and get a token before redirecting
          const current = auth.currentUser;
          if (!current) {
            safeSetError('No signed-in user available. Reload and try again.');
            return;
          }
          try {
            const token = await current.getIdToken();
            redirectToApp(token, current);
          } catch (e) {
            console.error('Failed to get token on manual Open App:', e);
            safeSetError('Failed to get token. See console.');
          }
        };
        buttonEl.disabled = false;
        loadingEl.style.display = 'none';
      }

      async function redirectToApp(token, user) {
        if (!user) {
          safeSetError('No signed-in user available to redirect.');
          return;
        }
        // If token not provided, fetch it
        if (!token) {
          try {
            token = await user.getIdToken();
          } catch (e) {
            console.error('Failed to fetch token before redirect:', e);
            safeSetError('Failed to fetch token. See console.');
            return;
          }
        }

        const userData = {
          uid: user.uid,
          email: user.email,
          displayName: user.displayName,
          photoURL: user.photoURL,
          token
        };

        const encodedData = encodeURIComponent(JSON.stringify(userData));
        // Attempt to open native app via deep link
        window.location.href = `${appScheme}://auth?data=${encodedData}`;

        // Fallback: after 2s, give user manual instructions
        setTimeout(() => {
          messageEl.innerHTML = 'If the app didn\'t open automatically, please open it manually.';
        }, 2000);
      }

      // ---------- End of script ----------
    </script>
  </body>
</html>