137 lines
4.5 KiB
Python
137 lines
4.5 KiB
Python
"""
|
|
用户认证 API 路由
|
|
使用邮箱和密码进行登录/注册
|
|
"""
|
|
from flask import Blueprint, request, jsonify, session
|
|
from db import create_user, verify_user
|
|
|
|
bp = Blueprint('auth', __name__, url_prefix='/api')
|
|
|
|
|
|
@bp.route('/register', methods=['POST'])
|
|
def register():
|
|
"""用户注册"""
|
|
try:
|
|
data = request.get_json()
|
|
email = data.get('email', '').strip().lower()
|
|
password = data.get('password', '')
|
|
|
|
if not email or not password:
|
|
return jsonify({'success': False, 'error': '邮箱和密码不能为空'}), 400
|
|
|
|
# 验证邮箱格式
|
|
import re
|
|
if not re.match(r'^[^\s@]+@[^\s@]+\.[^\s@]+$', email):
|
|
return jsonify({'success': False, 'error': '请输入有效的邮箱地址'}), 400
|
|
|
|
if len(password) < 6:
|
|
return jsonify({'success': False, 'error': '密码至少6位'}), 400
|
|
|
|
user, error = create_user(email, password)
|
|
if error:
|
|
return jsonify({'success': False, 'error': error}), 400
|
|
|
|
# 自动登录
|
|
session['user_id'] = user['id']
|
|
session['username'] = user['username'] # username存的是email
|
|
session['email'] = user['username']
|
|
|
|
return jsonify({
|
|
'success': True,
|
|
'user': {'id': user['id'], 'email': user['username'], 'username': user['username'].split('@')[0]}
|
|
})
|
|
except Exception as e:
|
|
return jsonify({'success': False, 'error': str(e)}), 500
|
|
|
|
|
|
@bp.route('/login', methods=['POST'])
|
|
def login():
|
|
"""用户登录"""
|
|
try:
|
|
data = request.get_json()
|
|
email = data.get('email', '').strip().lower()
|
|
password = data.get('password', '')
|
|
|
|
if not email or not password:
|
|
return jsonify({'success': False, 'error': '邮箱和密码不能为空'}), 400
|
|
|
|
user, error = verify_user(email, password)
|
|
if error:
|
|
return jsonify({'success': False, 'error': error}), 400
|
|
|
|
session['user_id'] = user['id']
|
|
session['username'] = user['username']
|
|
session['email'] = user['username']
|
|
|
|
return jsonify({
|
|
'success': True,
|
|
'user': {'id': user['id'], 'email': user['username'], 'username': user['username'].split('@')[0]}
|
|
})
|
|
except Exception as e:
|
|
return jsonify({'success': False, 'error': str(e)}), 500
|
|
|
|
|
|
@bp.route('/logout', methods=['POST'])
|
|
def logout():
|
|
"""用户登出"""
|
|
session.clear()
|
|
return jsonify({'success': True})
|
|
|
|
|
|
@bp.route('/change_password', methods=['POST'])
|
|
def change_password():
|
|
"""修改密码"""
|
|
if 'user_id' not in session:
|
|
return jsonify({'success': False, 'error': '请先登录'}), 401
|
|
|
|
try:
|
|
data = request.get_json()
|
|
old_password = data.get('old_password', '')
|
|
new_password = data.get('new_password', '')
|
|
|
|
if not old_password or not new_password:
|
|
return jsonify({'success': False, 'error': '请填写所有字段'}), 400
|
|
|
|
if len(new_password) < 6:
|
|
return jsonify({'success': False, 'error': '新密码至少6位'}), 400
|
|
|
|
from db import change_user_password
|
|
success, error = change_user_password(session['user_id'], old_password, new_password)
|
|
|
|
if success:
|
|
return jsonify({'success': True})
|
|
else:
|
|
return jsonify({'success': False, 'error': error}), 400
|
|
except Exception as e:
|
|
return jsonify({'success': False, 'error': str(e)}), 500
|
|
|
|
|
|
@bp.route('/me', methods=['GET'])
|
|
def get_current_user():
|
|
"""获取当前用户"""
|
|
if 'user_id' in session:
|
|
email = session.get('email', session.get('username', ''))
|
|
is_admin = False
|
|
try:
|
|
from db import get_db
|
|
conn = get_db()
|
|
if conn:
|
|
cur = conn.cursor()
|
|
cur.execute("SELECT is_admin FROM users WHERE id = %s", (session['user_id'],))
|
|
row = cur.fetchone()
|
|
if row:
|
|
is_admin = bool(row[0])
|
|
conn.close()
|
|
except Exception:
|
|
pass
|
|
return jsonify({
|
|
'success': True,
|
|
'user': {
|
|
'id': session['user_id'],
|
|
'email': email,
|
|
'username': email.split('@')[0] if '@' in email else email,
|
|
'is_admin': is_admin
|
|
}
|
|
})
|
|
return jsonify({'success': False, 'user': None})
|