Skip to content

ImportError when using get_frappe_io_auth_url() in hooks.py due to unbound site context #2656

@digikwal

Description

@digikwal

traceback.txt

Using get_frappe_io_auth_url() in hooks.py or any other import-time context leads to a RuntimeError: object is not bound when Frappe site context isn't initialized (e.g. in workers or CLI tools like bench version).

This breaks important workflows such as:

  • Running bench version
  • Running workers
  • Running provisioning tasks

Steps to Reproduce

  1. Define a route redirect in press/hooks.py like:
{"source": "/dashboard/f-login", "target": get_frappe_io_auth_url() or "/"},
  1. Start a worker container or run any CLI command like:
bench version
  1. You will encounter this error:
RuntimeError: object is not bound

Traceback includes:

frappe.local.site → frappe.get_last_doc() → frappe.db.has_column() → werkzeug.local.RuntimeError

Root Cause

get_frappe_io_auth_url() accesses frappe.local.site indirectly via database calls at import-time, when no active site context is available.


Suggested Fix

Refactor the function at press/api/account.py to safely catch all errors and return '/' as a fallback:

def get_frappe_io_auth_url() -> str:
    """Get auth URL for OAuth login with frappe.io, with a fallback to '/'."""
    try:
        provider = frappe.get_last_doc(
            "Social Login Key", filters={"enable_social_login": 1, "provider_name": "Frappe"}
        )
        if (
            provider.base_url
            and provider.client_id
            and get_oauth_keys(provider.name)
            and provider.get_password("client_secret")
        ):
            return get_oauth2_authorize_url(provider.name, redirect_to="")
    except Exception as e:
        # Log the error for debugging purposes
        frappe.log_error(message=str(e), title="Failed to get Frappe OAuth URL")
    
    # Fallback to root URL if any error occurs
    return "/"

Refactor the website_redirects list at press/hooks.py to safely catch all errors and return '/' as a fallback:

website_redirects = [
	{"source": "/dashboard/f-login", "target": get_frappe_io_auth_url()},
	{
		"source": "/suspended-site",
		"target": "/api/method/press.api.handle_suspended_site_redirection",
	},
	{"source": "/f-login", "target": "/dashboard/f-login"},
	{"source": "/signup", "target": "/erpnext/signup"},
]

Additional Notes

A PR is being prepared to encapsulate this logic and ensure the fallback is robust in CLI and background contexts.


Expected outcome

  • bench version should run cleanly
  • Workers and background jobs should not crash on import
  • OAuth redirect URL should degrade gracefully to '/' if misconfigured

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions