auth-demo.html 9.67 KB
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>认证工具使用示例</title>
  <script src="config.js"></script>
  <script src="auth-utils.js"></script>
  <style>
    body {
      font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
      margin: 20px;
      background: #f5f5f5;
    }
    .container {
      max-width: 800px;
      margin: 0 auto;
      background: white;
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    .section {
      margin: 20px 0;
      padding: 15px;
      border: 1px solid #ddd;
      border-radius: 8px;
    }
    .section h3 {
      margin-top: 0;
      color: #333;
    }
    .btn {
      background: #2196f3;
      color: white;
      border: none;
      padding: 10px 20px;
      border-radius: 5px;
      cursor: pointer;
      margin: 5px;
    }
    .btn:hover {
      background: #1976d2;
    }
    .btn.danger {
      background: #f44336;
    }
    .btn.danger:hover {
      background: #d32f2f;
    }
    .status {
      margin: 10px 0;
      padding: 10px;
      border-radius: 5px;
      font-family: monospace;
    }
    .status.success {
      background: #e8f5e9;
      border: 1px solid #4caf50;
      color: #2e7d32;
    }
    .status.error {
      background: #ffebee;
      border: 1px solid #f44336;
      color: #c62828;
    }
    .status.info {
      background: #e3f2fd;
      border: 1px solid #2196f3;
      color: #1565c0;
    }
    pre {
      background: #f5f5f5;
      padding: 10px;
      border-radius: 5px;
      overflow-x: auto;
      font-size: 12px;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>🔐 认证工具使用示例</h1>
    
    <div class="section">
      <h3>认证状态检查</h3>
      <button class="btn" onclick="checkAuthStatus()">检查认证状态</button>
      <button class="btn" onclick="showAuthInfo()">显示认证信息</button>
      <div id="authStatus" class="status info">点击按钮查看认证状态</div>
    </div>
    
    <div class="section">
      <h3>认证管理</h3>
      <button class="btn" onclick="clearAuth()">清除认证</button>
      <button class="btn" onclick="refreshAuth()">刷新认证状态</button>
      <div id="authManage" class="status info">-</div>
    </div>
    
    <div class="section">
      <h3>API调用示例</h3>
      <button class="btn" onclick="testAuthenticatedGet()">测试带认证的GET请求</button>
      <button class="btn" onclick="testAuthenticatedPost()">测试带认证的POST请求</button>
      <div id="apiTest" class="status info">-</div>
    </div>
    
    <div class="section">
      <h3>全局变量状态</h3>
      <pre id="globalState">-</pre>
    </div>
    
    <div class="section">
      <h3>localStorage状态</h3>
      <pre id="localStorageState">-</pre>
    </div>
  </div>

  <script>
    // 检查认证状态
    function checkAuthStatus() {
      const statusEl = document.getElementById('authStatus');
      
      if (window.AUTH_UTILS) {
        const isLoggedIn = window.AUTH_UTILS.isLoggedIn();
        const hasToken = !!window.AUTH_UTILS.getAuthToken();
        const userInfo = window.AUTH_UTILS.getUserInfo();
        const theme = window.AUTH_UTILS.getUserTheme();
        
        const status = {
          isLoggedIn,
          hasToken,
          userInfo,
          theme,
          tokenValid: window.AUTH_UTILS.isTokenValid()
        };
        
        statusEl.className = `status ${isLoggedIn ? 'success' : 'error'}`;
        statusEl.innerHTML = `
          <strong>认证状态:</strong><br>
          已登录: ${isLoggedIn ? '✅ 是' : '❌ 否'}<br>
          Token: ${hasToken ? '✅ 是' : '❌ 否'}<br>
          Token有效: ${status.tokenValid ? '✅ 是' : '❌ 否'}<br>
          用户信息: ${userInfo ? '✅ 有' : '❌ 无'}<br>
          主题: ${theme || '无'}
        `;
      } else {
        statusEl.className = 'status error';
        statusEl.textContent = '❌ 认证工具未加载';
      }
    }
    
    // 显示认证信息
    function showAuthInfo() {
      const statusEl = document.getElementById('authStatus');
      
      if (window.AUTH_UTILS) {
        const token = window.AUTH_UTILS.getAuthToken();
        const userInfo = window.AUTH_UTILS.getUserInfo();
        
        statusEl.className = 'status info';
        statusEl.innerHTML = `
          <strong>认证信息:</strong><br>
          Token: ${token ? token.substring(0, 50) + '...' : '无'}<br>
          用户信息: ${userInfo ? JSON.stringify(userInfo, null, 2) : '无'}
        `;
      } else {
        statusEl.className = 'status error';
        statusEl.textContent = '❌ 认证工具未加载';
      }
    }
    
    // 清除认证
    function clearAuth() {
      if (window.AUTH_UTILS) {
        window.AUTH_UTILS.clearAuthState();
        document.getElementById('authManage').className = 'status success';
        document.getElementById('authManage').textContent = '✅ 认证状态已清除';
        checkAuthStatus();
      } else {
        document.getElementById('authManage').className = 'status error';
        document.getElementById('authManage').textContent = '❌ 认证工具未加载';
      }
    }
    
    // 刷新认证状态
    function refreshAuth() {
      if (window.AUTH_UTILS) {
        window.AUTH_UTILS.initAuthState();
        document.getElementById('authManage').className = 'status success';
        document.getElementById('authManage').textContent = '✅ 认证状态已刷新';
        checkAuthStatus();
      } else {
        document.getElementById('authManage').className = 'status error';
        document.getElementById('authManage').textContent = '❌ 认证工具未加载';
      }
    }
    
    // 测试带认证的GET请求
    async function testAuthenticatedGet() {
      const apiTestEl = document.getElementById('apiTest');
      
      if (!window.AUTH_UTILS || !window.AUTH_UTILS.isLoggedIn()) {
        apiTestEl.className = 'status error';
        apiTestEl.textContent = '❌ 请先登录';
        return;
      }
      
      try {
        apiTestEl.className = 'status info';
        apiTestEl.textContent = '🔄 正在测试带认证的GET请求...';
        
        const apiBaseUrl = window.APP_CONFIG ? window.APP_CONFIG.getApiBaseUrl() : '';
        const response = await window.AUTH_UTILS.authenticatedGet(`${apiBaseUrl}/api/oauth/CurrentUser`);
        
        if (response.ok) {
          const result = await response.json();
          apiTestEl.className = 'status success';
          apiTestEl.innerHTML = `
             GET请求成功!<br>
            状态码: ${response.status}<br>
            响应数据: <pre>${JSON.stringify(result, null, 2)}</pre>
          `;
        } else {
          apiTestEl.className = 'status error';
          apiTestEl.textContent = `❌ GET请求失败: HTTP ${response.status}`;
        }
      } catch (error) {
        apiTestEl.className = 'status error';
        apiTestEl.textContent = `❌ 请求异常: ${error.message}`;
      }
    }
    
    // 测试带认证的POST请求
    async function testAuthenticatedPost() {
      const apiTestEl = document.getElementById('apiTest');
      
      if (!window.AUTH_UTILS || !window.AUTH_UTILS.isLoggedIn()) {
        apiTestEl.className = 'status error';
        apiTestEl.textContent = '❌ 请先登录';
        return;
      }
      
      try {
        apiTestEl.className = 'status info';
        apiTestEl.textContent = '🔄 正在测试带认证的POST请求...';
        
        const apiBaseUrl = window.APP_CONFIG ? window.APP_CONFIG.getApiBaseUrl() : '';
        const testData = { message: '这是一个测试请求', timestamp: Date.now() };
        
        const response = await window.AUTH_UTILS.authenticatedPost(`${apiBaseUrl}/api/test`, testData);
        
        if (response.ok) {
          const result = await response.json();
          apiTestEl.className = 'status success';
          apiTestEl.innerHTML = `
             POST请求成功!<br>
            状态码: ${response.status}<br>
            响应数据: <pre>${JSON.stringify(result, null, 2)}</pre>
          `;
        } else {
          apiTestEl.className = 'status error';
          apiTestEl.textContent = `❌ POST请求失败: HTTP ${response.status}`;
        }
      } catch (error) {
        apiTestEl.className = 'status error';
        apiTestEl.textContent = `❌ 请求异常: ${error.message}`;
      }
    }
    
    // 更新全局状态显示
    function updateGlobalState() {
      const globalStateEl = document.getElementById('globalState');
      const localStorageEl = document.getElementById('localStorageState');
      
      // 全局变量状态
      const globalState = {
        AUTH_TOKEN: window.AUTH_TOKEN || null,
        USER_INFO: window.USER_INFO || null,
        USER_THEME: window.USER_THEME || null,
        AUTH_STATE: window.AUTH_STATE || null,
        AUTH_UTILS: !!window.AUTH_UTILS
      };
      
      globalStateEl.textContent = JSON.stringify(globalState, null, 2);
      
      // localStorage状态
      const localStorageState = {
        authToken: localStorage.getItem('authToken'),
        userInfo: localStorage.getItem('userInfo'),
        userTheme: localStorage.getItem('userTheme')
      };
      
      localStorageEl.textContent = JSON.stringify(localStorageState, null, 2);
    }
    
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
      // 等待认证工具加载完成
      setTimeout(() => {
        checkAuthStatus();
        updateGlobalState();
      }, 500);
      
      // 定期更新状态
      setInterval(updateGlobalState, 2000);
    });
  </script>
</body>
</html>