bito-code-review[bot] commented on code in PR #38469:
URL: https://github.com/apache/superset/pull/38469#discussion_r3010773106


##########
superset/utils/oauth2.py:
##########
@@ -276,3 +280,142 @@ def check_for_oauth2(database: Database) -> 
Iterator[None]:
         if database.is_oauth2_enabled() and 
database.db_engine_spec.needs_oauth2(ex):
             database.db_engine_spec.start_oauth2_dance(database)
         raise
+
+
+def get_access_token_for_database(database: Database, user_id: int) -> str | 
None:
+    """
+    Return a valid OAuth2 access token for the given database and user.
+
+    First checks if the database has an upstream OAuth provider configured in 
its
+    ``encrypted_extra`` (key ``oauth2_upstream_provider``). If so, returns the 
saved
+    upstream login token for that provider.
+
+    Otherwise, falls back to the database-specific OAuth2 flow.
+    """
+    upstream_provider = 
database.get_encrypted_extra().get("oauth2_upstream_provider")
+    if upstream_provider:
+        return get_upstream_provider_token(upstream_provider, user_id)
+
+    oauth2_config = database.get_oauth2_config()
+    if oauth2_config:
+        return get_oauth2_access_token(
+            oauth2_config, database.id, user_id, database.db_engine_spec
+        )
+
+    return None
+
+
+def save_user_provider_token(
+    user_id: int,
+    provider: str,
+    token_response: dict[str, Any],
+) -> None:
+    """
+    Upsert an UpstreamOAuthToken row for the given user + provider.
+    """
+    from superset.models.core import UpstreamOAuthToken
+
+    token: UpstreamOAuthToken | None = (
+        db.session.query(UpstreamOAuthToken)
+        .filter_by(user_id=user_id, provider=provider)
+        .one_or_none()
+    )
+    if token is None:
+        token = UpstreamOAuthToken(user_id=user_id, provider=provider)
+
+    token.access_token = token_response.get("access_token")
+    expires_in = token_response.get("expires_in")
+    token.access_token_expiration = (
+        datetime.now() + timedelta(seconds=expires_in) if expires_in else None
+    )
+    token.refresh_token = token_response.get("refresh_token")
+    db.session.add(token)
+    db.session.commit()
+
+
[email protected]_exception(
+    backoff.expo,
+    AcquireDistributedLockFailedException,
+    factor=10,
+    base=2,
+    max_tries=5,
+)
+def get_upstream_provider_token(provider: str, user_id: int) -> str | None:
+    """
+    Retrieve a valid access token for the given provider and user.
+
+    If the token is expired and a refresh token exists, attempt to refresh it.
+    Returns None if no valid token is available.
+    """
+    from superset.models.core import UpstreamOAuthToken
+
+    token: UpstreamOAuthToken | None = (
+        db.session.query(UpstreamOAuthToken)
+        .filter_by(user_id=user_id, provider=provider)
+        .one_or_none()
+    )
+    if token is None:
+        return None
+
+    now = datetime.now()
+    if token.access_token_expiration is None or token.access_token_expiration 
> now:
+        return token.access_token
+
+    # Token is expired
+    if token.refresh_token:
+        return _refresh_upstream_provider_token(token, provider)
+
+    db.session.delete(token)
+    db.session.commit()
+    return None
+
+
+def _refresh_upstream_provider_token(
+    token: UpstreamOAuthToken,
+    provider: str,
+) -> str | None:
+    """
+    Use the refresh token to obtain a new access token from the provider.
+    Updates and persists the token if successful; deletes it on failure.
+    """
+    from flask import current_app as flask_app
+
+    with DistributedLock(
+        namespace="refresh_upstream_oauth_token",
+        user_id=token.user_id,
+        provider=provider,
+    ):
+        try:
+            remote_app = 
flask_app.extensions["authlib.integrations.flask_client"][
+                provider
+            ]
+            token_response = remote_app.fetch_access_token(
+                grant_type="refresh_token",
+                refresh_token=token.refresh_token,
+            )
+        except Exception:  # pylint: disable=broad-except
+            logger.warning(
+                "Failed to refresh upstream OAuth token for provider %s",
+                provider,
+                exc_info=True,
+            )
+            db.session.delete(token)
+            db.session.commit()
+            return None
+
+        if "access_token" not in token_response:
+            db.session.delete(token)
+            db.session.commit()
+            return None
+
+        token.access_token = token_response["access_token"]
+        expires_in = token_response.get("expires_in")
+        token.access_token_expiration = (
+            datetime.now() + timedelta(seconds=expires_in) if expires_in else 
None
+        )

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>datetime.now() called without timezone</b></div>
   <div id="fix">
   
   The `datetime.now()` call at line 414 is missing a `tz` argument. Use 
`datetime.now(tz=timezone.utc)` to ensure timezone-aware datetime objects, 
consistent with other uses in the file (e.g., line 188).
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ````suggestion
           token.access_token = token_response["access_token"]
           expires_in = token_response.get("expires_in")
           token.access_token_expiration = (
               datetime.now(tz=timezone.utc) + timedelta(seconds=expires_in) if 
expires_in else None
           )
   ````
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #570eb4</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a 
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to