Проблема создания пользователя с помощью Social Django
В моем файле settings.py есть -
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 = '/'
В urls.py моего проекта есть -
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)
в моем файле social_auth_backends.py у меня есть -
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
Итак, я пытаюсь создать пользователя при успешном входе в систему, если он ранее не существовал, или просто войти в систему, если он уже существовал.
Однако эта часть кода выполняется -
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
Что я делаю не так?
В консоли Google у меня в разделе Разрешенные URI перенаправления -
http://127.0.0.1:8000/auth/complete/google-oauth2/