first commit
This commit is contained in:
37
WebAdmin/signals.py
Executable file
37
WebAdmin/signals.py
Executable file
@@ -0,0 +1,37 @@
|
||||
from django.dispatch import receiver
|
||||
from allauth.account.signals import user_logged_in
|
||||
from allauth.socialaccount.models import SocialAccount
|
||||
from .models import User, UserSource
|
||||
|
||||
@receiver(user_logged_in)
|
||||
def user_logged_in_handler(request, user, **kwargs):
|
||||
print('1111111111111111111111111')
|
||||
try:
|
||||
social_account = SocialAccount.objects.get(user=user, provider='google')
|
||||
print(social_account.extra_data) # 打印 extra_data 内容以进行调试
|
||||
|
||||
google_id = social_account.extra_data['sub'] # 使用 'sub' 字段
|
||||
email = social_account.extra_data['email']
|
||||
username = social_account.extra_data['name']
|
||||
|
||||
try:
|
||||
custom_user = User.objects.get(google_id=google_id)
|
||||
except User.DoesNotExist:
|
||||
custom_user = User.objects.create(
|
||||
username=username,
|
||||
email=email,
|
||||
google_id=google_id,
|
||||
password_hash='', # Google 登录不需要密码
|
||||
)
|
||||
UserSource.objects.create(user=custom_user, source='Google')
|
||||
|
||||
# 更新登录次数和最后登录IP
|
||||
custom_user.login_count += 1
|
||||
custom_user.last_login_ip = request.META.get('REMOTE_ADDR')
|
||||
custom_user.save()
|
||||
|
||||
# 确保 Django 用户同步
|
||||
user.username = custom_user.username
|
||||
user.save()
|
||||
except SocialAccount.DoesNotExist:
|
||||
pass
|
||||
Reference in New Issue
Block a user