126 lines
5.2 KiB
Python
126 lines
5.2 KiB
Python
"""
|
|
api/user/auth_casdoor.py
|
|
|
|
用途:Casdoor 密码、授权码与刷新令牌认证路由。
|
|
依赖:auth.auth_bp、auth_support 兼容操作、services/auth/hxops。
|
|
逻辑:HTTP 参数与公开 URL 在本模块分组;登录编排仍复用已有 Casdoor 服务适配器。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from flask import current_app, jsonify, request
|
|
|
|
from app import db
|
|
from app.core.errors import AppError, UnauthorizedError, ValidationError
|
|
from app.services.auth.hxops.casdoor_authorize import CasdoorAuthorizeOptions
|
|
|
|
from . import auth as _compat
|
|
from .auth import auth_bp
|
|
|
|
|
|
@auth_bp.post('/casdoor/password-login', endpoint='casdoor_password_login')
|
|
def password_login():
|
|
"""使用 Casdoor password grant 登录,并返回 HXOPS 本地 API 会话。"""
|
|
if (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() != 'casdoor':
|
|
raise AppError(
|
|
code='AUTH.CASDOOR_PASSWORD_LOGIN_DISABLED',
|
|
message='Casdoor password login is disabled by AUTH_LOGIN_MODE',
|
|
http_status=403,
|
|
)
|
|
data = request.get_json() or {}
|
|
username = _compat._clean_str(data.get('username'))
|
|
password = data.get('password') or ''
|
|
if not username or not password:
|
|
raise ValidationError('Username and password are required')
|
|
try:
|
|
result = _compat._hxops_login_service().password(username, password)
|
|
db.session.commit()
|
|
return jsonify(result.login_payload())
|
|
except _compat.WeComLoginError:
|
|
db.session.rollback()
|
|
raise
|
|
except AppError:
|
|
db.session.rollback()
|
|
raise
|
|
except Exception as exc:
|
|
db.session.rollback()
|
|
_compat._raise_casdoor_auth_error(exc, context='password')
|
|
|
|
|
|
@auth_bp.get('/casdoor/authorize-url', endpoint='casdoor_authorize_url')
|
|
def authorize_url():
|
|
"""生成包含状态参数的 Casdoor 授权码登录地址。"""
|
|
try:
|
|
options = CasdoorAuthorizeOptions(
|
|
redirect_uri=request.args.get('redirect_uri'),
|
|
provider_hint=request.args.get('provider_hint'),
|
|
default_provider=request.args.get('default_provider'),
|
|
silent_signin=request.args.get('silent_signin'),
|
|
)
|
|
return jsonify(_compat._build_casdoor_authorize_payload(options))
|
|
except Exception as exc:
|
|
raise AppError(
|
|
code='SYSTEM.INTERNAL_ERROR',
|
|
message=f'Failed to build Casdoor authorize url: {exc}',
|
|
http_status=500,
|
|
) from exc
|
|
|
|
|
|
@auth_bp.post('/casdoor/login', endpoint='casdoor_login')
|
|
def authorization_code_login():
|
|
"""交换授权码、映射本地用户并签发 HXOPS API 会话。"""
|
|
data = request.get_json() or {}
|
|
code = _compat._clean_str(data.get('code'))
|
|
state = _compat._clean_str(data.get('state'))
|
|
if not code:
|
|
raise ValidationError('code is required')
|
|
current_app.logger.info('[casdoor_login] start code_len=%s state=%s', len(code), state[:24] if state else '')
|
|
redirect_uri = _compat._consume_casdoor_state(state)
|
|
if not redirect_uri:
|
|
current_app.logger.warning('[casdoor_login] invalid_state state=%s', state[:24] if state else '')
|
|
raise ValidationError('Invalid or expired Casdoor state')
|
|
try:
|
|
result = _compat._hxops_login_service().authorization_code(code, redirect_uri)
|
|
current_app.logger.info('[casdoor_login] user_resolved username=%s id=%s', result.user.username, result.user.id)
|
|
db.session.commit()
|
|
return jsonify(result.login_payload())
|
|
except _compat.WeComLoginError:
|
|
db.session.rollback()
|
|
current_app.logger.warning('[casdoor_login] business_reject')
|
|
raise
|
|
except AppError:
|
|
db.session.rollback()
|
|
raise
|
|
except Exception as exc:
|
|
db.session.rollback()
|
|
current_app.logger.exception('[casdoor_login] failed state=%s redirect_uri=%s', state[:24] if state else '', redirect_uri)
|
|
_compat._raise_casdoor_auth_error(exc, context='code')
|
|
|
|
|
|
@auth_bp.post('/casdoor/refresh', endpoint='casdoor_refresh')
|
|
def refresh():
|
|
"""以 Casdoor refresh token 换取新的 HXOPS API 会话。"""
|
|
data = request.get_json() or {}
|
|
refresh_token = _compat._clean_str(data.get('refresh_token'))
|
|
if not refresh_token:
|
|
raise ValidationError('refresh_token is required')
|
|
current_app.logger.info('[casdoor_refresh] start refresh=%s', _compat._token_brief(refresh_token))
|
|
try:
|
|
result = _compat._hxops_login_service().refresh(refresh_token)
|
|
current_app.logger.info(
|
|
'[casdoor_refresh] token_refresh_ok next_refresh=%s user_id=%s',
|
|
_compat._token_brief(result.refresh_token), result.user.id,
|
|
)
|
|
return jsonify(result.refresh_payload())
|
|
except AppError:
|
|
raise
|
|
except Exception as exc:
|
|
message = str(exc)
|
|
if 'unsupported_grant_type' in message or 'refresh_token is not supported' in message:
|
|
raise AppError(
|
|
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
|
|
message='Casdoor refresh token is not supported by current application config',
|
|
http_status=400,
|
|
) from exc
|
|
current_app.logger.exception('[casdoor_refresh] failed refresh=%s', _compat._token_brief(refresh_token))
|
|
raise UnauthorizedError(f'Casdoor refresh failed: {exc}') from exc
|