Quellcode durchsuchen

feat:login&registration

0235624 vor 1 Woche
Ursprung
Commit
252e31ec2a

+ 124 - 0
travel-web/package-lock.json

@@ -17,6 +17,7 @@
         "@fortawesome/fontawesome-free": "^6.7.2",
         "@types/echarts": "^4.9.22",
         "echarts": "^5.6.0",
+        "parse": "^6.1.1",
         "rxjs": "~7.8.0",
         "swiper": "^11.2.10",
         "tslib": "^2.3.0",
@@ -28,6 +29,7 @@
         "@angular/compiler-cli": "^20.0.0",
         "@types/jasmine": "~5.1.0",
         "@types/node": "^24.0.10",
+        "@types/parse": "^3.0.9",
         "jasmine-core": "~5.7.0",
         "karma": "~6.4.0",
         "karma-chrome-launcher": "~3.2.0",
@@ -734,6 +736,19 @@
         "node": ">=6.0.0"
       }
     },
+    "node_modules/@babel/runtime-corejs3": {
+      "version": "7.27.0",
+      "resolved": "https://registry.npmmirror.com/@babel/runtime-corejs3/-/runtime-corejs3-7.27.0.tgz",
+      "integrity": "sha512-UWjX6t+v+0ckwZ50Y5ShZLnlk95pP5MyW/pon9tiYzl3+18pkTHTFNTKr7rQbfRXPkowt2QAn30o1b6oswszew==",
+      "license": "MIT",
+      "dependencies": {
+        "core-js-pure": "^3.30.2",
+        "regenerator-runtime": "^0.14.0"
+      },
+      "engines": {
+        "node": ">=6.9.0"
+      }
+    },
     "node_modules/@babel/template": {
       "version": "7.27.2",
       "resolved": "https://registry.npmmirror.com/@babel/template/-/template-7.27.2.tgz",
@@ -3289,6 +3304,16 @@
         "undici-types": "~7.8.0"
       }
     },
+    "node_modules/@types/parse": {
+      "version": "3.0.9",
+      "resolved": "https://registry.npmmirror.com/@types/parse/-/parse-3.0.9.tgz",
+      "integrity": "sha512-DGTHygc7krgmNAK8h42giwmAofCd9uv2++RD+zw6OmWI7AEnlTYZwEuWsx22SA2CSMQrZW8P2INHLpQbnQFUng==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "@types/node": "*"
+      }
+    },
     "node_modules/@types/zrender": {
       "version": "4.0.6",
       "resolved": "https://registry.npmmirror.com/@types/zrender/-/zrender-4.0.6.tgz",
@@ -4120,6 +4145,17 @@
         "node": ">= 0.6"
       }
     },
+    "node_modules/core-js-pure": {
+      "version": "3.43.0",
+      "resolved": "https://registry.npmmirror.com/core-js-pure/-/core-js-pure-3.43.0.tgz",
+      "integrity": "sha512-i/AgxU2+A+BbJdMxh3v7/vxi2SbFqxiFmg6VsDwYB4jkucrd1BZNA9a9gphC0fYMG5IBSgQcbQnk865VCLe7xA==",
+      "hasInstallScript": true,
+      "license": "MIT",
+      "funding": {
+        "type": "opencollective",
+        "url": "https://opencollective.com/core-js"
+      }
+    },
     "node_modules/cors": {
       "version": "2.8.5",
       "resolved": "https://registry.npmmirror.com/cors/-/cors-2.8.5.tgz",
@@ -4165,6 +4201,13 @@
         "node": ">= 8"
       }
     },
+    "node_modules/crypto-js": {
+      "version": "4.2.0",
+      "resolved": "https://registry.npmmirror.com/crypto-js/-/crypto-js-4.2.0.tgz",
+      "integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
+      "license": "MIT",
+      "optional": true
+    },
     "node_modules/css-select": {
       "version": "5.2.2",
       "resolved": "https://registry.npmmirror.com/css-select/-/css-select-5.2.2.tgz",
@@ -5222,6 +5265,12 @@
         "node": ">=0.10.0"
       }
     },
+    "node_modules/idb-keyval": {
+      "version": "6.2.1",
+      "resolved": "https://registry.npmmirror.com/idb-keyval/-/idb-keyval-6.2.1.tgz",
+      "integrity": "sha512-8Sb3veuYCyrZL+VBt9LJfZjLUPWVvqn8tG28VqYNFCo43KHcKuq+b4EiXGeuaLAQWL2YmyDgMp2aSpH9JHsEQg==",
+      "license": "Apache-2.0"
+    },
     "node_modules/ignore-walk": {
       "version": "7.0.0",
       "resolved": "https://registry.npmmirror.com/ignore-walk/-/ignore-walk-7.0.0.tgz",
@@ -7059,6 +7108,47 @@
         "node": "^20.17.0 || >=22.9.0"
       }
     },
+    "node_modules/parse": {
+      "version": "6.1.1",
+      "resolved": "https://registry.npmmirror.com/parse/-/parse-6.1.1.tgz",
+      "integrity": "sha512-zf70XcHKesDcqpO2RVKyIc1l7pngxBsYQVl0Yl/A38pftOSP8BQeampqqLEqMknzUetNZy8B+wrR3k5uTQDXOw==",
+      "license": "Apache-2.0",
+      "dependencies": {
+        "@babel/runtime-corejs3": "7.27.0",
+        "idb-keyval": "6.2.1",
+        "react-native-crypto-js": "1.0.0",
+        "uuid": "10.0.0",
+        "ws": "8.18.1",
+        "xmlhttprequest": "1.8.0"
+      },
+      "engines": {
+        "node": "18 || 19 || 20 || 22"
+      },
+      "optionalDependencies": {
+        "crypto-js": "4.2.0"
+      }
+    },
+    "node_modules/parse/node_modules/ws": {
+      "version": "8.18.1",
+      "resolved": "https://registry.npmmirror.com/ws/-/ws-8.18.1.tgz",
+      "integrity": "sha512-RKW2aJZMXeMxVpnZ6bck+RswznaxmzdULiBr6KY7XkTnW8uvt0iT9H5DkHUChXrc+uurzwa0rVI16n/Xzjdz1w==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=10.0.0"
+      },
+      "peerDependencies": {
+        "bufferutil": "^4.0.1",
+        "utf-8-validate": ">=5.0.2"
+      },
+      "peerDependenciesMeta": {
+        "bufferutil": {
+          "optional": true
+        },
+        "utf-8-validate": {
+          "optional": true
+        }
+      }
+    },
     "node_modules/parse5": {
       "version": "7.3.0",
       "resolved": "https://registry.npmmirror.com/parse5/-/parse5-7.3.0.tgz",
@@ -7339,6 +7429,12 @@
         "node": ">= 0.8"
       }
     },
+    "node_modules/react-native-crypto-js": {
+      "version": "1.0.0",
+      "resolved": "https://registry.npmmirror.com/react-native-crypto-js/-/react-native-crypto-js-1.0.0.tgz",
+      "integrity": "sha512-FNbLuG/HAdapQoybeZSoes1PWdOj0w242gb+e1R0hicf3Gyj/Mf8M9NaED2AnXVOX01b2FXomwUiw1xP1K+8sA==",
+      "license": "MIT"
+    },
     "node_modules/readdirp": {
       "version": "4.1.2",
       "resolved": "https://registry.npmmirror.com/readdirp/-/readdirp-4.1.2.tgz",
@@ -7360,6 +7456,12 @@
       "dev": true,
       "license": "Apache-2.0"
     },
+    "node_modules/regenerator-runtime": {
+      "version": "0.14.1",
+      "resolved": "https://registry.npmmirror.com/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz",
+      "integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==",
+      "license": "MIT"
+    },
     "node_modules/require-directory": {
       "version": "2.1.1",
       "resolved": "https://registry.npmmirror.com/require-directory/-/require-directory-2.1.1.tgz",
@@ -8491,6 +8593,19 @@
         "node": ">= 0.4.0"
       }
     },
+    "node_modules/uuid": {
+      "version": "10.0.0",
+      "resolved": "https://registry.npmmirror.com/uuid/-/uuid-10.0.0.tgz",
+      "integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
+      "funding": [
+        "https://github.com/sponsors/broofa",
+        "https://github.com/sponsors/ctavan"
+      ],
+      "license": "MIT",
+      "bin": {
+        "uuid": "dist/bin/uuid"
+      }
+    },
     "node_modules/validate-npm-package-license": {
       "version": "3.0.4",
       "resolved": "https://registry.npmmirror.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz",
@@ -8847,6 +8962,15 @@
         }
       }
     },
+    "node_modules/xmlhttprequest": {
+      "version": "1.8.0",
+      "resolved": "https://registry.npmmirror.com/xmlhttprequest/-/xmlhttprequest-1.8.0.tgz",
+      "integrity": "sha512-58Im/U0mlVBLM38NdZjHyhuMtCqa61469k2YP/AaPbvCoV9aQGUpbJBj1QRm2ytRiVQBD/fsw7L2bJGDVQswBA==",
+      "license": "MIT",
+      "engines": {
+        "node": ">=0.4.0"
+      }
+    },
     "node_modules/y18n": {
       "version": "5.0.8",
       "resolved": "https://registry.npmmirror.com/y18n/-/y18n-5.0.8.tgz",

+ 2 - 0
travel-web/package.json

@@ -29,6 +29,7 @@
     "@fortawesome/fontawesome-free": "^6.7.2",
     "@types/echarts": "^4.9.22",
     "echarts": "^5.6.0",
+    "parse": "^6.1.1",
     "rxjs": "~7.8.0",
     "swiper": "^11.2.10",
     "tslib": "^2.3.0",
@@ -40,6 +41,7 @@
     "@angular/compiler-cli": "^20.0.0",
     "@types/jasmine": "~5.1.0",
     "@types/node": "^24.0.10",
+    "@types/parse": "^3.0.9",
     "jasmine-core": "~5.7.0",
     "karma": "~6.4.0",
     "karma-chrome-launcher": "~3.2.0",

+ 113 - 59
travel-web/src/lib/ncloud.ts

@@ -273,84 +273,138 @@ export class CloudUser extends CloudObject {
 
     /** 登录 */
     // CloudUser.ts
-async login(username: string, password: string) {
-    const query = new CloudQuery("UserTravel");
-    query.equalTo("username", username);
-    query.equalTo("password", password); // 注意:生产环境应加密比较
-    
+async login(identifier: string, password: string): Promise<CloudUser | null> {
     try {
-        const user = await query.first();
-        if (!user) {
-            console.error('用户名或密码错误');
-            return null;
-        }
-        
-        // 登录成功,生成会话令牌
+      // 创建查询条件数组
+      const conditions = [
+        { username: identifier },
+        { email: identifier },
+        { phone: identifier }
+      ];
+
+      const queries = conditions.map(cond => {
+        const query = new CloudQuery(this.className);
+        query.equalTo(Object.keys(cond)[0], Object.values(cond)[0]);
+        return query.find();
+      });
+
+      const results = await Promise.all(queries);
+      
+      // 合并结果并去重
+      const users = results.flat().filter((user, index, self) =>
+        index === self.findIndex(u => u.id === user.id)
+      );
+
+      // 查找匹配密码的用户
+      const user = users.find(u => u.get('password') === password);
+
+      if (user) {
+        // 设置当前用户信息
         this.id = user.id;
-        this.sessionToken = `custom_${user.id}_${Date.now()}`;
-        this.data = user.data;
+        this.set(user.data);
+        this.sessionToken = `session_${Date.now()}`;
         
+        // 保存到本地存储
         localStorage.setItem("NCloud/dev/User", JSON.stringify({
-            ...this.data,
-            objectId: this.id,
-            sessionToken: this.sessionToken
+          ...this.data,
+          objectId: this.id,
+          sessionToken: this.sessionToken
         }));
         
         return this;
+      }
+      return null;
     } catch (error) {
-        console.error('登录查询失败:', error);
-        return null;
+      console.error('登录失败:', error);
+      throw new Error('登录失败,请检查网络连接');
     }
-}
+  }
 
     /** 登出 */
-    async logout() {
-        this.clearUserCache();
-        return true; // 无需调用后端接口,直接清除本地状态
-    }
-    clearUserCache() {
-        // 清除用户信息
-        localStorage.removeItem("NCloud/dev/User")
-        this.id = undefined;
-        this.sessionToken = null;
-        this.data = {};
-    }
+    async logout(): Promise<boolean> {
+  try {
+    localStorage.removeItem("NCloud/dev/User");
+    this.id = undefined;
+    this.sessionToken = null;
+    this.data = {};
+    return true;
+  } catch (error) {
+    console.error('登出失败:', error);
+    throw error;
+  }
+}
+
+clearUserCache() {
+    this.id = undefined;
+    this.sessionToken = null;
+    this.data = {};
+    localStorage.removeItem("NCloud/dev/User");
+}
 
     /** 注册 */
     // CloudUser.ts
-async signUp(username: string, password: string, additionalData: Record<string, any> = {}) {
-    const userData = {
-        username,
-        password,
-        ...additionalData
-    };
-
-    // 关键修改:使用自定义表的创建接口
-    const response = await fetch(serverURL + `/classes/Usertable`, {
-        headers: {
-            "x-parse-application-id": "dev",
-            "Content-Type": "application/json"
-        },
-        body: JSON.stringify(userData),
-        method: "POST"
+async signUp(username: string, password: string, additionalData: Record<string, any> = {}): Promise<CloudUser | null> {
+    try {
+      // 检查用户名是否已存在
+      const usernameQuery = new CloudQuery(this.className);
+      usernameQuery.equalTo("username", username);
+      const existingUsers = await usernameQuery.find();
+      
+      if (existingUsers.length > 0) {
+        throw new Error('用户名已被使用');
+      }
+      
+      // 检查邮箱是否已存在
+      if (additionalData["email"]) {
+        const emailQuery = new CloudQuery(this.className);
+        emailQuery.equalTo("email", additionalData["email"]);
+        const existingEmails = await emailQuery.find();
+        
+        if (existingEmails.length > 0) {
+          throw new Error('邮箱已被注册');
+        }
+      }
+      
+      // 检查手机号是否已存在
+      if (additionalData["phone"]) {
+        const phoneQuery = new CloudQuery(this.className);
+        phoneQuery.equalTo("phone", additionalData["phone"]);
+        const existingPhones = await phoneQuery.find();
+        
+        if (existingPhones.length > 0) {
+          throw new Error('手机号已被注册');
+        }
+      }
+    
+    // 创建新用户
+    const userObj = new CloudObject(this.className);
+    userObj.set({
+      username,
+      password,
+      ...additionalData,
+      createdAt: new Date(),
+      updatedAt: new Date()
     });
-
-    const result = await response?.json();
-    if (result?.error) {
-        console.error('注册失败:', result.error);
-        return null;
-    }
-
-    // 保存用户信息到缓存
-    this.id = result.objectId;
-    this.sessionToken = `custom_${result.objectId}_${Date.now()}`; // 自定义会话令牌
-    this.data = result;
+    
+    const savedUser = await userObj.save();
+    
+    // 设置当前用户信息
+    this.id = savedUser.id;
+    this.set(savedUser.data);
+    this.sessionToken = `session_${Date.now()}`;
+    
+    // 保存到本地存储
     localStorage.setItem("NCloud/dev/User", JSON.stringify({
-        ...result,
-        sessionToken: this.sessionToken
+      ...this.data,
+      objectId: this.id,
+      sessionToken: this.sessionToken
     }));
     
     return this;
+  } catch (error) {
+    console.error('注册失败:', error);
+    throw error;
+  }
 }
 
     override async save() {

+ 6 - 1
travel-web/src/modules/shared/nav-pc-top-menu/nav-pc-top-menu.html

@@ -70,7 +70,7 @@
                     <form (ngSubmit)="login()">
                         <div class="form-group">
                             <i class="fas fa-user"></i>
-                            <input type="text" placeholder="用户名/手机号" [(ngModel)]="loginUsername" name="loginUsername" required>
+                            <input type="text" placeholder="用户名/手机号/邮箱" [(ngModel)]="loginUsername" name="loginUsername" required>
                         </div>
                         <div class="form-group">
                             <i class="fas fa-lock"></i>
@@ -97,6 +97,7 @@
                                 <button class="social-btn weibo"><i class="fab fa-weibo"></i></button>
                             </div>
                         </div>
+                        <div class="error-message" *ngIf="loginError">{{ loginError }}</div>
                     </form>
                 } @else {
                     <form (ngSubmit)="register()">
@@ -107,6 +108,9 @@
                         <div class="form-group">
                             <i class="fas fa-envelope"></i>
                             <input type="email" placeholder="邮箱" [(ngModel)]="registerEmail" name="registerEmail" required>
+                            @if (emailError) {
+                                    <div class="error-tip">邮箱格式不正确</div>
+                                }
                         </div>
                         <div class="form-group">
                             <i class="fas fa-phone"></i>
@@ -133,6 +137,7 @@
                                 注册
                             }
                         </button>
+                        <div class="error-message" *ngIf="registerError">{{ registerError }}</div>
                     </form>
                 }
             </div>

+ 21 - 0
travel-web/src/modules/shared/nav-pc-top-menu/nav-pc-top-menu.scss

@@ -457,4 +457,25 @@
     .auth-modal {
         width: 90%;
     }
+}
+
+
+
+.error-tip {
+  position: absolute;
+  bottom: -20px;
+  left: 0;
+  color: #e74c3c;
+  font-size: 0.8rem;
+  margin-top: 4px;
+}
+
+.error-message {
+  color: #e74c3c;
+  margin-top: 10px;
+  font-size: 0.9rem;
+  text-align: center;
+  background: rgba(231, 76, 60, 0.1);
+  padding: 8px;
+  border-radius: 4px;
 }

+ 94 - 37
travel-web/src/modules/shared/nav-pc-top-menu/nav-pc-top-menu.ts

@@ -2,7 +2,7 @@ import { Component, OnInit } from '@angular/core';
 import { CommonModule } from '@angular/common';
 import { Router, RouterModule } from '@angular/router';
 import { FormsModule } from '@angular/forms';
-import { CloudUser } from '../../../lib/ncloud'; 
+import { CloudObject, CloudQuery, CloudUser } from '../../../lib/ncloud';
 
 @Component({
   selector: 'app-nav-pc-top-menu',
@@ -12,11 +12,15 @@ import { CloudUser } from '../../../lib/ncloud';
   styleUrls: ['./nav-pc-top-menu.scss']
 })
 export class NavPcTopMenu implements OnInit {
-  user: any = null;
+  user: CloudUser | null = null;
   userAvatar: string | null = null;
   userInitials: string = '';
+  loginError: string = '';
+  registerError: string = '';
   isLoading: boolean = true;
   showMenu: boolean = false;
+  loginIdentifier: string = '';
+  emailError: boolean = false;
   
   // 登录注册模态框相关
   showAuthModal: boolean = false;
@@ -27,6 +31,7 @@ export class NavPcTopMenu implements OnInit {
   loginPassword: string = '';
   rememberMe: boolean = true;
   isLoggingIn: boolean = false;
+
   
   // 注册表单
   registerUsername: string = '';
@@ -40,29 +45,39 @@ export class NavPcTopMenu implements OnInit {
   constructor(private router: Router) {}
 
   async ngOnInit() {
-    // 初始化CloudUser
-    this.user = new CloudUser();
-    
     // 尝试获取当前用户
     try {
-      const currentUser = await this.user.current();//尝试获取当前登录用户
+      this.user = new CloudUser();
+      const currentUser = await this.user.current();
+      
       if (currentUser && this.user.id) {
-        this.user = currentUser;//登陆状态有效,保存用户信息
-        this.generateUserInitials();//生成头像首字母
+        this.user = currentUser;
+        this.generateUserInitials();
+      } else {
+        this.user = null;
       }
     } catch (error) {
       console.error('获取用户信息失败:', error);
+      this.user = null;
     } finally {
-      this.isLoading = false;//关闭加载态
+      this.isLoading = false;
     }
   }
 
   // 生成用户头像首字母
   generateUserInitials() {
+    if (!this.user) return;
+    
     const username = this.user.get('username') || '';
     if (username.length > 0) {
       this.userInitials = username.charAt(0).toUpperCase();
     }
+    
+    // 如果有头像URL,则设置
+    const avatar = this.user.get('avatar');
+    if (avatar && typeof avatar === 'string') {
+      this.userAvatar = avatar;
+    }
   }
 
   toggleMenu() {
@@ -72,12 +87,11 @@ export class NavPcTopMenu implements OnInit {
   openAuthModal(type: 'login' | 'register') {
     this.authType = type;
     this.showAuthModal = true;
-    this.showMenu = false; // 关闭用户菜单
+    this.showMenu = false;
   }
 
   closeAuthModal() {
     this.showAuthModal = false;
-    // 重置表单状态
     this.isLoggingIn = false;
     this.isRegistering = false;
   }
@@ -86,44 +100,76 @@ export class NavPcTopMenu implements OnInit {
     this.authType = type;
   }
 
-  async login() {
-    if (!this.loginUsername || !this.loginPassword) {//检验表单必填项
+async login() {
+    if (!this.loginIdentifier || !this.loginPassword) {
+      this.loginError = '请输入用户名/手机号/邮箱和密码';
       return;
     }
     
-    this.isLoggingIn = true; // 显示“登录中”加载态
+    this.isLoggingIn = true;
+    this.loginError = '';
     
     try {
-      const loggedInUser = await this.user.login(this.loginUsername, this.loginPassword);
-      if (loggedInUser) {
-        this.user = loggedInUser;// 保存登录后的用户信息
-        this.generateUserInitials();// 更新头像首字母
-        this.closeAuthModal();// 关闭模态框
+      const user = new CloudUser();
+      const loggedIn = await user.login(
+        this.loginIdentifier, 
+        this.loginPassword
+      );
+      
+      if (loggedIn) {
+        this.user = loggedIn;
+        this.generateUserInitials();
+        this.closeAuthModal();
+      } else {
+        this.loginError = '用户名或密码错误';
       }
     } catch (error) {
       console.error('登录失败:', error);
-      // 实际应用中应显示错误提示
+      this.loginError = '登录失败,请稍后重试';
     } finally {
-      this.isLoggingIn = false;// 关闭加载态
+      this.isLoggingIn = false;
     }
   }
 
+
   async register() {
-    if (!this.registerUsername || !this.registerEmail || !this.registerPassword) {
+    // 重置错误状态
+    this.registerError = '';
+    this.emailError = false;
+    // 表单验证
+    if (!this.registerUsername) {
+      alert('请输入用户名');
+      return;
+    }
+    
+    if (!this.registerEmail) {
+      alert('请输入邮箱');
+      return;
+    }else {
+      const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
+      if (!emailRegex.test(this.registerEmail)) {
+        this.emailError = true;
+        this.registerError = '邮箱格式不正确';
+        return;
+      }
+    }
+    
+    if (!this.registerPassword) {
+      alert('请输入密码');
       return;
     }
     
     if (this.registerPassword !== this.registerPasswordConfirm) {
-      // 实际应用中应显示错误提示
-      return;// 校验密码一致
+      alert('两次输入的密码不一致');
+      return;
     }
     
     if (!this.acceptTerms) {
-      // 实际应用中应显示错误提示
-      return; // 校验协议勾选
+      alert('请阅读并同意用户协议和隐私政策');
+      return;
     }
     
-    this.isRegistering = true;// 显示“注册中”加载态
+  this.isRegistering = true;
     
     try {
       const additionalData = {
@@ -131,35 +177,46 @@ export class NavPcTopMenu implements OnInit {
         phone: this.registerPhone
       };
       
-      const newUser = await this.user.signUp(
+      const user = new CloudUser();
+      const newUser = await user.signUp(
         this.registerUsername, 
         this.registerPassword, 
         additionalData
       );
       
       if (newUser) {
-        this.user = newUser;// 保存注册后的用户信息
-        this.generateUserInitials();// 更新头像首字母
-        this.closeAuthModal();// 关闭模态框
+        this.user = newUser;
+        this.generateUserInitials();
+        this.closeAuthModal();
+        // 注册成功后自动登录
+        this.loginIdentifier = this.registerUsername;
+        this.loginPassword = this.registerPassword;
+        await this.login();
+      } else {
+        this.registerError = '注册失败,请稍后重试';
       }
-    } catch (error) {
+    } catch (error: any) {
       console.error('注册失败:', error);
-      // 实际应用中应显示错误提示
+      this.registerError = error.message || '注册失败,请稍后重试';
     } finally {
       this.isRegistering = false;
     }
   }
 
+
   async logout() {
+    if (!this.user) return;
+    
     try {
-      await this.user.logout();// 调用后端退出接口
-      this.user = null; // 清除前端用户信息
+      await this.user.logout();
+      this.user = null;
       this.userAvatar = null;
       this.userInitials = '';
-      this.showMenu = false; // 关闭用户菜单
-      this.router.navigate(['/home']); // 跳转到首页
+      this.showMenu = false;
+      this.router.navigate(['/home']);
     } catch (error) {
       console.error('退出登录失败:', error);
+      alert('退出登录失败: ' + (error instanceof Error ? error.message : '未知错误'));
     }
   }
 }