730 lines
25 KiB
Python
730 lines
25 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, LoginAudit
|
|
from sqlalchemy.exc import IntegrityError, OperationalError
|
|
from datetime import datetime, timedelta
|
|
import uuid
|
|
import requests
|
|
from urllib.parse import quote
|
|
|
|
user_bp = Blueprint('user', __name__)
|
|
|
|
_WECOM_ACCESS_TOKEN_CACHE = {
|
|
'token': None,
|
|
'expires_at': None,
|
|
}
|
|
_WECOM_STATE_CACHE = {}
|
|
|
|
def _write_login_audit(
|
|
source: str,
|
|
status: str,
|
|
user: User = None,
|
|
username: str = None,
|
|
reason: str = None,
|
|
wecom_userid: str = None
|
|
):
|
|
try:
|
|
audit = LoginAudit(
|
|
user_id=user.id if user else None,
|
|
username=username or (user.username if user else None),
|
|
source=source,
|
|
status=status,
|
|
reason=reason,
|
|
wecom_userid=wecom_userid,
|
|
ip=request.headers.get('X-Forwarded-For', request.remote_addr),
|
|
user_agent=(request.user_agent.string or '')[:255]
|
|
)
|
|
db.session.add(audit)
|
|
except Exception:
|
|
# Do not break auth flow because of audit logging.
|
|
pass
|
|
|
|
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))
|
|
|
|
def _is_wecom_configured():
|
|
return all([
|
|
current_app.config.get('WECOM_ENABLED'),
|
|
current_app.config.get('WECOM_CORP_ID'),
|
|
current_app.config.get('WECOM_AGENT_ID'),
|
|
current_app.config.get('WECOM_SECRET'),
|
|
])
|
|
|
|
def _cleanup_wecom_state_cache():
|
|
now = datetime.utcnow()
|
|
expired = [k for k, v in _WECOM_STATE_CACHE.items() if not v or v < now]
|
|
for k in expired:
|
|
_WECOM_STATE_CACHE.pop(k, None)
|
|
|
|
def _issue_wecom_state():
|
|
_cleanup_wecom_state_cache()
|
|
state = f"hxops_wecom_{uuid.uuid4().hex}"
|
|
_WECOM_STATE_CACHE[state] = datetime.utcnow() + timedelta(minutes=10)
|
|
return state
|
|
|
|
def _consume_wecom_state(state: str):
|
|
if not state:
|
|
return False
|
|
_cleanup_wecom_state_cache()
|
|
exp = _WECOM_STATE_CACHE.pop(state, None)
|
|
return bool(exp and exp > datetime.utcnow())
|
|
|
|
def _get_wecom_access_token():
|
|
now = datetime.utcnow()
|
|
token = _WECOM_ACCESS_TOKEN_CACHE.get('token')
|
|
expires_at = _WECOM_ACCESS_TOKEN_CACHE.get('expires_at')
|
|
|
|
if token and expires_at and now < expires_at:
|
|
return token
|
|
|
|
corp_id = current_app.config.get('WECOM_CORP_ID')
|
|
secret = current_app.config.get('WECOM_SECRET')
|
|
token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
|
|
resp = requests.get(token_url, params={'corpid': corp_id, 'corpsecret': secret}, timeout=8)
|
|
data = resp.json()
|
|
|
|
if data.get('errcode') != 0 or not data.get('access_token'):
|
|
raise RuntimeError(f"Failed to fetch WeCom token: {data}")
|
|
|
|
_WECOM_ACCESS_TOKEN_CACHE['token'] = data['access_token']
|
|
_WECOM_ACCESS_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
|
|
return data['access_token']
|
|
|
|
def _build_login_payload(user: User, source: str = 'password'):
|
|
return {
|
|
'id': user.id,
|
|
'username': user.username,
|
|
'role': user.role,
|
|
'default_agent_id': user.default_agent_id,
|
|
'source': source,
|
|
}
|
|
|
|
def _sync_or_create_user_from_wecom(wecom_user: dict) -> User:
|
|
userid = wecom_user.get('userid')
|
|
email = wecom_user.get('email')
|
|
mobile = wecom_user.get('mobile')
|
|
unionid = wecom_user.get('unionid')
|
|
name = wecom_user.get('name') or userid or 'wecom_user'
|
|
|
|
user = None
|
|
if userid:
|
|
user = db.session.query(User).filter_by(wecom_userid=userid).first()
|
|
if not user and email:
|
|
user = db.session.query(User).filter_by(email=email).first()
|
|
if not user and mobile:
|
|
user = db.session.query(User).filter_by(phone_number=mobile).first()
|
|
|
|
if user:
|
|
if userid and not user.wecom_userid:
|
|
user.wecom_userid = userid
|
|
if unionid and not user.wecom_unionid:
|
|
user.wecom_unionid = unionid
|
|
if name and not user.real_name:
|
|
user.real_name = name
|
|
if email and not user.email:
|
|
user.email = email
|
|
if mobile and not user.phone_number:
|
|
user.phone_number = mobile
|
|
return user
|
|
|
|
if not current_app.config.get('WECOM_AUTO_CREATE_USER', True):
|
|
raise PermissionError('No linked account found. Contact admin to bind WeCom account.')
|
|
|
|
# Ensure unique username for auto-created user
|
|
base_username = (userid or email or mobile or f"wecom_{uuid.uuid4().hex[:8]}").replace('@', '_')
|
|
candidate = base_username
|
|
suffix = 1
|
|
while db.session.query(User).filter_by(username=candidate).first():
|
|
candidate = f"{base_username}_{suffix}"
|
|
suffix += 1
|
|
|
|
safe_email = email or f"{candidate}@wecom.local"
|
|
if db.session.query(User).filter_by(email=safe_email).first():
|
|
safe_email = f"{candidate}_{uuid.uuid4().hex[:6]}@wecom.local"
|
|
|
|
user = User(
|
|
username=candidate,
|
|
email=safe_email,
|
|
role='user',
|
|
status='active',
|
|
real_name=name,
|
|
phone_number=mobile,
|
|
wecom_userid=userid,
|
|
wecom_unionid=unionid,
|
|
)
|
|
# Set random password to make local password login explicit.
|
|
user.set_password(uuid.uuid4().hex)
|
|
db.session.add(user)
|
|
return user
|
|
|
|
@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:
|
|
_write_login_audit('password', 'failed', username=username, reason='missing_credentials')
|
|
return jsonify({'error': 'Username and password are required'}), 400
|
|
|
|
user = db.session.query(User).filter_by(username=username).first()
|
|
|
|
if not user:
|
|
_write_login_audit('password', 'failed', username=username, reason='user_not_found')
|
|
db.session.commit()
|
|
return jsonify({'error': 'User not found'}), 404
|
|
|
|
if not user.check_password(password):
|
|
_write_login_audit('password', 'failed', user=user, reason='incorrect_password')
|
|
db.session.commit()
|
|
return jsonify({'error': 'Incorrect password'}), 401
|
|
|
|
if user.status != 'active':
|
|
_write_login_audit('password', 'failed', user=user, reason='account_disabled')
|
|
db.session.commit()
|
|
return jsonify({'error': 'Account is disabled'}), 403
|
|
_write_login_audit('password', 'success', user=user)
|
|
db.session.commit()
|
|
return jsonify(_build_login_payload(user, 'password'))
|
|
except OperationalError as e:
|
|
print(f"Database connection error: {e}")
|
|
return jsonify({'error': 'Database connection failed'}), 503
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
print(f"Login error: {e}")
|
|
return jsonify({'error': 'Internal server error'}), 500
|
|
|
|
@user_bp.route('/wecom/authorize-url', methods=['GET'])
|
|
def wecom_authorize_url():
|
|
if not _is_wecom_configured():
|
|
return jsonify({'error': 'WeCom login is not configured'}), 400
|
|
|
|
redirect_uri = request.args.get('redirect_uri') or current_app.config.get('WECOM_REDIRECT_URI')
|
|
if not redirect_uri:
|
|
return jsonify({'error': 'redirect_uri is required'}), 400
|
|
|
|
state = _issue_wecom_state()
|
|
corp_id = current_app.config.get('WECOM_CORP_ID')
|
|
agent_id = current_app.config.get('WECOM_AGENT_ID')
|
|
|
|
url = (
|
|
"https://open.weixin.qq.com/connect/oauth2/authorize"
|
|
f"?appid={corp_id}"
|
|
f"&redirect_uri={quote(redirect_uri, safe='')}"
|
|
"&response_type=code"
|
|
f"&scope=snsapi_base&state={quote(state, safe='')}"
|
|
f"&agentid={agent_id}#wechat_redirect"
|
|
)
|
|
return jsonify({'url': url, 'state': state})
|
|
|
|
@user_bp.route('/wecom/login', methods=['POST'])
|
|
def wecom_login():
|
|
if not _is_wecom_configured():
|
|
return jsonify({'error': 'WeCom login is not configured'}), 400
|
|
|
|
data = request.get_json() or {}
|
|
code = data.get('code')
|
|
state = data.get('state')
|
|
if not code:
|
|
_write_login_audit('wecom', 'failed', reason='missing_code')
|
|
db.session.commit()
|
|
return jsonify({'error': 'code is required'}), 400
|
|
if not _consume_wecom_state(state):
|
|
_write_login_audit('wecom', 'failed', reason='invalid_state')
|
|
db.session.commit()
|
|
return jsonify({'error': 'Invalid or expired WeCom state'}), 400
|
|
|
|
try:
|
|
access_token = _get_wecom_access_token()
|
|
info_resp = requests.get(
|
|
'https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo',
|
|
params={'access_token': access_token, 'code': code},
|
|
timeout=8
|
|
)
|
|
info = info_resp.json()
|
|
if info.get('errcode') != 0 or not info.get('UserId'):
|
|
_write_login_audit('wecom', 'failed', reason=f"auth_failed:{info.get('errmsg')}")
|
|
db.session.commit()
|
|
return jsonify({'error': f"WeCom auth failed: {info.get('errmsg', 'unknown error')}"}), 401
|
|
|
|
user_resp = requests.get(
|
|
'https://qyapi.weixin.qq.com/cgi-bin/user/get',
|
|
params={'access_token': access_token, 'userid': info['UserId']},
|
|
timeout=8
|
|
)
|
|
wecom_user = user_resp.json()
|
|
if wecom_user.get('errcode') != 0:
|
|
_write_login_audit('wecom', 'failed', reason=f"user_fetch_failed:{wecom_user.get('errmsg')}", wecom_userid=info.get('UserId'))
|
|
db.session.commit()
|
|
return jsonify({'error': f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}"}), 401
|
|
|
|
user = _sync_or_create_user_from_wecom(wecom_user)
|
|
if user.status != 'active':
|
|
_write_login_audit('wecom', 'failed', user=user, reason='account_disabled', wecom_userid=wecom_user.get('userid'))
|
|
db.session.commit()
|
|
return jsonify({'error': 'Account is disabled'}), 403
|
|
_write_login_audit('wecom', 'success', user=user, wecom_userid=wecom_user.get('userid'))
|
|
db.session.commit()
|
|
return jsonify(_build_login_payload(user, 'wecom'))
|
|
except PermissionError as e:
|
|
db.session.rollback()
|
|
_write_login_audit('wecom', 'failed', reason='bind_required')
|
|
db.session.commit()
|
|
return jsonify({'error': str(e)}), 403
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
_write_login_audit('wecom', 'failed', reason=f'exception:{str(e)[:160]}')
|
|
db.session.commit()
|
|
return jsonify({'error': f'WeCom login failed: {str(e)}'}), 500
|
|
|
|
@user_bp.route('/wecom/binding', methods=['GET'])
|
|
def get_wecom_binding():
|
|
user = _get_current_user()
|
|
if not user:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
return jsonify({
|
|
'bound': bool(user.wecom_userid),
|
|
'wecom_userid': user.wecom_userid,
|
|
'wecom_unionid': user.wecom_unionid,
|
|
})
|
|
|
|
@user_bp.route('/wecom/unbind', methods=['POST'])
|
|
def unbind_wecom_self():
|
|
user = _get_current_user()
|
|
if not user:
|
|
return jsonify({'error': 'Unauthorized'}), 401
|
|
user.wecom_userid = None
|
|
user.wecom_unionid = None
|
|
db.session.commit()
|
|
return jsonify({'status': 'ok', 'message': 'WeCom account unbound'})
|
|
|
|
@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,
|
|
'language': user.language,
|
|
'theme_preference': user.theme_preference or 'system',
|
|
},
|
|
'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,
|
|
'theme_preference': user.theme_preference or 'system',
|
|
})
|
|
|
|
# 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']
|
|
if 'theme_preference' in data:
|
|
if data['theme_preference'] not in ['light', 'dark', 'system']:
|
|
return jsonify({'error': 'Invalid theme preference'}), 400
|
|
user.theme_preference = data['theme_preference']
|
|
|
|
# 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'})
|