CoolFace
Apppublic

kashafaman123/Phase_3_Back

sourceHugging Faceupdated 8mo agoView on Hugging Face
0likes
debug_jwt.py134 linesDownload Raw Back to root
1"""2Debug JWT Token and Database State3Helps identify why data isn't showing up.4"""5 6import os7import sys8 9# Load environment10env_file = ".env"11if os.path.exists(env_file):12    with open(env_file) as f:13        for line in f:14            line = line.strip()15            if line and not line.startswith("#") and "=" in line:16                key, value = line.split("=", 1)17                os.environ[key] = value18 19print("=" * 70)20print("JWT & DATABASE DEBUG TOOL")21print("=" * 70)22 23# Check secrets24better_auth_secret = os.getenv("BETTER_AUTH_SECRET", "")25print(f"\n[1] BETTER_AUTH_SECRET: {better_auth_secret[:20]}... (length: {len(better_auth_secret)})")26 27if better_auth_secret == "your-secret-here-minimum-32-characters":28    print("    WARNING: Using placeholder secret! JWT verification will fail.")29    print("    Generate a real secret with: openssl rand -base64 32")30 31# Decode a sample JWT (if provided)32print("\n[2] JWT Token Decoder")33print("    Paste a JWT token from your browser (or press Enter to skip):")34sample_token = input("    Token: ").strip()35 36if sample_token:37    try:38        from jose import jwt, JWTError39 40        # Decode without verification first to see payload41        print("\n    [a] Token payload (unverified):")42        unverified = jwt.get_unverified_claims(sample_token)43        for key, value in unverified.items():44            print(f"        {key}: {value}")45 46        # Now verify with secret47        print("\n    [b] Verifying token with BETTER_AUTH_SECRET...")48        try:49            verified = jwt.decode(sample_token, better_auth_secret, algorithms=["HS256"])50            print("        ✓ Token verification SUCCESSFUL!")51            print(f"        User ID (sub): {verified.get('sub')}")52        except JWTError as e:53            print(f"        X Token verification FAILED: {e}")54            print("        This means:")55            print("          - The BETTER_AUTH_SECRET doesn't match frontend")56            print("          - OR the token is expired")57            print("          - OR the token format is invalid")58    except ImportError:59        print("    python-jose not installed, skipping JWT decode")60    except KeyboardInterrupt:61        print("\n    Skipped.")62 63# Check database64print("\n[3] Checking database...")65db_url = os.getenv("DATABASE_URL")66if not db_url:67    print("    X DATABASE_URL not set!")68    sys.exit(1)69 70try:71    import psycopg272 73    conn = psycopg2.connect(db_url)74    cursor = conn.cursor()75 76    # Check users table77    print("\n    [a] Users in database:")78    cursor.execute("SELECT id, email, created_at FROM users ORDER BY created_at DESC LIMIT 10")79    users = cursor.fetchall()80    if users:81        for user_id, email, created_at in users:82            print(f"        - {user_id[:20]}... ({email}) created {created_at}")83    else:84        print("        (No users found)")85        print("        ^ THIS IS THE PROBLEM! Register a user first!")86 87    # Check tasks table88    print("\n    [b] Tasks in database:")89    cursor.execute("""90        SELECT t.id, t.user_id, t.title, t.completed, t.created_at91        FROM tasks t92        ORDER BY t.created_at DESC93        LIMIT 1094    """)95    tasks = cursor.fetchall()96    if tasks:97        for task_id, user_id, title, completed, created_at in tasks:98            status = "✓" if completed else " "99            print(f"        [{status}] Task #{task_id}: {title[:40]} (user: {user_id[:10]}...) at {created_at}")100    else:101        print("        (No tasks found)")102 103    cursor.close()104    conn.close()105 106    print("\n" + "=" * 70)107    print("DIAGNOSIS:")108    print("=" * 70)109 110    if not users:111        print("⚠ NO USERS FOUND - You need to register a user first!")112        print("  1. Go to http://localhost:3000/signup")113        print("  2. Create an account")114        print("  3. Try creating tasks again")115    elif not tasks:116        print("⚠ NO TASKS FOUND - Database is working but no tasks created yet.")117        print("  Possible causes:")118        print("  - JWT token verification failing (check secrets match)")119        print("  - API requests not reaching backend")120        print("  - Tasks created under different user_id")121    else:122        print("✓ Database has users AND tasks!")123        print("  If data isn't showing in UI:")124        print("  - Check that JWT token has correct user_id in 'sub' claim")125        print("  - Check browser console for API errors")126        print("  - Verify BETTER_AUTH_SECRET matches between frontend/backend")127 128except ImportError:129    print("    psycopg2 not installed")130except Exception as e:131    print(f"    X Database error: {e}")132 133print("\n" + "=" * 70)134