| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django.http import HttpRequest |
| 4 |
|
| 5 |
from allauth.socialaccount import app_settings |
| 6 |
from allauth.socialaccount.adapter import get_adapter |
| 7 |
from allauth.socialaccount.providers.oauth2.views import ( |
| 8 |
OAuth2Adapter, |
| 9 |
OAuth2CallbackView, |
| 10 |
OAuth2LoginView, |
| 11 |
) |
| 12 |
|
| 13 |
|
| 14 |
class TrainingPeaksOAuth2Adapter(OAuth2Adapter): |
| 15 |
# https://github.com/TrainingPeaks/PartnersAPI/wiki/OAuth |
| 16 |
provider_id = "trainingpeaks" |
| 17 |
|
| 18 |
def get_settings(self): |
| 19 |
"""Provider settings""" |
| 20 |
return app_settings.PROVIDERS.get(self.provider_id, {}) |
| 21 |
|
| 22 |
def get_hostname(self): |
| 23 |
"""Return hostname depending on sandbox setting""" |
| 24 |
settings = self.get_settings() |
| 25 |
if settings.get("USE_PRODUCTION"): |
| 26 |
return "trainingpeaks.com" |
| 27 |
return "sandbox.trainingpeaks.com" |
| 28 |
|
| 29 |
@property |
| 30 |
def access_token_url(self): |
| 31 |
return f"https://oauth.{self.get_hostname()}/oauth/token" |
| 32 |
|
| 33 |
@property |
| 34 |
def authorize_url(self): |
| 35 |
return f"https://oauth.{self.get_hostname()}/OAuth/Authorize" |
| 36 |
|
| 37 |
@property |
| 38 |
def profile_url(self): |
| 39 |
return f"https://api.{self.get_hostname()}/v1/athlete/profile" |
| 40 |
|
| 41 |
@property |
| 42 |
def api_hostname(self): |
| 43 |
"""Return https://api.hostname.tld""" |
| 44 |
return f"https://api.{self.get_hostname()}" |
| 45 |
|
| 46 |
# https://oauth.sandbox.trainingpeaks.com/oauth/deauthorize |
| 47 |
|
| 48 |
scope_delimiter = " " |
| 49 |
|
| 50 |
def complete_login(self, request: HttpRequest, app, token, **kwargs): |
| 51 |
headers = {"Authorization": f"Bearer {token.token}"} |
| 52 |
with get_adapter().get_requests_session() as sess: |
| 53 |
response = sess.get(self.profile_url, headers=headers) |
| 54 |
response.raise_for_status() |
| 55 |
extra_data = response.json() |
| 56 |
return self.get_provider().sociallogin_from_response(request, extra_data) |
| 57 |
|
| 58 |
|
| 59 |
oauth2_login = OAuth2LoginView.adapter_view(TrainingPeaksOAuth2Adapter) |
| 60 |
oauth2_callback = OAuth2CallbackView.adapter_view(TrainingPeaksOAuth2Adapter) |