Source

django-piston / piston / authentication / oauth / __init__.py

import oauth2 as oauth
from django.conf import settings
from django.http import HttpResponse
from django.template import loader

from piston.authentication.oauth.store import store, InvalidConsumerError, InvalidTokenError
from piston.authentication.oauth.utils import get_oauth_request, verify_oauth_request


class OAuthAuthentication(object):
    def __init__(self, realm='API'):
        self.realm = realm

    def is_authenticated(self, request):
        oauth_request = get_oauth_request(request)

        try:
            consumer = store.get_consumer(request, oauth_request, oauth_request['oauth_consumer_key'])
            access_token = store.get_access_token(request, oauth_request, consumer, oauth_request['oauth_token'])
        except (InvalidConsumerError, InvalidTokenError):
            return False
    
        if not verify_oauth_request(request, oauth_request, consumer, access_token):
            return False

        request.user = store.get_user_for_access_token(request, oauth_request, access_token)
        request.consumer = store.get_consumer_for_access_token(request, oauth_request, access_token)
        request.throttle_extra = request.consumer.key

        return True
        
    def challenge(self):
        """
        Returns a 401 response with a small bit on
        what OAuth is, and where to learn more about it.
        
        When this was written, browsers did not understand
        OAuth authentication on the browser side, and hence
        the helpful template we render. Maybe some day in the
        future, browsers will take care of this stuff for us
        and understand the 401 with the realm we give it.
        """
        response = HttpResponse()
        response.status_code = 401

        for k, v in oauth.build_authenticate_header(realm=self.realm).iteritems():
            response[k] = v

        tmpl = loader.render_to_string('piston/oauth/challenge.html',
            { 'MEDIA_URL': settings.MEDIA_URL })

        response.content = tmpl

        return response
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.