Update auth.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071import osfrom typing import Optional, Dictfrom authlib.integrations.requests_client import OAuth2Sessionclass OAuthManager:"""Manages OAuth2 flows for third-party services: GitHub, Google Drive, Slack."""def __init__(self):self.providers: Dict[str, Dict] = {'github': {'client_id': os.getenv('GITHUB_CLIENT_ID'),'client_secret': os.getenv('GITHUB_CLIENT_SECRET'),'authorize_url': 'https://github.com/login/oauth/authorize','token_url': 'https://github.com/login/oauth/access_token','scope': 'repo read:org'},'google': {'client_id': os.getenv('GOOGLE_CLIENT_ID'),'client_secret': os.getenv('GOOGLE_CLIENT_SECRET'),'authorize_url': 'https://accounts.google.com/o/oauth2/auth','token_url': 'https://oauth2.googleapis.com/token','scope': 'openid email profile https://www.googleapis.com/auth/drive.readonly'},'slack': {'client_id': os.getenv('SLACK_CLIENT_ID'),'client_secret': os.getenv('SLACK_CLIENT_SECRET'),'authorize_url': 'https://slack.com/oauth/v2/authorize','token_url': 'https://slack.com/api/oauth.v2.access','scope': 'channels:read chat:write'}}def _create_session(self, provider: str, redirect_uri: str) -> OAuth2Session:cfg = self.providers.get(provider)if not cfg or not cfg['client_id'] or not cfg['client_secret']:raise RuntimeError(f"OAuth credentials for '{provider}' are not configured.")return OAuth2Session(cfg['client_id'],cfg['client_secret'],scope=cfg['scope'],redirect_uri=redirect_uri)def get_authorization_url(self, provider: str, redirect_uri: str, state: Optional[str] = None) -> (str, str):"""Generate the OAuth2 authorization URL and state.Returns:(authorization_url, state)"""session = self._create_session(provider, redirect_uri)url, state = session.create_authorization_url(self.providers[provider]['authorize_url'], state=state)return url, statedef fetch_token(self, provider: str, redirect_uri: str, authorization_response: str) -> Dict:"""Exchange the authorization response for an access token.Returns:Token dict containing access_token, refresh_token, expires_in, etc."""session = self._create_session(provider, redirect_uri)token = session.fetch_token(self.providers[provider]['token_url'],authorization_response=authorization_response)return token# Instantiate a global manageroauth_manager = OAuthManager()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136# auth.py"""Centralised OAuth 2.0 helper for GitHub, Google Drive and Slack.Usage-----from auth import oauth_manager# 1) Redirect user to consent pageauth_url, state = oauth_manager.get_authorization_url(provider="github",redirect_uri="https://your‑app.com/callback")# 2) In your callback handler, exchange the code for a tokentoken = oauth_manager.fetch_token(provider="github",redirect_uri="https://your‑app.com/callback",authorization_response=request.url # full URL with ?code=...)"""from __future__ import annotationsimport osfrom dataclasses import dataclassfrom typing import Dict, Optional, Tuplefrom authlib.integrations.requests_client import OAuth2Session# ------------------------------------------------------------------ ## 1 Provider configuration# ------------------------------------------------------------------ #@dataclass(frozen=True)class ProviderConfig:client_id: str | Noneclient_secret: str | Noneauthorize_url: strtoken_url: strscope: strdef _env(name: str) -> str | None:"""Shorthand for os.getenv with strip()."""val = os.getenv(name)return val.strip() if val else NonePROVIDERS: Dict[str, ProviderConfig] = {"github": ProviderConfig(client_id=_env("GITHUB_CLIENT_ID"),client_secret=_env("GITHUB_CLIENT_SECRET"),authorize_url="https://github.com/login/oauth/authorize",token_url="https://github.com/login/oauth/access_token",scope="repo read:org",),"google": ProviderConfig(client_id=_env("GOOGLE_CLIENT_ID"),client_secret=_env("GOOGLE_CLIENT_SECRET"),authorize_url="https://accounts.google.com/o/oauth2/auth",token_url="https://oauth2.googleapis.com/token",scope="openid email profile https://www.googleapis.com/auth/drive.readonly",),"slack": ProviderConfig(client_id=_env("SLACK_CLIENT_ID"),client_secret=_env("SLACK_CLIENT_SECRET"),authorize_url="https://slack.com/oauth/v2/authorize",token_url="https://slack.com/api/oauth.v2.access",scope="channels:read chat:write",),}# ------------------------------------------------------------------ ## 2 OAuth manager# ------------------------------------------------------------------ #class OAuthManager:"""Tiny wrapper around Authlib’s OAuth2Session per provider."""def __init__(self, providers: Dict[str, ProviderConfig]):self.providers = providers# ---------- helpers -------------------------------------------------def _session(self, provider: str, redirect_uri: str) -> OAuth2Session:cfg = self.providers.get(provider)if not cfg:raise KeyError(f"Unsupported provider '{provider}'.")if not (cfg.client_id and cfg.client_secret):raise RuntimeError(f"OAuth credentials for '{provider}' are missing. ""Set the *_CLIENT_ID and *_CLIENT_SECRET env‑vars.")return OAuth2Session(client_id=cfg.client_id,client_secret=cfg.client_secret,scope=cfg.scope,redirect_uri=redirect_uri,)# ---------- public API ----------------------------------------------def get_authorization_url(self, provider: str, redirect_uri: str, state: Optional[str] = None) -> Tuple[str, str]:"""Return (auth_url, state) for the given provider.Pass the *state* back into `fetch_token` to mitigate CSRF."""sess = self._session(provider, redirect_uri)cfg = self.providers[provider]auth_url, final_state = sess.create_authorization_url(cfg.authorize_url, state=state)return auth_url, final_statedef fetch_token(self, provider: str, redirect_uri: str, authorization_response: str) -> Dict:"""Exchange ?code=… for an access token.Returns the token dict from Authlib (includes access_token,refresh_token, expires_in, etc.)."""sess = self._session(provider, redirect_uri)cfg = self.providers[provider]return sess.fetch_token(cfg.token_url,authorization_response=authorization_response,client_secret=cfg.client_secret, # some providers require it explicitly)# Singleton instance used throughout the appoauth_manager = OAuthManager(PROVIDERS)
auth.py+119-54