def get_or_create_user(token_details): """ Get a Django User with a matching Globus uuid (sub) or create one if it does not exist. The UserSocialAuth user instance is created whether or not a user logged in via social auth or simply passed a token into the API. This allows the user to do either in either order. token_details -- Token response details from introspecting a Globus Token """ try: return UserSocialAuth.objects.get(uid=token_details['sub']).user except UserSocialAuth.DoesNotExist: name = token_details['name'].split(' ', 1) first_name, last_name = name if len(name) > 1 else (name, '') user = User(username=token_details['username'], first_name=first_name, last_name=last_name, email=token_details['email']) user.save() usa = UserSocialAuth(user=user, provider='globus', uid=token_details['sub']) usa.save() return user
def ensure_social_user(self, provider, user_id, username, extra_data=None, firstname=None, lastname=None): from social_django.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 load_github_avatar(response: Dict, social: UserSocialAuth, *args, **kwargs) -> Dict: """ Add GitHub avatar url to the extra data stored by social_django app Args: response: request dictionary social: Social auth user model object *args: Variable length argument list. **kwargs: Arbitrary keyword arguments. Returns: return a dictionary with the Social auth user object in it or empty if no action are taken """ # assume github-org backend, add <if backend.name == 'github-org'> # if other backend are implemented # if social and social.get('extra_data', None) # print(vars(social)) if 'avatar_url' not in social.extra_data: logger.info('Adding GitHub avatar url to user extra data') social.extra_data['avatar_url'] = response['avatar_url'] social.save() return {'social': social} return {}
def post(self, request, *args, **kwargs): try: signed_request = request.POST['signed_request'] encoded_sig, payload = signed_request.split('.') except (ValueError, KeyError): return HttpResponse(status=400, content='Invalid request') try: # Reference for request decoding: https://developers.facebook.com/docs/games/gamesonfacebook/login#parsingsr # For some reason, the request needs to be padded in order to be decoded. See https://stackoverflow.com/a/6102526/2628463 decoded_payload = base64.urlsafe_b64decode(payload + "==").decode('utf-8') decoded_payload = json.loads(decoded_payload) if type(decoded_payload ) is not dict or 'user_id' not in decoded_payload.keys(): return HttpResponse(status=400, content='Invalid payload data') except (ValueError, json.JSONDecodeError): return HttpResponse(status=400, content='Could not decode payload') try: secret = settings.SOCIAL_AUTH_FACEBOOK_SECRET sig = base64.urlsafe_b64decode(encoded_sig + "==") expected_sig = hmac.new(bytes(secret, 'utf-8'), bytes(payload, 'utf-8'), hashlib.sha256) except: return HttpResponse(status=400, content='Could not decode signature') if not hmac.compare_digest(expected_sig.digest(), sig): return HttpResponse(status=400, content='Invalid request') user_id = decoded_payload['user_id'] try: social_account = UserSocialAuth.objects.get(uid=user_id) except UserSocialAuth.DoesNotExist: return HttpResponse(status=200) # Own custom logic here try: UserSocialAuth.disconnect(social_account) except: HttpResponse(status=400, content='Could not disconnect account') code = ''.join( random.choices(string.ascii_uppercase + string.digits, k=10)) return JsonResponse({ 'url': f"https://eurovisiontippning.se{reverse(login.views.confirm_deletion)}", 'confirmation_code': code })
def put(self, request, *args, **kwargs): body = json.loads(request.body.decode('utf-8')) body['auth_time'] = int(datetime.now().strftime('%s')) form = self.form_class(body) if not form.is_valid(): return JsonResponse({'result': 'error'}, status=400) social_auth = UserSocialAuth.get_social_auth(provider='twitter', uid=form.data['user_id']) display_name = get_display_name(form.data['user_id'], form.data['oauth_token'], form.data['oauth_token_secret']) if social_auth: user = social_auth.user user.username = form.data['screen_name'] user.first_name = display_name user.save() social_auth.user = user extra_data = social_auth.extra_data extra_data['auth_time'] = form.data['auth_time'] extra_data['access_token']['screen_name'] = form.data[ 'screen_name'] social_auth.extra_data = extra_data social_auth.save() return JsonResponse({'result': 'success'}) user = self.user_model.objects.create_user( username=form.data['screen_name'], first_name=display_name, is_active=True) user.save() extra_data = { 'auth_time': form.data['auth_time'], 'id': form.data['user_id'], 'access_token': { 'oauth_token': form.data['oauth_token'], 'oauth_token_secret': form.data['oauth_token_secret'], 'user_id': int(form.data['user_id']), 'screen_name': form.data['screen_name'] } } social_auth = UserSocialAuth(user=user, provider='twitter', uid=int(form.data['user_id']), extra_data=extra_data) social_auth.save() return JsonResponse({'result': 'success'})
def process_request(request, userID, socialID): user = uMod.User.objects.get(id=userID) form = MergeForm(request) if form.is_valid(): junk = uMod.Junk.objects.get(identifier = socialID) social_user = UserSocialAuth() social_user.provider = junk.data1 social_user.uid = junk.data2 social_user.extra_data = json.loads(junk.data3) social_user.user_id = user.id social_user.save() junk.delete() form.commit() return HttpResponseRedirect('/homepage/index/') context = { 'user': user, 'form': form, } return request.dmp.render('merge_accounts.html', context)
def setUpClass(cls): Edit.ingest_jsonlines('store/testdata/one_or_batch.json') cls.batch = Batch.objects.get() cls.client = Client() cls.mary = User(username='******', password='******') cls.mary.save() mary_auth = UserSocialAuth( user=cls.mary, provider='wikidata', uid='39834872', extra_data= {"access_token": {"oauth_token": "12345", "oauth_token_secret": "67890"}, "auth_time": 1520695332}) mary_auth.save() cls.john = User(username='******', password='******') cls.john.save()
def test_not_implemented_igitt_repo_creation(self): self.auth = UserSocialAuth( user=self.user, provider='unknownprovider') self.auth.set_extra_data({ 'access_token': 'stupidshit' }) self.auth.save() with self.assertRaises(NotImplementedError): repo = Repository( user=self.user, provider='unknownprovider', full_name='some_repo', active=False ).igitt_repo
def create_links(self): """ Create all needed links to Django and/or UserSocialAuth. """ extra_data = json.loads(self.extra_data) 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() django_user = None defaults = { 'first_name': first_name, 'last_name': last_name, 'email': email } if 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: username = hash_lti_user_data( self.user_id, extra_data.get('tool_consumer_instance_guid', ''), extra_data.get('lis_person_sourcedid', '') ) django_user, _ = User.objects.get_or_create( username=username, defaults=defaults ) if email: social = UserSocialAuth( user=django_user, provider='email', uid=email, extra_data=extra_data ) social.save() self.django_user = django_user self.save()
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 refresh_fb_friend_status(user): try: ex_user = Ex_User.objects.get(user=user) if ex_user.access_token != '' and ex_user.access_token != 'EXPIRED': url = 'https://graph.facebook.com/v2.11/me?fields=friends&access_token=' + ex_user.access_token response = requests.get(url) if (response.status_code == 400): ex_user.access_token = 'EXPIRED' elif (response.status_code == 200): friends = response.json()['friends']['data'] for friend in friends: try: friend_by_id = UserSocialAuth.get_social_auth( 'facebook', friend['id']).user if friend_by_id is not None: try: ex_user_friend = Ex_User.objects.get( user=friend_by_id) ex_user.fb_friends.add(ex_user_friend) except Exception: pass except Exception: pass ex_user.save() except (Ex_User.DoesNotExist): pass
def migrate_accounts(self): self.stdout.write( self.style.SUCCESS('Going through all SocialAccount objects...')) # Retrieve existing objects providers = {} for usa in UserSocialAuth.objects.all(): provider = providers.setdefault(usa.provider, {}) provider[usa.uid] = usa with transaction.atomic(): create_objs = [] for sa in SocialAccount.objects.all(): provider = providers.setdefault(sa.provider, {}) if sa.uid in provider: continue usa = provider[sa.uid] = UserSocialAuth( user=sa.user, provider=sa.provider, uid=sa.uid, extra_data=sa.extra_data, ) create_objs.append(usa) self.stdout.write( self.style.SUCCESS('Adding provider {}, uid {}'.format( sa.provider, sa.uid))) if len(create_objs) == 1000: self.stdout.write(self.style.SUCCESS('Saving')) UserSocialAuth.objects.bulk_create(create_objs) create_objs = [] if create_objs: UserSocialAuth.objects.bulk_create(create_objs) self.stdout.write(self.style.SUCCESS('Done.'))
def test_social_auth_has_access_token(self): access_token = 'token' user = self.create_gitlab_user(save=False) user.social_auth = UserSocialAuth() user.social_auth.extra_data['access_token'] = access_token self.assertTrue(user.has_access_token()) self.assertEqual(user.get_access_token(), access_token)
def check_user(strategy, user, request, **kwargs): print(kwargs) if user is None and kwargs['is_new']: messages.error(request, 'To use this, you need to connect your account first.') return redirect('http://localhost:4200/sign_in') try: uid = user.social_auth.get(provider='facebook').uid if kwargs['response']['id'] != uid: messages.error( request, 'This snu-moim ID is already connected to another Facebook account.' ) return redirect('http://localhost:4200/sign_in') except Exception: pass try: fb_user = UserSocialAuth.get_social_auth('facebook', kwargs['response']['id']).user if user.id != fb_user.id: messages.error( request, 'This Facebook account is already connected to another snu-moim ID.' ) return redirect('http://localhost:4200/sign_in') except Exception: pass
def setUp(self): self.tz = timezone('America/Denver') self.user = User.objects.create_user('tethys1', '*****@*****.**', 'pass') self.social_auth = UserSocialAuth.create_social_auth( self.user, 'username', 'UITPlus') self.uitplusjob = UitPlusJob( name='uit_job', user=self.user, description='test_description', label='test_label', workspace='test_ws', node_type='compute', system='topaz', job_id='J0001', project_id='P001', num_nodes=10, processes_per_node=5, max_time=timedelta(hours=10, seconds=42), max_cleanup_time=timedelta(hours=10, seconds=60), job_script='PBSScript', transfer_input_files=['file1.xml', 'file10.xml'], archive_input_files=['file2.xml', 'file3.txt'], home_input_files=['file3.xml', 'file4.xml'], transfer_output_files=['transfer_out.out', 'transfer_out2.out'], archive_output_files=['archive_out.out', 'archive_out2.out'], home_output_files=['home.out', 'test_home.out'], _modules={'OpenGL': 'load'}) self.uitplusjob.save()
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 _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 test_get_social_auth(self): User = get_user_model() user = User.objects.create_user(username="******") user_social = UserSocialAuth.objects.create(user=user, provider='my-provider', uid='1234') other = UserSocialAuth.get_social_auth('my-provider', '1234') self.assertEqual(other, user_social)
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. """ UserPropsFormSet = _get_user_props_formset(request.user.is_staff) form_classes = [settings_form] + get_profile_forms() _forms = None user_props_form_set = None competition_select_form = None if request.method == "POST": if request.POST.get('user_props_submit', None): user_props_form_set = UserPropsFormSet(request.POST, instance=request.user) if user_props_form_set.is_valid(): user_props_form_set.save() return redirect(reverse('account_settings') + '#props') elif request.POST.get('contests_submit', None): competition_select_form = IgnoreCompetitionForm( request.user, request.POST) if competition_select_form.is_valid(): competition_select_form.save() return redirect(reverse('account_settings') + '#contests') else: _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') if not _forms: _forms = [form(user=request.user) for form in form_classes] if not user_props_form_set: user_props_form_set = UserPropsFormSet( instance=request.user, queryset=UserProperty.objects.visible(request.user)) if not competition_select_form: competition_select_form = IgnoreCompetitionForm(user=request.user) return render( request, 'trojsten/people/settings.html', { 'account_associations': UserSocialAuth.get_social_auth_for_user(request.user), 'forms': _forms, 'user_props_form_set': user_props_form_set, 'competition_select_form': competition_select_form, })
def get_or_create_user(soundcloud_user): try: social_auth = UserSocialAuth.objects.get(uid=soundcloud_user['id']) user = User.objects.get(pk=social_auth.user_id) user.last_login = datetime.now() user.save() return user except UserSocialAuth.DoesNotExist: useremail = str(uuid.uuid4()).replace("-", "") + '@dopehotz.com' password = '******' + str(uuid.uuid4()).replace("-", "") while User.objects.filter(email=useremail).exists(): useremail = str(uuid.uuid4()).replace("-", "") + '@dopehotz.com' user = User.objects.create(email=useremail, password=password) social_auth = UserSocialAuth() social_auth.provider = 'soundcloud' social_auth.uid = soundcloud_user['id'] social_auth.user_id = user.id social_auth.save() user.is_active = 0 user.username = soundcloud_user['username'] user.soundcloud_url = soundcloud_user['permalink_url'] user.profile_picture = soundcloud_user['avatar_url'] user.last_login = datetime.now() user.save() return user
def create_user_social_auth(user, **kwargs): fields = { 'user': user, 'provider': 'github', 'uid': '1045555', 'extra_data': { 'auth_time': 1558545074, 'id': 1045555, 'expires': None, 'login': '******', 'access_token': '8q6e36515ee784fec53e', 'token_type': 'bearer' } } fields.update(kwargs) user_social_auth = UserSocialAuth(**fields) user_social_auth.save() return user_social_auth
def run(self): if 'avatar' in self.external_user: self.external_user["avatar"] = Downloader( self.external_user["avatar"], 'user', self.external_user['date_joined']).download() try: user = User(**self.external_user) user.save() if self.social_auth: self.social_auth['user'] = user social_auth = UserSocialAuth(**self.social_auth) social_auth.save() print(user.id) except IntegrityError: print('error') except DataError: print('error data')
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 # EmailUser can have address that is not linked with profile, hence the exclude ''' This functionality no longer in use due to more than just
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 ''' This functionality no longer in use due to more than just
def create_links(self): """ Create all needed links to Django and/or UserSocialAuth. """ extra_data = json.loads(self.extra_data) 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() django_user = None defaults = { 'first_name': first_name, 'last_name': last_name, 'email': email } if 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: username = hash_lti_user_data( self.user_id, extra_data.get('tool_consumer_instance_guid', ''), extra_data.get('lis_person_sourcedid', '')) django_user, _ = User.objects.get_or_create(username=username, defaults=defaults) if email: social = UserSocialAuth(user=django_user, provider='email', uid=email, extra_data=extra_data) social.save() self.django_user = django_user self.save()
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 create_user_entries(user_id, name, surname, token): user = AppUser(email=user_id, first_name=name, last_name=surname, access_token=token) user.save() logger.info(f'Local user for {user_id} successfully created') social_user = UserSocialAuth( user=user, uid=user_id, provider=settings.LOCAL_BACKENDS_ASSOC_SOCIAL_BACKENDS['vk'], extra_data={ "id": user_id, "expires": 0, "auth_time": time.time(), "token_type": 'null', "access_token": token }) social_user.save() logger.info(f'Social user for {user_id} created successfully')
def create_admin_user(sender, instance, created, **kwargs): if created: AdminUser.objects.create(user=instance) Token.objects.create(user=instance) if instance.is_superuser is True: social_user = UserSocialAuth.create_social_auth(instance, instance.id, 'quantummanagement') credential = { 'username': instance.username, 'password': instance.password, } credentials = CredentialsModel(user=instance, credentials=credential) social_user.save() credentials.save()
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 get_avatar_url(self) -> str: """Get the URL for the user's avatar from GitHub. If the user has no associated GitHub account (e.g. a Django superuser), return the URL to the default user avatar. Returns: The avatar URL. """ social = UserSocialAuth.get_social_auth_for_user(self.author).first() if social and "avatar_url" in social.extra_data: return social.extra_data["avatar_url"] else: return static("img/user-32.png")
def test_get_social_auth(self): usa = self.usa # Model self.assertEqual( UserSocialAuth.get_social_auth(provider=usa.provider, uid=usa.uid), usa) self.assertIsNone(UserSocialAuth.get_social_auth(provider='a', uid=1)) # Mixin self.assertEqual( super(AbstractUserSocialAuth, usa).get_social_auth(provider=usa.provider, uid=usa.uid), usa) self.assertIsNone( super(AbstractUserSocialAuth, usa).get_social_auth(provider='a', uid=1)) # Manager self.assertEqual( UserSocialAuth.objects.get_social_auth(provider=usa.provider, uid=usa.uid), usa) self.assertIsNone( UserSocialAuth.objects.get_social_auth(provider='a', uid=1))
def test_success_create_put(self): user = self.user_model.objects.create_user( username=self.parameter['screen_name'], first_name='This is display_name', is_active=True) user.save() extra_data = { 'auth_time': int(datetime.now().strftime('%s')), 'id': self.parameter['user_id'], 'access_token': { 'oauth_token': self.parameter['oauth_token'], 'oauth_token_secret': self.parameter['oauth_token_secret'], 'user_id': self.parameter['user_id'], 'screen_name': self.parameter['screen_name'] } } user_social_auth = UserSocialAuth(user=user, provider='twitter', uid=self.parameter['user_id'], extra_data=extra_data) user_social_auth.save() with patch('requests.get') as patcher: mock_json = Mock() mock_json.json.return_value = {'name': 'This is display_name'} patcher.return_value = mock_json request = self.factory.put(self.endpoint, json.dumps(self.parameter)) request.content_type = 'application/json' response = self.auth_view(request) self.assertEqual(json.loads(response.content.decode('utf-8')), {'result': 'success'}) self.assertEqual(response.status_code, 200)
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 __init__(self, user): info = UserSocialAuth.get_social_auth_for_user(user, provider='twitter').first() assert info is not None user_token = info.access_token['oauth_token'] user_secret = info.access_token['oauth_token_secret'] app_token = settings.SOCIAL_AUTH_TWITTER_KEY app_secret = settings.SOCIAL_AUTH_TWITTER_SECRET self.twit = twitter.Twitter( auth=twitter.OAuth( user_token, user_secret, app_token, app_secret ) )
def display_name(self): """ Returns the users credit-name from ORCID if one exists for this user, otherwise calls `get_full_name`. """ if self.is_anon: return None social_auth = UserSocialAuth.get_social_auth_for_user( self.user).first() if not isinstance(social_auth, UserSocialAuth): return self.full_name else: credit_name = social_auth.extra_data.get('credit-name', None) if not credit_name: return self.full_name return credit_name
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 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, })