Spaces:
Running

hub / backend /scripts /gmail_refresh_token.py
Andre
deploy: snapshot 2fb662d -- e-mails da plataforma pela Gmail API (1.4.7)
b15ebfe
Raw History Blame Contribute Delete
3.5 kB
"""One-time helper: get a Gmail API refresh token for the platform sender.
Run on your own PC (needs a browser), never on the Space:
python backend/scripts/gmail_refresh_token.py path/to/client_secret.json
`client_secret.json` is the "Desktop app" OAuth client downloaded from
Google Cloud Console (Gmail API enabled). The script opens the Google consent
page; sign in with the sender account and allow "Send email on your behalf".
It then prints the three values to store as Space secrets:
GMAIL_CLIENT_ID, GMAIL_CLIENT_SECRET, GMAIL_REFRESH_TOKEN
Stdlib only, scope limited to gmail.send (cannot read the mailbox). The
consent screen must be "In production", not "Testing": Testing-mode refresh
tokens expire after 7 days.
"""
from __future__ import annotations
import http.server
import json
import secrets
import sys
import urllib.parse
import urllib.request
import webbrowser
SCOPE = "https://www.googleapis.com/auth/gmail.send"
AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"
TOKEN_URL = "https://oauth2.googleapis.com/token"
def main() -> None:
if len(sys.argv) != 2:
sys.exit(__doc__)
with open(sys.argv[1], encoding="utf-8") as f:
cfg = json.load(f)
client = cfg.get("installed") or cfg.get("web") or {}
client_id, client_secret = client["client_id"], client["client_secret"]
state = secrets.token_urlsafe(16)
result: dict[str, str] = {}
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self): # noqa: N802 - stdlib naming
qs = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
result.update({k: v[0] for k, v in qs.items()})
self.send_response(200)
self.send_header("content-type", "text/plain; charset=utf-8")
self.end_headers()
self.wfile.write(b"Done - you can close this tab and go back to the terminal.")
def log_message(self, *args):
pass
server = http.server.HTTPServer(("127.0.0.1", 0), Handler)
redirect_uri = f"http://127.0.0.1:{server.server_port}"
url = AUTH_URL + "?" + urllib.parse.urlencode({
"client_id": client_id,
"redirect_uri": redirect_uri,
"response_type": "code",
"scope": SCOPE,
"access_type": "offline",
"prompt": "consent", # forces a refresh_token even on re-runs
"state": state,
})
print("Opening browser for consent. If it doesn't open, visit:\n" + url)
webbrowser.open(url)
while "code" not in result and "error" not in result:
server.handle_request()
if result.get("state") != state:
sys.exit("State mismatch - aborting.")
if "error" in result:
sys.exit(f"Consent denied: {result['error']}")
body = urllib.parse.urlencode({
"code": result["code"],
"client_id": client_id,
"client_secret": client_secret,
"redirect_uri": redirect_uri,
"grant_type": "authorization_code",
}).encode()
with urllib.request.urlopen(urllib.request.Request(TOKEN_URL, data=body), timeout=20) as resp:
tokens = json.load(resp)
if "refresh_token" not in tokens:
sys.exit(f"No refresh_token in response: {tokens}")
print("\nStore these as Space secrets (Settings -> Variables and secrets):\n")
print(f"GMAIL_CLIENT_ID={client_id}")
print(f"GMAIL_CLIENT_SECRET={client_secret}")
print(f"GMAIL_REFRESH_TOKEN={tokens['refresh_token']}")
if __name__ == "__main__":
main()