Ai_Admin/WebAdmin/signals.py
2024-09-23 09:56:57 +00:00

68 lines
3.2 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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('信号处理开始: user_logged_in_handler 被触发')
# 防止信号被重复处理
if hasattr(request, '_google_user_logged_in_handled'):
print('重复信号,跳过处理')
return
request._google_user_logged_in_handled = True
print('处理信号标志设置完成')
try:
social_account = SocialAccount.objects.get(user=user, provider='google')
print(f'找到 social_account用户ID: {user.id}')
google_id = social_account.extra_data.get('sub')
email = social_account.extra_data.get('email')
username = social_account.extra_data.get('name')
print(f'从 social_account 获取的 google_id: {google_id}, email: {email}, username: {username}')
if not google_id:
# 如果 google_id 为空,不要继续创建用户,记录日志或处理错误
print('google_id 为空,终止处理')
return
# 优化:根据 google_id 和 email 双重检查用户是否已存在
try:
custom_user = User.objects.get(google_id=google_id)
print(f'根据 google_id 找到用户: {custom_user.username}')
except User.DoesNotExist:
print(f'没有找到 google_id 为 {google_id} 的用户,检查 email: {email}')
# 进一步检查是否有相同的 email 用户存在
if User.objects.filter(email=email).exists():
custom_user = User.objects.get(email=email)
print(f'找到 email 为 {email} 的用户: {custom_user.username}')
# 如果用户存在但 google_id 不同,更新 google_id
custom_user.google_id = google_id
custom_user.save()
print(f'更新用户的 google_id 为: {google_id}')
else:
custom_user = User.objects.create(
username=username,
email=email,
google_id=google_id,
# password_hash='', # Google 登录不需要密码
)
print(f'创建新用户: {custom_user.username}google_id: {google_id}')
UserSource.objects.create(user=custom_user, source='Google')
print(f'创建 UserSource 记录,来源为 Google')
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0] # 可能有多个 IP 地址,取第一个
else:
ip = request.META.get('REMOTE_ADDR') # 使用 REMOTE_ADDR 作为备用
# 更新登录次数和 IP 地址
custom_user.login_count += 1
custom_user.last_login_ip = ip
custom_user.save()
print(f'更新用户信息: 登录次数 {custom_user.login_count}, IP 地址 {custom_user.last_login_ip}')
except SocialAccount.DoesNotExist:
print('未找到与用户关联的 Google social_account')