Files

98 lines
4.3 KiB
Python
Raw Permalink Normal View History

"""Company Web login. Secrets and codes stay server-side; identity never grants a role."""
import hashlib
import json
import urllib.error
import urllib.parse
import urllib.request
from django.conf import settings
from django.core.cache import cache
from django.utils.crypto import salted_hmac
class WeComUnavailable(Exception):
pass
def configured():
base = urllib.parse.urlsplit(settings.PUBLIC_BASE_URL)
return bool(settings.WECOM_ENABLED and settings.WECOM_CORP_ID and settings.WECOM_AGENT_ID
and settings.WECOM_SECRET and base.scheme == "https" and base.hostname
and not base.username and not base.password and not base.query and not base.fragment
and base.path in ("", "/"))
def authorization_url(state):
if not configured():
raise WeComUnavailable("企业微信登录尚未配置,请使用账号密码登录。")
params = dict(login_type="CorpApp", appid=settings.WECOM_CORP_ID,
agentid=settings.WECOM_AGENT_ID, state=state, lang="zh",
redirect_uri=settings.PUBLIC_BASE_URL + "/auth/wecom/callback/")
return "https://login.work.weixin.qq.com/wwlogin/sso/login?" + urllib.parse.urlencode(params)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
def _api(path, parameters):
# Only fixed provider endpoints; no user-controlled host or redirects carrying secrets.
url = "https://qyapi.weixin.qq.com/cgi-bin/" + path + "?" + urllib.parse.urlencode(parameters)
opener = urllib.request.build_opener(NoRedirect(), urllib.request.ProxyHandler({}))
try:
with opener.open(url, timeout=8) as response:
raw = response.read(65537)
if len(raw) > 65536:
raise ValueError("Oversized identity response")
body = json.loads(raw)
if not isinstance(body, dict) or body.get("errcode") != 0:
raise ValueError("Provider rejected identity request")
return body
except (OSError, ValueError, TypeError, urllib.error.URLError):
# Do not expose provider URLs, tokens, response bodies or auth codes in logs.
raise WeComUnavailable("企业微信验证暂不可用或授权已过期,请重新扫码。") from None
def identity_from_code(code):
if not configured() or not isinstance(code, str) or not 1 <= len(code.encode()) <= 512:
raise WeComUnavailable("企业微信授权无效,请重新扫码。")
token_key = "wecom-token:" + salted_hmac("wecom-config", settings.WECOM_CORP_ID + settings.WECOM_SECRET).hexdigest()
token = cache.get(token_key)
if not token:
body = _api("gettoken", {"corpid": settings.WECOM_CORP_ID, "corpsecret": settings.WECOM_SECRET})
token = body.get("access_token")
if not isinstance(token, str) or not token:
raise WeComUnavailable("企业微信应用凭据不可用。")
try:
lifetime = int(body.get("expires_in", 7200))
except (TypeError, ValueError):
raise WeComUnavailable("企业微信应用凭据返回异常。") from None
cache.set(token_key, token, max(1, min(lifetime, 7200) - 120))
try:
body = _api("auth/getuserinfo", {"access_token": token, "code": code})
except WeComUnavailable:
cache.delete(token_key)
raise
# userid is a company member. openid alone must NEVER qualify as an employee.
kind, subject = ("member", body.get("userid")) if body.get("userid") else ("external", body.get("openid"))
if not isinstance(subject, str) or not 1 <= len(subject) <= 128 or subject.strip() != subject:
raise WeComUnavailable("未取得可绑定的企业微信身份。")
if body.get("corpid", settings.WECOM_CORP_ID) != settings.WECOM_CORP_ID:
raise WeComUnavailable("企业微信身份不属于当前配置的企业。")
return settings.WECOM_CORP_ID, kind, subject
def identity_digest(identity):
return salted_hmac("wecom-binding-audit", json.dumps(identity), algorithm="sha256").hexdigest()
def state_digest(value):
return hashlib.sha256(value.encode()).hexdigest()
def session_digest(request):
if not request.session.session_key:
request.session.create()
return salted_hmac("wecom-session", request.session.session_key, algorithm="sha256").hexdigest()