wechat_login_service.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """微信小程序登录业务:openid + 手机号一致性校验(仅快捷登录绑号)。"""
  2. from __future__ import annotations
  3. from datetime import datetime
  4. from typing import Optional, Tuple
  5. from sqlalchemy.orm import Session
  6. from app.crud.user import user_crud
  7. from app.models.models import SysUser
  8. from app.services.wechat_mini_auth import normalize_cn_mobile, phones_match
  9. def resolve_wechat_login_user(
  10. db: Session, *, openid: str, phone: str
  11. ) -> Tuple[Optional[SysUser], Optional[str], Optional[int]]:
  12. oid = (openid or "").strip()
  13. if not oid:
  14. return None, "微信未返回 openid", 400
  15. if not normalize_cn_mobile(phone):
  16. return None, "请授权手机号登录,或使用账号密码登录", 400
  17. bound = user_crud.get_by_wx_openid(db, oid)
  18. if bound:
  19. if getattr(bound, "status", "1") != "1":
  20. return None, "账号已被停用,请联系管理员", 403
  21. if not phones_match(getattr(bound, "phone_no", None), phone):
  22. return (
  23. None,
  24. "微信与账号不匹配,请联系管理员",
  25. 401,
  26. )
  27. return bound, None, None
  28. users = user_crud.list_active_by_phone_no(db, phone)
  29. if not users:
  30. return (
  31. None,
  32. "未找到对应员工账号(请确认手机号已在系统维护)",
  33. 401,
  34. )
  35. if len(users) > 1:
  36. return None, "手机号对应多个账号,请联系管理员", 400
  37. user = users[0]
  38. other = user_crud.get_by_wx_openid(db, oid)
  39. if other and other.id != user.id:
  40. return None, "微信与账号不匹配,请联系管理员", 409
  41. existing_oid = (getattr(user, "wx_openid", None) or "").strip()
  42. if existing_oid and existing_oid != oid:
  43. return None, "微信与账号不匹配,请联系管理员", 409
  44. user.wx_openid = oid
  45. user.update_time = datetime.now()
  46. db.add(user)
  47. db.commit()
  48. db.refresh(user)
  49. return user, None, None