harvestconnect-api / api /adapters.py
Dayozoe's picture
Upload folder using huggingface_hub
c701fb5 verified
Raw History Blame Contribute Delete
2.41 kB
import logging
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from django.contrib.auth.models import User
logger = logging.getLogger(__name__)
class CustomSocialAccountAdapter(DefaultSocialAccountAdapter):
"""Headless social account adapter for REST API and SSO authentication.
Ensures that social signups (Google, GitHub) are automatically completed
without HTML redirects to signup forms, and automatically links existing
users with the same email.
"""
def is_auto_signup_allowed(self, request, sociallogin):
return True
def pre_social_login(self, request, sociallogin):
# If user is already authenticated in session, connect directly
if getattr(request, "user", None) and request.user.is_authenticated:
if not sociallogin.is_existing:
sociallogin.connect(request, request.user)
return
# If already linked to a socialaccount, nothing to do
if sociallogin.is_existing:
return
# Extract email from social account data
email = None
if sociallogin.email_addresses:
email = sociallogin.email_addresses[0].email
elif isinstance(sociallogin.account.extra_data, dict):
email = sociallogin.account.extra_data.get("email")
if email:
try:
existing_user = User.objects.filter(email__iexact=email).first()
if existing_user:
sociallogin.connect(request, existing_user)
logger.info("Connected social login (%s) to existing user %s", sociallogin.account.provider, existing_user.email)
except Exception as exc:
logger.warning("Error auto-connecting social account: %s", exc)
def populate_user(self, request, sociallogin, data):
user = super().populate_user(request, sociallogin, data)
# Ensure username is never blank and unique
if not user.username:
raw_base = data.get("email") or data.get("username") or "user"
base_username = raw_base.split("@")[0].strip() or "user"
candidate = base_username
counter = 1
while User.objects.filter(username=candidate).exists():
candidate = f"{base_username}_{counter}"
counter += 1
user.username = candidate
return user