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
11 from apiclient.models import OAuthConnection
12 from apiclient import wl_consumer
13 from apiclient.settings import WL_REQUEST_TOKEN_URL, WL_ACCESS_TOKEN_URL, WL_AUTHORIZE_URL
14 from apiclient.settings import BETA_REQUEST_TOKEN_URL, BETA_ACCESS_TOKEN_URL, BETA_AUTHORIZE_URL
18 def oauth(request, beta=False):
19 if wl_consumer is None:
20 return HttpResponse("OAuth consumer not configured.")
22 client = oauth2.Client(wl_consumer)
23 resp, content = client.request(WL_REQUEST_TOKEN_URL if not beta else BETA_REQUEST_TOKEN_URL)
24 if resp['status'] != '200':
25 raise Exception("Invalid response %s." % resp['status'])
27 request_token = dict(parse_qsl(content.decode('utf-8')))
29 conn = OAuthConnection.get(request.user, beta)
30 # this might reset existing auth!
32 conn.token = request_token['oauth_token']
33 conn.token_secret = request_token['oauth_token_secret']
36 url = "%s?oauth_token=%s&oauth_callback=%s" % (
37 WL_AUTHORIZE_URL if not beta else BETA_AUTHORIZE_URL,
38 request_token['oauth_token'],
39 request.build_absolute_uri(reverse("apiclient_oauth_callback" if not beta else "apiclient_beta_callback")),
42 return HttpResponseRedirect(url)
46 def oauth_callback(request, beta=False):
47 if wl_consumer is None:
48 return HttpResponse("OAuth consumer not configured.")
50 oauth_verifier = request.GET.get('oauth_verifier')
51 conn = OAuthConnection.get(request.user, beta)
52 token = oauth2.Token(conn.token, conn.token_secret)
53 token.set_verifier(oauth_verifier)
54 client = oauth2.Client(wl_consumer, token)
55 _resp, content = client.request(WL_ACCESS_TOKEN_URL if not beta else BETA_ACCESS_TOKEN_URL, method="POST")
56 access_token = dict(parse_qsl(content.decode('utf-8')))
59 conn.token = access_token['oauth_token']
60 conn.token_secret = access_token['oauth_token_secret']
63 return HttpResponseRedirect('/')