File size: 1,276 Bytes
55ce00a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
"""Gate for gated models: a Hugging Face token of a member of the organization (whoami, cached for ten minutes)."""

from __future__ import annotations

import hashlib
import threading
import time


def bearer(headers) -> str | None:
    h = headers.get("authorization", "")
    return h[7:].strip() or None if h.lower().startswith("bearer ") else None


class Gate:
    def __init__(self, org: str = "SQuADDS", ttl_s: float = 600):
        self.org, self.ttl_s = org, ttl_s
        self._memo: dict = {}
        self._lock = threading.Lock()

    def is_member(self, token: str) -> bool:
        from huggingface_hub import whoami
        from huggingface_hub.errors import HfHubHTTPError

        k = hashlib.sha256(token.encode()).hexdigest()
        with self._lock:
            hit = self._memo.get(k)
        if hit and time.monotonic() - hit[1] < self.ttl_s:
            return hit[0]
        try:
            info = whoami(token=token)
            ok = any(o.get("name") == self.org for o in info.get("orgs", []))
        except HfHubHTTPError as exc:
            if getattr(exc.response, "status_code", None) not in (401, 403):
                raise
            ok = False
        with self._lock:
            self._memo[k] = (ok, time.monotonic())
        return ok