djangogoogle-oauth

How to fix Constant Errors When Implementing Google OAuth Sign-in with Django


I decided to put a google sign in method into my Django website, but I have been encountering errors related to the social_auth_app_django library. For example, at first I got a ValueError (Expected 2 got 1) from one of the utils.py in the library code. Note that I am new to adding google sign in to a Django application.

Here are my version specifications:

Here is my settings.py (note that the API keys will be hidden for security purposes)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "games.apps.GamesConfig",
    "account.apps.AccountConfig",
    "forums.apps.ForumsConfig",
    "play.apps.PlayConfig",
    "make_game.apps.MakeGameConfig",
    "administration.apps.AdministrationConfig",
    "bootstrap5",
    "payments.apps.PaymentsConfig",
    "social_django"
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'account.middleware.DeviceDetectionMiddleware',
    # "django.middleware.debug.DebugMiddleware",
    'social_django.middleware.SocialAuthExceptionMiddleware',
]

ROOT_URLCONF = 'superstarstudios.urls'



SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "my-google-key"
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "my-google-secret"
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [
    "email",
]
AUTHENTICATION_BACKENDS = (
    'social_core.backends.google.GoogleOAuth2'
)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR / "templates"
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'account.context_processors.device_type',
                "social_django.context_processors.backends",
                'social_django.context_processors.login_redirect'
            ],
        },
    },
]

LOGIN_REDIRECT_URL = "/games"
LOGOUT_REDIRECT_URL = "/"

SOCIAL_AUTH_PIPELINE = (
    'social_core.pipeline.social_auth.social_details', 
    'social_core.pipeline.social_auth.social_uid',
    'social_core.pipeline.social_auth.auth_allowed',
    'social_core.pipeline.social_auth.social_user',
    'social_core.pipeline.user.get_username', 
    'social_core.pipeline.user.create_user',
    'account.pipeline.create_user',
    'social_core.pipeline.social_auth.associate_user',
    'social_core.pipeline.social_auth.load_extra_data',
    'social_core.pipeline.user.user_details',
)

Here is the function where the main ValueError is being caused:

def module_member(name):
    try:
        mod, member = name.rsplit(".", 1)
        module = import_module(mod)
        return getattr(module, member)
    except (ValueError, AttributeError, ImportError) as e:
        print(f"Couldn't import {name}: {e}")

**Here is the function where a TypeError (issubclass() arg 1 must be a class) is being caused **

def load_backends(backends, force_load=False):
    """
    Load backends defined on SOCIAL_AUTH_AUTHENTICATION_BACKENDS, backends will
    be imported and cached on BACKENDSCACHE. The key in that dict will be the
    backend name, and the value is the backend class.

    Only subclasses of BaseAuth (and sub-classes) are considered backends.

    Previously there was a BACKENDS attribute expected on backends modules,
    this is not needed anymore since it's enough with the
    AUTHENTICATION_BACKENDS setting. BACKENDS was used because backends used to
    be split on two classes the authentication backend and another class that
    dealt with the auth mechanism with the provider, those classes are joined
    now.

    A force_load boolean argument is also provided so that get_backend
    below can retry a requested backend that may not yet be discovered.
    """
    global BACKENDSCACHE
    if force_load:
        BACKENDSCACHE = OrderedDict()
    if not BACKENDSCACHE:
        for auth_backend in backends:
            backend = module_member(auth_backend)
            if issubclass(backend, BaseAuth):
                BACKENDSCACHE[backend.name] = backend
    return BACKENDSCACHE

I have tried various methods, like changing the rsplit from (".", 1) to (".", 2), as well as a lot of asking questions from AI for help, but none of them worked. As said above, I just kept continously getting errors over and over again. Here is a detailed (very detailed) error message:

Couldn't import s: not enough values to unpack (expected 2, got 1)
Internal Server Error: /account-sys/login/google-oauth2/
Traceback (most recent call last):
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\backends\utils.py", line 49, in get_backend
    return BACKENDSCACHE[name]
KeyError: 'google-oauth2'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\cache.py", line 62, in _wrapper_view_func
    response = view_func(request, *args, **kwargs)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_django\utils.py", line 63, in wrapper
    return func(request, backend, *args, **kwargs)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_django\utils.py", line 44, in wrapper
    request.backend = load_backend(
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_django\utils.py", line 27, in load_backend
    return strategy.get_backend(name, redirect_uri=redirect_uri)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\strategy.py", line 176, in get_backend
    Backend = self.get_backend_class(name)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\strategy.py", line 172, in get_backend_class
    return get_backend(self.get_backends(), name)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\backends\utils.py", line 52, in get_backend
    load_backends(backends, force_load=True)
  File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\backends\utils.py", line 35, in load_backends
    if issubclass(backend, BaseAuth):
TypeError: issubclass() arg 1 must be a class

Thank you for all possible help.


Solution

  • I fixed my error: The backend name was incorrect.