Start replacing Piston in OAuth flow with OAuthLib.
[wolnelektury.git] / src / api / drf_auth.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 ResourceEndpoint
6 from rest_framework.authentication import BaseAuthentication
7 from .request_validator import PistonRequestValidator
8
9
10 class PistonOAuthAuthentication(BaseAuthentication):
11     def __init__(self):
12         validator = PistonRequestValidator()
13         self.provider = ResourceEndpoint(validator)
14
15     def authenticate_header(self, request):
16         return 'OAuth realm="API"'
17
18     def authenticate(self, request):
19         v, r = self.provider.validate_protected_resource_request(
20             request.build_absolute_uri(),
21             http_method=request.method,
22             body=request.body,
23             headers={
24                 "Authorization": request.META['HTTP_AUTHORIZATION'],
25                 "Content-Type": request.content_type,
26             } if 'HTTP_AUTHORIZATION' in request.META else None
27         )
28         if v:
29             return r.token.user, r.token