def get_user_id(auth_data): provider = auth_data['provider'] uid = auth_data['uid'] logger.debug('uid = {}'.format(uid)) user_social_auth = UserSocialAuth.get_social_auth(provider, uid) if user_social_auth: user = YMUser.objects.get(id=user_social_auth.user_id) else: user = YMUser() if 'email' in auth_data: user.email = auth_data['email'] if 'username' in auth_data: user.username = auth_data['username'] if 'first_name' in auth_data: user.first_name = auth_data['first_name'] if 'last_name' in auth_data: user.last_name = auth_data['last_name'] if 'picture' in auth_data: user.icon_url = auth_data['picture'] if 'locale' in auth_data: user.locale = auth_data['locale'] # logger.debug('user save called...') user.save() if user_social_auth: return (user.id, False) user_social_auth = UserSocialAuth(user_id=user.id, provider=provider, uid=uid, extra_data=auth_data) user_social_auth.save() return (user.id, True)
def ensure_social_user(self, provider, user_id, username, extra_data=None, firstname=None, lastname=None): from social.apps.django_app.default.models import UserSocialAuth import uuid try: social_auth = UserSocialAuth.objects.get(provider=provider, uid=user_id) user = social_auth.user except UserSocialAuth.DoesNotExist: internal_username = username while User.objects.filter(username=internal_username).exists(): internal_username = username + uuid.uuid4().hex[:16] user = User.objects.create(username=internal_username, first_name=firstname or '', last_name=lastname or '') social_auth = UserSocialAuth(user=user, provider=provider, uid=user_id, extra_data=extra_data or {}) social_auth.save() return user, social_auth
def save(self, profile_request): user = User.objects.create_user( username=self.cleaned_data['username'], email=self.cleaned_data['email'], first_name=self.cleaned_data['first_name'], last_name=self.cleaned_data['last_name'], ) user.password = profile_request.password user.is_active = self.cleaned_data['is_active'] user.is_staff = self.cleaned_data['is_staff'] user.is_superuser = self.cleaned_data['is_superuser'] user.groups = self.cleaned_data['groups'] user.save() if profile_request.provider and profile_request.uid: social = UserSocialAuth( user=user, provider=profile_request.provider, uid=profile_request.uid, ) social.save() user_profile = UserProfile.objects.get(user=user) user_profile.email_visible = self.cleaned_data['email_visible_to_others'] user_profile.phone_number = self.cleaned_data['phone_number'] user_profile.phone_visible = self.cleaned_data['phone_visible_to_others'] user_profile.status = self.cleaned_data['status'] user_profile.save() user_profile.current_room = self.cleaned_data['current_room'] user_profile.former_rooms = self.cleaned_data['former_rooms'] user_profile.former_houses = self.cleaned_data['former_houses'] user_profile.save() return user
def _googleAuth(user): google_auth = UserSocialAuth() google_auth.user = user google_auth.provider = "google" google_auth.uid = user.email google_auth.extra_data = "{}" return google_auth
def ensure_social_user(self, provider, user_id, username, extra_data=None, firstname=None, lastname=None): from social.apps.django_app.default.models import UserSocialAuth import uuid try: social_auth = UserSocialAuth.objects.get( provider=provider, uid=user_id) user = social_auth.user except UserSocialAuth.DoesNotExist: internal_username = username while User.objects.filter(username=internal_username).exists(): internal_username = username + uuid.uuid4().hex[:16] user = User.objects.create( username=internal_username, first_name=firstname or '', last_name=lastname or '') social_auth = UserSocialAuth( user=user, provider=provider, uid=user_id, extra_data=extra_data or {} ) social_auth.save() return user, social_auth
def get_user_id(auth_data): provider = auth_data['provider'] uid = auth_data['uid'] user = UserSocialAuth.get_social_auth(provider, uid) if user: return user.id user = YMUser() if 'email' in auth_data: user.email = auth_data['email'] if 'username' in auth_data: user.username = auth_data['username'] if 'first_name' in auth_data: user.first_name = auth_data['first_name'] if 'last_name' in auth_data: user.last_name = auth_data['last_name'] user.save() user_social_auth = UserSocialAuth(user_id = user.id, provider = provider, uid = uid, extra_data = auth_data) user_social_auth.save() return user.id
def download_sheet_with_user(user, filename="membership.csv"): """ Download the membership with a user's credentials :type user: users.models.User :param user: :return: boolean of successful download """ try: social = UserSocialAuth.get_social_auth_for_user(user).get() except UserSocialAuth.DoesNotExist: return False extra = social.extra_data expiry = datetime.utcnow() + timedelta(seconds=int(extra["expires"])) credentials = OAuth2Credentials( extra["access_token"], settings.SOCIAL_AUTH_GOOGLE_OAUTH2_KEY, settings.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET, extra["refresh_token"], expiry, GOOGLE_TOKEN_URI, None, revoke_uri=GOOGLE_REVOKE_URI, ) service = build_service_from_credentials(credentials) try: file = service.files().get(fileId=settings.GOOGLE_MEMBERSHIP_FILE_ID).execute() except googleapiclient.errors.HttpError: return False url = file["exportLinks"]["text/csv"] resp, content = service._http.request(url) open(filename, "wb").write(content) return True
def settings(request, settings_form=UserProfileForm): """ Presents the user a form with their settings, basically the register form minus username minus password. Also presents additional app-specific forms listed in the KSP_LOGIN_PROFILE_FORMS setting to the user. """ form_classes = [settings_form] + get_profile_forms() if request.method == "POST": forms = [ form(request.POST, user=request.user) for form in form_classes ] if all(form.is_valid() for form in forms): for form in forms: form.save() return redirect('account_settings') else: forms = [form(user=request.user) for form in form_classes] return render( request, 'ksp_login/settings.html', { 'account_associations': UserSocialAuth.get_social_auth_for_user(request.user), 'forms': forms, })
def _post_save(sender, instance, **kwargs): original_instance = getattr(instance, "_original_instance") if hasattr( instance, "_original_instance") else None # add user's email to email identity and social auth if not exist if not instance.is_dummy_user: EmailIdentity.objects.get_or_create(email=instance.email, user=instance) if not UserSocialAuth.objects.filter(user=instance, provider="email", uid=instance.email).exists(): user_social_auth = UserSocialAuth.create_social_auth( instance, instance.email, 'email') user_social_auth.extra_data = {'email': [instance.email]} user_social_auth.save() if original_instance and original_instance.email != instance.email: if not original_instance.is_dummy_user: # delete the user's email from email identity and social auth EmailIdentity.objects.filter(email=original_instance.email, user=original_instance).delete() UserSocialAuth.objects.filter(provider="email", uid=original_instance.email, user=original_instance).delete() # update profile's email if profile's email is original email Profile.objects.filter(email=original_instance.email, user=instance).update(email=instance.email) if original_instance and any([ original_instance.first_name != instance.first_name, original_instance.last_name != instance.last_name ]): # user changed first name or last name, send a named_changed signal. name_changed.send(sender=instance.__class__, user=instance)
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """ Creates user. Depends on get_username pipeline. """ if user: return {'user': user} if not username: return None email = details.get('email') original_email = None # email is required if not email: message = _("""your social account needs to have a verified email address in order to proceed.""") raise AuthFailed(backend, message) # Avoid hitting field max length if email and len(email) > 75: original_email = email email = '' return { 'user': UserSocialAuth.create_user(username=username, email=email, sync_emailaddress=False), 'original_email': original_email, 'is_new': True }
def download_sheet_with_user(user, filename='membership.csv'): """ Download the membership with a user's credentials :type user: users.models.User :param user: :return: boolean of successful download """ try: social = UserSocialAuth.get_social_auth_for_user(user).get() except UserSocialAuth.DoesNotExist: return False extra = social.extra_data expiry = datetime.utcnow() + timedelta(seconds=int(extra['expires'])) credentials = OAuth2Credentials(extra['access_token'], settings.SOCIAL_AUTH_GOOGLE_OAUTH2_KEY, settings.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET, extra['refresh_token'], expiry, GOOGLE_TOKEN_URI, None, revoke_uri=GOOGLE_REVOKE_URI) service = build_service_from_credentials(credentials) try: file = service.files().get( fileId=settings.GOOGLE_MEMBERSHIP_FILE_ID).execute() except googleapiclient.errors.HttpError: return False url = file['exportLinks']['text/csv'] resp, content = service._http.request(url) open(filename, 'wb').write(content) return True
def social_auth_user(strategy, uid, user=None, *args, **kwargs): """ Allows user to create a new account and associate a social account, even if that social account is already connected to a different user. It effectively 'steals' the social association from the existing user. This can be a useful option during the testing phase of a project. Return UserSocialAuth account for backend/uid pair or None if it doesn't exist. Delete UserSocialAuth if UserSocialAuth entry belongs to another user. """ social = UserSocialAuth.get_social_auth(kwargs['backend'].name, uid) if social: if user and social.user != user: # Delete UserSocialAuth pairing so this account can now connect social.delete() social = None elif not user: user = social.user return { 'social': social, 'user': user, 'is_new': user is None, 'new_association': False }
def social_auth_user(strategy, uid, user=None, *args, **kwargs): """ Allows user to create a new account and associate a social account, even if that social account is already connected to a different user. It effectively 'steals' the social association from the existing user. This can be a useful option during the testing phase of a project. Return UserSocialAuth account for backend/uid pair or None if it doesn't exist. Delete UserSocialAuth if UserSocialAuth entry belongs to another user. """ social = UserSocialAuth.get_social_auth(kwargs['backend'].name, uid) if social: if user and social.user != user: # Delete UserSocialAuth pairing so this account can now connect social.delete() social = None elif not user: user = social.user return {'social': social, 'user': user, 'is_new': user is None, 'new_association': False}
def box_detail(request, slug): if request.user.is_staff: box = get_object_or_404(Box.objects.select_related( 'units', 'instructor', 'links'), slug=slug) else: box = get_object_or_404(Box.published_boxes.select_related( 'units', 'instructor', 'links'), slug=slug) box.register_user(request.user) extra_context = {} extra_context['box'] = box extra_context['box_tags'] = box.get_tags() extra_context['search_form'] = LiveSearchForm() files = [] if box.drive_folder_url: config = SiteConfiguration.objects.get() access_token = UserSocialAuth.get_social_auth_for_user( request.user, provider='google-oauth2').get().tokens credentials = OAuth2Credentials(access_token, config.google_oauth2_key, config.google_oauth2_secret, None, None, None, None) # Create an httplib2.Http object and authorize it with our credentials http = httplib2.Http() http = credentials.authorize(http) drive_service = build('drive', 'v2', http=http) folder_id = box.drive_folder_url.split("/")[-1] page_token = None while True: try: param = {} if page_token: param['pageToken'] = page_token folder_files = drive_service.files().list( q='\'%s\' in parents' % folder_id, **param).execute() files.extend(folder_files['items']) page_token = folder_files.get('nextPageToken') if not page_token: break except: break extra_context['files'] = files return render_to_response('main/box_detail.html', extra_context, context_instance=RequestContext(request))
def __init__(self, user, request=None, provider='google-oauth2'): self.user = user self.request = request self.provider = provider self.strategy = load_strategy(request) self.user_social = UserSocialAuth.get_social_auth_for_user(user=self.user, provider=self.provider)[0] self.backend = self.user_social.get_backend_instance(strategy=self.strategy)
def get(self, request): socAuth = next( iter(UserSocialAuth.get_social_auth_for_user(request.user)), None) if not socAuth: return Response(status=HTTP_404_NOT_FOUND) else: return Response({"social_provider": socAuth.provider}, status=HTTP_200_OK)
def setUp(self): provider = 'facebook' self.user = User.objects.create_user(email='*****@*****.**', password='******', username="******") self.user = User.objects.get(pk=self.user.pk) uid = '662706953856122' extra_data = '{"expires": "5108950", "id": "662706953856122", "access_token": "CAAH4lDiSMqkBAJWOEsle5ISozhx5xkPIF2ZA2sCpHsn4tIbR9WdYyw9ZAIBQN4XVMddWoXwvFNDrUZB8RSJcNJulE4byJn2Vnxffz9qyLPmz0lVakSZCqbPN2U6BzV3WPGZBl1ro5DvkKJzhRIOtyFy3Oi1yyvJjEk4f4bFIVCTN7VoJ2t1EdCHZBBG6uNZBnqiUj1vhIwOepnEHWkT2rZBZA"}' social_auth = UserSocialAuth(user=self.user, provider=provider, uid=uid, extra_data=extra_data) social_auth.save() self.user_friend = User.objects.create_user(email='*****@*****.**', password='******', username="******") self.user_friend = User.objects.get(pk=self.user_friend.pk) uid = '10206250137793732' extra_data = '{"expires": "5183999", "id": "10206250137793732", "access_token": "CAAH4lDiSMqkBAJ4rz1HutjMkUv7gg3Blc3CR7caKWPTXwWQwoVvaleg4CWnJopnxRwoXl83JkbOZACRNeenEasyIrHOKKwQTieL9s9SaxZCbEqRZBwsC9StEn686dgshAqqtIly1ojrZBR7PSxXb9klwm0qg09qSqal98ZCZBkyGpdihlSzjfPqf7MpYR2IgejdEK9ScDzQiyeKpyQQ6ZBS"}' self.social_auth_friend = UserSocialAuth(user=self.user_friend, provider=provider, uid=uid, extra_data=extra_data) self.social_auth_friend.save() self.user_no_friend = User.objects.create_user(email='*****@*****.**', password='******', username="******") self.user_no_friend = User.objects.get(pk=self.user_no_friend.pk) uid = '10153139013369780' extra_data = '{"expires": "5183999", "id": "10153139013369780", "access_token": "CAAH4lDiSMqkBACz9b3PYRoSgsxRUx19cdxxR8U5BWGRgVHlRwdHIL5HtMsCvlNaZBbZBK4qgr8AUPZAZBZCjIjPfjapLbyBDcelLi3rRAbGeImR8tuiK8naRQVW6sqTwP5GgZAX5BqIwFKZAlTgcCD2PzUsymZByJqld1UuSQVzMugM5V5yc9mKCgXJqhRy62MNULbZAQ0ZB543mOZAryBbZB0sn"}' social_auth = UserSocialAuth(user=self.user_no_friend, provider=provider, uid=uid, extra_data=extra_data) social_auth.save() self.url = '/api/facebook/friend/'
def create_links(self): """ Create all needed links to Django and/or UserSocialAuth. """ extra_data = json.loads(self.extra_data) username = extra_data.get( 'lis_person_name_full', extra_data.get('lis_person_sourcedid', self.user_id) ) first_name = extra_data.get('lis_person_name_given', '') last_name = extra_data.get('lis_person_name_family', '') email = extra_data.get('lis_person_contact_email_primary', '').lower() defaults = { 'first_name': first_name, 'last_name': last_name, } if email: defaults['email'] = email social = UserSocialAuth.objects.filter( provider='email', uid=email ).first() if social: django_user = social.user else: django_user = User.objects.filter(email=email).first() if not django_user: django_user, created = User.objects.get_or_create( username=username, defaults=defaults ) social = UserSocialAuth( user=django_user, provider='email', uid=email, extra_data=extra_data ) social.save() else: django_user, created = User.objects.get_or_create( username=username, defaults=defaults ) self.django_user = django_user self.save()
def profile_image_for_user(user): try: auth = UserSocialAuth.get_social_auth_for_user(user)[0] backend = auth.get_backend().name if backend == "google-oauth2": return HttpResponseRedirect(auth.extra_data["image"]["url"]) elif backend == "facebook": return HttpResponseRedirect(fb_profile_image(auth.uid,50,50)) except Exception, e: pass
def create_users(): User.objects.exclude(pk=1).delete() for pk, fields in users.iteritems(): if pk != 1: if fields['email'] != '': existing = User.objects.filter(email = fields['email']) if existing.count() > 0: ou = existing[0] if ou.is_active == False and fields['is_active'] == True: replace_users[ou.pk] = pk for k,v in replace_users.iteritems(): if v == ou.pk: replace_users[k] = pk ou.delete() elif ou.is_active == True and fields['is_active'] == False: replace_users[pk] = ou.pk for k,v in replace_users.iteritems(): if v == pk: replace_users[k] = ou.pk continue else: replace_users[ou.pk] = pk for k,v in replace_users.iteritems(): if v == ou.pk: replace_users[k] = pk ou.delete() #print "email:", fields['email'] nu = User(pk=pk) nu.username = fields['username'] if fields['email']: nu.email = fields['email'] nu.status = 1 nu.password = fields['password'] nu.full_name = fields['profile']['full_name'] nu.message = fields['profile']['message'] nu.is_active = fields['is_active'] nu.is_staff = fields['is_staff'] nu.is_superuser = fields['is_superuser'] nu.comment_count = fields['profile']['comment_count'] nu.dateo_count = fields['profile']['item_count'] nu.vote_count = fields['profile']['vote_count'] nu.client_domain = datea nu.save() joined = date_parser(fields['date_joined']) lastlog = date_parser(fields['last_login']) User.objects.filter(pk=nu.pk).update(date_joined=joined, created=joined, last_login=lastlog) for pk, fields in usersSocial.iteritems(): if fields['user'] != 1: nusoc = UserSocialAuth(pk=pk) nusoc.provider = fields['provider'] nusoc.uid = fields['uid'] nusoc.user_id = get_user(int(fields['user'])) nusoc.extra_data = fields['extra_data'] nusoc.save()
def __init__(self, user, request=None, provider='google-oauth2'): self.user = user self.request = request self.provider = provider self.strategy = load_strategy(request) self.user_social = UserSocialAuth.get_social_auth_for_user( user=self.user, provider=self.provider)[0] self.backend = self.user_social.get_backend_instance( strategy=self.strategy)
def test__email(self): job = running_jobs.pop(0) test_project = Project(collab=job["collab_id"], context=uuid4()) test_project.save() test_quota = Quota(project=test_project, platform=job["hardware_platform"], usage=0, limit=1000, units="foo-hours") test_quota.save() if USE_MOCKS: user = User(username="******", email="*****@*****.**") user.save() sa = UserSocialAuth(user=user, uid=job['user_id']) sa.save() log = "\n".join(str(x) for x in range(105)) log_response = self.client.put("/api/v2/log/{}".format(job["id"]), data=json.dumps({"content": log}), content_type="application/json") self.assertEqual(log_response.status_code, 201) job['timestamp_submission'] = job['timestamp_submission'].isoformat() job['status'] = "finished" job["provenance"]["version"] = 123 job["resource_usage"] = 23 job['hardware_config']["resource_allocation_id"] = test_quota.pk resource_uri = "/api/v2/queue/{}".format(job["id"]) response = self.client.put(resource_uri, data=json.dumps(job), content_type="application/json") self.assertEqual(response.status_code, 204) message = mail.outbox[0] self.assertEqual(message.to, ["*****@*****.**"]) self.assertEqual(message.subject, "[HBP Neuromorphic] job {} finished".format(job["id"])) self.assertIn("Job {} finished".format(job["id"]), message.body) self.assertIn("0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n", message.body) self.assertIn("27\n28\n29\n\n. . .\n\n35\n36\n37", # cut at :30 and -70: message.body) self.assertIn("95\n96\n97\n98\n99\n100\n101\n102\n103\n104", message.body) self.assertIn("https://collab.humanbrainproject.eu/#/collab/{}/nav/{}?state=job.{}".format(job["collab_id"], job["provenance"]["collaboratory"]["nav_item"], job["id"]), message.body)
def get_large_user_image(user): try: auth = UserSocialAuth.get_social_auth_for_user(user)[0] backend = auth.get_backend().name if backend == "google-oauth2": url = auth.extra_data["image"]["url"] return HttpResponseRedirect("%s%i" % (url[:-2],200)) elif backend == "facebook": return HttpResponseRedirect(fb_profile_image(auth.uid,200,200)) except Exception, e: pass
def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs): """ Load extra data from provider and store it on current UserSocialAuth extra_data field. """ social_user = social_user or UserSocialAuth.get_social_auth( backend.name, uid) # create verified email address if kwargs['is_new'] and EMAIL_CONFIRMATION: from ..models import EmailAddress # check if email exist before creating it # we might be associating an exisiting user if EmailAddress.objects.filter(email=user.email).count() < 1: EmailAddress.objects.create(user=user, email=user.email, verified=True, primary=True) if social_user: extra_data = backend.extra_data(user, uid, response, details) if kwargs.get('original_email') and 'email' not in extra_data: extra_data['email'] = kwargs.get('original_email') # update extra data if anything has changed if extra_data and social_user.extra_data != extra_data: if social_user.extra_data: social_user.extra_data.update(extra_data) else: social_user.extra_data = extra_data social_user.save() # fetch additional data from facebook on creation if backend.name == 'facebook' and kwargs['is_new']: response = json.loads( requests.get( 'https://graph.facebook.com/%s?access_token=%s' % (extra_data['id'], extra_data['access_token'])).content) try: user.city, user.country = response.get('hometown').get( 'name').split(', ') except (AttributeError, TypeError): pass try: user.birth_date = datetime.strptime(response.get('birthday'), '%m/%d/%Y').date() except (AttributeError, TypeError): pass user.save() return {'social_user': social_user}
def setUp(self): user = User.objects.create_user(username='******', email='*****@*****.**', password='******') user_social_auth = UserSocialAuth() user_social_auth.provider = 'evernote-sandbox' user_social_auth.uid = '596560' user_social_auth.extra_data = '{"access_token": {"edam_webApiUrlPrefix": "https://sandbox.evernote.com/shard/s1/", "edam_shard": "s1", "oauth_token": "S=s1:U=91a50:E=158f7ee9efa:C=151a03d7140:P=185:A=koichi-ezato-3816:V=2:H=1a4e5efcc8f63951e17852d0c8019cab", "edam_expires": "1481628360442", "edam_userId": "596560", "edam_noteStoreUrl": "https://sandbox.evernote.com/shard/s1/notestore"}, "expires": 1481628360, "store_url": "https://sandbox.evernote.com/shard/s1/notestore", "oauth_token": "S=s1:U=91a50:E=158f7ee9efa:C=151a03d7140:P=185:A=koichi-ezato-3816:V=2:H=1a4e5efcc8f63951e17852d0c8019cab"}' user_social_auth.user = user user_social_auth.save()
def _googleAuth(user): google_auth = UserSocialAuth() google_auth.user = user google_auth.provider = 'google' google_auth.uid = user.email google_auth.extra_data = '{}' return google_auth
def delete(self, request): # If this is a Google social account, revoke its Google tokens socAuth = next( iter(UserSocialAuth.get_social_auth_for_user(request.user)), None) if socAuth and socAuth.provider == 'google-oauth2': refresh_token = socAuth.extra_data.get( 'refresh_token', socAuth.extra_data['access_token']) makerequest.post( 'https://accounts.google.com/o/oauth2/revoke?token=' + refresh_token) request.user.delete() return Response(status=HTTP_200_OK)
def disconnect(request, backend, association_id): """ If the user has at least one other social account association or a valid password, disconnects the given social account, otherwise asks the user to set up a password before proceeding. """ associations = UserSocialAuth.get_social_auth_for_user(request.user) has_assoc = associations.exclude(id=association_id).count() has_pass = request.user.has_usable_password() if has_assoc or has_pass: return social_disconnect(request=request, backend=backend, association_id=association_id) return render(request, 'ksp_login/invalid_disconnect.html')
def create_links(self): """ Create all needed links to Django and/or UserSocialAuth. """ extra_data = json.loads(self.extra_data) username = extra_data.get( 'lis_person_name_full', extra_data.get('lis_person_sourcedid', self.user_id)) first_name = extra_data.get('lis_person_name_given', '') last_name = extra_data.get('lis_person_name_family', '') email = extra_data.get('lis_person_contact_email_primary', '').lower() defaults = { 'first_name': first_name, 'last_name': last_name, } if email: defaults['email'] = email social = UserSocialAuth.objects.filter(provider='email', uid=email).first() if social: django_user = social.user else: django_user = User.objects.filter(email=email).first() if not django_user: django_user, created = User.objects.get_or_create( username=username, defaults=defaults) social = UserSocialAuth(user=django_user, provider='email', uid=email, extra_data=extra_data) social.save() else: django_user, created = User.objects.get_or_create( username=username, defaults=defaults) self.django_user = django_user self.save()
def get_search_fields(self, request=None): search_fields = getattr(settings, setting_name('ADMIN_USER_SEARCH_FIELDS'), None) if search_fields is None: _User = UserSocialAuth.user_model() username = getattr(_User, 'USERNAME_FIELD', None) or \ hasattr(_User, 'username') and 'username' or \ None fieldnames = ('first_name', 'last_name', 'email', username) all_names = _User._meta.get_all_field_names() search_fields = [ name for name in fieldnames if name and name in all_names ] return ['user__' + name for name in search_fields]
def get_search_fields(self): search_fields = getattr( settings, setting_name('ADMIN_USER_SEARCH_FIELDS'), None ) if search_fields is None: _User = UserSocialAuth.user_model() username = getattr(_User, 'USERNAME_FIELD', None) or \ hasattr(_User, 'username') and 'username' or \ None fieldnames = ('first_name', 'last_name', 'email', username) all_names = _User._meta.get_all_field_names() search_fields = [name for name in fieldnames if name and name in all_names] return ['user_' + name for name in search_fields]
def password(request): """ Sets, changes or removes the currently logged in user's passwords, depending on whether they have any social account associations. """ has_assoc = UserSocialAuth.get_social_auth_for_user(request.user).count() if request.user.has_usable_password(): def form(*args, **kwargs): return PasswordChangeForm(not has_assoc, *args, **kwargs) else: form = SetPasswordForm return password_change(request, post_change_redirect=reverse('account_settings'), password_change_form=form, template_name='ksp_login/password.html')
def social_user(backend, uid, user=None, *args, **kwargs): """Return UserSocialAuth account for backend/uid pair or None if it doesn't exists. CHANGE: Raise AuthAlreadyAssociated if UserSocialAuth entry belongs to another user. INSTEAD: Set new UserSocialAuth to user if associated before. """ social_user = UserSocialAuth.get_social_auth(backend.name, uid) if social_user: if user and social_user.user != user: social_user.user = user social_user.save() elif not user: user = social_user.user return {'social_user': social_user, 'user': user}
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """Create user. Depends on get_username pipeline.""" if user: return {'user': user} if not username: return None user = UserSocialAuth.create_user(username=get_unique_username(), ) permission = Permission.objects.get(codename=u'is_requester') user.user_permissions.add(permission) profile = Profile.objects.create(user=user) user.set_username_by_id() user.save() return { 'user': user, 'is_new': True }
def _post_save(sender, instance, **kwargs): if not hasattr(instance, "auth_identity"): # not triggered by user. return original_instance = getattr(instance, "_original_instance") if hasattr(instance, "_original_instance") else None auth_identity = getattr(instance, "auth_identity") if auth_identity: # add email to email identity and social auth if not exist EmailIdentity.objects.get_or_create(email=instance.email, user=instance.user) if not UserSocialAuth.objects.filter(user=instance.user, provider="email", uid=instance.email).exists(): user_social_auth = UserSocialAuth.create_social_auth(instance.user, instance.email, 'email') user_social_auth.extra_data = {'email': [instance.email]} user_social_auth.save() if original_instance and (original_instance.email != instance.email or not auth_identity): # delete the profile's email from email identity and social auth EmailIdentity.objects.filter(email=original_instance.email, user=original_instance.user).delete() UserSocialAuth.objects.filter(provider="email", uid=original_instance.email, user=original_instance.user).delete()
def social_auth_user(strategy, uid, user=None, *args, **kwargs): """Return UserSocialAuth account for backend/uid pair or None if it doesn't exists. Delete UserSocialAuth if UserSocialAuth entry belongs to another user. """ social = UserSocialAuth.get_social_auth(strategy.backend.name, uid) if social: if user and social.user != user: # Delete UserSocialAuth pairing so this account can now connect social.delete() social = None elif not user: user = social.user return {'social': social, 'user': user, 'is_new': user is None, 'new_association': False}
def social_auth_user(strategy, uid, user=None, *args, **kwargs): """Return UserSocialAuth account for backend/uid pair or None if it doesn't exists. Delete UserSocialAuth if UserSocialAuth entry belongs to another user. """ social = UserSocialAuth.get_social_auth(strategy.backend.name, uid) if social: if user and social.user != user: # Delete UserSocialAuth pairing so this account can now connect social.delete() social = None elif not user: user = social.user return { 'social': social, 'user': user, 'is_new': user is None, 'new_association': False }
def _post_save(sender, instance, **kwargs): original_instance = getattr(instance, "_original_instance") if hasattr(instance, "_original_instance") else None # add user's email to email identity and social auth if not exist if not instance.is_dummy_user: EmailIdentity.objects.get_or_create(email=instance.email, user=instance) if not UserSocialAuth.objects.filter(user=instance, provider="email", uid=instance.email).exists(): user_social_auth = UserSocialAuth.create_social_auth(instance, instance.email, 'email') user_social_auth.extra_data = {'email': [instance.email]} user_social_auth.save() if original_instance and original_instance.email != instance.email: if not original_instance.is_dummy_user: # delete the user's email from email identity and social auth EmailIdentity.objects.filter(email=original_instance.email, user=original_instance).delete() UserSocialAuth.objects.filter(provider="email", uid=original_instance.email, user=original_instance).delete() # update profile's email if profile's email is original email Profile.objects.filter(email=original_instance.email, user=instance).update(email=instance.email) if original_instance and any([original_instance.first_name != instance.first_name, original_instance.last_name != instance.last_name]): # user changed first name or last name, send a named_changed signal. name_changed.send(sender=instance.__class__, user=instance)
def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs): """ Load extra data from provider and store it on current UserSocialAuth extra_data field. """ social_user = social_user or UserSocialAuth.get_social_auth(backend.name, uid) # create verified email address if kwargs['is_new'] and EMAIL_CONFIRMATION: from ..models import EmailAddress # check if email exist before creating it # we might be associating an exisiting user if EmailAddress.objects.filter(email=user.email).count() < 1: EmailAddress.objects.create(user=user, email=user.email, verified=True, primary=True) if social_user: extra_data = backend.extra_data(user, uid, response, details) if kwargs.get('original_email') and 'email' not in extra_data: extra_data['email'] = kwargs.get('original_email') # update extra data if anything has changed if extra_data and social_user.extra_data != extra_data: if social_user.extra_data: social_user.extra_data.update(extra_data) else: social_user.extra_data = extra_data social_user.save() # fetch additional data from facebook on creation if backend.name == 'facebook' and kwargs['is_new']: response = json.loads(requests.get('https://graph.facebook.com/%s?access_token=%s' % (extra_data['id'], extra_data['access_token'])).content) try: user.city, user.country = response.get('hometown').get('name').split(', ') except AttributeError: pass try: user.birth_date = datetime.strptime(response.get('birthday'), '%m/%d/%Y').date() except AttributeError: pass user.save() return {'social_user': social_user}
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """ Creates user. Depends on get_username pipeline. """ if user: return {'user': user} if not username: return None email = details.get('email') original_email = None # email is required if not email: message = _( """your social account needs to have a verified email address in order to proceed.""" ) raise AuthFailed(backend, message) # Avoid hitting field max length if email and len(email) > 75: original_email = email email = '' return { 'user': UserSocialAuth.create_user(username=username, email=email, sync_emailaddress=False), 'original_email': original_email, 'is_new': True }
def settings(request, settings_form=UserProfileForm): """ Presents the user a form with their settings, basically the register form minus username minus password. Also presents additional app-specific forms listed in the KSP_LOGIN_PROFILE_FORMS setting to the user. """ form_classes = [settings_form] + get_profile_forms() if request.method == "POST": forms = [form(request.POST, user=request.user) for form in form_classes] if all(form.is_valid() for form in forms): for form in forms: form.save() return redirect('account_settings') else: forms = [form(user=request.user) for form in form_classes] return render(request, 'ksp_login/settings.html', { 'account_associations': UserSocialAuth.get_social_auth_for_user(request.user), 'forms': forms, })
def youtube_embed_url(user): try: return UserSocialAuth.get_social_auth('google-oauth2',user.email).extra_data['image']['url'] except: return '/static/global/images/placeholder/user.png'
"""Admin settings""" from django.contrib import admin from social.apps.django_app.default.models import UserSocialAuth, Nonce, \ Association _User = UserSocialAuth.user_model() username = getattr(_User, 'USERNAME_FIELD', None) or \ hasattr(_User, 'username') and 'username' or \ None fieldnames = ('first_name', 'last_name', 'email', username) all_names = _User._meta.get_all_field_names() user_search_fields = ['user__' + name for name in fieldnames if name and name in all_names] class UserSocialAuthOption(admin.ModelAdmin): """Social Auth user options""" list_display = ('id', 'user', 'provider', 'uid') search_fields = user_search_fields list_filter = ('provider',) raw_id_fields = ('user',) list_select_related = True class NonceOption(admin.ModelAdmin): """Nonce options""" list_display = ('id', 'server_url', 'timestamp', 'salt') search_fields = ('server_url',)
def _post_save(sender, instance, **kwargs): if not hasattr(instance, "auth_identity"): # not triggered by user. return original_instance = getattr(instance, "_original_instance") if hasattr(instance, "_original_instance") else None auth_identity = getattr(instance, "auth_identity") if auth_identity: # add email to email identity and social auth if not exist EmailIdentity.objects.get_or_create(email=instance.email, user=instance.user) if not UserSocialAuth.objects.filter(user=instance.user, provider="email", uid=instance.email).exists(): user_social_auth = UserSocialAuth.create_social_auth(instance.user, instance.email, 'email') user_social_auth.extra_data = {'email': [instance.email]} user_social_auth.save() if original_instance and (original_instance.email != instance.email or not auth_identity): # delete the profile's email from email identity and social auth EmailIdentity.objects.filter(email=original_instance.email, user=original_instance.user).delete() UserSocialAuth.objects.filter(provider="email", uid=original_instance.email, user=original_instance.user).delete() if not original_instance: address = instance.postal_address try: # Check if the user has the same profile address # Check if there is a user address oscar_add = UserAddress.objects.get( line1 = address.line1, line2 = address.line2, line3 = address.line3, line4 = address.locality, state = address.state, postcode = address.postcode, country = Country.objects.get(iso_3166_1_a2=address.country), user = instance.user ) if not address.oscar_address: address.oscar_address = oscar_add address.save() elif address.oscar_address.id != oscar_add.id: address.oscar_address = oscar_add address.save() except UserAddress.DoesNotExist: oscar_address = UserAddress.objects.create( line1 = address.line1, line2 = address.line2, line3 = address.line3, line4 = address.locality, state = address.state, postcode = address.postcode, country = Country.objects.get(iso_3166_1_a2=address.country), user = instance.user ) address.oscar_address = oscar_address address.save() # Clear out unused addresses user = instance.user user_addr = Address.objects.filter(user=user) for u in user_addr: if not u.profiles.all(): u.oscar_address.delete() u.delete()
def youtube_embed_url(user): try: return UserSocialAuth.get_social_auth( 'google-oauth2', user.email).extra_data['image']['url'] except: return '/static/global/images/placeholder/user.png'
def create_user(**kwargs): user = EmailUser.objects.create(**kwargs) UserSocialAuth.create_social_auth(user, user.email, "email") return user
class UserResourceTest(ResourceTestCase): def setUp(self): provider = 'facebook' self.user = User.objects.create_user(email='*****@*****.**', password='******', username="******") self.user = User.objects.get(pk=self.user.pk) uid = '662706953856122' extra_data = '{"expires": "5108950", "id": "662706953856122", "access_token": "CAAH4lDiSMqkBAJWOEsle5ISozhx5xkPIF2ZA2sCpHsn4tIbR9WdYyw9ZAIBQN4XVMddWoXwvFNDrUZB8RSJcNJulE4byJn2Vnxffz9qyLPmz0lVakSZCqbPN2U6BzV3WPGZBl1ro5DvkKJzhRIOtyFy3Oi1yyvJjEk4f4bFIVCTN7VoJ2t1EdCHZBBG6uNZBnqiUj1vhIwOepnEHWkT2rZBZA"}' social_auth = UserSocialAuth(user=self.user, provider=provider, uid=uid, extra_data=extra_data) social_auth.save() self.user_friend = User.objects.create_user(email='*****@*****.**', password='******', username="******") self.user_friend = User.objects.get(pk=self.user_friend.pk) uid = '10206250137793732' extra_data = '{"expires": "5183999", "id": "10206250137793732", "access_token": "CAAH4lDiSMqkBAJ4rz1HutjMkUv7gg3Blc3CR7caKWPTXwWQwoVvaleg4CWnJopnxRwoXl83JkbOZACRNeenEasyIrHOKKwQTieL9s9SaxZCbEqRZBwsC9StEn686dgshAqqtIly1ojrZBR7PSxXb9klwm0qg09qSqal98ZCZBkyGpdihlSzjfPqf7MpYR2IgejdEK9ScDzQiyeKpyQQ6ZBS"}' self.social_auth_friend = UserSocialAuth(user=self.user_friend, provider=provider, uid=uid, extra_data=extra_data) self.social_auth_friend.save() self.user_no_friend = User.objects.create_user(email='*****@*****.**', password='******', username="******") self.user_no_friend = User.objects.get(pk=self.user_no_friend.pk) uid = '10153139013369780' extra_data = '{"expires": "5183999", "id": "10153139013369780", "access_token": "CAAH4lDiSMqkBACz9b3PYRoSgsxRUx19cdxxR8U5BWGRgVHlRwdHIL5HtMsCvlNaZBbZBK4qgr8AUPZAZBZCjIjPfjapLbyBDcelLi3rRAbGeImR8tuiK8naRQVW6sqTwP5GgZAX5BqIwFKZAlTgcCD2PzUsymZByJqld1UuSQVzMugM5V5yc9mKCgXJqhRy62MNULbZAQ0ZB543mOZAryBbZB0sn"}' social_auth = UserSocialAuth(user=self.user_no_friend, provider=provider, uid=uid, extra_data=extra_data) social_auth.save() self.url = '/api/facebook/friend/' def test_post(self): response = self.client.post(self.url) self.assertEqual(405, response.status_code) def test_get_without_parameters(self): response = self.client.get(self.url, format='json') self.assertEqual(404, response.status_code) def test_get_only_email_parameter(self): response = self.client.get(self.url, {'email': '*****@*****.**'}, format='json') self.assertEqual(404, response.status_code) def test_get_only_email_friend_parameter(self): response = self.client.get(self.url, {'email_friend': '*****@*****.**'}, format='json') self.assertEqual(404, response.status_code) def test_get_with_both_parameters_user_no_exist(self): response = self.client.get(self.url, {'email': '*****@*****.**', 'email_friend': '*****@*****.**'}, format='json') self.assertEqual(404, response.status_code) def test_get_with_both_parameter_user_exist(self): response = self.client.get(self.url, {'email': self.user.email, 'email_friend': self.user_friend.email}, format='json') self.assertEqual(200, response.status_code) content = response.content expected = {'objects': [{'resource_uri': '', 'value': True}]} self.assertEqual(expected, json.loads(content)) def test_get_with_both_parameter_user_no_friend(self): response = self.client.get(self.url, {'email': self.user.email, 'email_friend': self.user_no_friend.email}, format='json') self.assertEqual(200, response.status_code) content = response.content expected = {'objects': [{'resource_uri': '', 'value': False}]} self.assertEqual(expected, json.loads(content)) def test_get_with_both_parameter_friend_no_facebook(self): self.social_auth_friend.delete() response = self.client.get(self.url, {'email': self.user.email, 'email_friend': self.user_friend.email}, format='json') self.assertEqual(404, response.status_code)
def setUp(self): user = EmailUser.objects.create(email=REGISTERED_USER_EMAIL) UserSocialAuth.create_social_auth(user, user.email, 'email') self.client = Client()
def _post_save(sender, instance, **kwargs): if not hasattr(instance, "auth_identity"): # not triggered by user. return original_instance = getattr(instance, "_original_instance") if hasattr( instance, "_original_instance") else None auth_identity = getattr(instance, "auth_identity") if auth_identity: # add email to email identity and social auth if not exist EmailIdentity.objects.get_or_create(email=instance.email, user=instance.user) if not UserSocialAuth.objects.filter(user=instance.user, provider="email", uid=instance.email).exists(): user_social_auth = UserSocialAuth.create_social_auth( instance.user, instance.email, 'email') user_social_auth.extra_data = {'email': [instance.email]} user_social_auth.save() if original_instance and (original_instance.email != instance.email or not auth_identity): # delete the profile's email from email identity and social auth EmailIdentity.objects.filter(email=original_instance.email, user=original_instance.user).delete() UserSocialAuth.objects.filter( provider="email", uid=original_instance.email, user=original_instance.user).delete() if not original_instance: address = instance.postal_address try: # Check if the user has the same profile address # Check if there is a user address oscar_add = UserAddress.objects.get( line1=address.line1, line2=address.line2, line3=address.line3, line4=address.locality, state=address.state, postcode=address.postcode, country=Country.objects.get(iso_3166_1_a2=address.country), user=instance.user) if not address.oscar_address: address.oscar_address = oscar_add address.save() elif address.oscar_address.id != oscar_add.id: address.oscar_address = oscar_add address.save() except UserAddress.DoesNotExist: oscar_address = UserAddress.objects.create( line1=address.line1, line2=address.line2, line3=address.line3, line4=address.locality, state=address.state, postcode=address.postcode, country=Country.objects.get(iso_3166_1_a2=address.country), user=instance.user) address.oscar_address = oscar_address address.save() # Clear out unused addresses user = instance.user user_addr = Address.objects.filter(user=user) for u in user_addr: if not u.profiles.all(): u.oscar_address.delete() u.delete()
def save_profile(backend, strategy, uid, response={} or object(), details={}, *args, **kwargs): print('response: ' + str(response)) print('details: ' + str(details)) print('args: ' + str(args)) print('kwargs: ' + str(kwargs)) user = Account.objects.filter(auth_via=backend.name, social_id=uid).first() if user: login_user = auth.authenticate(username=details['email'], password='******') social = UserSocialAuth(login_user, uid, backend.name) strategy.session_set('email', details['email']) else: if details['email'] == '': raise AuthTokenError('error') avatar = '/media/default_avatar.png' if response['photo']: avatar = response['photo'] # reg user hasher = get_hasher('default') if 'bdate' in response and len(response['bdate'].split('.')) != 3: date = response['bdate'].split('.') date = date[-1] + '.' + date[1] + '.' + date[0] try: Account.objects.create(password=hasher.encode( '55', hasher.salt()), email=details['email'], first_name=details['first_name'], last_name=details['last_name'], auth_via=backend.name, access_token=response['access_token'], social_id=uid, avatar=avatar, sex=response['sex'], birthday=date) except IntegrityError: raise AuthMissingParameter else: try: Account.objects.create(password=hasher.encode( '55', hasher.salt()), email=details['email'], first_name=details['first_name'], last_name=details['last_name'], auth_via=backend.name, access_token=response['access_token'], social_id=uid, avatar=avatar, sex=response['sex']) except IntegrityError: raise AuthMissingParameter # login user login_user = auth.authenticate(username=details['email'], password='******') social = UserSocialAuth(login_user, uid, backend.name) strategy.session_set('email', details['email']) return {'user': login_user, 'social': social}