前后端更新
This commit is contained in:
1 parent
a0c8721fbb
commit
24da604727
33 files changed
+1951
-580
No files matched your search
+411
-135
@@ -1,185 +1,215 @@
|
||||
"""
|
||||
backend/app/api/user.py
|
||||
文件用途:用户相关 API 路由
|
||||
引用文件:flask, models, decorators
|
||||
逻辑关系:提供用户登录、首页配置、收藏夹、常用问题等接口
|
||||
"""
|
||||
from flask import Blueprint, jsonify, request, g, current_app
|
||||
from flask import Blueprint, request, jsonify, current_app, url_for
|
||||
from app import db
|
||||
from app.models import User, Agent, UserFavoriteAgent, UserHomepageConfig, QuickQuestion, UserDefaultAgent
|
||||
from app.decorators import _get_current_user
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, Announcement
|
||||
from sqlalchemy.exc import IntegrityError, OperationalError
|
||||
from datetime import datetime, timedelta
|
||||
import uuid
|
||||
|
||||
user_bp = Blueprint('user', __name__)
|
||||
|
||||
def _get_current_user():
|
||||
"""
|
||||
Helper to get current user from headers
|
||||
"""
|
||||
user_id = request.headers.get('X-User-Id')
|
||||
if not user_id:
|
||||
return None
|
||||
return db.session.get(User, int(user_id))
|
||||
|
||||
@user_bp.route('/register', methods=['POST'])
|
||||
def register():
|
||||
"""
|
||||
User registration
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
|
||||
required_fields = ['username', 'password', 'email', 'real_name', 'employee_id', 'phone_number']
|
||||
for field in required_fields:
|
||||
if not data.get(field):
|
||||
return jsonify({'error': f'{field} is required'}), 400
|
||||
|
||||
if db.session.query(User).filter_by(username=data['username']).first():
|
||||
return jsonify({'error': 'Username already exists'}), 400
|
||||
if db.session.query(User).filter_by(email=data['email']).first():
|
||||
return jsonify({'error': 'Email already exists'}), 400
|
||||
if db.session.query(User).filter_by(employee_id=data['employee_id']).first():
|
||||
return jsonify({'error': 'Employee ID already exists'}), 400
|
||||
|
||||
try:
|
||||
user = User(
|
||||
username=data['username'],
|
||||
email=data['email'],
|
||||
real_name=data['real_name'],
|
||||
employee_id=data['employee_id'],
|
||||
phone_number=data['phone_number'],
|
||||
department=data.get('department'),
|
||||
role='user',
|
||||
status='active'
|
||||
)
|
||||
user.set_password(data['password'])
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({'message': 'Registration successful', 'id': user.id}), 201
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@user_bp.route('/login', methods=['POST'])
|
||||
def login():
|
||||
data = request.get_json() or {}
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
|
||||
user = User.query.filter_by(username=username).first()
|
||||
if user and user.check_password(password):
|
||||
"""
|
||||
User login with detailed error messages
|
||||
"""
|
||||
try:
|
||||
data = request.get_json() or {}
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
|
||||
if not username or not password:
|
||||
return jsonify({'error': 'Username and password are required'}), 400
|
||||
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
|
||||
if not user:
|
||||
return jsonify({'error': 'User not found'}), 404
|
||||
|
||||
if not user.check_password(password):
|
||||
return jsonify({'error': 'Incorrect password'}), 401
|
||||
|
||||
if user.status != 'active':
|
||||
return jsonify({'error': 'Account is disabled'}), 403
|
||||
|
||||
return jsonify({
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'token': 'dummy-token' # In real app use JWT
|
||||
'default_agent_id': user.default_agent_id
|
||||
})
|
||||
return jsonify({'error': 'Invalid credentials'}), 401
|
||||
except OperationalError as e:
|
||||
print(f"Database connection error: {e}")
|
||||
return jsonify({'error': 'Database connection failed'}), 503
|
||||
except Exception as e:
|
||||
print(f"Login error: {e}")
|
||||
return jsonify({'error': 'Internal server error'}), 500
|
||||
|
||||
@user_bp.route('/home', methods=['GET'])
|
||||
def get_user_home():
|
||||
def home():
|
||||
"""
|
||||
Get user homepage data
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
# Get all agents available to user (including public ones)
|
||||
if user.role == 'admin':
|
||||
agents = db.session.query(Agent).filter_by(is_active=True).all()
|
||||
else:
|
||||
# User permissions
|
||||
agents = user.agents
|
||||
|
||||
# Favorites
|
||||
favorites = db.session.query(Agent).join(UserFavoriteAgent).filter(UserFavoriteAgent.user_id == user.id).all()
|
||||
favorite_ids = [a.id for a in favorites]
|
||||
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||||
favorite_ids = [f.agent_id for f in favorites]
|
||||
|
||||
# Quick Questions (Global + User specific)
|
||||
qqs = db.session.query(QuickQuestion).filter(
|
||||
(QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None)
|
||||
).all()
|
||||
|
||||
# Layout
|
||||
config = UserHomepageConfig.query.get(user.id)
|
||||
layout = config.layout if config else {}
|
||||
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||
layout = layout_config.layout if layout_config else {}
|
||||
|
||||
# Embedded agents
|
||||
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
|
||||
embedded_agents = []
|
||||
udas = UserDefaultAgent.query.filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
|
||||
for uda in udas:
|
||||
agent = Agent.query.get(uda.agent_id)
|
||||
for rel in embedded_rel:
|
||||
agent = db.session.get(Agent, rel.agent_id)
|
||||
if agent:
|
||||
embedded_agents.append({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'icon_url': agent.icon_url,
|
||||
'description': agent.description
|
||||
})
|
||||
|
||||
# Quick questions
|
||||
qqs = QuickQuestion.query.filter_by(user_id=user.id).all()
|
||||
quick_questions = [{
|
||||
'id': q.id,
|
||||
'title': q.title,
|
||||
'question': q.question,
|
||||
'agent_id': q.agent_id
|
||||
} for q in qqs]
|
||||
|
||||
# All active agents (for selection)
|
||||
all_agents = Agent.query.filter_by(is_active=True).all()
|
||||
agents_list = [{
|
||||
'id': a.id,
|
||||
'name': a.name
|
||||
} for a in all_agents]
|
||||
embedded_agents.append({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None
|
||||
})
|
||||
|
||||
return jsonify({
|
||||
'user': {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'real_name': user.real_name,
|
||||
'department': user.department
|
||||
'default_agent_id': user.default_agent_id
|
||||
},
|
||||
'agents': [{
|
||||
'id': a.id,
|
||||
'name': a.name,
|
||||
'description': a.description,
|
||||
'icon_url': a.icon_url
|
||||
} for a in agents],
|
||||
'favorite_agent_ids': favorite_ids,
|
||||
'layout': layout,
|
||||
'quick_questions': [{
|
||||
'id': q.id,
|
||||
'title': q.title,
|
||||
'question': q.question,
|
||||
'agent_id': q.agent_id
|
||||
} for q in qqs],
|
||||
'embedded_agents': embedded_agents,
|
||||
'quick_questions': quick_questions,
|
||||
'agents': agents_list
|
||||
'layout': layout
|
||||
})
|
||||
|
||||
@user_bp.route('/agents/<int:agent_id>', methods=['GET'])
|
||||
def get_agent_details(agent_id):
|
||||
"""
|
||||
获取单个 Agent 详情
|
||||
"""
|
||||
@user_bp.route('/favorites/<int:agent_id>', methods=['POST', 'DELETE'])
|
||||
def toggle_favorite(agent_id: int):
|
||||
user = _get_current_user()
|
||||
agent = Agent.query.get(agent_id)
|
||||
|
||||
if not agent:
|
||||
return jsonify({'error': 'Agent not found'}), 404
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
if request.method == 'POST':
|
||||
exists = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).first()
|
||||
if not exists:
|
||||
fav = UserFavoriteAgent(user_id=user.id, agent_id=agent_id)
|
||||
db.session.add(fav)
|
||||
else:
|
||||
db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).delete()
|
||||
|
||||
# Check permission (optional, but good practice)
|
||||
# For now, allow if active or user is admin
|
||||
if not agent.is_active and user.role != 'admin':
|
||||
return jsonify({'error': 'Agent is not active'}), 403
|
||||
|
||||
return jsonify({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'description': agent.description,
|
||||
'icon_url': agent.icon_url,
|
||||
'type': agent.type,
|
||||
'extra_config': agent.extra_config
|
||||
})
|
||||
|
||||
@user_bp.route('/config', methods=['GET'])
|
||||
def get_user_config():
|
||||
"""
|
||||
获取用户/系统配置
|
||||
"""
|
||||
user = _get_current_user()
|
||||
return jsonify({
|
||||
'feedback_enabled': current_app.config.get('FEEDBACK_ENABLED', True)
|
||||
})
|
||||
|
||||
@user_bp.route('/favorites/<int:agent_id>', methods=['POST'])
|
||||
def add_favorite(agent_id):
|
||||
user = _get_current_user()
|
||||
if not UserFavoriteAgent.query.filter_by(user_id=user.id, agent_id=agent_id).first():
|
||||
fav = UserFavoriteAgent(user_id=user.id, agent_id=agent_id)
|
||||
db.session.add(fav)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/favorites/<int:agent_id>', methods=['DELETE'])
|
||||
def remove_favorite(agent_id):
|
||||
user = _get_current_user()
|
||||
fav = UserFavoriteAgent.query.filter_by(user_id=user.id, agent_id=agent_id).first()
|
||||
if fav:
|
||||
db.session.delete(fav)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/homepage-layout', methods=['PUT'])
|
||||
def update_layout():
|
||||
user = _get_current_user()
|
||||
data = request.get_json() or {}
|
||||
config = UserHomepageConfig.query.get(user.id)
|
||||
if not config:
|
||||
config = UserHomepageConfig(user_id=user.id)
|
||||
db.session.add(config)
|
||||
|
||||
config.layout = data.get('layout', {})
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/embedded-agents', methods=['PUT'])
|
||||
def update_embedded_agents():
|
||||
@user_bp.route('/quick-questions', methods=['POST'])
|
||||
def add_quick_question():
|
||||
user = _get_current_user()
|
||||
data = request.get_json() or {}
|
||||
agent_ids = data.get('agent_ids', [])
|
||||
|
||||
if len(agent_ids) > 2:
|
||||
return jsonify({'error': 'Max 2 embedded agents'}), 400
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
# Clear existing
|
||||
UserDefaultAgent.query.filter_by(user_id=user.id).delete()
|
||||
|
||||
for i, aid in enumerate(agent_ids):
|
||||
uda = UserDefaultAgent(user_id=user.id, agent_id=aid, sort_order=i)
|
||||
db.session.add(uda)
|
||||
|
||||
data = request.get_json() or {}
|
||||
if not data.get('title') or not data.get('question') or not data.get('agent_id'):
|
||||
return jsonify({'error': 'Missing fields'}), 400
|
||||
|
||||
qq = QuickQuestion(
|
||||
user_id=user.id,
|
||||
title=data['title'],
|
||||
question=data['question'],
|
||||
agent_id=data['agent_id']
|
||||
)
|
||||
db.session.add(qq)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
return jsonify({'message': 'Added', 'id': qq.id}), 201
|
||||
|
||||
@user_bp.route('/quick-questions/<int:qq_id>', methods=['PUT'])
|
||||
@user_bp.route('/quick-questions/<int:qq_id>', methods=['PUT', 'DELETE'])
|
||||
def update_quick_question(qq_id: int):
|
||||
"""
|
||||
更新常用问题
|
||||
"""
|
||||
user = _get_current_user()
|
||||
data = request.get_json() or {}
|
||||
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
qq = db.session.query(QuickQuestion).filter_by(id=qq_id, user_id=user.id).first()
|
||||
if not qq:
|
||||
return jsonify({"error": "QuickQuestion not found"}), 404
|
||||
return jsonify({"error": "QuickQuestion not found or permission denied"}), 404
|
||||
|
||||
if request.method == 'DELETE':
|
||||
db.session.delete(qq)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
data = request.get_json() or {}
|
||||
if 'title' in data:
|
||||
qq.title = data['title']
|
||||
if 'question' in data:
|
||||
@@ -189,3 +219,249 @@ def update_quick_question(qq_id: int):
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({"status": "ok"})
|
||||
|
||||
@user_bp.route('/homepage-layout', methods=['PUT'])
|
||||
def update_layout():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
data = request.get_json() or {}
|
||||
layout = data.get('layout', {})
|
||||
|
||||
config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||
if not config:
|
||||
config = UserHomepageConfig(user_id=user.id, layout=layout)
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.layout = layout
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/profile', methods=['GET', 'PUT'])
|
||||
def user_profile():
|
||||
"""
|
||||
User profile management
|
||||
GET: Get details
|
||||
PUT: Update basic info
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
if request.method == 'GET':
|
||||
return jsonify({
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'real_name': user.real_name,
|
||||
'email': user.email,
|
||||
'phone_number': user.phone_number,
|
||||
'employee_id': user.employee_id,
|
||||
'department': user.department,
|
||||
'role': user.role,
|
||||
'language': user.language
|
||||
})
|
||||
|
||||
# PUT
|
||||
data = request.get_json() or {}
|
||||
|
||||
if 'real_name' in data:
|
||||
user.real_name = data['real_name']
|
||||
if 'phone_number' in data:
|
||||
user.phone_number = data['phone_number']
|
||||
if 'language' in data:
|
||||
user.language = data['language']
|
||||
|
||||
# Allow editing email, employee_id, department
|
||||
if 'email' in data:
|
||||
# Check uniqueness
|
||||
if data['email']:
|
||||
existing = db.session.query(User).filter_by(email=data['email']).first()
|
||||
if existing and existing.id != user.id:
|
||||
return jsonify({'error': 'Email already exists'}), 400
|
||||
user.email = data['email']
|
||||
|
||||
if 'employee_id' in data:
|
||||
# Check uniqueness
|
||||
if data['employee_id']:
|
||||
existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first()
|
||||
if existing and existing.id != user.id:
|
||||
return jsonify({'error': 'Employee ID already exists'}), 400
|
||||
user.employee_id = data['employee_id']
|
||||
|
||||
if 'department' in data:
|
||||
user.department = data['department']
|
||||
|
||||
try:
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Profile updated successfully'})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@user_bp.route('/change-password', methods=['POST'])
|
||||
def change_password():
|
||||
"""
|
||||
Change password
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
data = request.get_json() or {}
|
||||
|
||||
current_password = data.get('current_password')
|
||||
new_password = data.get('new_password')
|
||||
|
||||
if not current_password or not new_password:
|
||||
return jsonify({'error': 'Current and new password are required'}), 400
|
||||
|
||||
if not user.check_password(current_password):
|
||||
return jsonify({'error': 'Incorrect current password'}), 403
|
||||
|
||||
try:
|
||||
user.set_password(new_password)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Password changed successfully'})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@user_bp.route('/reset-password-by-email', methods=['POST'])
|
||||
def reset_password_request():
|
||||
"""
|
||||
Request password reset via email
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
email = data.get('email')
|
||||
|
||||
if not email:
|
||||
return jsonify({'error': 'Email is required'}), 400
|
||||
|
||||
user = db.session.query(User).filter_by(email=email).first()
|
||||
if not user:
|
||||
# For security, don't reveal if email exists
|
||||
return jsonify({'message': 'If the email exists, a reset link has been sent.'})
|
||||
|
||||
# Generate token
|
||||
token = str(uuid.uuid4())
|
||||
user.reset_token = token
|
||||
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
|
||||
db.session.commit()
|
||||
|
||||
# Mock send email
|
||||
reset_link = f"http://localhost:5173/reset-password?token={token}"
|
||||
print(f"============================================")
|
||||
print(f"MOCK EMAIL TO: {email}")
|
||||
print(f"SUBJECT: Password Reset Request")
|
||||
print(f"LINK: {reset_link}")
|
||||
print(f"============================================")
|
||||
|
||||
return jsonify({'message': 'If the email exists, a reset link has been sent.'})
|
||||
|
||||
@user_bp.route('/reset-password-confirm', methods=['POST'])
|
||||
def reset_password_confirm():
|
||||
"""
|
||||
Reset password with token
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
token = data.get('token')
|
||||
new_password = data.get('new_password')
|
||||
|
||||
if not token or not new_password:
|
||||
return jsonify({'error': 'Token and new password are required'}), 400
|
||||
|
||||
user = db.session.query(User).filter_by(reset_token=token).first()
|
||||
|
||||
if not user or not user.reset_token_expiry or user.reset_token_expiry < datetime.utcnow():
|
||||
return jsonify({'error': 'Invalid or expired token'}), 400
|
||||
|
||||
try:
|
||||
user.set_password(new_password)
|
||||
user.reset_token = None
|
||||
user.reset_token_expiry = None
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Password has been reset successfully'})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@user_bp.route('/agents/<int:id>', methods=['GET'])
|
||||
def get_agent_details(id):
|
||||
"""
|
||||
Get agent details with permission check
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
agent = db.session.get(Agent, id)
|
||||
if not agent:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
|
||||
# Check permission
|
||||
# Admin can access all
|
||||
if user.role != 'admin':
|
||||
has_permission = agent in user.agents
|
||||
if not has_permission:
|
||||
return jsonify({'error': 'Access denied'}), 403
|
||||
|
||||
return jsonify({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'description': agent.description,
|
||||
'icon_url': agent.extra_config.get('icon_url') if agent.extra_config else None,
|
||||
'welcome_message': agent.extra_config.get('welcome_message') if agent.extra_config else None,
|
||||
'suggested_questions': agent.extra_config.get('suggested_questions', []) if agent.extra_config else []
|
||||
})
|
||||
|
||||
@user_bp.route('/announcements', methods=['GET'])
|
||||
def get_announcements():
|
||||
"""
|
||||
Get active announcements (Public)
|
||||
"""
|
||||
try:
|
||||
anns = db.session.query(Announcement).filter_by(is_active=True).order_by(Announcement.created_at.desc()).all()
|
||||
return jsonify([{
|
||||
'id': a.id,
|
||||
'title': a.title,
|
||||
'content': a.content,
|
||||
'created_at': a.created_at.isoformat()
|
||||
} for a in anns])
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@user_bp.route('/announcements', methods=['POST'])
|
||||
def create_announcement():
|
||||
"""
|
||||
Create announcement (Admin only)
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user or user.role != 'admin':
|
||||
return jsonify({'error': 'Unauthorized'}), 403
|
||||
|
||||
data = request.get_json() or {}
|
||||
if not data.get('title') or not data.get('content'):
|
||||
return jsonify({'error': 'Missing fields'}), 400
|
||||
|
||||
ann = Announcement(
|
||||
title=data['title'],
|
||||
content=data['content'],
|
||||
is_active=True
|
||||
)
|
||||
db.session.add(ann)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Created', 'id': ann.id}), 201
|
||||
|
||||
@user_bp.route('/announcements/<int:id>', methods=['DELETE'])
|
||||
def delete_announcement(id):
|
||||
user = _get_current_user()
|
||||
if not user or user.role != 'admin':
|
||||
return jsonify({'error': 'Unauthorized'}), 403
|
||||
|
||||
ann = db.session.get(Announcement, id)
|
||||
if ann:
|
||||
db.session.delete(ann)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Deleted'})
|
||||
Reference in new issue
Block a user