Skip to content

用户管理 API

本文档描述了 Trae 用户管理功能的 API 接口。

概述

用户管理 API 提供了用户注册、认证、资料管理、权限控制等功能,支持完整的用户生命周期管理。

端点

用户注册

http
POST /api/users/register

请求参数

参数类型必需描述
usernamestring用户名 (3-20字符)
emailstring邮箱地址
passwordstring密码 (最少8字符)
full_namestring全名
companystring公司名称
rolestring角色 (developer/designer/manager)
invite_codestring邀请码

请求示例

json
{
  "username": "alice_dev",
  "email": "alice@example.com",
  "password": "SecurePass123!",
  "full_name": "Alice Johnson",
  "company": "Tech Corp",
  "role": "developer"
}

响应

json
{
  "user_id": "user_123",
  "username": "alice_dev",
  "email": "alice@example.com",
  "full_name": "Alice Johnson",
  "company": "Tech Corp",
  "role": "developer",
  "status": "pending_verification",
  "created_at": "2024-01-01T12:00:00Z",
  "verification": {
    "email_sent": true,
    "expires_at": "2024-01-02T12:00:00Z"
  }
}

用户登录

http
POST /api/users/login

请求参数

参数类型必需描述
emailstring邮箱地址或用户名
passwordstring密码
remember_meboolean是否记住登录状态
device_infoobject设备信息

请求示例

json
{
  "email": "alice@example.com",
  "password": "SecurePass123!",
  "remember_me": true,
  "device_info": {
    "device_name": "MacBook Pro",
    "browser": "Chrome 120.0",
    "os": "macOS 14.0",
    "ip_address": "192.168.1.100"
  }
}

响应

json
{
  "user": {
    "user_id": "user_123",
    "username": "alice_dev",
    "email": "alice@example.com",
    "full_name": "Alice Johnson",
    "avatar_url": "https://cdn.trae.ai/avatars/user_123.jpg",
    "role": "developer",
    "status": "active",
    "last_login": "2024-01-01T12:00:00Z"
  },
  "tokens": {
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "expires_in": 3600,
    "token_type": "Bearer"
  },
  "session": {
    "session_id": "sess_456",
    "device_id": "dev_789",
    "expires_at": "2024-01-08T12:00:00Z"
  }
}

刷新令牌

http
POST /api/users/refresh

请求参数

参数类型必需描述
refresh_tokenstring刷新令牌

响应

json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expires_in": 3600,
  "token_type": "Bearer"
}

用户登出

http
POST /api/users/logout

请求参数

参数类型必需描述
all_devicesboolean是否登出所有设备

响应

json
{
  "message": "Successfully logged out",
  "logged_out_sessions": 1
}

获取用户资料

http
GET /api/users/me

响应

json
{
  "user_id": "user_123",
  "username": "alice_dev",
  "email": "alice@example.com",
  "full_name": "Alice Johnson",
  "avatar_url": "https://cdn.trae.ai/avatars/user_123.jpg",
  "company": "Tech Corp",
  "role": "developer",
  "status": "active",
  "created_at": "2024-01-01T12:00:00Z",
  "last_login": "2024-01-01T12:00:00Z",
  "email_verified": true,
  "two_factor_enabled": false,
  "preferences": {
    "theme": "dark",
    "language": "zh-CN",
    "timezone": "Asia/Shanghai",
    "notifications": {
      "email": true,
      "push": true,
      "desktop": false
    }
  },
  "subscription": {
    "plan": "pro",
    "status": "active",
    "expires_at": "2024-12-31T23:59:59Z"
  },
  "usage": {
    "projects_count": 15,
    "storage_used": 2048576,
    "api_calls_this_month": 1250
  }
}

更新用户资料

http
PUT /api/users/me

请求参数

参数类型必需描述
full_namestring全名
companystring公司名称
biostring个人简介
locationstring位置
websitestring个人网站
social_linksobject社交媒体链接

请求示例

json
{
  "full_name": "Alice Johnson Smith",
  "company": "New Tech Corp",
  "bio": "Full-stack developer passionate about AI and web technologies",
  "location": "San Francisco, CA",
  "website": "https://alice.dev",
  "social_links": {
    "github": "https://github.com/alice",
    "linkedin": "https://linkedin.com/in/alice",
    "twitter": "https://twitter.com/alice_dev"
  }
}

响应

json
{
  "user_id": "user_123",
  "username": "alice_dev",
  "email": "alice@example.com",
  "full_name": "Alice Johnson Smith",
  "company": "New Tech Corp",
  "bio": "Full-stack developer passionate about AI and web technologies",
  "location": "San Francisco, CA",
  "website": "https://alice.dev",
  "social_links": {
    "github": "https://github.com/alice",
    "linkedin": "https://linkedin.com/in/alice",
    "twitter": "https://twitter.com/alice_dev"
  },
  "updated_at": "2024-01-01T12:00:00Z"
}

上传头像

http
POST /api/users/me/avatar

请求参数

  • Content-Type: multipart/form-data
  • avatar: 图片文件 (最大 5MB, 支持 JPG/PNG/GIF)

响应

json
{
  "avatar_url": "https://cdn.trae.ai/avatars/user_123.jpg",
  "uploaded_at": "2024-01-01T12:00:00Z"
}

更改密码

http
PUT /api/users/me/password

请求参数

参数类型必需描述
current_passwordstring当前密码
new_passwordstring新密码
confirm_passwordstring确认新密码

请求示例

json
{
  "current_password": "OldPass123!",
  "new_password": "NewSecurePass456!",
  "confirm_password": "NewSecurePass456!"
}

响应

json
{
  "message": "Password updated successfully",
  "updated_at": "2024-01-01T12:00:00Z",
  "security_alert_sent": true
}

更新用户偏好设置

http
PUT /api/users/me/preferences

请求参数

json
{
  "theme": "dark",
  "language": "zh-CN",
  "timezone": "Asia/Shanghai",
  "editor": {
    "font_size": 14,
    "font_family": "Fira Code",
    "tab_size": 2,
    "word_wrap": true,
    "line_numbers": true,
    "minimap": false
  },
  "notifications": {
    "email": {
      "project_updates": true,
      "collaboration_invites": true,
      "security_alerts": true,
      "marketing": false
    },
    "push": {
      "mentions": true,
      "comments": true,
      "builds": false
    },
    "desktop": {
      "enabled": true,
      "sound": false
    }
  },
  "privacy": {
    "profile_visibility": "public",
    "activity_visibility": "friends",
    "project_visibility": "private"
  }
}

响应

json
{
  "preferences": {
    "theme": "dark",
    "language": "zh-CN",
    "timezone": "Asia/Shanghai",
    "editor": {
      "font_size": 14,
      "font_family": "Fira Code",
      "tab_size": 2,
      "word_wrap": true,
      "line_numbers": true,
      "minimap": false
    },
    "notifications": {
      "email": {
        "project_updates": true,
        "collaboration_invites": true,
        "security_alerts": true,
        "marketing": false
      },
      "push": {
        "mentions": true,
        "comments": true,
        "builds": false
      },
      "desktop": {
        "enabled": true,
        "sound": false
      }
    },
    "privacy": {
      "profile_visibility": "public",
      "activity_visibility": "friends",
      "project_visibility": "private"
    }
  },
  "updated_at": "2024-01-01T12:00:00Z"
}

获取用户列表 (管理员)

http
GET /api/users?limit={limit}&offset={offset}&search={search}&role={role}&status={status}

查询参数

参数类型必需描述
limitnumber返回数量限制
offsetnumber偏移量
searchstring搜索关键词
rolestring角色过滤
statusstring状态过滤
sortstring排序字段
orderstring排序方向 (asc/desc)

响应

json
{
  "users": [
    {
      "user_id": "user_123",
      "username": "alice_dev",
      "email": "alice@example.com",
      "full_name": "Alice Johnson",
      "avatar_url": "https://cdn.trae.ai/avatars/user_123.jpg",
      "company": "Tech Corp",
      "role": "developer",
      "status": "active",
      "created_at": "2024-01-01T12:00:00Z",
      "last_login": "2024-01-01T12:00:00Z",
      "projects_count": 15,
      "subscription": {
        "plan": "pro",
        "status": "active"
      }
    }
  ],
  "total": 1,
  "pagination": {
    "limit": 20,
    "offset": 0,
    "has_more": false
  }
}

获取特定用户信息 (管理员)

http
GET /api/users/{user_id}

响应

json
{
  "user_id": "user_123",
  "username": "alice_dev",
  "email": "alice@example.com",
  "full_name": "Alice Johnson",
  "avatar_url": "https://cdn.trae.ai/avatars/user_123.jpg",
  "company": "Tech Corp",
  "role": "developer",
  "status": "active",
  "created_at": "2024-01-01T12:00:00Z",
  "last_login": "2024-01-01T12:00:00Z",
  "email_verified": true,
  "two_factor_enabled": false,
  "subscription": {
    "plan": "pro",
    "status": "active",
    "expires_at": "2024-12-31T23:59:59Z"
  },
  "usage": {
    "projects_count": 15,
    "storage_used": 2048576,
    "api_calls_this_month": 1250,
    "last_activity": "2024-01-01T11:30:00Z"
  },
  "security": {
    "login_attempts": 0,
    "last_password_change": "2024-01-01T12:00:00Z",
    "active_sessions": 2,
    "trusted_devices": 3
  }
}

更新用户状态 (管理员)

http
PUT /api/users/{user_id}/status

请求参数

参数类型必需描述
statusstring新状态 (active/suspended/banned)
reasonstring状态变更原因
notify_userboolean是否通知用户

请求示例

json
{
  "status": "suspended",
  "reason": "Violation of terms of service",
  "notify_user": true
}

响应

json
{
  "user_id": "user_123",
  "status": "suspended",
  "reason": "Violation of terms of service",
  "updated_by": "admin_456",
  "updated_at": "2024-01-01T12:00:00Z",
  "notification_sent": true
}

删除用户账户

http
DELETE /api/users/me

请求参数

参数类型必需描述
passwordstring当前密码确认
confirmationstring确认文本 "DELETE"
reasonstring删除原因

请求示例

json
{
  "password": "CurrentPass123!",
  "confirmation": "DELETE",
  "reason": "No longer need the service"
}

响应

json
{
  "message": "Account deletion initiated",
  "deletion_id": "del_789",
  "scheduled_at": "2024-01-08T12:00:00Z",
  "grace_period_days": 7,
  "recovery_instructions": "Contact support within 7 days to recover your account"
}

两步验证设置

启用两步验证

http
POST /api/users/me/2fa/enable

响应

json
{
  "secret": "JBSWY3DPEHPK3PXP",
  "qr_code_url": "https://api.trae.ai/users/me/2fa/qr?secret=JBSWY3DPEHPK3PXP",
  "backup_codes": [
    "12345678",
    "87654321",
    "11223344",
    "44332211",
    "55667788"
  ],
  "setup_instructions": "Scan the QR code with your authenticator app and enter the verification code"
}

验证并完成两步验证设置

http
POST /api/users/me/2fa/verify

请求参数

参数类型必需描述
codestring验证码

请求示例

json
{
  "code": "123456"
}

响应

json
{
  "message": "Two-factor authentication enabled successfully",
  "enabled_at": "2024-01-01T12:00:00Z",
  "backup_codes_remaining": 5
}

禁用两步验证

http
POST /api/users/me/2fa/disable

请求参数

参数类型必需描述
passwordstring当前密码
codestring验证码

会话管理

获取活跃会话

http
GET /api/users/me/sessions

响应

json
{
  "sessions": [
    {
      "session_id": "sess_456",
      "device_id": "dev_789",
      "device_name": "MacBook Pro",
      "browser": "Chrome 120.0",
      "os": "macOS 14.0",
      "ip_address": "192.168.1.100",
      "location": "San Francisco, CA",
      "created_at": "2024-01-01T12:00:00Z",
      "last_activity": "2024-01-01T12:00:00Z",
      "is_current": true
    },
    {
      "session_id": "sess_457",
      "device_id": "dev_790",
      "device_name": "iPhone 15",
      "browser": "Safari 17.0",
      "os": "iOS 17.0",
      "ip_address": "192.168.1.101",
      "location": "San Francisco, CA",
      "created_at": "2024-01-01T10:00:00Z",
      "last_activity": "2024-01-01T11:30:00Z",
      "is_current": false
    }
  ],
  "total": 2
}

终止特定会话

http
DELETE /api/users/me/sessions/{session_id}

响应

json
{
  "message": "Session terminated successfully",
  "session_id": "sess_457",
  "terminated_at": "2024-01-01T12:00:00Z"
}

终止所有其他会话

http
DELETE /api/users/me/sessions/others

响应

json
{
  "message": "All other sessions terminated",
  "terminated_sessions": 3,
  "terminated_at": "2024-01-01T12:00:00Z"
}

示例

用户注册和验证流程

javascript
// 用户注册
const registerUser = async (userData) => {
  const response = await fetch('/api/users/register', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(userData)
  });
  
  const result = await response.json();
  
  if (response.ok) {
    console.log('注册成功,请检查邮箱验证邮件');
    return result;
  } else {
    throw new Error(result.message);
  }
};

// 使用示例
try {
  const newUser = await registerUser({
    username: 'alice_dev',
    email: 'alice@example.com',
    password: 'SecurePass123!',
    full_name: 'Alice Johnson',
    company: 'Tech Corp',
    role: 'developer'
  });
  
  console.log('用户已注册:', newUser.user_id);
} catch (error) {
  console.error('注册失败:', error.message);
}

用户登录和令牌管理

javascript
// 用户登录
const loginUser = async (email, password, rememberMe = false) => {
  const response = await fetch('/api/users/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      email,
      password,
      remember_me: rememberMe,
      device_info: {
        device_name: navigator.platform,
        browser: navigator.userAgent,
        os: navigator.platform
      }
    })
  });
  
  const result = await response.json();
  
  if (response.ok) {
    // 保存令牌
    localStorage.setItem('access_token', result.tokens.access_token);
    localStorage.setItem('refresh_token', result.tokens.refresh_token);
    
    console.log('登录成功:', result.user.username);
    return result;
  } else {
    throw new Error(result.message);
  }
};

// 自动刷新令牌
const refreshToken = async () => {
  const refreshToken = localStorage.getItem('refresh_token');
  
  if (!refreshToken) {
    throw new Error('No refresh token available');
  }
  
  const response = await fetch('/api/users/refresh', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      refresh_token: refreshToken
    })
  });
  
  const result = await response.json();
  
  if (response.ok) {
    localStorage.setItem('access_token', result.access_token);
    localStorage.setItem('refresh_token', result.refresh_token);
    return result;
  } else {
    // 刷新失败,需要重新登录
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    throw new Error('Token refresh failed');
  }
};

// 带自动刷新的 API 请求
const apiRequest = async (url, options = {}) => {
  const token = localStorage.getItem('access_token');
  
  const response = await fetch(url, {
    ...options,
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
      ...options.headers
    }
  });
  
  if (response.status === 401) {
    // 令牌过期,尝试刷新
    try {
      await refreshToken();
      
      // 重新发送请求
      const newToken = localStorage.getItem('access_token');
      return fetch(url, {
        ...options,
        headers: {
          'Authorization': `Bearer ${newToken}`,
          'Content-Type': 'application/json',
          ...options.headers
        }
      });
    } catch (error) {
      // 刷新失败,重定向到登录页
      window.location.href = '/login';
      throw error;
    }
  }
  
  return response;
};

// 使用示例
try {
  const user = await loginUser('alice@example.com', 'SecurePass123!', true);
  console.log('欢迎回来,', user.user.full_name);
} catch (error) {
  console.error('登录失败:', error.message);
}

用户资料管理

javascript
// 获取用户资料
const getUserProfile = async () => {
  const response = await apiRequest('/api/users/me');
  const profile = await response.json();
  
  if (response.ok) {
    return profile;
  } else {
    throw new Error(profile.message);
  }
};

// 更新用户资料
const updateUserProfile = async (updates) => {
  const response = await apiRequest('/api/users/me', {
    method: 'PUT',
    body: JSON.stringify(updates)
  });
  
  const result = await response.json();
  
  if (response.ok) {
    console.log('资料更新成功');
    return result;
  } else {
    throw new Error(result.message);
  }
};

// 上传头像
const uploadAvatar = async (file) => {
  const formData = new FormData();
  formData.append('avatar', file);
  
  const token = localStorage.getItem('access_token');
  
  const response = await fetch('/api/users/me/avatar', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`
    },
    body: formData
  });
  
  const result = await response.json();
  
  if (response.ok) {
    console.log('头像上传成功:', result.avatar_url);
    return result;
  } else {
    throw new Error(result.message);
  }
};

// 使用示例
try {
  const profile = await getUserProfile();
  console.log('当前用户:', profile.full_name);
  
  // 更新资料
  await updateUserProfile({
    bio: '热爱编程的全栈开发者',
    location: '北京',
    website: 'https://mywebsite.com'
  });
  
  console.log('资料已更新');
} catch (error) {
  console.error('操作失败:', error.message);
}

偏好设置管理

javascript
// 更新用户偏好设置
const updatePreferences = async (preferences) => {
  const response = await apiRequest('/api/users/me/preferences', {
    method: 'PUT',
    body: JSON.stringify(preferences)
  });
  
  const result = await response.json();
  
  if (response.ok) {
    console.log('偏好设置已更新');
    return result;
  } else {
    throw new Error(result.message);
  }
};

// 主题切换
const toggleTheme = async () => {
  const profile = await getUserProfile();
  const currentTheme = profile.preferences.theme;
  const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
  
  await updatePreferences({
    theme: newTheme
  });
  
  // 应用主题到页面
  document.body.className = `theme-${newTheme}`;
  
  console.log(`主题已切换到: ${newTheme}`);
};

// 通知设置
const updateNotificationSettings = async (settings) => {
  await updatePreferences({
    notifications: settings
  });
  
  console.log('通知设置已更新');
};

// 使用示例
try {
  // 切换主题
  await toggleTheme();
  
  // 更新通知设置
  await updateNotificationSettings({
    email: {
      project_updates: true,
      collaboration_invites: true,
      security_alerts: true,
      marketing: false
    },
    push: {
      mentions: true,
      comments: false,
      builds: false
    }
  });
} catch (error) {
  console.error('设置更新失败:', error.message);
}

会话管理

javascript
// 获取活跃会话
const getActiveSessions = async () => {
  const response = await apiRequest('/api/users/me/sessions');
  const sessions = await response.json();
  
  if (response.ok) {
    return sessions;
  } else {
    throw new Error(sessions.message);
  }
};

// 终止特定会话
const terminateSession = async (sessionId) => {
  const response = await apiRequest(`/api/users/me/sessions/${sessionId}`, {
    method: 'DELETE'
  });
  
  const result = await response.json();
  
  if (response.ok) {
    console.log('会话已终止');
    return result;
  } else {
    throw new Error(result.message);
  }
};

// 显示会话列表
const displaySessions = async () => {
  try {
    const sessions = await getActiveSessions();
    
    console.log('活跃会话:');
    sessions.sessions.forEach(session => {
      console.log(`- ${session.device_name} (${session.browser})`);
      console.log(`  位置: ${session.location}`);
      console.log(`  最后活动: ${new Date(session.last_activity).toLocaleString()}`);
      console.log(`  当前会话: ${session.is_current ? '是' : '否'}`);
      console.log('---');
    });
  } catch (error) {
    console.error('获取会话失败:', error.message);
  }
};

// 安全检查:终止可疑会话
const securityCheck = async () => {
  const sessions = await getActiveSessions();
  const now = new Date();
  
  for (const session of sessions.sessions) {
    const lastActivity = new Date(session.last_activity);
    const daysSinceActivity = (now - lastActivity) / (1000 * 60 * 60 * 24);
    
    // 终止超过30天未活动的会话
    if (daysSinceActivity > 30 && !session.is_current) {
      console.log(`终止不活跃会话: ${session.device_name}`);
      await terminateSession(session.session_id);
    }
  }
};

// 使用示例
displaySessions();
securityCheck();

两步验证设置

javascript
// 启用两步验证
const enable2FA = async () => {
  const response = await apiRequest('/api/users/me/2fa/enable', {
    method: 'POST'
  });
  
  const result = await response.json();
  
  if (response.ok) {
    console.log('两步验证设置:');
    console.log('密钥:', result.secret);
    console.log('二维码:', result.qr_code_url);
    console.log('备用码:', result.backup_codes);
    
    return result;
  } else {
    throw new Error(result.message);
  }
};

// 验证并完成设置
const verify2FA = async (code) => {
  const response = await apiRequest('/api/users/me/2fa/verify', {
    method: 'POST',
    body: JSON.stringify({ code })
  });
  
  const result = await response.json();
  
  if (response.ok) {
    console.log('两步验证已启用');
    return result;
  } else {
    throw new Error(result.message);
  }
};

// 禁用两步验证
const disable2FA = async (password, code) => {
  const response = await apiRequest('/api/users/me/2fa/disable', {
    method: 'POST',
    body: JSON.stringify({ password, code })
  });
  
  const result = await response.json();
  
  if (response.ok) {
    console.log('两步验证已禁用');
    return result;
  } else {
    throw new Error(result.message);
  }
};

// 使用示例
try {
  // 启用两步验证
  const setup = await enable2FA();
  
  // 用户扫描二维码后输入验证码
  const verificationCode = prompt('请输入验证器应用中的6位数字:');
  
  if (verificationCode) {
    await verify2FA(verificationCode);
    console.log('两步验证设置完成!');
    
    // 保存备用码
    console.log('请妥善保存这些备用码:');
    setup.backup_codes.forEach(code => console.log(code));
  }
} catch (error) {
  console.error('两步验证设置失败:', error.message);
}

您的终极 AI 驱动 IDE 学习指南