diff --git a/django_mailbox/google_utils.py b/django_mailbox/google_utils.py index b834f59c..a3e3fbaa 100644 --- a/django_mailbox/google_utils.py +++ b/django_mailbox/google_utils.py @@ -3,7 +3,10 @@ from django.conf import settings import requests from social.apps.django_app.default.models import UserSocialAuth - +try: + from allauth.socialaccount.models import SocialAccount, SocialApp +except ImportError: + SocialAccount, SocialApp = None, None logger = logging.getLogger(__name__) @@ -17,37 +20,45 @@ class RefreshTokenNotFound(Exception): def get_google_consumer_key(): + if SocialApp: + app = SocialApp.objects.filter(provider='google').first() + if app: + return app.client_id return settings.SOCIAL_AUTH_GOOGLE_OAUTH2_KEY def get_google_consumer_secret(): + if SocialApp: + app = SocialApp.objects.filter(provider='google').first() + if app: + return app.secret return settings.SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET +def get_google_account(email, key=None): + try: + if SocialAccount: + me = SocialAccount.objects.get(uid=email, provider='google') + else: + me = UserSocialAuth.objects.get(uid=email, provider="google-oauth2") + return me.extra_data[key] if key else me + except (UserSocialAuth.DoesNotExist, SocialAccount.DoesNotExist, KeyError): + raise RefreshTokenNotFound if key == 'refresh_token' else AccessTokenNotFound + + def get_google_access_token(email): # TODO: This should be cacheable - try: - me = UserSocialAuth.objects.get(uid=email, provider="google-oauth2") - return me.extra_data['access_token'] - except (UserSocialAuth.DoesNotExist, KeyError): - raise AccessTokenNotFound + return get_google_account(email, key='access_token') def update_google_extra_data(email, extra_data): - try: - me = UserSocialAuth.objects.get(uid=email, provider="google-oauth2") - me.extra_data = extra_data - me.save() - except (UserSocialAuth.DoesNotExist, KeyError): - raise AccessTokenNotFound + me = get_google_account(email) + me.extra_data = extra_data + me.save() def get_google_refresh_token(email): - try: - me = UserSocialAuth.objects.get(uid=email, provider="google-oauth2") - return me.extra_data['refresh_token'] - except (UserSocialAuth.DoesNotExist, KeyError): - raise RefreshTokenNotFound + return get_google_account(email, key='refresh_token') def google_api_get(email, url):