| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- """微信小程序登录业务:openid + 手机号一致性校验。"""
- from __future__ import annotations
- from datetime import datetime
- from typing import Optional, Tuple
- from sqlalchemy.orm import Session
- from app.crud.user import user_crud
- from app.models.models import SysUser
- from app.services.wechat_mini_auth import normalize_cn_mobile, phones_match
- def resolve_wechat_login_by_openid_only(
- db: Session, *, openid: str
- ) -> Tuple[Optional[SysUser], Optional[str], Optional[int]]:
- """已绑定 openid 时静默换票(无需手机号授权)。"""
- oid = (openid or "").strip()
- if not oid:
- return None, "微信未返回 openid", 400
- bound = user_crud.get_by_wx_openid(db, oid)
- if not bound:
- return None, "请授权手机号登录,或使用账号密码登录", 400
- if getattr(bound, "status", "1") != "1":
- return None, "账号已停用", 403
- return bound, None, None
- def resolve_wechat_login_user(
- db: Session, *, openid: str, phone: str
- ) -> Tuple[Optional[SysUser], Optional[str], Optional[int]]:
- """
- 根据 openid + 本次授权手机号解析可登录员工。
- Returns:
- (user, error_message, error_code)
- 成功时 error_message/error_code 为 None;失败时 user 为 None。
- """
- oid = (openid or "").strip()
- if not oid:
- return None, "微信未返回 openid", 400
- if not normalize_cn_mobile(phone):
- return None, "请授权手机号登录,或使用账号密码登录", 400
- bound = user_crud.get_by_wx_openid(db, oid)
- if bound:
- if not phones_match(getattr(bound, "phone_no", None), phone):
- return (
- None,
- "授权手机号与绑定账号不一致,请使用账号密码登录或联系管理员",
- 401,
- )
- return bound, None, None
- users = user_crud.list_active_by_phone_no(db, phone)
- if not users:
- return None, "未找到与该手机号匹配的员工账号,请使用账号密码登录", 401
- if len(users) > 1:
- return None, "手机号对应多个账号,请使用账号密码登录", 400
- user = users[0]
- other = user_crud.get_by_wx_openid(db, oid)
- if other and other.id != user.id:
- return None, "该微信已绑定其他账号", 409
- existing_oid = (getattr(user, "wx_openid", None) or "").strip()
- if existing_oid and existing_oid != oid:
- return None, "该账号已绑定其他微信,请联系管理员", 409
- user.wx_openid = oid
- user.update_time = datetime.now()
- db.add(user)
- db.commit()
- db.refresh(user)
- return user, None, None
|