Skip to content

Commit

Permalink
fix:jupyter notebook rich format removal
Browse files Browse the repository at this point in the history
  • Loading branch information
SafetyQuincyF committed Oct 30, 2024
1 parent 9ee0b67 commit 5aa23c8
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 28 deletions.
10 changes: 10 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@
],
"console": "integratedTerminal"
},
{
"name": "Safety Auth Login --headless",
"type": "debugpy",
"request": "launch",
"module": "safety",
"args": [
"auth","login","--headless"
],
"console": "integratedTerminal"
},
{
"name": "Safety Auth Logout",
"type": "debugpy",
Expand Down
41 changes: 13 additions & 28 deletions safety/auth/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import click
from safety.auth.cli_utils import load_auth_session

from safety.auth.utils import is_jupyter_notebook
from safety.console import main_console as console

from safety.auth.constants import AUTH_SERVER_URL, CLI_AUTH_SUCCESS, CLI_LOGOUT_SUCCESS, HOST
Expand Down Expand Up @@ -189,23 +190,13 @@ def process_browser_callback(uri: str, **kwargs: Any) -> Any:

class ThreadedHTTPServer(http.server.HTTPServer):
def __init__(self, server_address: Tuple, RequestHandlerClass: Any) -> None:
"""
Initialize the ThreadedHTTPServer.
Args:
server_address (Tuple): The server address as a tuple (host, port).
RequestHandlerClass (Any): The request handler class.
"""
super().__init__(server_address, RequestHandlerClass)
self.initial_state = None
self.ctx = None
self.callback = None
self.timeout_reached = False

def handle_timeout(self) -> None:
"""
Handle server timeout.
"""
self.timeout_reached = True
return super().handle_timeout()

Expand All @@ -222,54 +213,48 @@ def handle_timeout(self) -> None:

message = "Copy and paste this url into your browser:"


if not headless:
# Start a threaded HTTP server to handle the callback
server = ThreadedHTTPServer((HOST, PORT), CallbackHandler)
server.initial_state = initial_state
server.timeout = kwargs.get("timeout", 600)
server.ctx = ctx
server_thread = threading.Thread(target=server.handle_request)
server_thread.start()
message = f"If the browser does not automatically open in 5 seconds, " \
"copy and paste this url into your browser:"
message = f"If the browser does not automatically open in 5 seconds, copy and paste this url into your browser:"

target = uri if headless else f"{uri}&port={PORT}"
console.print(f"{message} [link={target}]{target}[/link]")
console.print()

if is_jupyter_notebook():
console.print(f"{message} {target}")
else:
console.print(f"{message} [link={target}]{target}[/link]")

if headless:
# Handle the headless mode where user manually provides the response
exchange_data = None
while not exchange_data:
auth_code_text = Prompt.ask("Paste the response here", default=None, console=console)
try:
exchange_data = json.loads(auth_code_text)
state = exchange_data["state"]
code = exchange_data["code"]
except Exception as e:
except Exception:
code = state = None

return auth_process(code=code,
state=state,
initial_state=initial_state,
code_verifier=ctx.obj.auth.code_verifier,
client=ctx.obj.auth.client)
state=state,
initial_state=initial_state,
code_verifier=ctx.obj.auth.code_verifier,
client=ctx.obj.auth.client)
else:
# Wait for the browser authentication in non-headless mode
wait_msg = "waiting for browser authentication"

with console.status(wait_msg, spinner="bouncingBar"):
time.sleep(2)
click.launch(target)
server_thread.join()

except OSError as e:
if e.errno == socket.errno.EADDRINUSE:
reason = f"The port {HOST}:{PORT} is currently being used by another" \
"application or process. Please choose a different port or " \
"terminate the conflicting application/process to free up " \
"the port."
reason = f"The port {HOST}:{PORT} is currently being used by another application or process. Please choose a different port or terminate the conflicting application/process to free up the port."
else:
reason = "An error occurred while performing this operation."

Expand Down
11 changes: 11 additions & 0 deletions safety/auth/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,3 +425,14 @@ def send(self, request: requests.PreparedRequest, **kwargs: Any) -> requests.Res
"""
request.headers.pop("Authorization", None)
return super().send(request, **kwargs)


def is_jupyter_notebook() -> bool:
"""Check if the code is being executed inside a Jupyter Notebook."""
try:
from IPython import get_ipython
if 'IPKernelApp' not in get_ipython().config:
return False
except Exception:
return False
return True

0 comments on commit 5aa23c8

Please sign in to comment.