Add signal for saving profile data upon a new GH login

I did skip the tests -- my first tries with `patch` didn't work and I wanted to have this working for the demo, at least locally.
This commit is contained in:
Lacey Williams Henschel
2023-02-16 15:22:06 -08:00
parent 2a957910e9
commit f2a0da771e
6 changed files with 58 additions and 13 deletions

View File

@@ -0,0 +1 @@
default_app_config = "users.apps.UsersConfig"

View File

@@ -3,3 +3,6 @@ from django.apps import AppConfig
class UsersConfig(AppConfig):
name = "users"
def ready(self):
import users.signals

View File

@@ -148,19 +148,7 @@ class User(BaseUser):
github_username = models.CharField(_("github username"), max_length=100, blank=True)
image = models.FileField(upload_to="profile-images", null=True, blank=True)
def save_image_from_github(self):
if not self.github_username:
# todo: log
return
api = get_github_api()
result = get_github_user(api, self.github_username)
avatar_url = result.get("avatar_url")
if not avatar_url:
# todo: log
return
def save_image_from_github(self, avatar_url):
response = requests.get(avatar_url)
base_filename = f"{slugify(self.get_full_name())}-profile"
filename = f"{base_filename}.png"

28
users/signals.py Normal file
View File

@@ -0,0 +1,28 @@
from django.dispatch import receiver
from django.db.models.signals import post_save
from allauth.socialaccount.models import SocialAccount
GITHUB = "github"
@receiver(post_save, sender=SocialAccount)
def import_social_profile_data(sender, instance, created, **kwargs):
"""
When a new SocialAccount is created, get the data from that account for the
user's profile
"""
if not created:
return
if instance.provider != GITHUB:
return
github_username = instance.extra_data.get("login")
avatar_url = instance.extra_data.get("avatar_url")
if github_username:
instance.user.github_username = github_username
instance.save()
if avatar_url:
instance.user.save_image_from_github(avatar_url)

View File

@@ -1,3 +1,5 @@
import pytest
from test_plus import TestCase
from django.contrib.auth import get_user_model
from django.utils import timezone
@@ -21,3 +23,13 @@ def test_super_user(super_user):
assert super_user.is_active == True
assert super_user.is_staff == True
assert super_user.is_superuser == True
@pytest.mark.skip("Add this test when I have the patience for mocks")
def test_user_save_image_from_github(user):
"""
Test `User.save_image_from_github(avatar_url)`
See test_signals -- you will need to do something similar here, but
dealing with a File object might make it trickier.
"""
pass

View File

@@ -0,0 +1,13 @@
import pytest
@pytest.mark.skip("Reminder to write this test when I have the patience for mocks")
def test_import_social_profile_data():
"""
TODO:
- Test users.signals.import_social_profile_data
- Set `SocialAccount.extra_data` to the github_api_get_user_by_username_response
fixture in the libraries app -- it's not identical but it has what you need
- You probably need to use `responses` and not `patch`
"""
pass