All files / src/server/routes user-info.ts

0% Statements 0/213
0% Branches 0/1
0% Functions 0/1
0% Lines 0/213

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
/**
 * 用户信息管理相关的 API 路由
 *
 * 提供用户信息的设置、获取、更新和清除接口
 * 支持与 Web 应用和 MCP 服务器的用户信息同步
 */
 
import type express from 'express'
import { userInfoService } from '../../services/user-info-service'
import { logger } from '../../utils/logger-adapter'
 
/**
 * 注册用户信息相关路由
 */
export function registerUserInfoRoutes(app: express.Express): void {
  // 获取当前用户信息
  app.get('/api/user/info', async (req, res) => {
    try {
      const userInfo = userInfoService.getUserInfo()
      const loginState = userInfoService.getLoginState()
 
      res.json({
        success: true,
        data: {
          userInfo,
          isLoggedIn: userInfoService.isLoggedIn(),
          loginState,
          isExpiringSoon: userInfoService.isUserInfoExpiringSoon(),
        },
      })
    }
    catch (error) {
      logger.error('[UserInfo API] 获取用户信息失败', error)
      res.status(500).json({
        success: false,
        error: '获取用户信息失败',
        message: error instanceof Error ? error.message : '未知错误',
      })
    }
  })
 
  // 设置用户信息(来自 Web 应用)
  app.post('/api/user/info', async (req, res) => {
    try {
      const { userInfo, source = 'web' } = req.body
 
      if (!userInfo) {
        return res.status(400).json({
          success: false,
          error: '缺少用户信息数据',
        })
      }
 
      // 验证用户信息格式
      if (!userInfoService.validateUserInfo(userInfo)) {
        return res.status(400).json({
          success: false,
          error: '用户信息格式无效',
        })
      }
 
      await userInfoService.setUserInfo(userInfo, source)
 
      logger.info('[UserInfo API] 用户信息已设置', {
        uid: userInfo.uid,
        uname: userInfo.uname,
        source,
      })
 
      res.json({
        success: true,
        message: '用户信息设置成功',
        data: {
          uid: userInfo.uid,
          uname: userInfo.uname,
          zhname: userInfo.zhname,
        },
      })
    }
    catch (error) {
      logger.error('[UserInfo API] 设置用户信息失败', error)
      res.status(500).json({
        success: false,
        error: '设置用户信息失败',
        message: error instanceof Error ? error.message : '未知错误',
      })
    }
  })
 
  // 更新用户信息
  app.patch('/api/user/info', async (req, res) => {
    try {
      const { updates } = req.body
 
      if (!updates || typeof updates !== 'object') {
        return res.status(400).json({
          success: false,
          error: '缺少更新数据',
        })
      }
 
      if (!userInfoService.isLoggedIn()) {
        return res.status(401).json({
          success: false,
          error: '用户未登录',
        })
      }
 
      await userInfoService.updateUserInfo(updates)
 
      logger.info('[UserInfo API] 用户信息已更新', updates)
 
      res.json({
        success: true,
        message: '用户信息更新成功',
        data: userInfoService.getUserInfo(),
      })
    }
    catch (error) {
      logger.error('[UserInfo API] 更新用户信息失败', error)
      res.status(500).json({
        success: false,
        error: '更新用户信息失败',
        message: error instanceof Error ? error.message : '未知错误',
      })
    }
  })
 
  // 清除用户信息(登出)
  app.delete('/api/user/info', async (req, res) => {
    try {
      await userInfoService.clearUserInfo()
 
      logger.info('[UserInfo API] 用户信息已清除')
 
      res.json({
        success: true,
        message: '用户已登出',
      })
    }
    catch (error) {
      logger.error('[UserInfo API] 清除用户信息失败', error)
      res.status(500).json({
        success: false,
        error: '登出失败',
        message: error instanceof Error ? error.message : '未知错误',
      })
    }
  })
 
  // 检查登录状态
  app.get('/api/user/login-status', async (req, res) => {
    try {
      const isLoggedIn = userInfoService.isLoggedIn()
      const userDisplayName = userInfoService.getUserDisplayName()
      const userId = userInfoService.getUserId()
      const loginState = userInfoService.getLoginState()
 
      res.json({
        success: true,
        data: {
          isLoggedIn,
          userDisplayName,
          userId,
          loginState,
          isExpiringSoon: userInfoService.isUserInfoExpiringSoon(),
        },
      })
    }
    catch (error) {
      logger.error('[UserInfo API] 检查登录状态失败', error)
      res.status(500).json({
        success: false,
        error: '检查登录状态失败',
        message: error instanceof Error ? error.message : '未知错误',
      })
    }
  })
 
  // 为 MCP 服务器提供用户信息(内部接口)
  app.get('/api/internal/user/info', async (req, res) => {
    try {
      // 验证请求来源(可以添加更严格的验证)
      const userAgent = req.get('User-Agent') || ''
      if (!userAgent.includes('dalidev-mcp') && !userAgent.includes('node')) {
        logger.warn('[UserInfo API] 可疑的内部API访问', { userAgent, ip: req.ip })
      }
 
      const userInfo = await userInfoService.handleUserInfoRequestFromMCP()
 
      res.json({
        success: true,
        data: userInfo,
      })
    }
    catch (error) {
      logger.error('[UserInfo API] MCP 获取用户信息失败', error)
      res.status(500).json({
        success: false,
        error: 'MCP 获取用户信息失败',
        message: error instanceof Error ? error.message : '未知错误',
      })
    }
  })
 
  // 处理来自 Web 应用的用户信息同步(带验证)
  app.post('/api/user/sync', async (req, res) => {
    try {
      const { userInfo, timestamp } = req.body
 
      // 基本验证
      if (!userInfo || !timestamp) {
        return res.status(400).json({
          success: false,
          error: '缺少必要参数',
        })
      }
 
      // 检查时间戳是否在合理范围内(5分钟内)
      const now = Date.now()
      const requestTime = Number.parseInt(timestamp)
      if (Math.abs(now - requestTime) > 5 * 60 * 1000) {
        return res.status(400).json({
          success: false,
          error: '请求时间戳无效',
        })
      }
 
      await userInfoService.handleUserInfoFromWeb(userInfo)
 
      res.json({
        success: true,
        message: '用户信息同步成功',
      })
    }
    catch (error) {
      logger.error('[UserInfo API] 用户信息同步失败', error)
      res.status(500).json({
        success: false,
        error: '用户信息同步失败',
        message: error instanceof Error ? error.message : '未知错误',
      })
    }
  })
 
  // 获取用于 Analytics 的用户信息(清理版本)
  app.get('/api/user/analytics-info', async (req, res) => {
    try {
      const userInfo = userInfoService.getUserInfoForAPI()
 
      res.json({
        success: true,
        data: userInfo,
      })
    }
    catch (error) {
      logger.error('[UserInfo API] 获取Analytics用户信息失败', error)
      res.status(500).json({
        success: false,
        error: '获取Analytics用户信息失败',
        message: error instanceof Error ? error.message : '未知错误',
      })
    }
  })
 
  logger.info('[UserInfo API] 用户信息路由已注册')
}