diff --git a/apps/auth/views.py b/apps/auth/views.py index 03bafabb..d1165172 100644 --- a/apps/auth/views.py +++ b/apps/auth/views.py @@ -5,6 +5,7 @@ from facepy.exceptions import FacepyError from django.contrib.auth import get_user_model, logout, login, views from django.contrib.auth.forms import AuthenticationForm +from django.core.files.base import ContentFile from django.http import JsonResponse from django.urls import reverse_lazy from django.utils.decorators import method_decorator @@ -135,27 +136,34 @@ class FacebookLoginOrRegistration(View): graph = GraphAPI(access_token) try: data = graph.get('/me?fields=email, first_name, last_name') + photo_data = graph.get('/me/picture?height=120') except FacepyError: return JsonResponse({"success": False}) fb_id = data.get('id') - lilcity_user_settings = User.objects.filter(fb_id=fb_id) - if lilcity_user_settings.count(): - login(requests, user=lilcity_user_settings[0]) - return JsonResponse({"success": True}) - - email = requests.POST.get('email') or data.get('email') - if not email: - return JsonResponse({"success": False, - "errors": {"email": 'is field required'} - }) + try: + user = User.objects.get(fb_id=fb_id) + except User.DoesNotExist: + email = requests.POST.get('email') or data.get('email') + if not email: + return JsonResponse({"success": False, + "errors": {"email": 'is field required'} + }) + else: + first_name = data.get('first_name', '') + last_name = data.get('last_name', '') + + user = User.objects.create_user(username=email, email=email, first_name=first_name, last_name=last_name, password=uuid4().hex) + user.is_email_proved = True + user.fb_id = fb_id + if photo_data: + photo = ContentFile(photo_data) + fname = str(fb_id) + '.jpg' + user.photo.save(fname, photo, save=True) + user.save() + login(requests, user=user) + return JsonResponse({"success": True}) else: - first_name = data.get('first_name', '') - last_name = data.get('last_name', '') - - user = User.objects.create_user(username=email, email=email, first_name=first_name, last_name=last_name, password=uuid4().hex) - user.is_email_proved = True - user.fb_id = fb_id - user.save() + login(requests, user=user) return JsonResponse({"success": True})