1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from urllib.parse import parse_qsl
6 from django.contrib.auth.decorators import login_required
7 from django.urls import reverse
8 from django.http import HttpResponseRedirect, HttpResponse
9 from django.views.decorators.http import require_POST
12 from apiclient.models import OAuthConnection
13 from apiclient import wl_consumer
14 from apiclient.settings import WL_REQUEST_TOKEN_URL, WL_ACCESS_TOKEN_URL, WL_AUTHORIZE_URL
15 from apiclient.settings import BETA_REQUEST_TOKEN_URL, BETA_ACCESS_TOKEN_URL, BETA_AUTHORIZE_URL
19 def oauth(request, beta=False):
20 if wl_consumer is None:
21 return HttpResponse("OAuth consumer not configured.")
23 client = oauth2.Client(wl_consumer)
24 resp, content = client.request(WL_REQUEST_TOKEN_URL if not beta else BETA_REQUEST_TOKEN_URL)
25 if resp['status'] != '200':
26 raise Exception("Invalid response %s." % resp['status'])
28 request_token = dict(parse_qsl(content.decode('utf-8')))
30 conn = OAuthConnection.get(request.user, beta)
31 # this might reset existing auth!
33 conn.token = request_token['oauth_token']
34 conn.token_secret = request_token['oauth_token_secret']
37 url = "%s?oauth_token=%s&oauth_callback=%s" % (
38 WL_AUTHORIZE_URL if not beta else BETA_AUTHORIZE_URL,
39 request_token['oauth_token'],
40 request.build_absolute_uri(reverse("apiclient_oauth_callback" if not beta else "apiclient_beta_callback")),
43 return HttpResponseRedirect(url)
47 def oauth_callback(request, beta=False):
48 if wl_consumer is None:
49 return HttpResponse("OAuth consumer not configured.")
51 oauth_verifier = request.GET.get('oauth_verifier')
52 conn = OAuthConnection.get(request.user, beta)
53 token = oauth2.Token(conn.token, conn.token_secret)
54 token.set_verifier(oauth_verifier)
55 client = oauth2.Client(wl_consumer, token)
56 _resp, content = client.request(WL_ACCESS_TOKEN_URL if not beta else BETA_ACCESS_TOKEN_URL, method="POST")
57 access_token = dict(parse_qsl(content.decode('utf-8')))
60 conn.token = access_token['oauth_token']
61 conn.token_secret = access_token['oauth_token_secret']
64 return HttpResponseRedirect('/')
69 def disconnect(request):
70 request.user.oauthconnection_set.filter(beta=False).delete()
71 return HttpResponseRedirect(reverse('documents_user'))