File size: 3,454 Bytes
3ca89b9
 
fe65af5
3ca89b9
 
a10d8ea
 
 
3ca89b9
fe65af5
a10d8ea
fe65af5
405ce13
fe65af5
405ce13
 
3ca89b9
 
 
 
 
 
 
 
a10d8ea
3ca89b9
 
 
fe65af5
 
 
 
405ce13
3ca89b9
405ce13
3ca89b9
 
 
 
 
405ce13
3ca89b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a10d8ea
405ce13
fe65af5
 
405ce13
 
 
3ca89b9
 
 
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
// Native auth using SocialLogin plugin + Firebase REST API
// No Firebase SDK on native - avoids protocol errors
// SocialLogin accessed via window.Capacitor.Plugins to avoid breaking web builds

const FIREBASE_API_KEY = 'AIzaSyAVQWsCgnaIXOqtPLWOhb17Bk8C9R2hpOE';
function isNative() {
  return typeof window !== 'undefined' && window.Capacitor !== undefined;
}

function getSocialLogin() {
  if (isNative() && window.Capacitor.Plugins) {
    return window.Capacitor.Plugins.SocialLogin || null;
  }
  return null;
}

// Get stored user from localStorage
export const getCurrentUser = () => {
  const stored = localStorage.getItem('dublfit_user');
  return stored ? JSON.parse(stored) : null;
};

// Sign in with Google
export const signInWithGoogle = async () => {
  if (!isNative()) {
    throw new Error('Google sign-in only available in app');
  }

  const SL = getSocialLogin();
  if (!SL) {
    throw new Error('SocialLogin plugin not available');
  }

  // Initialize and login with Google
  await SL.initialize({
    google: {
      iOSClientId: '171636644437-k9fupe9qbjj1ru75gmjqjbjbq0am980u.apps.googleusercontent.com'
    }
  });

  const res = await SL.login({
    provider: 'google',
    options: { scopes: ['email', 'profile'] }
  });

  console.log('SocialLogin response:', JSON.stringify(res, null, 2));

  // Get the idToken - might be in different places depending on plugin version
  const idToken = res.result?.idToken || res.result?.authentication?.idToken || res.idToken;
  console.log('idToken:', idToken ? 'found' : 'NOT FOUND');

  if (!idToken) {
    // Fallback: use Google profile directly without Firebase
    const profile = res.result?.profile || res.result;
    const user = {
      uid: profile.id,
      email: profile.email,
      displayName: profile.name,
      photoURL: profile.imageUrl
    };
    console.log('Using Google profile directly (no idToken):', user);
    localStorage.setItem('dublfit_user', JSON.stringify(user));
    return user;
  }

  // Exchange Google token for Firebase user via REST API
  console.log('Calling Firebase REST API...');
  const response = await fetch(
    `https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key=${FIREBASE_API_KEY}`,
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        postBody: `id_token=${idToken}&providerId=google.com`,
        requestUri: 'http://localhost',
        returnSecureToken: true
      })
    }
  );

  if (!response.ok) {
    const error = await response.json();
    console.log('Firebase error:', error);
    throw new Error(error.error?.message || 'Firebase auth failed');
  }

  const data = await response.json();
  console.log('Firebase response - uid:', data.localId, 'email:', data.email);

  const user = {
    uid: data.localId,
    email: data.email,
    displayName: data.displayName,
    photoURL: data.photoUrl
  };

  console.log('Logged in with Firebase uid:', user.uid);
  localStorage.setItem('dublfit_user', JSON.stringify(user));
  return user;
};

// Sign out
export const signOut = async () => {
  localStorage.removeItem('dublfit_user');
  // Also sign out of Google so next login shows account picker
  if (isNative()) {
    try {
      const SL = getSocialLogin();
      if (SL) await SL.logout({ provider: 'google' });
    } catch (e) {
      console.log('Google logout error (ok to ignore):', e);
    }
  }
  return Promise.resolve();
};