Skip to content

Instantly share code, notes, and snippets.

@elcolie
Created October 3, 2017 13:09
Show Gist options
  • Save elcolie/1e291af47aa7312ec7d06f76c91f797e to your computer and use it in GitHub Desktop.
Save elcolie/1e291af47aa7312ec7d06f76c91f797e to your computer and use it in GitHub Desktop.
import logging
from soken_web.apps.shops.api.serializers import ShopSerializer
from soken_web.apps.userprofiles.api.serializers import UserProfileSerializer
from soken_web.apps.userprofiles.models import UserProfile
logger = logging.getLogger('django')
# token.py
def jwt_response_payload_handler(token, user=None, request=None):
""" Custom response payload handler.
This function controls the custom payload after login or token refresh. This data is returned through the web API.
"""
try:
profile = user.userprofile
userprofile_serializer = UserProfileSerializer(profile)
userprofile_data = userprofile_serializer.data
shop_serializer = ShopSerializer(profile.shop)
shop_data = shop_serializer.data
except UserProfile.DoesNotExist as err:
# superuser logged in
logger.info(f'{user} has no userprofile. Possible superuser')
userprofile_data = {
'role': UserProfile.RoleType.staff,
'given_name': user.first_name,
'family_name': user.last_name,
'phone_number': "",
'mobile_number': "",
'email': user.email,
'image': None,
}
shop_data = None
return {
'token': token,
'userprofile': userprofile_data,
'shop': shop_data
}
# serializer.py
class UserProfileSerializer(serializers.ModelSerializer):
"""For JWT token"""
image = serializers.ImageField(source='profile_picture', use_url=True)
class Meta:
model = UserProfile
fields = [
'role',
'given_name',
'family_name',
'phone_number',
'mobile_number',
'email',
'image',
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment