Allow uploading audiobooks via API.
[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, OAuth1Error
6 from django.contrib.auth.decorators import login_required
7 from django import forms
8 from django.http import HttpResponse, 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 class OAuth1AuthorizationEndpoint(AuthorizationEndpoint):
25     def create_verifier(self, request, credentials):
26         verifier = super(OAuth1AuthorizationEndpoint, self).create_verifier(request, credentials)
27         return {
28             'oauth_token': verifier['oauth_token'],
29         }
30
31
32 @login_required
33 def oauth_user_auth(request):
34     endpoint = OAuth1AuthorizationEndpoint(PistonRequestValidator())
35
36     if request.method == "GET":
37         # Why not just get oauth_token here?
38         # This is fairly straightforward, in't?
39         try:
40             realms, credentials = endpoint.get_realms_and_credentials(
41                 **oauthlib_request(request))
42         except OAuth1Error as e:
43             return HttpResponse(e.message, status=400)
44         callback = request.GET.get('oauth_callback')
45
46         form = OAuthAuthenticationForm(initial={
47             'oauth_token': credentials['resource_owner_key'],
48             'oauth_callback': callback,
49         })
50
51         return render(request, 'piston/authorize_token.html', {'form': form})
52
53     elif request.method == "POST":
54         try:
55             response = oauthlib_response(
56                 endpoint.create_authorization_response(
57                     credentials={"user": request.user},
58                     **oauthlib_request(request)
59                 )
60             )
61         except OAuth1Error as e:
62             return HttpResponse(e.message, status=400)
63         else:
64             return response