Files
syops/backend/app/api/user/auth_local.py
T

129 lines
5.8 KiB
Python

"""
api/user/auth_local.py
用途:注册、传统密码登录与改密 HTTP 路由。
依赖:auth.auth_bp、auth_support 的共享认证操作。
逻辑:本模块仅装配本地密码职责;业务处理暂由兼容实现承接,后续迁移不改变公开 URL。
"""
from __future__ import annotations
from flask import current_app, jsonify, request
from sqlalchemy.exc import DatabaseError, OperationalError
from app import db
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError
from . import auth as _compat
from .auth import auth_bp
@auth_bp.post('/register', endpoint='register')
def register():
"""校验必填和唯一字段后创建本地用户,保持原有注册响应。"""
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):
raise ValidationError(f'{field} is required')
if db.session.query(_compat.User).filter_by(username=data['username']).first():
raise ValidationError('Username already exists')
if db.session.query(_compat.User).filter_by(email=data['email']).first():
raise ValidationError('Email already exists')
if db.session.query(_compat.User).filter_by(employee_id=data['employee_id']).first():
raise ValidationError('Employee ID already exists')
try:
user = _compat.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 exc:
db.session.rollback()
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) from exc
@auth_bp.post('/login', endpoint='login')
def login():
"""处理兼容的本地用户名密码登录;委托原有审计与重试逻辑。"""
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', True)):
raise AppError(
code='AUTH.PASSWORD_LOGIN_DISABLED',
message='Password login is disabled. Please use Casdoor login.',
http_status=403,
)
def attempt_login():
"""校验本地密码并写入登录审计;用于可恢复数据库失败的一次重试。"""
data = request.get_json() or {}
username = data.get('username')
password = data.get('password')
if not username or not password:
_compat._write_login_audit('password', 'failed', username=username, reason='missing_credentials')
raise ValidationError('Username and password are required')
user = db.session.query(_compat.User).filter_by(username=username).first()
if not user:
_compat._write_login_audit('password', 'failed', username=username, reason='user_not_found')
db.session.commit()
raise AppError(code='AUTH.USER_NOT_FOUND', message='User not found', http_status=404)
if not user.check_password(password):
_compat._write_login_audit('password', 'failed', user=user, reason='incorrect_password')
db.session.commit()
raise AppError(code='AUTH.INCORRECT_PASSWORD', message='Incorrect password', http_status=401)
if user.status != 'active':
_compat._write_login_audit('password', 'failed', user=user, reason='account_disabled')
db.session.commit()
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
_compat._write_login_audit('password', 'success', user=user)
db.session.commit()
return jsonify(_compat._build_login_payload(user, 'password'))
try:
return attempt_login()
except (OperationalError, DatabaseError):
db.session.rollback()
db.session.remove()
try:
return attempt_login()
except (OperationalError, DatabaseError) as retry_exc:
current_app.logger.warning('Password login retry failed: %s', retry_exc)
raise ServiceUnavailableError('Database connection failed') from retry_exc
except AppError:
raise
except Exception as exc:
db.session.rollback()
current_app.logger.exception('Login error: %s', exc)
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Internal server error', http_status=500) from exc
@auth_bp.post('/change-password', endpoint='change_password')
def change_password():
"""校验当前身份并同步更新本地与 Casdoor 密码。"""
user = _compat._get_current_user()
if not user:
raise UnauthorizedError('Unauthorized')
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:
raise ValidationError('Current and new password are required')
try:
_compat._verify_current_password_for_change(user, current_password)
_compat._sync_casdoor_password(user.username, current_password, new_password)
user.set_password(new_password)
db.session.commit()
return jsonify({'message': 'Password changed successfully'})
except AppError:
raise
except RuntimeError as exc:
db.session.rollback()
if _compat._is_casdoor_password_error(str(exc)):
_compat._raise_incorrect_current_password()
_compat._raise_casdoor_set_password_error(exc)
except Exception as exc:
db.session.rollback()
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) from exc