2
0
Просмотр исходного кода

✨ feat(auth): 添加微信用户头像自动下载功能

- 重构服务实例化方式,将服务实例创建移至路由处理函数内部
- 引入FileService服务用于文件处理
- 为新用户添加微信头像下载和保存功能
- 为已有用户但无头像的情况添加微信头像下载和更新功能
yourname 6 месяцев назад
Родитель
Сommit
1332609b2d
2 измененных файлов с 37 добавлено и 4 удалено
  1. 7 4
      src/server/api/auth/wechat/wechat-login.ts
  2. 30 0
      src/server/modules/wechat/wechat-auth.service.ts

+ 7 - 4
src/server/api/auth/wechat/wechat-login.ts

@@ -7,6 +7,7 @@ import { UserService } from '@/server/modules/users/user.service';
 import { AuthService } from '@/server/modules/auth/auth.service';
 import { AuthService } from '@/server/modules/auth/auth.service';
 import { UserSchema } from '@/server/modules/users/user.schema'
 import { UserSchema } from '@/server/modules/users/user.schema'
 import { parseWithAwait } from '@/server/utils/parseWithAwait';
 import { parseWithAwait } from '@/server/utils/parseWithAwait';
+import { FileService } from '@/server/modules/files/file.service';
 
 
 const WechatLoginSchema = z.object({
 const WechatLoginSchema = z.object({
   code: z.string().min(1).openapi({
   code: z.string().min(1).openapi({
@@ -23,10 +24,6 @@ const TokenResponseSchema = z.object({
   user: UserSchema.omit({ password: true })
   user: UserSchema.omit({ password: true })
 })
 })
 
 
-const userService = new UserService(AppDataSource);
-const authService = new AuthService(userService);
-const wechatAuthService = new WechatAuthService(userService, authService);
-
 const wechatLoginRoute = createRoute({
 const wechatLoginRoute = createRoute({
   method: 'post',
   method: 'post',
   path: '/login',
   path: '/login',
@@ -70,6 +67,12 @@ const wechatLoginRoute = createRoute({
 const app = new OpenAPIHono().openapi(wechatLoginRoute, async (c) => {
 const app = new OpenAPIHono().openapi(wechatLoginRoute, async (c) => {
   try {
   try {
     const { code } = await c.req.json();
     const { code } = await c.req.json();
+
+    const userService = new UserService(AppDataSource);
+    const authService = new AuthService(userService);
+    const fileService = new FileService(AppDataSource)
+
+    const wechatAuthService = new WechatAuthService(userService, authService, fileService);
     const result = await wechatAuthService.wechatLogin(code);
     const result = await wechatAuthService.wechatLogin(code);
     
     
     // 使用 parseWithAwait 确保返回数据符合Schema定义
     // 使用 parseWithAwait 确保返回数据符合Schema定义

+ 30 - 0
src/server/modules/wechat/wechat-auth.service.ts

@@ -97,6 +97,36 @@ export class WechatAuthService {
             // 头像下载失败不影响主要流程
             // 头像下载失败不影响主要流程
           }
           }
         }
         }
+      } else {
+        // 已有用户:如果avatarFileId为空,也下载微信头像
+        if (!user.avatarFileId) {
+          try {
+            // 获取最新的用户信息
+            const userInfo = await this.getUserInfo(access_token, openid);
+            
+            if (userInfo.headimgurl) {
+              const avatarResult = await this.fileService.downloadAndSaveFromUrl(
+                userInfo.headimgurl,
+                {
+                  uploadUserId: user.id,
+                  customPath: 'avatars/wechat/',
+                  mimeType: 'image/jpeg'
+                }
+              );
+              
+              // 更新用户的 avatarFileId
+              await this.userService.updateUser(user.id, {
+                avatarFileId: avatarResult.file.id
+              });
+              
+              // 更新返回的用户对象
+              user.avatarFileId = avatarResult.file.id;
+            }
+          } catch (error) {
+            logger.error('为已有用户下载微信头像失败:', error);
+            // 头像下载失败不影响主要流程
+          }
+        }
       }
       }
 
 
       // 5. 生成JWT token
       // 5. 生成JWT token