3c7e50f4faf09e1f16296c9095d193ef5cec3eda
[wolnelektury.git] / src / api / piston_patch.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from oauthlib.oauth1 import AuthorizationEndpoint
6 from django.contrib.auth.decorators import login_required
7 from django import forms
8 from django.http import HttpResponseRedirect
9 from django.shortcuts import render
10 from .request_validator import PistonRequestValidator
11 from .utils import oauthlib_request, oauthlib_response
12
13
14 class HttpResponseAppRedirect(HttpResponseRedirect):
15     allowed_schemes = HttpResponseRedirect.allowed_schemes + ['wolnelekturyapp']
16
17
18 class OAuthAuthenticationForm(forms.Form):
19     oauth_token = forms.CharField(widget=forms.HiddenInput)
20     oauth_callback = forms.CharField(widget=forms.HiddenInput)  # changed from URLField - too strict
21     # removed authorize_access - redundant
22
23
24 @login_required
25 def oauth_user_auth(request):
26     endpoint = AuthorizationEndpoint(PistonRequestValidator())
27
28     if request.method == "GET":
29         # Why not just get oauth_token here?
30         # This is fairly straightforward, in't?
31         realms, credentials = endpoint.get_realms_and_credentials(
32             **oauthlib_request(request))
33         callback = request.GET.get('oauth_callback')
34
35         form = OAuthAuthenticationForm(initial={
36             'oauth_token': credentials['resource_owner_key'],
37             'oauth_callback': callback,
38         })
39
40         return render(request, 'piston/authorize_token.html', {'form': form})
41
42     elif request.method == "POST":
43         response = oauthlib_response(
44             endpoint.create_authorization_response(
45                 credentials={"user": request.user},
46                 **oauthlib_request(request)
47             )
48         )
49
50         return response