File size: 7,082 Bytes
75e6472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Firebase Authentication Test Script
Tests sign-in and API access with Firebase ID tokens
"""

import requests
import json
import sys

# Fix Windows console encoding
if sys.platform == 'win32':
    import codecs
    sys.stdout = codecs.getwriter('utf-8')(sys.stdout.buffer, 'strict')
    sys.stderr = codecs.getwriter('utf-8')(sys.stderr.buffer, 'strict')

# Firebase Configuration
FIREBASE_WEB_API_KEY = "AIzaSyCPTqGkHtQmSkJiEjRHxmylBXJQGGEErG0"
FIREBASE_AUTH_URL = f"https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key={FIREBASE_WEB_API_KEY}"

# API Configuration
API_BASE_URL = "https://logicgoinfotechspaces-face-swap-video.hf.space"

# Test Credentials
TEST_EMAIL = "itisha.logicgo@gmail.com"
TEST_PASSWORD = "mBQ2KjjlioRbK7FFCUcbvGWqTf62"  # NOTE: This might be a UID, not password. Use actual password if different.

def sign_in_with_email_password(email: str, password: str):
    """Sign in with Firebase Auth and get ID token"""
    print(f"\n{'='*60}")
    print("Signing in to Firebase...")
    print(f"Email: {email}")
    
    payload = {
        "email": email,
        "password": password,
        "returnSecureToken": True
    }
    
    try:
        response = requests.post(FIREBASE_AUTH_URL, json=payload)
        response.raise_for_status()
        data = response.json()
        
        if "idToken" in data:
            print("βœ… Sign-in successful!")
            print(f"User ID: {data.get('localId')}")
            print(f"Email: {data.get('email')}")
            print(f"ID Token (first 50 chars): {data['idToken'][:50]}...")
            return data["idToken"]
        else:
            print(f"❌ Sign-in failed: {data}")
            return None
            
    except requests.exceptions.HTTPError as e:
        error_data = e.response.json() if e.response.text else {}
        error_message = error_data.get("error", {}).get("message", str(e))
        print(f"❌ Sign-in error: {error_message}")
        
        if "INVALID_PASSWORD" in error_message or "EMAIL_NOT_FOUND" in error_message:
            print("\nπŸ’‘ Note: If this is a new account, you may need to:")
            print("   1. Create the user in Firebase Console β†’ Authentication β†’ Users")
            print("   2. Or use signUpWithPassword endpoint first")
        
        return None
    except Exception as e:
        print(f"❌ Error: {str(e)}")
        return None

def test_api_with_token(id_token: str):
    """Test API endpoints with Firebase ID token"""
    headers = {
        "Authorization": f"Bearer {id_token}"
    }
    
    endpoints = [
        ("GET", "/api/me", "Get current user info"),
        ("GET", "/api/health", "Health check"),
        ("GET", "/api/source-images", "List source images"),
        ("GET", "/api/target-videos", "List target videos"),
    ]
    
    print(f"\n{'='*60}")
    print("Testing API Endpoints with Firebase ID Token")
    print(f"{'='*60}")
    
    for method, endpoint, description in endpoints:
        print(f"\n[TEST] {description}")
        print(f"       {method} {endpoint}")
        
        try:
            url = f"{API_BASE_URL}{endpoint}"
            response = requests.request(method, url, headers=headers, timeout=10)
            
            print(f"       Status: {response.status_code}")
            
            if response.status_code == 200:
                try:
                    data = response.json()
                    print(f"       βœ… Success!")
                    if endpoint == "/api/me":
                        print(f"       Auth Mode: {data.get('auth_mode')}")
                        if data.get('auth_mode') == 'firebase':
                            print(f"       User ID: {data.get('user_id')}")
                            print(f"       Email: {data.get('email')}")
                except:
                    print(f"       βœ… Success (non-JSON response)")
            else:
                print(f"       ❌ Failed")
                try:
                    error = response.json()
                    print(f"       Error: {error.get('detail', 'Unknown error')}")
                except:
                    print(f"       Error: {response.text[:100]}")
                    
        except Exception as e:
            print(f"       ❌ Exception: {str(e)}")

def test_sign_up(email: str, password: str):
    """Try to sign up a new user (if needed)"""
    print(f"\n{'='*60}")
    print("Attempting to sign up (if user doesn't exist)...")
    
    signup_url = f"https://identitytoolkit.googleapis.com/v1/accounts:signUp?key={FIREBASE_WEB_API_KEY}"
    payload = {
        "email": email,
        "password": password,
        "returnSecureToken": True
    }
    
    try:
        response = requests.post(signup_url, json=payload)
        response.raise_for_status()
        data = response.json()
        
        if "idToken" in data:
            print("βœ… Sign-up successful!")
            print(f"User ID: {data.get('localId')}")
            return data["idToken"]
        else:
            print(f"❌ Sign-up failed: {data}")
            return None
    except requests.exceptions.HTTPError as e:
        error_data = e.response.json() if e.response.text else {}
        error_message = error_data.get("error", {}).get("message", str(e))
        print(f"❌ Sign-up error: {error_message}")
        
        if "EMAIL_EXISTS" in error_message:
            print("ℹ️  User already exists, proceeding with sign-in...")
            return None
        return None
    except Exception as e:
        print(f"❌ Error: {str(e)}")
        return None

def main():
    print("="*60)
    print("Firebase Authentication Test Script")
    print("="*60)
    
    # Try sign-in first
    id_token = sign_in_with_email_password(TEST_EMAIL, TEST_PASSWORD)
    
    # If sign-in fails, try sign-up (if user doesn't exist)
    if not id_token:
        print("\n⚠️  Sign-in failed. Trying sign-up...")
        id_token = test_sign_up(TEST_EMAIL, TEST_PASSWORD)
    
    # If still no token, try sign-in again (in case sign-up created the user)
    if not id_token:
        print("\n⚠️  Sign-up failed or user already exists. Retrying sign-in...")
        id_token = sign_in_with_email_password(TEST_EMAIL, TEST_PASSWORD)
    
    if id_token:
        # Test API endpoints
        test_api_with_token(id_token)
        
        print(f"\n{'='*60}")
        print("βœ… Testing Complete!")
        print(f"{'='*60}")
        print("\nπŸ“ To use this token in curl/Postman:")
        print(f"   Authorization: Bearer {id_token[:50]}...")
    else:
        print(f"\n{'='*60}")
        print("❌ Could not obtain Firebase ID token")
        print(f"{'='*60}")
        print("\nπŸ’‘ Troubleshooting:")
        print("   1. Verify email/password in Firebase Console")
        print("   2. Check that Email/Password auth is enabled")
        print("   3. Create user manually in Firebase Console if needed")
        print("   4. Verify Web API key is correct")

if __name__ == "__main__":
    main()