diff --git a/controller/LoginController.py b/controller/LoginController.py index b048e10..dcf1c0e 100644 --- a/controller/LoginController.py +++ b/controller/LoginController.py @@ -1,4 +1,4 @@ -from robyn import jsonify, Response +from robyn import jsonify, Response, Request from app import app from datetime import datetime, timedelta import uuid @@ -12,11 +12,34 @@ def generate_token() -> str: """生成随机token""" return str(uuid.uuid4()) +def validate_token(token: str) -> dict: + """验证token并返回用户信息""" + if not token or token not in TEMP_TOKENS: + return None + + # 检查token是否过期 + if datetime.now() > TEMP_TOKENS[token]["expires_at"]: + del TEMP_TOKENS[token] + return None + + return TEMP_TOKENS[token]["user"] + @app.post("/api/login") def login_route(request): """登录接口""" try: - request_data = json.loads(request.body) if request.body else {} + # 解析请求数据 + request_data = {} + if request.body: + try: + request_data = json.loads(request.body) + except json.JSONDecodeError: + pass + + # 如果JSON解析失败,尝试从form_data获取 + if not request_data and hasattr(request, 'form_data'): + request_data = getattr(request, 'form_data', {}) + username = request_data.get("username", "").strip() password = request_data.get("password", "").strip() remember = request_data.get("remember", False) @@ -83,26 +106,28 @@ def user_info_route(request): query_params = getattr(request, 'query_params', {}) token = query_params.get("token", "") - # 验证token是否存在 - if not token or token not in TEMP_TOKENS: + # 验证token + user = validate_token(token) + if not user: return Response( status_code=401, description=jsonify({"success": False, "message": "未登录或登录已过期"}), headers={"Content-Type": "application/json; charset=utf-8"} ) - # 检查token是否过期 - if datetime.now() > TEMP_TOKENS[token]["expires_at"]: - del TEMP_TOKENS[token] - return Response( - status_code=401, - description=jsonify({"success": False, "message": "登录已过期"}), - headers={"Content-Type": "application/json; charset=utf-8"} - ) + # 从数据库获取最新的用户信息 + username = user["username"] + db_user = user_service.get_user_info(username) + if db_user: + # 更新TEMP_TOKENS中的用户信息 + TEMP_TOKENS[token]["user"] = db_user + user_info = db_user + else: + user_info = user return Response( status_code=200, - description=jsonify({"success": True, "user": TEMP_TOKENS[token]["user"]}), + description=jsonify({"success": True, "user": user_info}), headers={"Content-Type": "application/json; charset=utf-8"} ) except Exception as e: @@ -113,140 +138,100 @@ def user_info_route(request): ) @app.post("/api/updateAvatar") -def update_avatar_route(request): +async def update_avatar_route(request: Request): """更新用户头像接口""" try: - # 打印调试信息 - print(f"请求类型: {type(request)}") - print(f"请求属性: {dir(request)}") - - # 在Robyn中,文件上传的数据存储在request.files中 - # 表单字段存储在request.form中 - form_data = getattr(request, 'form', {}) - files_data = getattr(request, 'files', {}) - - print(f"表单数据: {form_data}") - print(f"文件数据: {files_data}") - print(f"表单数据类型: {type(form_data)}") - print(f"文件数据类型: {type(files_data)}") - - # 获取token - 尝试多种方式获取 + # 从files中获取文件和token + avatar_file = request.files.get('avatar') if hasattr(request, 'files') else None token = None - # 方法1: 从form_data中获取 - if isinstance(form_data, dict) and "token" in form_data: - token = form_data["token"] - print(f"从form_data获取token: {token}") - - # 方法2: 如果form_data不是字典,尝试其他方式 - if not token and hasattr(form_data, 'get'): - token = form_data.get("token", "") - print(f"通过form_data.get()获取token: {token}") + # 从form_data中获取token + if hasattr(request, 'form_data'): + token = request.form_data.get('token') + + # 如果files中没有直接找到'avatar',尝试获取第一个文件 + if not avatar_file and hasattr(request, 'files') and request.files: + first_key = list(request.files.keys())[0] + avatar_file = request.files[first_key] - # 方法3: 尝试从request的属性中直接获取 + # 如果form_data中没有token,尝试从headers获取 if not token: - # 尝试从request中获取所有可能的属性 - for attr_name in dir(request): - if 'token' in attr_name.lower() or 'form' in attr_name.lower(): - try: - attr_value = getattr(request, attr_name) - print(f"request.{attr_name}: {type(attr_value)} = {attr_value}") - - # 如果是字典类型,检查是否包含token - if isinstance(attr_value, dict) and 'token' in attr_value: - token = attr_value['token'] - print(f"从request.{attr_name}获取token: {token}") - break - except Exception as e: - print(f"访问request.{attr_name}时出错: {e}") - - # 方法4: 从查询参数中获取 - if not token: - query_params = getattr(request, 'query_params', {}) - if isinstance(query_params, dict) and "token" in query_params: - token = query_params["token"] - print(f"从查询参数获取token: {token}") - - # 方法5: 从headers中获取 - if not token: - headers = getattr(request, 'headers', {}) - if isinstance(headers, dict) and "Authorization" in headers: - auth_header = headers["Authorization"] - if auth_header.startswith("Bearer "): - token = auth_header[7:] - print(f"从Authorization头获取token: {token}") - - print(f"最终获取的token: {token}") - print(f"TEMP_TOKENS中的keys: {list(TEMP_TOKENS.keys())}") - + headers_dict = {} + if hasattr(request, 'headers'): + try: + headers_dict = dict(request.headers) + except: + pass + token = headers_dict.get('Authorization') or headers_dict.get('authorization') + + # 如果还是没有token,尝试从body中解析 + if not token and hasattr(request, 'body'): + try: + body_data = json.loads(request.body) + token = body_data.get('token') + except: + pass + # 验证token - if not token or token not in TEMP_TOKENS: - print(f"Token验证失败: {token}") + user = validate_token(token) + if not user: return Response( status_code=401, description=jsonify({"success": False, "message": "未登录或登录已过期"}), headers={"Content-Type": "application/json; charset=utf-8"} ) - # 检查token是否过期 - if datetime.now() > TEMP_TOKENS[token]["expires_at"]: - del TEMP_TOKENS[token] - print("Token已过期") + # 检查文件是否存在 + if not avatar_file: return Response( - status_code=401, - description=jsonify({"success": False, "message": "登录已过期"}), + status_code=400, + description=jsonify({"success": False, "message": "未上传头像文件"}), headers={"Content-Type": "application/json; charset=utf-8"} ) - # 获取上传的文件 - avatar_file = files_data.get("avatar") if isinstance(files_data, dict) else None - - # 如果没有通过"avatar"键获取到文件,尝试直接访问files_data的第一个元素 - if not avatar_file and isinstance(files_data, dict) and len(files_data) > 0: - # 获取第一个文件作为头像文件 - first_key = list(files_data.keys())[0] - avatar_file = files_data[first_key] - print(f"通过备用方法获取文件,键名: {first_key}") - - if not avatar_file: - print("未找到avatar文件") - print(f"可用的文件键: {list(files_data.keys()) if isinstance(files_data, dict) else '无法获取键列表'}") + # 获取文件内容和文件名 + file_content = None + filename = "" + + # Robyn框架中,files字典的值通常是字节数据 + if isinstance(avatar_file, bytes): + file_content = avatar_file + filename = list(request.files.keys())[0] if request.files else "avatar.jpg" + elif isinstance(avatar_file, str): + filename = avatar_file + else: + if avatar_file is not None: + # 尝试获取文件内容的其他方式 + if hasattr(avatar_file, 'content'): + file_content = avatar_file.content + elif hasattr(avatar_file, 'read'): + file_content = avatar_file.read() + filename = getattr(avatar_file, 'filename', 'avatar.jpg') + + # 如果我们有文件内容,继续处理 + if not file_content: return Response( status_code=400, - description=jsonify({"success": False, "message": "未上传头像文件"}), + description=jsonify({"success": False, "message": "无法读取文件内容"}), headers={"Content-Type": "application/json; charset=utf-8"} ) - print(f"获取的文件: {avatar_file}") - print(f"文件属性: {dir(avatar_file) if avatar_file else '无文件'}") + # 处理文件名 + if not filename: + filename = "avatar.jpg" + + file_extension = filename.split('.')[-1] if '.' in filename else 'jpg' - # 检查文件类型 - 使用多种方法验证 + # 验证文件类型 is_valid_image = False - file_extension = "" - # 方法1: 检查content_type - content_type = getattr(avatar_file, 'content_type', '') - if content_type and content_type.startswith("image/"): + # 通过扩展名验证 + if file_extension.lower() in ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']: is_valid_image = True - print(f"通过content_type验证: {content_type}") - - # 方法2: 检查文件名和扩展名 - filename = getattr(avatar_file, 'filename', '') - if filename: - file_extension = os.path.splitext(filename)[1].lower() - valid_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'] - if file_extension in valid_extensions: - is_valid_image = True - print(f"通过文件扩展名验证: {file_extension}") - - # 如果两种方法都失败,尝试读取文件头 + + # 如果扩展名验证失败,尝试读取文件头验证 if not is_valid_image: try: - # 读取文件前几个字节来检测文件类型 - file_content = avatar_file.read(1024) - avatar_file.seek(0) # 重置文件指针 - - # 检查常见图片格式的文件头 if (file_content.startswith(b'\xFF\xD8\xFF') or # JPEG file_content.startswith(b'\x89PNG\r\n\x1a\n') or # PNG file_content.startswith(b'GIF87a') or # GIF @@ -254,64 +239,47 @@ def update_avatar_route(request): file_content.startswith(b'BM') or # BMP file_content.startswith(b'RIFF') and b'WEBP' in file_content[:12]): # WebP is_valid_image = True - print(f"通过文件头验证成功") - else: - print(f"文件头验证失败,文件前16字节: {file_content[:16]}") - except Exception as e: - print(f"读取文件内容进行验证时出错: {e}") + except Exception: + pass if not is_valid_image: - print(f"文件类型验证失败 - content_type: {content_type}, filename: {filename}, extension: {file_extension}") return Response( status_code=400, description=jsonify({"success": False, "message": f"文件类型必须是图片 (支持的格式: JPG, PNG, GIF, BMP, WebP, SVG)"}), headers={"Content-Type": "application/json; charset=utf-8"} ) - # 获取文件内容 - file_content = avatar_file.file_data - print(f"读取的文件大小: {len(file_content)} 字节") - # 生成唯一的文件名 import time import random - filename = getattr(avatar_file, 'filename', '') - file_extension = filename.split('.')[-1] if '.' in filename else 'jpg' timestamp = int(time.time()) random_num = random.randint(1000, 9999) - username = TEMP_TOKENS[token]["user"]["username"] + username = user["username"] new_filename = f"{username}_{timestamp}_{random_num}.{file_extension}" - # 定义文件保存路径 - avatar_dir = "D:/zhishitupu/MedKG/resource/avatar" - file_path = f"{avatar_dir}/{new_filename}" - - print(f"保存文件到: {file_path}") + # 定义文件保存路径(使用相对路径) + current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + avatar_dir = os.path.join(current_dir, "resource", "avatar") + file_path = os.path.join(avatar_dir, new_filename) # 确保目录存在 - import os os.makedirs(avatar_dir, exist_ok=True) # 保存文件到磁盘 with open(file_path, "wb") as f: f.write(file_content) - print(f"文件保存成功") - # 更新用户头像到数据库,存储相对路径 avatar_relative_path = f"/resource/avatar/{new_filename}" success = user_service.update_user_avatar(username, avatar_relative_path) if not success: - print("数据库更新失败") return Response( status_code=500, description=jsonify({"success": False, "message": "更新头像失败"}), headers={"Content-Type": "application/json; charset=utf-8"} ) - print("数据库更新成功") - # 更新token中的用户信息 TEMP_TOKENS[token]["user"]["avatar"] = avatar_relative_path @@ -325,9 +293,6 @@ def update_avatar_route(request): headers={"Content-Type": "application/json; charset=utf-8"} ) except Exception as e: - print(f"更新头像异常: {str(e)}") - import traceback - traceback.print_exc() return Response( status_code=500, description=jsonify({"success": False, "message": f"更新头像失败: {str(e)}"}), @@ -338,23 +303,15 @@ def update_avatar_route(request): def update_password_route(request): """更新用户密码接口""" try: - print("开始处理密码更新请求") - # 解析请求数据 request_data = json.loads(request.body) if request.body else {} - print(f"请求数据: {request_data}") token = request_data.get("token", "") current_password = request_data.get("currentPassword", "") new_password = request_data.get("newPassword", "") - print(f"Token: {token}") - print(f"当前密码长度: {len(current_password)}") - print(f"新密码长度: {len(new_password)}") - # 验证输入 if not current_password or not new_password: - print("密码为空") return Response( status_code=400, description=jsonify({"success": False, "message": "当前密码和新密码不能为空"}), @@ -362,46 +319,29 @@ def update_password_route(request): ) # 验证token - if not token or token not in TEMP_TOKENS: - print(f"Token验证失败: {token}") + user = validate_token(token) + if not user: return Response( status_code=401, description=jsonify({"success": False, "message": "未登录或登录已过期"}), headers={"Content-Type": "application/json; charset=utf-8"} ) - # 检查token是否过期 - if datetime.now() > TEMP_TOKENS[token]["expires_at"]: - del TEMP_TOKENS[token] - print("Token已过期") - return Response( - status_code=401, - description=jsonify({"success": False, "message": "登录已过期"}), - headers={"Content-Type": "application/json; charset=utf-8"} - ) - # 获取用户信息 - username = TEMP_TOKENS[token]["user"]["username"] - print(f"用户名: {username}") + username = user["username"] # 验证当前密码 - user = user_service.get_user_by_username(username) - if not user: - print("用户不存在") + db_user = user_service.get_user_by_username(username) + if not db_user: return Response( status_code=404, description=jsonify({"success": False, "message": "用户不存在"}), headers={"Content-Type": "application/json; charset=utf-8"} ) - print(f"用户信息: {user}") - # 验证密码 - is_password_valid = user_service.verify_password(current_password, user["password"]) - print(f"密码验证结果: {is_password_valid}") - + is_password_valid = user_service.verify_password(current_password, db_user["password"]) if not is_password_valid: - print("当前密码不正确") return Response( status_code=401, description=jsonify({"success": False, "message": "当前密码不正确"}), @@ -410,69 +350,25 @@ def update_password_route(request): # 更新密码 success = user_service.update_user_password(username, new_password) - print(f"密码更新结果: {success}") - if not success: - print("密码更新失败") return Response( status_code=500, description=jsonify({"success": False, "message": "密码更新失败"}), headers={"Content-Type": "application/json; charset=utf-8"} ) - print("密码更新成功") return Response( status_code=200, description=jsonify({"success": True, "message": "密码更新成功"}), headers={"Content-Type": "application/json; charset=utf-8"} ) except Exception as e: - print(f"密码更新异常: {str(e)}") - import traceback - traceback.print_exc() return Response( status_code=500, description=jsonify({"success": False, "message": f"密码更新失败: {str(e)}"}), headers={"Content-Type": "application/json; charset=utf-8"} ) -@app.get("/api/test/db") -def test_db_connection(request): - """测试数据库连接""" - try: - # 检查数据库连接状态 - is_connected = user_service.mysql.is_connected() - print(f"数据库连接状态: {is_connected}") - - # 尝试查询用户表 - sql = "SELECT COUNT(*) as user_count FROM users" - result = user_service.mysql.execute_query(sql) - print(f"查询结果: {result}") - - # 打印当前的token信息用于调试 - print(f"当前TEMP_TOKENS: {TEMP_TOKENS}") - - return Response( - status_code=200, - description=jsonify({ - "success": True, - "message": "数据库连接测试成功", - "is_connected": is_connected, - "user_count": result[0]["user_count"] if result else 0, - "tokens": list(TEMP_TOKENS.keys()) # 返回当前有效的token列表 - }), - headers={"Content-Type": "application/json; charset=utf-8"} - ) - except Exception as e: - print(f"数据库连接测试失败: {str(e)}") - import traceback - traceback.print_exc() - return Response( - status_code=500, - description=jsonify({"success": False, "message": f"数据库连接测试失败: {str(e)}"}), - headers={"Content-Type": "application/json; charset=utf-8"} - ) - @app.after_request("/") def add_cors_headers(response): """添加CORS头,支持跨域请求""" diff --git a/controller/RegisterController.py b/controller/RegisterController.py new file mode 100644 index 0000000..07b2bfb --- /dev/null +++ b/controller/RegisterController.py @@ -0,0 +1,182 @@ +from robyn import jsonify, Response +from app import app +import os +import uuid +from service.UserService import user_service + +# 头像上传目录 +AVATAR_UPLOAD_FOLDER = 'resource/avatar' + +@app.post("/api/register") +def register_route(request): + """用户注册接口""" + try: + # 获取表单数据 + form_data = getattr(request, 'form_data', {}) if hasattr(request, 'form_data') else {} + + # 获取文件上传 + files = getattr(request, 'files', {}) if hasattr(request, 'files') else {} + + username = form_data.get("username", "").strip() + password = form_data.get("password", "").strip() + + # 验证必填字段 + if not username or not password: + return Response( + status_code=400, + description=jsonify({"success": False, "message": "用户名和密码不能为空"}), + headers={"Content-Type": "application/json; charset=utf-8"} + ) + + # 检查用户名是否已存在 + existing_user = user_service.get_user_by_username(username) + if existing_user: + return Response( + status_code=409, + description=jsonify({"success": False, "message": "用户名已存在"}), + headers={"Content-Type": "application/json; charset=utf-8"} + ) + + # 处理头像上传 + avatar_path = "/resource/avatar/4.png" # 默认头像 + + # 获取头像文件 + avatar_file = files.get('avatar') + + # 如果有头像文件,处理上传 + if avatar_file: + # 获取文件内容和文件名 + file_content = None + filename = "" + + # Robyn框架中,files字典的值通常是字节数据 + if isinstance(avatar_file, bytes): + file_content = avatar_file + filename = "avatar.jpg" + elif hasattr(avatar_file, 'content'): + file_content = avatar_file.content + filename = getattr(avatar_file, 'filename', 'avatar.jpg') + elif hasattr(avatar_file, 'read'): + file_content = avatar_file.read() + filename = getattr(avatar_file, 'filename', 'avatar.jpg') + else: + filename = avatar_file if isinstance(avatar_file, str) else 'avatar.jpg' + + # 如果我们有文件内容,继续处理 + if file_content: + # 处理文件名 + file_extension = filename.split('.')[-1] if '.' in filename else 'jpg' + + # 验证文件类型 + is_valid_image = False + + # 通过扩展名验证 + if file_extension.lower() in ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg']: + is_valid_image = True + + # 如果扩展名验证失败,尝试读取文件头验证 + if not is_valid_image: + try: + if (file_content.startswith(b'\xFF\xD8\xFF') or # JPEG + file_content.startswith(b'\x89PNG\r\n\x1a\n') or # PNG + file_content.startswith(b'GIF87a') or # GIF + file_content.startswith(b'GIF89a')): # GIF + is_valid_image = True + except: + pass + + if not is_valid_image: + return Response( + status_code=400, + description=jsonify({"success": False, "message": "不支持的图片格式"}), + headers={"Content-Type": "application/json; charset=utf-8"} + ) + + # 确保上传目录存在 + if not os.path.exists(AVATAR_UPLOAD_FOLDER): + os.makedirs(AVATAR_UPLOAD_FOLDER) + + # 生成唯一文件名 + unique_filename = f"{uuid.uuid4().hex}.{file_extension}" + file_path = os.path.join(AVATAR_UPLOAD_FOLDER, unique_filename) + + # 保存文件 + try: + with open(file_path, 'wb') as f: + f.write(file_content) + avatar_path = f"/{file_path}" + except Exception as e: + print(f"保存头像失败: {e}") + return Response( + status_code=500, + description=jsonify({"success": False, "message": "头像保存失败"}), + headers={"Content-Type": "application/json; charset=utf-8"} + ) + + # 创建用户 + user_id = user_service.create_user(username, password, avatar_path) + if user_id: + return Response( + status_code=201, + description=jsonify({ + "success": True, + "message": "注册成功", + "user": { + "id": user_id, + "username": username, + "avatar": avatar_path + } + }), + headers={"Content-Type": "application/json; charset=utf-8"} + ) + else: + return Response( + status_code=500, + description=jsonify({"success": False, "message": "注册失败,请稍后再试"}), + headers={"Content-Type": "application/json; charset=utf-8"} + ) + except Exception as e: + print(f"注册异常: {e}") + return Response( + status_code=500, + description=jsonify({"success": False, "message": f"注册失败: {str(e)}"}), + headers={"Content-Type": "application/json; charset=utf-8"} + ) + +@app.get("/api/checkUsername") +def check_username_route(request): + """检查用户名是否可用""" + try: + # 获取查询参数 + username = "" + + # 尝试从query_params获取 + if hasattr(request, 'query_params') and request.query_params: + username = request.query_params.get("username", "").strip() + + if not username: + return Response( + status_code=400, + description=jsonify({"success": False, "message": "用户名不能为空"}), + headers={"Content-Type": "application/json; charset=utf-8"} + ) + + # 检查用户名是否已存在 + existing_user = user_service.get_user_by_username(username) + + return Response( + status_code=200, + description=jsonify({ + "success": True, + "available": existing_user is None, + "message": "用户名可用" if not existing_user else "用户名已存在" + }), + headers={"Content-Type": "application/json; charset=utf-8"} + ) + except Exception as e: + print(f"检查用户名异常: {e}") + return Response( + status_code=500, + description=jsonify({"success": False, "message": f"检查失败: {str(e)}"}), + headers={"Content-Type": "application/json; charset=utf-8"} + ) \ No newline at end of file diff --git a/resource/avatar/1_1766477129_1706.jpg b/resource/avatar/1_1766477129_1706.jpg new file mode 100644 index 0000000..2c96fbf Binary files /dev/null and b/resource/avatar/1_1766477129_1706.jpg differ diff --git a/resource/avatar/2.jpg b/resource/avatar/2.jpg new file mode 100644 index 0000000..1c0c2d3 Binary files /dev/null and b/resource/avatar/2.jpg differ diff --git a/resource/avatar/4.png b/resource/avatar/4.png new file mode 100644 index 0000000..8f86dc4 Binary files /dev/null and b/resource/avatar/4.png differ diff --git a/resource/avatar/admin_1766388917_8519.jpg b/resource/avatar/admin_1766388917_8519.jpg new file mode 100644 index 0000000..1c0c2d3 Binary files /dev/null and b/resource/avatar/admin_1766388917_8519.jpg differ diff --git a/resource/avatar/admin_1766389471_9334.jpg b/resource/avatar/admin_1766389471_9334.jpg new file mode 100644 index 0000000..1c0c2d3 Binary files /dev/null and b/resource/avatar/admin_1766389471_9334.jpg differ diff --git a/resource/avatar/f8c6732809a04f74bc4f3856b949de5e.jpg b/resource/avatar/f8c6732809a04f74bc4f3856b949de5e.jpg new file mode 100644 index 0000000..2c96fbf Binary files /dev/null and b/resource/avatar/f8c6732809a04f74bc4f3856b949de5e.jpg differ diff --git a/service/UserService.py b/service/UserService.py index 1a7b9ac..fa765b8 100644 --- a/service/UserService.py +++ b/service/UserService.py @@ -29,10 +29,15 @@ class UserService: # 验证密码 - 使用bcrypt验证 if bcrypt.checkpw(password.encode('utf-8'), stored_password.encode('utf-8')): + avatar_path = user.get("avatar") + # 如果头像为空,设置默认头像 + if not avatar_path: + avatar_path = "/resource/avatar/4.png" + return { "id": user.get("id"), "username": user.get("username"), - "avatar": user.get("avatar") + "avatar": avatar_path } return None @@ -40,6 +45,27 @@ class UserService: print(f"验证用户失败: {e}") return None + def get_user_info(self, username: str) -> Optional[Dict[str, Any]]: + """获取用户信息(不验证密码)""" + try: + user = self.get_user_by_username(username) + if not user: + return None + + avatar_path = user.get("avatar") + # 如果头像为空,设置默认头像 + if not avatar_path: + avatar_path = "/resource/avatar/4.png" + + return { + "id": user.get("id"), + "username": user.get("username"), + "avatar": avatar_path + } + except Exception as e: + print(f"获取用户信息失败: {e}") + return None + def update_user_avatar(self, username: str, avatar_path: str) -> bool: """更新用户头像""" try: @@ -96,10 +122,50 @@ class UserService: except Exception as e: print(f"验证密码失败: {e}") return False + + def create_user(self, username: str, password: str, avatar_path: str = None) -> int: + """创建新用户""" + try: + # 检查数据库连接状态 + if not self.mysql.is_connected(): + print("数据库未连接,尝试重新连接...") + if not self.mysql.connect(): + print("数据库连接失败") + return 0 + + # 使用bcrypt加密密码 + hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8') + + # 设置默认头像 + if not avatar_path: + avatar_path = "/resource/avatar/4.png" + + # 插入新用户 + sql = "INSERT INTO users (username, password, avatar) VALUES (%s, %s, %s)" + print(f"执行SQL: {sql}") + print(f"参数: {username}, {hashed_password}, {avatar_path}") + + # 执行插入 + result = self.mysql.execute_update(sql, (username, hashed_password, avatar_path)) + + if result > 0: + # 获取插入的用户ID + id_sql = "SELECT LAST_INSERT_ID() as user_id" + id_result = self.mysql.execute_query(id_sql) + if id_result: + user_id = id_result[0].get("user_id", 0) + print(f"插入结果,用户ID: {user_id}") + return user_id + + return 0 + except Exception as e: + print(f"创建用户失败: {e}") + import traceback + traceback.print_exc() + return 0 # 创建全局用户服务实例 user_service = UserService() - # 初始化MySQL连接 def init_mysql_connection(): """初始化MySQL连接""" @@ -107,4 +173,4 @@ def init_mysql_connection(): return user_service.mysql.connect() except Exception as e: print(f"初始化MySQL连接失败: {e}") - return False \ No newline at end of file + return False diff --git a/vue/src/api/register.js b/vue/src/api/register.js new file mode 100644 index 0000000..7a0f90d --- /dev/null +++ b/vue/src/api/register.js @@ -0,0 +1,33 @@ +// src/api/register.js +import request from '@/utils/request'; + +/** + * 用户注册 + * 后端接口:POST /api/register + * @param {FormData} formData - 包含用户名、密码和头像的表单数据 + */ +export function register(formData) { + return request({ + url: '/api/register', + method: 'post', + data: formData, + headers: { + 'Content-Type': 'multipart/form-data' + } + }); +} + +/** + * 检查用户名是否可用 + * 后端接口:GET /api/checkUsername + * @param {string} username - 要检查的用户名 + */ +export function checkUsername(username) { + return request({ + url: '/api/checkUsername', + method: 'get', + params: { + username + } + }); +} \ No newline at end of file diff --git a/vue/src/router/index.js b/vue/src/router/index.js index 406d92d..a410e6a 100644 --- a/vue/src/router/index.js +++ b/vue/src/router/index.js @@ -1,5 +1,6 @@ import { createRouter, createWebHistory } from 'vue-router' import Login from '../system/Login.vue' +import Register from '../system/Register.vue' import Index from '../system/Index.vue' import Profile from '../system/Profile.vue' import Display from '../system/GraphDemo.vue' @@ -17,6 +18,11 @@ const routes = [ component: Login }, { + path: '/register', + name: 'Register', + component: Register + }, + { path: '/index', name: 'Index', component: Index diff --git a/vue/src/system/Login.vue b/vue/src/system/Login.vue index cb7e137..42b952f 100644 --- a/vue/src/system/Login.vue +++ b/vue/src/system/Login.vue @@ -73,7 +73,7 @@
@@ -152,6 +152,11 @@ const handleLogin = async () => { loading.value = false; } }; + +// 跳转到注册页面 +const goToRegister = () => { + router.push('/register'); +}; + + \ No newline at end of file