170 lines
8.6 KiB
Python
170 lines
8.6 KiB
Python
|
|
import secrets
|
||
|
|
from datetime import timedelta
|
||
|
|
|
||
|
|
from django.contrib import messages
|
||
|
|
from django.contrib.auth import login
|
||
|
|
from django.contrib.auth.decorators import login_required
|
||
|
|
from django.contrib.auth.decorators import permission_required
|
||
|
|
from django.contrib.admin.views.decorators import staff_member_required
|
||
|
|
from django.db import IntegrityError, transaction
|
||
|
|
from django.http import HttpResponse
|
||
|
|
from django.conf import settings
|
||
|
|
from django.shortcuts import redirect, render
|
||
|
|
from django.utils import timezone
|
||
|
|
from django.utils.http import url_has_allowed_host_and_scheme
|
||
|
|
from django.views.decorators.cache import never_cache
|
||
|
|
from django.views.decorators.debug import sensitive_post_parameters, sensitive_variables
|
||
|
|
from django.views.decorators.http import require_GET, require_POST
|
||
|
|
|
||
|
|
from . import wecom
|
||
|
|
from .models import User, WeComBinding, WeComBindingEvent, WeComLoginState
|
||
|
|
|
||
|
|
|
||
|
|
def denied(message, status=400):
|
||
|
|
response = HttpResponse(message, status=status, content_type="text/plain; charset=utf-8")
|
||
|
|
response["Cache-Control"] = "no-store"
|
||
|
|
response["Referrer-Policy"] = "no-referrer"
|
||
|
|
return response
|
||
|
|
|
||
|
|
|
||
|
|
def allowed_account(user):
|
||
|
|
return user.is_active and user.account_status not in (User.AccountStatus.SUSPENDED, User.AccountStatus.DEPARTED)
|
||
|
|
|
||
|
|
|
||
|
|
@never_cache
|
||
|
|
@require_POST
|
||
|
|
@sensitive_post_parameters("password")
|
||
|
|
def start(request):
|
||
|
|
if not wecom.configured():
|
||
|
|
return denied("企业微信登录尚未配置,请先使用账号密码。", 503)
|
||
|
|
purpose = request.POST.get("purpose", "login")
|
||
|
|
if purpose not in ("login", "bind"):
|
||
|
|
return denied("无效操作。")
|
||
|
|
user = request.user
|
||
|
|
if purpose == "bind":
|
||
|
|
if not user.is_authenticated or not allowed_account(user):
|
||
|
|
return denied("请先登录有效的平台账号。", 403)
|
||
|
|
if not user.has_usable_password() or not user.check_password(request.POST.get("password", "")):
|
||
|
|
return denied("请验证当前平台密码后再绑定。", 403)
|
||
|
|
elif user.is_authenticated:
|
||
|
|
return redirect("portal-dashboard")
|
||
|
|
digest = wecom.session_digest(request)
|
||
|
|
now = timezone.now()
|
||
|
|
if WeComLoginState.objects.filter(session_digest=digest, created_at__gt=now - timedelta(minutes=5)).count() >= 10:
|
||
|
|
return denied("扫码请求过于频繁,请稍后再试。", 429)
|
||
|
|
next_path = request.POST.get("next", "/")
|
||
|
|
if (len(next_path) > 512 or not next_path.startswith("/") or "\\" in next_path
|
||
|
|
or not url_has_allowed_host_and_scheme(next_path, allowed_hosts=set(), require_https=True)):
|
||
|
|
next_path = "/"
|
||
|
|
state = secrets.token_urlsafe(32)
|
||
|
|
WeComLoginState.objects.create(digest=wecom.state_digest(state), session_digest=digest,
|
||
|
|
purpose=purpose, user=user if purpose == "bind" else None,
|
||
|
|
expires_at=now + timedelta(minutes=5), next_path=next_path)
|
||
|
|
return redirect(wecom.authorization_url(state))
|
||
|
|
|
||
|
|
|
||
|
|
@never_cache
|
||
|
|
@require_GET
|
||
|
|
@sensitive_variables()
|
||
|
|
def callback(request):
|
||
|
|
raw_state = request.GET.get("state", "")
|
||
|
|
if not wecom.configured() or not 20 <= len(raw_state) <= 128 or not request.session.session_key:
|
||
|
|
return denied("扫码会话无效,请从本站重新扫码。")
|
||
|
|
state = WeComLoginState.objects.filter(digest=wecom.state_digest(raw_state),
|
||
|
|
session_digest=wecom.session_digest(request), consumed_at__isnull=True,
|
||
|
|
expires_at__gt=timezone.now()).first()
|
||
|
|
if not state:
|
||
|
|
return denied("扫码会话已过期或已使用,请重新扫码。")
|
||
|
|
if state.purpose == "bind" and (not request.user.is_authenticated or state.user_id != request.user.pk):
|
||
|
|
return denied("绑定账号已变化,请重新登录后绑定。", 403)
|
||
|
|
if state.purpose == "login" and request.user.is_authenticated:
|
||
|
|
return denied("当前已有登录账号,请先退出后再扫码。", 409)
|
||
|
|
# Atomic consume across workers: session pop alone is insufficient for simultaneous callbacks.
|
||
|
|
if WeComLoginState.objects.filter(pk=state.pk, consumed_at__isnull=True,
|
||
|
|
expires_at__gt=timezone.now()).update(consumed_at=timezone.now()) != 1:
|
||
|
|
return denied("扫码会话已使用,请重新扫码。")
|
||
|
|
try:
|
||
|
|
identity = wecom.identity_from_code(request.GET.get("code", ""))
|
||
|
|
except wecom.WeComUnavailable as exc:
|
||
|
|
return denied(str(exc), 503)
|
||
|
|
corp, kind, subject = identity
|
||
|
|
try:
|
||
|
|
with transaction.atomic():
|
||
|
|
if state.purpose == "bind":
|
||
|
|
user = User.objects.select_for_update().get(pk=state.user_id)
|
||
|
|
if not allowed_account(user):
|
||
|
|
return denied("账号已停用,不能绑定。", 403)
|
||
|
|
existing = WeComBinding.objects.filter(user=user).first()
|
||
|
|
if existing and (existing.corp_id, existing.kind, existing.subject_id) != identity:
|
||
|
|
return denied("该平台账号已绑定其他身份,请先验证密码解绑。", 409)
|
||
|
|
if not existing:
|
||
|
|
WeComBinding.objects.create(user=user, corp_id=corp, kind=kind, subject_id=subject)
|
||
|
|
WeComBindingEvent.objects.create(user=user, action="bind", identity_digest=wecom.identity_digest(identity))
|
||
|
|
# No name/email matching, account merging or promotion of identity_type/is_staff.
|
||
|
|
messages.success(request, "企业微信已绑定;员工身份与套餐仍按后台审核结果执行。")
|
||
|
|
return redirect("wecom-account")
|
||
|
|
candidate = WeComBinding.objects.filter(corp_id=corp, kind=kind, subject_id=subject).first()
|
||
|
|
if not candidate:
|
||
|
|
return denied("此企业微信尚未绑定平台账号。请先使用密码登录,在个人绑定页面完成绑定。", 403)
|
||
|
|
user = User.objects.select_for_update().get(pk=candidate.user_id)
|
||
|
|
binding = WeComBinding.objects.select_for_update().filter(pk=candidate.pk,
|
||
|
|
corp_id=corp, kind=kind, subject_id=subject).first()
|
||
|
|
if not binding or not allowed_account(user):
|
||
|
|
return denied("绑定已失效或平台账号已停用。", 403)
|
||
|
|
binding.last_login_at = timezone.now()
|
||
|
|
binding.save(update_fields=["last_login_at"])
|
||
|
|
login(request, user, backend="django.contrib.auth.backends.ModelBackend")
|
||
|
|
except IntegrityError:
|
||
|
|
return denied("该企业微信身份已绑定其他账号,不能重复绑定。", 409)
|
||
|
|
response = redirect(state.next_path)
|
||
|
|
response["Referrer-Policy"] = "no-referrer"
|
||
|
|
return response
|
||
|
|
|
||
|
|
|
||
|
|
@login_required
|
||
|
|
@never_cache
|
||
|
|
@require_GET
|
||
|
|
def account(request):
|
||
|
|
return render(request, "registration/wecom_account.html", {
|
||
|
|
"binding": WeComBinding.objects.filter(user=request.user).first(),
|
||
|
|
"wecom_available": wecom.configured(),
|
||
|
|
})
|
||
|
|
|
||
|
|
|
||
|
|
@login_required
|
||
|
|
@never_cache
|
||
|
|
@require_POST
|
||
|
|
@sensitive_post_parameters("password")
|
||
|
|
def unbind(request):
|
||
|
|
with transaction.atomic():
|
||
|
|
user = User.objects.select_for_update().get(pk=request.user.pk)
|
||
|
|
if not allowed_account(user) or not user.has_usable_password() or not user.check_password(request.POST.get("password", "")):
|
||
|
|
return denied("请验证有效账号的当前密码后再解绑。", 403)
|
||
|
|
binding = WeComBinding.objects.select_for_update().filter(user=user).first()
|
||
|
|
if binding:
|
||
|
|
WeComBindingEvent.objects.create(user=user, action="unbind",
|
||
|
|
identity_digest=wecom.identity_digest((binding.corp_id, binding.kind, binding.subject_id)))
|
||
|
|
binding.delete()
|
||
|
|
WeComLoginState.objects.filter(user=user, consumed_at__isnull=True).update(consumed_at=timezone.now())
|
||
|
|
messages.success(request, "企业微信已解绑。平台密码、套餐和配置保持不变。")
|
||
|
|
return redirect("wecom-account")
|
||
|
|
|
||
|
|
|
||
|
|
@staff_member_required
|
||
|
|
@permission_required("accounts.view_wecombinding", raise_exception=True)
|
||
|
|
@never_cache
|
||
|
|
@require_GET
|
||
|
|
def integrations(request):
|
||
|
|
from control.models import Plan, PlanApplication
|
||
|
|
return render(request, "admin/wecom_integrations.html", {
|
||
|
|
"title": "企业微信与套餐收款", "wecom_available": wecom.configured(),
|
||
|
|
"binding_count": WeComBinding.objects.count(),
|
||
|
|
"callback_url": settings.PUBLIC_BASE_URL + "/auth/wecom/callback/",
|
||
|
|
"config_checks": [("启用开关", settings.WECOM_ENABLED),
|
||
|
|
("企业 CorpID", bool(settings.WECOM_CORP_ID)),
|
||
|
|
("应用 AgentID", bool(settings.WECOM_AGENT_ID)),
|
||
|
|
("应用 Secret(仅服务端)", bool(settings.WECOM_SECRET))],
|
||
|
|
"monthly_plan": Plan.objects.filter(slug="monthly-1024g").first(),
|
||
|
|
"pending_applications": PlanApplication.objects.filter(status="pending").count(),
|
||
|
|
})
|