Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:ALwrity ALwrity BingOAuthService

From Leeroopedia
Knowledge Sources
Domains OAuth, Bing, Integration
Last Updated 2026-10-24 00:00 GMT

Overview

Concrete tool for Bing Webmaster OAuth2 authorization URL generation and callback processing with state-token validation, provided by the ALwrity OAuth integration subsystem.

Description

The BingOAuthService class (inheriting OAuthProviderBase) implements the Bing Webmaster OAuth2 flow. generate_authorization_url creates a secure state parameter ({user_id}:{random_token}), stores it in the per-user SQLite DB with a 20-minute expiry, and builds the Bing authorization URL with proper URL encoding. handle_oauth_callback extracts the user_id from the state, validates it against the stored state, exchanges the authorization code for access/refresh tokens via the Bing token endpoint, and stores the encrypted tokens in the per-user DB. The service inherits Fernet encryption and plaintext migration from OAuthProviderBase.

Usage

Import this service when:

  • A user connects their Bing Webmaster account via OAuth.
  • An authorization URL with state-token validation is needed.
  • The OAuth callback must exchange a code for tokens and store them encrypted.

Code Reference

Source Location

  • Repository: ALwrity
  • File: backend/services/integrations/bing_oauth.py (L21-141)

Signature

class BingOAuthService(OAuthProviderBase):
    """Bing Webmaster OAuth2 integration."""

    def __init__(self):
        self.client_id = os.getenv("BING_CLIENT_ID")
        self.client_secret = os.getenv("BING_CLIENT_SECRET")
        self.redirect_uri = os.getenv("BING_OAUTH_REDIRECT_URI", ...)
        self.base_url = "https://www.bing.com"
        self.token_encryption_key = resolve_encryption_key("bing")
        self._fernet = self._initialize_fernet()
        self._migration_done = set()
        self._select_plaintext_tokens_sql = ...
        self._update_token_sql = ...

    def generate_authorization_url(
        self,
        user_id: str,
        scope: str = "webmaster.manage",
    ) -> Dict[str, Any]:
        """Generate Bing Webmaster OAuth2 authorization URL with state token."""

    def handle_oauth_callback(
        self,
        code: str,
        state: str,
    ) -> Optional[Dict[str, Any]]:
        """Handle OAuth callback: validate state, exchange code for tokens."""

Import

from services.integrations.bing_oauth import BingOAuthService

I/O Contract

Inputs

Name Type Required Description
user_id str Yes Clerk user ID (embedded in state)
scope str No OAuth scope (default 'webmaster.manage')
code str Yes (callback) OAuth authorization code
state str Yes (callback) State token containing user_id:random

Outputs

Name Type Description
generate_authorization_url Dict[str, Any] {auth_url, state} or None if unconfigured
handle_oauth_callback Optional[Dict[str, Any]] Token data (access_token, refresh_token, expiry) or None on failure
side effect DB State token stored (20-min expiry); encrypted tokens stored on success

Usage Examples

Generating an authorization URL

from services.integrations.bing_oauth import BingOAuthService

service = BingOAuthService()
result = service.generate_authorization_url(
    user_id="clerk_user_123",
    scope="webmaster.manage",
)
if result:
    print(f"Authorize at: {result['auth_url']}")
    # Redirect user to result['auth_url']; state is stored in DB for 20 min

Handling the callback

tokens = service.handle_oauth_callback(
    code="auth_code_from_redirect",
    state="clerk_user_123:random_token_value",
)
if tokens:
    print(f"Access token stored (encrypted) for user")
    print(f"Expires at: {tokens.get('expires_at')}")

Related Pages

Implements Principle

Requires Environment

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment