整合register端口进入login端口
This commit is contained in:
154
app.py
154
app.py
@@ -1897,7 +1897,7 @@ def send_verification_code():
|
||||
|
||||
@app.route('/api/auth/login-with-code', methods=['POST'])
|
||||
def login_with_verification_code():
|
||||
"""使用验证码登录"""
|
||||
"""使用验证码登录/注册(自动注册)"""
|
||||
try:
|
||||
data = request.get_json()
|
||||
credential = data.get('credential') # 手机号或邮箱
|
||||
@@ -1932,13 +1932,47 @@ def login_with_verification_code():
|
||||
|
||||
# 验证码正确,查找用户
|
||||
user = None
|
||||
is_new_user = False
|
||||
|
||||
if login_type == 'phone':
|
||||
user = User.query.filter_by(phone=credential).first()
|
||||
if not user:
|
||||
# 自动注册新用户
|
||||
is_new_user = True
|
||||
# 生成唯一用户名
|
||||
base_username = f"user_{credential}"
|
||||
username = base_username
|
||||
counter = 1
|
||||
while User.query.filter_by(username=username).first():
|
||||
username = f"{base_username}_{counter}"
|
||||
counter += 1
|
||||
|
||||
# 创建新用户
|
||||
user = User(username=username, phone=credential)
|
||||
user.phone_confirmed = True
|
||||
user.email = f"{username}@valuefrontier.temp" # 临时邮箱
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
elif login_type == 'email':
|
||||
user = User.query.filter_by(email=credential).first()
|
||||
if not user:
|
||||
# 自动注册新用户
|
||||
is_new_user = True
|
||||
# 从邮箱生成用户名
|
||||
email_prefix = credential.split('@')[0]
|
||||
base_username = f"user_{email_prefix}"
|
||||
username = base_username
|
||||
counter = 1
|
||||
while User.query.filter_by(username=username).first():
|
||||
username = f"{base_username}_{counter}"
|
||||
counter += 1
|
||||
|
||||
if not user:
|
||||
return jsonify({'success': False, 'error': '用户不存在'}), 404
|
||||
# 创建新用户
|
||||
user = User(username=username, email=credential)
|
||||
user.email_confirmed = True
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
# 清除验证码
|
||||
session.pop(session_key, None)
|
||||
@@ -1957,7 +1991,8 @@ def login_with_verification_code():
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'message': '登录成功',
|
||||
'message': '注册成功' if is_new_user else '登录成功',
|
||||
'isNewUser': is_new_user,
|
||||
'user': {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
@@ -1969,62 +2004,10 @@ def login_with_verification_code():
|
||||
}
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
print(f"验证码登录错误: {e}")
|
||||
return jsonify({'success': False, 'error': '登录失败'}), 500
|
||||
|
||||
|
||||
@app.route('/api/auth/register', methods=['POST'])
|
||||
def register():
|
||||
"""用户注册 - 使用Session"""
|
||||
username = request.form.get('username')
|
||||
email = request.form.get('email')
|
||||
password = request.form.get('password')
|
||||
|
||||
# 验证输入
|
||||
if not all([username, email, password]):
|
||||
return jsonify({'success': False, 'error': '所有字段都是必填的'}), 400
|
||||
|
||||
# 检查用户名和邮箱是否已存在
|
||||
if User.is_username_taken(username):
|
||||
return jsonify({'success': False, 'error': '用户名已存在'}), 400
|
||||
|
||||
if User.is_email_taken(email):
|
||||
return jsonify({'success': False, 'error': '邮箱已被使用'}), 400
|
||||
|
||||
try:
|
||||
# 创建新用户
|
||||
user = User(username=username, email=email)
|
||||
user.set_password(password)
|
||||
user.email_confirmed = True # 暂时默认已确认
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
# 自动登录
|
||||
session.permanent = True
|
||||
session['user_id'] = user.id
|
||||
session['username'] = user.username
|
||||
session['logged_in'] = True
|
||||
|
||||
# Flask-Login 登录
|
||||
login_user(user, remember=True)
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'message': '注册成功',
|
||||
'user': {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'nickname': user.nickname or user.username,
|
||||
'email': user.email
|
||||
}
|
||||
}), 201
|
||||
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
print(f"注册失败: {e}")
|
||||
return jsonify({'success': False, 'error': '注册失败,请重试'}), 500
|
||||
print(f"验证码登录/注册错误: {e}")
|
||||
return jsonify({'success': False, 'error': '登录失败'}), 500
|
||||
|
||||
|
||||
def send_sms_code(phone, code, template_id):
|
||||
@@ -2821,61 +2804,6 @@ def login_with_wechat():
|
||||
}), 500
|
||||
|
||||
|
||||
@app.route('/api/auth/register/wechat', methods=['POST'])
|
||||
def register_with_wechat():
|
||||
"""微信注册(保留用于特殊情况)"""
|
||||
data = request.get_json()
|
||||
session_id = data.get('session_id')
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
|
||||
if not all([session_id, username, password]):
|
||||
return jsonify({'error': '所有字段都是必填的'}), 400
|
||||
|
||||
# 验证session
|
||||
session = wechat_qr_sessions.get(session_id)
|
||||
if not session:
|
||||
return jsonify({'error': '微信验证失败或状态无效'}), 400
|
||||
|
||||
if User.query.filter_by(username=username).first():
|
||||
return jsonify({'error': '用户名已存在'}), 400
|
||||
|
||||
# 检查微信OpenID是否已被其他用户使用
|
||||
wechat_openid = session.get('wechat_openid')
|
||||
wechat_unionid = session.get('wechat_unionid')
|
||||
|
||||
if wechat_unionid and User.query.filter_by(wechat_union_id=wechat_unionid).first():
|
||||
return jsonify({'error': '该微信号已被其他用户绑定'}), 400
|
||||
if User.query.filter_by(wechat_open_id=wechat_openid).first():
|
||||
return jsonify({'error': '该微信号已被其他用户绑定'}), 400
|
||||
|
||||
# 创建用户
|
||||
try:
|
||||
wechat_info = session['user_info']
|
||||
user = User(username=username)
|
||||
user.set_password(password)
|
||||
# 使用清理后的昵称
|
||||
user.nickname = user._sanitize_nickname(wechat_info.get('nickname', username))
|
||||
user.avatar_url = wechat_info.get('avatar_url')
|
||||
user.wechat_open_id = wechat_openid
|
||||
user.wechat_union_id = wechat_unionid
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
# 清除session
|
||||
del wechat_qr_sessions[session_id]
|
||||
|
||||
return jsonify({
|
||||
'message': '注册成功',
|
||||
'user': user.to_dict()
|
||||
}), 201
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
print(f"WeChat register error: {e}")
|
||||
return jsonify({'error': '注册失败,请重试'}), 500
|
||||
|
||||
|
||||
@app.route('/api/account/wechat/unbind', methods=['POST'])
|
||||
def unbind_wechat_account():
|
||||
"""解绑当前登录用户的微信"""
|
||||
|
||||
@@ -212,59 +212,6 @@ export const AuthProvider = ({ children }) => {
|
||||
}
|
||||
};
|
||||
|
||||
// 注册方法
|
||||
const register = async (username, email, password) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
|
||||
const formData = new URLSearchParams();
|
||||
formData.append('username', username);
|
||||
formData.append('email', email);
|
||||
formData.append('password', password);
|
||||
|
||||
const response = await fetch(`/api/auth/register`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
credentials: 'include',
|
||||
body: formData
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok || !data.success) {
|
||||
throw new Error(data.error || '注册失败');
|
||||
}
|
||||
|
||||
// 注册成功后自动登录
|
||||
setUser(data.user);
|
||||
setIsAuthenticated(true);
|
||||
|
||||
toast({
|
||||
title: "注册成功",
|
||||
description: "欢迎加入价值前沿!",
|
||||
status: "success",
|
||||
duration: 3000,
|
||||
isClosable: true,
|
||||
});
|
||||
|
||||
// ⚡ 注册成功后显示欢迎引导(延迟2秒)
|
||||
setTimeout(() => {
|
||||
showWelcomeGuide();
|
||||
}, 2000);
|
||||
|
||||
return { success: true };
|
||||
|
||||
} catch (error) {
|
||||
logger.error('AuthContext', 'register', error);
|
||||
|
||||
// ❌ 移除错误 toast,静默失败
|
||||
return { success: false, error: error.message };
|
||||
} finally{
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 手机号注册
|
||||
const registerWithPhone = async (phone, code, username, password) => {
|
||||
@@ -475,7 +422,6 @@ export const AuthProvider = ({ children }) => {
|
||||
isLoading,
|
||||
updateUser,
|
||||
login,
|
||||
register,
|
||||
registerWithPhone,
|
||||
registerWithEmail,
|
||||
sendSmsCode,
|
||||
|
||||
Reference in New Issue
Block a user