Problem creating a user with Social Django
In my settings.py I have -
INSTALLED_APPS = [
***
'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',
'social_django.middleware.SocialAuthExceptionMiddleware',
]
# Authentication backends
AUTHENTICATION_BACKENDS = (
'cloud.social_auth_backends.CustomGoogleOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
# Google OAuth2 credentials
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = os.getenv('SOCIAL_AUTH_GOOGLE_OAUTH2_KEY')
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = os.getenv('SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET')
# Login and logout redirection
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
In my project's urls.py I have -
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('cloud.urls')),
path('ckeditor/', include('ckeditor_uploader.urls')),
path('auth/', include('social_django.urls', namespace='social')),
]
urlpatterns += [
path("ckeditor5/", include('django_ckeditor_5.urls'), name="ck_editor_5_upload_file"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in my social_auth_backends.py I have -
from django.contrib.auth import get_user_model
from social_core.backends.google import GoogleOAuth2
class CustomGoogleOAuth2(GoogleOAuth2):
def user_data(self, access_token, *args, **kwargs):
print(f"Fetching user data with access token: {access_token}")
data = super().user_data(access_token, *args, **kwargs)
print(f"User data fetched: {data}")
return data
def new_user(self, user, *args, **kwargs):
email = user.email
print(f"Creating a new user with email: {email}")
if not email:
raise ValueError("Email is required to create a user.")
User = get_user_model()
username = email.split('@')[0]
print(f"Attempting to get or create user with email: {email} and username: {username}")
user, created = User.objects.get_or_create(
email=email,
defaults={'username': username}
)
if created:
print(f"User created with email: {email}")
user.set_unusable_password() # Optionally set a default password or other user setup.
user.save()
print(f"User with email: {email} has been saved with an unusable password.")
else:
print(f"User with email: {email} already exists.")
return user
So, I am trying to create the user when they successfully log in if they did not previously exist, or just log them in if they already existed.
However, this part of the code is getting executed -
def user_data(self, access_token, *args, **kwargs):
print(f"Fetching user data with access token: {access_token}")
data = super().user_data(access_token, *args, **kwargs)
print(f"User data fetched: {data}")
return data
But this part is not -
def new_user(self, user, *args, **kwargs):
email = user.email
print(f"Creating a new user with email: {email}")
if not email:
raise ValueError("Email is required to create a user.")
User = get_user_model()
username = email.split('@')[0]
print(f"Attempting to get or create user with email: {email} and username: {username}")
user, created = User.objects.get_or_create(
email=email,
defaults={'username': username}
)
if created:
print(f"User created with email: {email}")
user.set_unusable_password() # Optionally set a default password or other user setup.
user.save()
print(f"User with email: {email} has been saved with an unusable password.")
else:
print(f"User with email: {email} already exists.")
return user
What am I doing wrong?
In my Google console I have under Authorized redirect URIs -
http://127.0.0.1:8000/auth/complete/google-oauth2/