Files
dbx-main/app/modules/inout/gmail.py
T
king 08fe894d1b feat(inout): 물류센터 이메일 옵션 · 입고 저장 뒤 입고 요청 메일(Gmail, 본문 안 사진 600px)
- 옵션 → 물류센터 탭: 물류센터 담당자 이메일·입고 요청 메일 참조(기본 king@·bj@dbxcorp.co.kr)
- 입고 저장 → 미리보기 팝업 바로 → [메일 발송](입고 담당 본인 Gmail), 입고 기록 줄 보내기/다시 보내기
- 제목 "[입고 요청] yyyy년 mm월 dd일(요일) 입고 요청 합니다.", 본문 = 전산 등록 부탁 + 상품 이름·코드·입고 수량·비고 표
- 입고증 사진은 첨부가 아니라 본문 안 이미지(CID multipart/related), 가로 최대 600px·비율 유지로 줄임
- Gmail 연결 권한을 발주 담당 → 발주·입고 담당으로
- 마이그레이션 inout_db 005(inout_settings·inout_receipt_mails), 초기화 SQL 에도 반영

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:33:46 +09:00

193 lines
9.3 KiB
Python

"""발주 메일 — 발주 담당자 본인 Gmail 로 보내기(2026-10-16 사용자 요청, Gmail API).
연결(사람마다 한 번): [Gmail 연결] → 구글 동의 화면(로그인과 같은 OAuth 클라이언트 GOOGLE_CLIENT_ID, 범위 = gmail.send 만)
→ /inout/gmail/callback 에서 ① 고른 구글 계정이 ERP 로그인 계정과 같은지(다르면 거절 — 남의 메일함으로 보내지 않게)
② gmail.send 를 허락했는지 ③ 갱신 토큰이 왔는지 확인 → 갱신 토큰을 APP_ENCRYPTION_KEY(실적 모듈과 같은 마스터 키,
AES-256-GCM, AAD = inout:gmail:{email})로 암호화해 inout_gmail_tokens 에. 원문·접근 토큰은 저장·출력하지 않는다.
보내기: 갱신 토큰 → 접근 토큰(oauth2.googleapis.com/token) → gmail.users.messages.send(raw = RFC 822, 글 + HTML).
사람이 [메일 발송]을 눌렀을 때만 보낸다(자동 발송 없음). 연결이 끊겼으면(invalid_grant·권한 없음) 다시 연결 안내.
구글 클라우드 준비(관리자 1회): Gmail API 사용 설정 · OAuth 동의 화면에 …/auth/gmail.send 범위 추가 ·
OAuth 클라이언트의 승인된 리디렉션 URI 에 {PUBLIC_BASE_URL}/inout/gmail/callback 추가. 상세 docs/INOUT_MODULE.md.
"""
from __future__ import annotations
import base64
import os
from email.message import EmailMessage
from email.utils import formataddr
from typing import Any
import httpx
GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send"
TOKEN_URI = "https://oauth2.googleapis.com/token"
SEND_URI = "https://gmail.googleapis.com/gmail/v1/users/me/messages/send"
REVOKE_URI = "https://oauth2.googleapis.com/revoke"
CLIENT_NAME = "inout_gmail"
class GmailNotConnected(Exception):
"""Gmail 연결이 없거나 끊김 — 다시 [Gmail 연결]."""
class GmailError(Exception):
"""보내기 실패(구글 오류 등) — 문구는 화면에 그대로(비밀값 없음)."""
def _http() -> httpx.Client:
"""HTTP 클라이언트 — 테스트가 바꿔 끼운다."""
return httpx.Client(timeout=20.0)
# ── 토큰 암호화(실적 모듈과 같은 마스터 키) ─────────────────
def _ring() -> Any:
from app.modules.performance.security.crypto import CryptoConfigError, KeyRing # noqa: WPS433
try:
return KeyRing.from_env()
except CryptoConfigError as exc:
raise GmailError(f"암호화 키가 없어 Gmail 연결을 저장할 수 없습니다 — {exc}") from None
def _aad(email: str) -> str:
return f"inout:gmail:{(email or '').strip().lower()}"
def encrypt_token(email: str, refresh_token: str) -> str:
from app.modules.performance.security.crypto import encrypt # noqa: WPS433
return encrypt(refresh_token, aad=_aad(email), ring=_ring())
def decrypt_token(email: str, enc: str) -> str:
from app.modules.performance.security.crypto import DecryptError, decrypt # noqa: WPS433
try:
return decrypt(enc, aad=_aad(email), ring=_ring())
except DecryptError:
raise GmailNotConnected("저장된 Gmail 연결을 읽을 수 없습니다(암호화 키가 바뀌었을 수 있음) — 다시 연결하세요.") from None
# ── OAuth 클라이언트(로그인과 같은 GOOGLE_CLIENT_ID, 범위만 다름) ──
def oauth_client() -> Any:
from app.main import env, oauth # noqa: WPS433
if not env("GOOGLE_CLIENT_ID") or not env("GOOGLE_CLIENT_SECRET"):
raise GmailError("GOOGLE_CLIENT_ID/SECRET 이 없어 Gmail 을 연결할 수 없습니다.")
client = oauth.create_client(CLIENT_NAME)
if client is None:
oauth.register(
name=CLIENT_NAME,
client_id=env("GOOGLE_CLIENT_ID"),
client_secret=env("GOOGLE_CLIENT_SECRET"),
server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
client_kwargs={"scope": f"openid email {GMAIL_SCOPE}"},
)
client = oauth.create_client(CLIENT_NAME)
return client
def check_grant(token: dict[str, Any], *, expected_email: str) -> tuple[str, str]:
"""콜백 토큰 확인 → (갱신 토큰, 허락된 범위). 계정이 다르거나 발송 권한·갱신 토큰이 없으면 GmailError."""
info = token.get("userinfo") or {}
got = str(info.get("email") or "").strip().lower()
want = (expected_email or "").strip().lower()
if not got or got != want:
raise GmailError(f"ERP 로그인 계정({want})과 다른 구글 계정({got or '알 수 없음'})을 골랐습니다 — 같은 계정으로 다시 연결하세요.")
scopes = str(token.get("scope") or "")
if GMAIL_SCOPE not in scopes.split():
raise GmailError("메일 보내기 권한(gmail.send)을 허락하지 않았습니다 — 동의 화면에서 체크한 뒤 다시 연결하세요.")
refresh = str(token.get("refresh_token") or "")
if not refresh:
raise GmailError("구글이 갱신 토큰을 주지 않았습니다 — 구글 계정 → 보안 → 타사 앱 접근에서 이 앱을 지우고 다시 연결하세요.")
return refresh, scopes
# ── 보내기 ──────────────────────────────────────────────
def _google_message(resp: httpx.Response) -> str:
try:
body = resp.json()
except ValueError:
return f"HTTP {resp.status_code}"
err = body.get("error")
if isinstance(err, dict):
return str(err.get("message") or err.get("status") or resp.status_code)[:200]
return str(body.get("error_description") or err or resp.status_code)[:200]
def access_token(refresh_token: str) -> str:
from app.main import env # noqa: WPS433
try:
with _http() as client:
resp = client.post(TOKEN_URI, data={"client_id": env("GOOGLE_CLIENT_ID"), "client_secret": env("GOOGLE_CLIENT_SECRET"),
"refresh_token": refresh_token, "grant_type": "refresh_token"})
except httpx.HTTPError as exc:
raise GmailError(f"구글 인증 서버에 연결하지 못했습니다({type(exc).__name__}).") from None
if resp.status_code != 200:
try:
code = str(resp.json().get("error") or "")
except ValueError:
code = ""
if code in ("invalid_grant", "unauthorized_client", "invalid_client"):
raise GmailNotConnected("Gmail 연결이 끊겼습니다(권한 취소·비밀번호 변경 등) — 다시 연결하세요.")
raise GmailError(f"구글 인증 실패: {_google_message(resp)}")
token = str(resp.json().get("access_token") or "")
if not token:
raise GmailError("구글 인증 서버가 접근 토큰을 주지 않았습니다.")
return token
def build_message(*, sender_name: str, sender_email: str, to: list[str], cc: list[str], subject: str,
text: str, html: str, inline_images: list[dict[str, Any]] | None = None) -> bytes:
"""글 + HTML(multipart/alternative). inline_images = [{cid, data(JPEG)}] 면 HTML 쪽을 multipart/related 로 만들어
<img src="cid:…"> 가 첨부가 아니라 본문 안 이미지로 보이게 한다(입고 요청 메일, 2026-10-19)."""
msg = EmailMessage()
msg["From"] = formataddr((sender_name or sender_email, sender_email))
msg["To"] = ", ".join(to)
if cc:
msg["Cc"] = ", ".join(cc)
msg["Subject"] = subject
msg.set_content(text)
msg.add_alternative(html, subtype="html")
if inline_images:
html_part = msg.get_payload()[1]
for im in inline_images: # 파일 이름은 붙이지 않는다 — 메일 프로그램이 첨부 목록에 따로 띄우지 않게
html_part.add_related(im["data"], maintype="image", subtype="jpeg", cid=f"<{im['cid']}>", disposition="inline")
return msg.as_bytes()
def send(refresh_token: str, raw: bytes) -> str:
"""보내고 Gmail 메시지 id 를 돌려준다."""
token = access_token(refresh_token)
body = {"raw": base64.urlsafe_b64encode(raw).decode("ascii")}
try:
with _http() as client:
resp = client.post(SEND_URI, json=body, headers={"Authorization": f"Bearer {token}"})
except httpx.HTTPError as exc:
raise GmailError(f"Gmail 에 연결하지 못했습니다({type(exc).__name__}).") from None
if resp.status_code in (401, 403):
msg = _google_message(resp)
if "has not been used" in msg or "disabled" in msg.lower():
raise GmailError(f"Gmail API 가 꺼져 있습니다 — 관리자가 구글 클라우드에서 Gmail API 를 사용 설정해야 합니다. ({msg})")
raise GmailNotConnected(f"Gmail 보내기 권한이 없습니다 — 다시 연결하세요. ({msg})")
if resp.status_code != 200:
raise GmailError(f"메일을 보내지 못했습니다: {_google_message(resp)}")
return str(resp.json().get("id") or "")
def revoke(refresh_token: str) -> None:
"""연결 끊기 — 구글 쪽 권한도 취소(실패해도 무시, 우리 쪽 토큰은 지운다)."""
try:
with _http() as client:
client.post(REVOKE_URI, data={"token": refresh_token})
except httpx.HTTPError:
pass
def configured() -> bool:
"""APP_ENCRYPTION_KEY·GOOGLE_CLIENT_ID/SECRET 이 있는지(화면 안내용)."""
return bool(os.getenv("APP_ENCRYPTION_KEY", "").strip() and os.getenv("GOOGLE_CLIENT_ID", "").strip()
and os.getenv("GOOGLE_CLIENT_SECRET", "").strip())