Files
benchcoach-django/teamsnap/views.py
2022-06-02 08:52:38 -05:00

106 lines
3.4 KiB
Python

import requests
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from django.views.generic.edit import FormView
from .forms import PreferencesForm
from .models import Preferences
from .provider import TeamsnapProvider
class TeamsnapAdapter(OAuth2Adapter):
provider_id = TeamsnapProvider.id
# Fetched programmatically, must be reachable from container
access_token_url = "{}/oauth/token/".format("https://auth.teamsnap.com")
profile_url = "{}/me/".format("https://api.teamsnap.com/v3/")
# Accessed by the user browser, must be reachable by the host
authorize_url = "{}/oauth/authorize/".format("https://auth.teamsnap.com/")
# NOTE: trailing slashes in URLs are important, don't miss it
def complete_login(self, request, app, token, **kwargs):
headers = {"Authorization": f"Bearer {token.token}"}
resp = requests.get(self.profile_url, headers=headers)
j = resp.json()
if j.get("collection", {}).get("items"):
extra_data = {
i["name"]: i["value"] for i in j["collection"]["items"][0]["data"]
}
return self.get_provider().sociallogin_from_response(request, extra_data)
def populate_user(self, request, sociallogin, data):
user = super().populate_user(request, sociallogin, data)
user.username = user.email
return user
# def get_callback_url(self, request, app):
# callback_url = reverse(self.provider_id + "_callback")
# protocol = self.redirect_uri_protocol
# return build_absolute_uri(request, callback_url, protocol)
# return "urn:ietf:wg:oauth:2.0:oob"
oauth2_login = OAuth2LoginView.adapter_view(TeamsnapAdapter)
oauth2_callback = OAuth2CallbackView.adapter_view(TeamsnapAdapter)
class PreferencesFormView(FormView):
template_name = "preferences.html"
form_class = PreferencesForm
success_url = "/"
def form_valid(self, form):
# This method is called when valid form data has been POSTed.
# It should return an HttpResponse.
if form.data["user"] == str(self.request.user.id):
form.save()
return super().form_valid(form)
def get_initial(self):
"""
Returns the initial data to use for forms on this view.
"""
initial = super().get_initial()
initial["user"] = self.request.user
# initial['managed_team_id']
return initial
def get_form(self):
"""
Returns the initial data to use for forms on this view.
"""
import pyteamsnap
ts_account = self.request.user.socialaccount_set.first()
ts_token = ts_account.socialtoken_set.first()
# ts_token =
ts = pyteamsnap.TeamSnap(token=ts_token)
me = pyteamsnap.api.Me(ts)
teams = [
(id, pyteamsnap.api.Team.get(ts, id=id))
for id in me.data["managed_team_ids"]
]
try:
contact = Preferences.objects.get(user=self.request.user)
form = PreferencesForm(instance=contact, **self.get_form_kwargs())
except Preferences.DoesNotExist:
form = super().get_form(self.form_class)
choices = [
(id, f"{team.data['name']} ({team.data['season_name']})")
for id, team in teams
]
form.fields["managed_team_id"].widget.choices = choices
return form