| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- """微信小程序登录业务: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_user(
- db: Session, *, openid: str, phone: str
- ) -> Tuple[Optional[SysUser], Optional[str], Optional[int]]:
- 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 getattr(bound, "status", "1") != "1":
- return None, "账号已被停用,请联系管理员", 403
- 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
|