468 lines
15 KiB
Python
468 lines
15 KiB
Python
from flask import Blueprint, request, jsonify, current_app, url_for
|
|
from app import db
|
|
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():
|
|
"""
|
|
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,
|
|
'default_agent_id': user.default_agent_id
|
|
})
|
|
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 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(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
|
|
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 = []
|
|
for rel in embedded_rel:
|
|
agent = db.session.get(Agent, rel.agent_id)
|
|
if agent:
|
|
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,
|
|
'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,
|
|
'quick_questions': [{
|
|
'id': q.id,
|
|
'title': q.title,
|
|
'question': q.question,
|
|
'agent_id': q.agent_id
|
|
} for q in qqs],
|
|
'embedded_agents': embedded_agents,
|
|
'layout': layout
|
|
})
|
|
|
|
@user_bp.route('/favorites/<int:agent_id>', methods=['POST', 'DELETE'])
|
|
def toggle_favorite(agent_id: int):
|
|
user = _get_current_user()
|
|
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()
|
|
|
|
db.session.commit()
|
|
return jsonify({'status': 'ok'})
|
|
|
|
@user_bp.route('/quick-questions', methods=['POST'])
|
|
def add_quick_question():
|
|
user = _get_current_user()
|
|
if not user:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
|
|
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({'message': 'Added', 'id': qq.id}), 201
|
|
|
|
@user_bp.route('/quick-questions/<int:qq_id>', methods=['PUT', 'DELETE'])
|
|
def update_quick_question(qq_id: int):
|
|
user = _get_current_user()
|
|
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 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:
|
|
qq.question = data['question']
|
|
if 'agent_id' in data:
|
|
qq.agent_id = data['agent_id']
|
|
|
|
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'})
|