filesend/backend/app/routes/auth.py

124 lines
3.8 KiB
Python
Raw Normal View History

2025-10-10 17:25:29 +08:00
from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from datetime import timedelta
from ..models import User, SystemSettings, db
auth_bp = Blueprint('auth', __name__)
@auth_bp.route('/register', methods=['POST'])
def register():
# 检查是否允许注册
allow_registration = SystemSettings.get_value('allow_registration', True)
if not allow_registration:
return jsonify({'message': '当前不允许新用户注册'}), 403
data = request.get_json()
# 验证必要字段
if not all(k in data for k in ('username', 'email', 'password')):
return jsonify({'message': '缺少必要字段'}), 400
# 检查用户名和邮箱是否已存在
if User.query.filter_by(username=data['username']).first():
return jsonify({'message': '用户名已存在'}), 400
if User.query.filter_by(email=data['email']).first():
return jsonify({'message': '邮箱已被注册'}), 400
# 获取默认每日配额
daily_quota = SystemSettings.get_value('daily_quota', 5)
require_admin_approval = SystemSettings.get_value('require_admin_approval', True)
# 创建新用户
user = User(
username=data['username'],
email=data['email'],
daily_quota=daily_quota,
is_active=not require_admin_approval # 根据设置决定是否需要管理员激活
)
user.set_password(data['password'])
db.session.add(user)
db.session.commit()
if require_admin_approval:
return jsonify({'message': '注册成功,请等待管理员激活'}), 201
else:
return jsonify({'message': '注册成功'}), 201
@auth_bp.route('/login', methods=['POST'])
def login():
data = request.get_json()
if not all(k in data for k in ('username', 'password')):
return jsonify({'message': '缺少用户名或密码'}), 400
user = User.query.filter_by(username=data['username']).first()
if not user or not user.check_password(data['password']):
return jsonify({'message': '用户名或密码错误'}), 401
if not user.is_active:
return jsonify({'message': '账号未激活,请联系管理员'}), 403
# 创建访问令牌有效期1天
access_token = create_access_token(
identity=str(user.id),
additional_claims={'is_admin': user.is_admin},
expires_delta=timedelta(days=1)
)
return jsonify({
'access_token': access_token,
'user': user.to_dict()
}), 200
@auth_bp.route('/me', methods=['GET'])
@jwt_required()
def get_current_user():
user_id = get_jwt_identity()
user = User.query.get_or_404(user_id)
return jsonify(user.to_dict()), 200
@auth_bp.route('/reset-password', methods=['POST'])
@jwt_required()
def reset_password():
user_id = get_jwt_identity()
user = User.query.get_or_404(user_id)
data = request.get_json()
if not all(k in data for k in ('old_password', 'new_password')):
return jsonify({'message': '缺少必要字段'}), 400
if not user.check_password(data['old_password']):
return jsonify({'message': '原密码错误'}), 401
user.set_password(data['new_password'])
db.session.commit()
return jsonify({'message': '密码重置成功'}), 200
@auth_bp.route('/health', methods=['GET'])
def health_check():
"""健康检查端点用于Docker容器监控"""
try:
# 检查数据库连接
db.session.execute('SELECT 1')
return jsonify({
'status': 'healthy',
'service': 'filesend-backend',
'database': 'connected'
}), 200
except Exception as e:
return jsonify({
'status': 'unhealthy',
'service': 'filesend-backend',
'database': 'disconnected',
'error': str(e)
}), 503