Skip to content

Commit

Permalink
feat(auth): add support for Google Colab token retrieval
Browse files Browse the repository at this point in the history
  • Loading branch information
not-lain committed Jan 3, 2025
1 parent 1571b28 commit 003a4a7
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
7 changes: 6 additions & 1 deletion projects/fal/src/fal/auth/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,18 @@

import click

from fal.auth import auth0, local
from fal.auth import auth0, colab, local
from fal.console import console
from fal.console.icons import CHECK_ICON
from fal.exceptions.auth import UnauthenticatedException


def key_credentials() -> tuple[str, str] | None:
# Load token from colab secrets if running in colab
token = colab.get_token()
if token is not None:
return token

# Ignore key credentials when the user forces auth by user.
if os.environ.get("FAL_FORCE_AUTH_BY_USER") == "1":
return None
Expand Down
43 changes: 43 additions & 0 deletions projects/fal/src/fal/auth/colab.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from __future__ import annotations

from threading import Lock
from typing import Optional


class GoogleColabState:
def __init__(self):
self.is_checked = False
self.lock = Lock()
self.secret: Optional[str] = None


_colab_state = GoogleColabState()


def is_google_colab() -> bool:
try:
return "google.colab" in str(get_ipython()) # noqa: F821
except NameError:
return False


def get_token() -> Optional[str]:
if not is_google_colab():
return None
with _colab_state.lock:
if _colab_state.is_checked: # request access only once
return _colab_state.secret

try:
from google.colab import userdata # noqa: I001
except ImportError:
return None

try:
token = userdata.get("FAL_KEY")
_colab_state.secret = token.strip()
except Exception:
_colab_state.secret = None

_colab_state.is_checked = True
return _colab_state.secret

0 comments on commit 003a4a7

Please sign in to comment.