061f6baaf1
## 背景 / 需求 新增「微信登录」链路:用户用微信授权登录 App。openid 已绑账号即直接登入; 未绑则走「绑手机号」建号,并处理「手机号已被别的账号占用」的冲突(M2), 以及绑微信后展示昵称/头像的替换策略(M3 §10)。 关键取舍:微信登录**不套用**钱包提现里 bind-wechat 的「撞号即 409」逻辑 ——登录场景 openid 命中就应登入,不能因撞号把用户挡在门外。 ## 改动概览:新增 5 个端点(前缀 `/api/v1/auth`) | 方法 | 路径 | 作用 | |---|---|---| | POST | `/wechat-login` | code→openid。命中已绑用户→直接登入;未命中→签发 `bind_ticket`,返回 `need_bind_phone`(**此刻不建号**);未配 APP_ID/SECRET→503 | | POST | `/wechat/bind-phone/sms` | 持 `bind_ticket` + 手机号 + 短信码绑号 | | POST | `/wechat/bind-phone/jverify` | 持 `bind_ticket` + 极光本机号一键取号绑号 | | POST | `/wechat/conflict/continue` | 占用冲突·继续绑定=**登录老账号**(老号没绑微信则把 openid 绑上;已绑别的微信则只登入、丢弃本次 openid) | | POST | `/wechat/conflict/rebind` | 占用冲突·换绑=**单事务**注销老账号 X(腾号)+ 用该号重建新账号 Y + 写换绑台账;受 30 天限制 | 绑号两条取号路径(sms / jverify)尾段共用 `_finish_wechat_bind`: 手机号未注册→建微信账号(channel=wechat,昵称头像取微信)登入; 已被占用→返回 `phone_occupied`(带占用账号昵称/头像/注册时间/`has_wechat`、 `conflict_ticket`、`rebind_available`、`rebind_blocked_days`),交前端冲突页。 冲突页三选一,后端提供 continue / rebind 两个动作(「取消」为前端本地行为)。 ## 关键设计 **两种短时令牌(`core/security.py`,复用 `JWT_SECRET_KEY`,靠 `typ` 区分):** - `bind_ticket`(typ=wechat_bind,sub=openid,附微信昵称/头像,TTL 10min): openid 未命中时下发,覆盖「授权→输手机号→收码→验码」整个绑定流程。 - `conflict_ticket`(typ=wechat_conflict):比 bind_ticket **多编码已验证的手机号**; 换绑 / 继续绑定只认票里的 phone,堵住「拿别人手机号去夺号」的接管漏洞。 **30 天换绑限制:** 新增台账表 `phone_rebind_log`(手机号级、渠道无关), 记录「腾号重建」这一破坏性事件,靠 `rebound_at` 算窗口; 阈值走配置 `PHONE_REBIND_LIMIT_DAYS`。命中限制的换绑请求返回 409。 **M3 §10 昵称/头像替换:** 绑微信默认用微信昵称/头像替换展示, 抽成共享 helper,登录绑号路径与钱包绑微信路径两处共用 (故 `wallet.py`、`tests/test_withdraw.py` 一并有改动)。 --------- Co-authored-by: guke <guke@autohome.com.cn> Reviewed-on: #139
233 lines
10 KiB
Python
233 lines
10 KiB
Python
"""微信登录 M2 测试:conflict_ticket 令牌、继续绑定(attach/只登入)、换绑(建号+软删+30天限)。
|
|
|
|
沿用 tests/test_wechat_login.py 风格:HTTP 走 client;微信 code→openid 用 monkeypatch;
|
|
短信走 SMS_MOCK(任意 6 位过)。数据变更用"再走一遍 wechat-login 看 openid 落在哪个账号"做行为断言。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import pytest
|
|
|
|
from app.api.v1 import auth # noqa: F401 (后续测试打桩 verify_and_get_phone 用)
|
|
from app.core import security
|
|
from app.integrations import wxpay
|
|
from app.models.phone_rebind_log import PhoneRebindLog
|
|
|
|
|
|
def _fake_userinfo(openid: str, nickname: str | None = "微信昵称", avatar: str | None = "http://x/a.png"):
|
|
def _f(code: str) -> dict:
|
|
return {"openid": openid, "nickname": nickname, "avatar_url": avatar, "raw": {}}
|
|
return _f
|
|
|
|
|
|
def _sms_occupy(client, phone: str) -> int:
|
|
"""用普通短信登录占用一个手机号(register_channel=sms),返回该账号 id。"""
|
|
assert client.post("/api/v1/auth/sms/send", json={"phone": phone}).status_code == 200
|
|
r = client.post("/api/v1/auth/sms/login", json={"phone": phone, "code": "123456"})
|
|
assert r.status_code == 200, r.text
|
|
return r.json()["user"]["id"]
|
|
|
|
|
|
def _occupy_via_conflict(client, monkeypatch, openid: str, phone: str, device_id: str) -> dict:
|
|
"""微信登录(新 openid)→ 绑同一手机号 → 返回 phone_occupied 的响应体(含 conflict_ticket)。"""
|
|
monkeypatch.setattr(wxpay, "code_to_userinfo", _fake_userinfo(openid))
|
|
ticket = client.post(
|
|
"/api/v1/auth/wechat-login", json={"code": "c", "device_id": device_id}
|
|
).json()["bind_ticket"]
|
|
r = client.post(
|
|
"/api/v1/auth/wechat/bind-phone/sms",
|
|
json={"bind_ticket": ticket, "phone": phone, "code": "123456", "device_id": device_id},
|
|
)
|
|
assert r.status_code == 200, r.text
|
|
body = r.json()
|
|
assert body["status"] == "phone_occupied"
|
|
return body
|
|
|
|
|
|
# ===== Task 1: 模型可导入(建表由 conftest 的 create_all 完成) =====
|
|
|
|
def test_phone_rebind_log_model_importable() -> None:
|
|
assert PhoneRebindLog.__tablename__ == "phone_rebind_log"
|
|
|
|
|
|
# ===== Task 2: conflict_ticket 令牌 =====
|
|
|
|
def test_conflict_ticket_roundtrip() -> None:
|
|
token = security.create_conflict_ticket(
|
|
openid="oid1", wechat_nickname="昵", wechat_avatar_url="http://a", phone="13900139000"
|
|
)
|
|
claims = security.decode_conflict_ticket(token)
|
|
assert claims["openid"] == "oid1"
|
|
assert claims["wnk"] == "昵"
|
|
assert claims["wav"] == "http://a"
|
|
assert claims["phone"] == "13900139000"
|
|
|
|
|
|
def test_conflict_ticket_wrong_type_rejected() -> None:
|
|
# bind_ticket 冒充 conflict_ticket → TokenError(typ 不匹配)
|
|
bind = security.create_bind_ticket(openid="oid", wechat_nickname=None, wechat_avatar_url=None)
|
|
with pytest.raises(security.TokenError):
|
|
security.decode_conflict_ticket(bind)
|
|
|
|
|
|
def test_conflict_ticket_expired_rejected(monkeypatch) -> None:
|
|
monkeypatch.setattr(security.settings, "WECHAT_BIND_TICKET_EXPIRE_MINUTES", -1)
|
|
token = security.create_conflict_ticket(
|
|
openid="oid", wechat_nickname=None, wechat_avatar_url=None, phone="13900139000"
|
|
)
|
|
with pytest.raises(security.TokenError):
|
|
security.decode_conflict_ticket(token)
|
|
|
|
|
|
# ===== Task 3: 占用响应扩展 =====
|
|
|
|
def test_phone_occupied_returns_conflict_ticket_and_flags(client, monkeypatch) -> None:
|
|
phone = "13900139101"
|
|
_sms_occupy(client, phone) # 老账号 X(sms,无微信)
|
|
body = _occupy_via_conflict(client, monkeypatch, "openid_occ_101", phone, "devO1")
|
|
assert body["conflict_ticket"]
|
|
assert body["rebind_available"] is True # 首次,未换绑过
|
|
assert body["rebind_blocked_days"] == 0
|
|
assert body["occupied_account"]["has_wechat"] is False # X 是 sms 账号
|
|
|
|
|
|
# ===== Task 4: 继续绑定 =====
|
|
|
|
def test_continue_attaches_wechat_and_logs_into_existing(client, monkeypatch) -> None:
|
|
"""X 无微信 → 继续绑定并入 openid + 登入 X;之后同 openid 登录直接命中 X。"""
|
|
phone = "13900139201"
|
|
x_id = _sms_occupy(client, phone) # X:sms 账号,无微信
|
|
body = _occupy_via_conflict(client, monkeypatch, "openid_cont_201", phone, "devC1")
|
|
|
|
r = client.post(
|
|
"/api/v1/auth/wechat/conflict/continue",
|
|
json={"conflict_ticket": body["conflict_ticket"], "device_id": "devC1"},
|
|
)
|
|
assert r.status_code == 200, r.text
|
|
assert r.json()["status"] == "logged_in"
|
|
assert r.json()["token"]["user"]["id"] == x_id # 登入的是老账号 X
|
|
|
|
# openid 现已并入 X:再走 wechat-login 直接命中 X
|
|
r = client.post("/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devC1"})
|
|
assert r.json()["status"] == "logged_in"
|
|
assert r.json()["token"]["user"]["id"] == x_id
|
|
|
|
|
|
def test_continue_when_existing_has_wechat_logs_in_and_discards_openid(client, monkeypatch) -> None:
|
|
"""X 已绑别的微信 → 继续绑定只登入 X、丢弃本次 openid(不覆盖)。"""
|
|
phone = "13900139202"
|
|
# 先建一个已绑微信 O1 的账号 X(微信登录 O1 + 短信绑号)
|
|
monkeypatch.setattr(wxpay, "code_to_userinfo", _fake_userinfo("openid_o1_202"))
|
|
t = client.post("/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devC2"}).json()["bind_ticket"]
|
|
x = client.post(
|
|
"/api/v1/auth/wechat/bind-phone/sms",
|
|
json={"bind_ticket": t, "phone": phone, "code": "123456", "device_id": "devC2"},
|
|
).json()
|
|
x_id = x["token"]["user"]["id"]
|
|
|
|
# 新 openid O2 撞同号 → 占用(has_wechat=True)→ 继续绑定
|
|
body = _occupy_via_conflict(client, monkeypatch, "openid_o2_202", phone, "devC2b")
|
|
assert body["occupied_account"]["has_wechat"] is True
|
|
r = client.post(
|
|
"/api/v1/auth/wechat/conflict/continue",
|
|
json={"conflict_ticket": body["conflict_ticket"], "device_id": "devC2b"},
|
|
)
|
|
assert r.status_code == 200, r.text
|
|
assert r.json()["token"]["user"]["id"] == x_id # 登入 X
|
|
|
|
# O2 被丢弃:再走 wechat-login(O2)→ 仍未命中(need_bind_phone)
|
|
monkeypatch.setattr(wxpay, "code_to_userinfo", _fake_userinfo("openid_o2_202"))
|
|
assert client.post(
|
|
"/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devC2b"}
|
|
).json()["status"] == "need_bind_phone"
|
|
|
|
|
|
def test_continue_expired_ticket_returns_401(client, monkeypatch) -> None:
|
|
monkeypatch.setattr(security.settings, "WECHAT_BIND_TICKET_EXPIRE_MINUTES", -1)
|
|
expired = security.create_conflict_ticket(
|
|
openid="oid", wechat_nickname=None, wechat_avatar_url=None, phone="13900139209"
|
|
)
|
|
r = client.post(
|
|
"/api/v1/auth/wechat/conflict/continue",
|
|
json={"conflict_ticket": expired, "device_id": "devC3"},
|
|
)
|
|
assert r.status_code == 401, r.text
|
|
|
|
|
|
# ===== Task 5: 换绑 =====
|
|
|
|
def test_rebind_creates_new_account_and_binds_openid(client, monkeypatch) -> None:
|
|
"""换绑 → 建全新微信账号 Y(≠X)+ openid 落到 Y;老账号 X 被注销(手机号归 Y)。"""
|
|
phone = "13900139301"
|
|
x_id = _sms_occupy(client, phone)
|
|
body = _occupy_via_conflict(client, monkeypatch, "openid_rb_301", phone, "devR1")
|
|
|
|
r = client.post(
|
|
"/api/v1/auth/wechat/conflict/rebind",
|
|
json={"conflict_ticket": body["conflict_ticket"], "device_id": "devR1"},
|
|
)
|
|
assert r.status_code == 200, r.text
|
|
y = r.json()["token"]["user"]
|
|
assert r.json()["status"] == "logged_in"
|
|
assert y["phone"] == phone
|
|
assert y["register_channel"] == "wechat"
|
|
assert y["id"] != x_id # 是全新账号,不是老账号
|
|
|
|
# openid 落到 Y:再走 wechat-login 命中 Y
|
|
r = client.post("/api/v1/auth/wechat-login", json={"code": "c", "device_id": "devR1"})
|
|
assert r.json()["status"] == "logged_in"
|
|
assert r.json()["token"]["user"]["id"] == y["id"]
|
|
|
|
|
|
# ===== §10: continue 路径也应用展示身份回填规则 =====
|
|
|
|
def test_continue_applies_section10(client, monkeypatch) -> None:
|
|
"""§10 via M2 attach 路径: X 是默认昵称+null头像的 sms 账号;
|
|
continue 绑定微信后,展示昵称/头像应被微信值替换,并体现在响应的 token.user 中。"""
|
|
phone = "13900139211"
|
|
_sms_occupy(client, phone) # 建 X:默认昵称, null avatar
|
|
body = _occupy_via_conflict(
|
|
client, monkeypatch, "openid_s10", phone, "devS10"
|
|
) # fake_userinfo 默认 nickname="微信昵称", avatar="http://x/a.png"
|
|
|
|
r = client.post(
|
|
"/api/v1/auth/wechat/conflict/continue",
|
|
json={"conflict_ticket": body["conflict_ticket"], "device_id": "devS10"},
|
|
)
|
|
assert r.status_code == 200, r.text
|
|
user_out = r.json()["token"]["user"]
|
|
assert user_out["nickname"] == "微信昵称"
|
|
assert user_out["avatar_url"] == "http://x/a.png"
|
|
|
|
|
|
def test_rebind_blocked_within_30_days(client, monkeypatch) -> None:
|
|
"""同一手机号 30 天内二次换绑 → 409;占用响应 rebind_available=False。"""
|
|
phone = "13900139302"
|
|
_sms_occupy(client, phone)
|
|
body = _occupy_via_conflict(client, monkeypatch, "openid_rb_302a", phone, "devR2")
|
|
assert client.post(
|
|
"/api/v1/auth/wechat/conflict/rebind",
|
|
json={"conflict_ticket": body["conflict_ticket"], "device_id": "devR2"},
|
|
).status_code == 200
|
|
|
|
# 第二次:新 openid 撞同号 → 占用响应此时 rebind_available=False
|
|
body2 = _occupy_via_conflict(client, monkeypatch, "openid_rb_302b", phone, "devR2b")
|
|
assert body2["rebind_available"] is False
|
|
assert body2["rebind_blocked_days"] >= 1
|
|
r = client.post(
|
|
"/api/v1/auth/wechat/conflict/rebind",
|
|
json={"conflict_ticket": body2["conflict_ticket"], "device_id": "devR2b"},
|
|
)
|
|
assert r.status_code == 409, r.text
|
|
|
|
|
|
def test_rebind_expired_ticket_returns_401(client, monkeypatch) -> None:
|
|
monkeypatch.setattr(security.settings, "WECHAT_BIND_TICKET_EXPIRE_MINUTES", -1)
|
|
expired = security.create_conflict_ticket(
|
|
openid="oid", wechat_nickname=None, wechat_avatar_url=None, phone="13900139309"
|
|
)
|
|
r = client.post(
|
|
"/api/v1/auth/wechat/conflict/rebind",
|
|
json={"conflict_ticket": expired, "device_id": "devR3"},
|
|
)
|
|
assert r.status_code == 401, r.text
|