#!/usr/bin/env python3
"""
测试JWT Token解析
"""

import requests
import json

# 登录获取Token
login_data = {
    "username": "admin",
    "password": "admin123"
}

print("1. 登录...")
# 先通过前端proxy登录（会自动添加签名）
from playwright.sync_api import sync_playwright
import time

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()
    
    page.goto("http://localhost:3002/login")
    page.wait_for_load_state("networkidle")
    page.fill('input[placeholder="请输入用户名"]', 'admin')
    page.fill('input[placeholder="请输入密码"]', 'admin123')
    page.click('button:has-text("登录")')
    
    # 等待Token
    for i in range(10):
        time.sleep(1)
        token = page.evaluate("localStorage.getItem('token')")
        if token:
            break
    
    browser.close()

print(f"\nToken: {token[:100]}...")
print(f"\nToken长度: {len(token)}")

# 解析Token的payload
import base64

def decode_jwt_payload(token):
    parts = token.split('.')
    if len(parts) != 3:
        return None
    
    payload = parts[1]
    # 添加padding
    padding = len(payload) % 4
    if padding:
        payload += '=' * (4 - padding)
    
    decoded = base64.b64decode(payload)
    return json.loads(decoded)

payload = decode_jwt_payload(token)
print(f"\nToken Payload:")
print(json.dumps(payload, indent=2))
