I am using Django allauth to associate already logged in in Django users with their social accounts. For frontend I use Vue js, it sends in body pw and username.
My idea was to save Django user id in session parameters after login and grab it back during the allauth flow. As far as I understood it should work: Passing a dynamic state parameter using django-allauth during social login
However, by some reason when I am trying to access the session parameter in allauth flow it is empty. The id is set in session and it should be fine. Currently, it is tested on Google OAuth2.
My login view:
@api_view(('POST',))
def login_user(request):
# get credentials from Body
request_data = json.loads(request.body)
print(request_data) # DEBUG
username = request_data['username']
password = request_data['password']
try:
# get user instance
if not User.objects.filter(username=username).exists():
raise ValidationError("The user does not exist")
else:
if username and password:
# authenticate user
user = authenticate(username=username, password=password)
if not user:
raise ValidationError("Incorrect password or username")
if not user.is_active:
raise ValidationError("This user is no longer active")
print(user) # DEBUG
# set session cookie with user id
print('SESSION UID', user.id)
request.session['user_id'] = user.id # works
session_uid = request.session.get('user_id', 'LOGIN NO SESSION UID')
# get RefreshToken for user
token_refresh = RefreshToken.for_user(user)
# response dict
data = {'token': str(token_refresh.access_token), 'refresh_token': str(token_refresh)}
# convert to utf-8 byte format for decoding
access_token = bytes(str(token_refresh.access_token), encoding="utf-8")
# decode token to get additional data
valid_data = TokenBackend(algorithm='HS256').decode(access_token, verify=False)
# add additional data to response dict
data['uuid'] = valid_data['user_id']
data['validUntil'] = valid_data['exp'] * 1000
data['clientId'] = 'default'
print(valid_data['user_id'])
return JsonResponse(data, status=status.HTTP_200_OK)
except ValidationError as v:
return HttpResponse(f"Validation error: {v}", status=status.HTTP_400_BAD_REQUEST)
except User.DoesNotExist:
raise HttpResponse("User does not exists", status=status.HTTP_404_NOT_FOUND)
My allauth signals, I always get "User Id not found":
EDITED
@receiver(user_logged_in)
def logged_in(request, user, **kwargs):
print(user) # Here django creates a new user using the chosen gmail account from login popup
request = kwargs['request']
user_id = request.session.get('user_id', 'User Id not found')
print('SESSION UID AUTH FLOW logged_in', user_id)
@receiver(pre_social_login)
def get_data(request, sociallogin, **kwargs):
session_uid = request.session.get("user_id", 'User Id not found')
print('SESSION UID AUTH FLOW get_data', session_uid)
print(request.user) # Here django creates a new user using the chosen gmail account from login popup
My adapter:
Here django creates a new user using the chosen gmail account from login popup
class MySocialAccountAdapter(DefaultSocialAccountAdapter):
def pre_social_login(self, request, sociallogin):
user_request = request.user
print('MySocialAccountAdapter', user_request, user_request.id, user_request.email)
user = sociallogin.user
if user.id:
print('MySocialAccountAdapter', user.id)
print('MySocialAccountAdapter', user.username)
return
if not user.email:
return
try:
user = User.objects.get(email=user.email) # if user exists, connect the account to the existing account and login
print('MySocialAccountAdapter', user)
sociallogin.connect(request, user)
except User.DoesNotExist:
print('User does not exist')
pass