Commits

Erik van Zijst committed 5b1d315

Removed OAuth support from Piston.

Comments (0)

Files changed (16)

piston/authentication/__init__.py

-from piston.authentication.basic import HttpBasicAuthentication, HttpBasicSimple
-
 class NoAuthentication(object):
     """
     Authentication handler that always returns

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, require_params
-
-
-class OAuthAuthentication(object):
-    def __init__(self, realm='API', two_legged=False):
-        self.realm = realm
-        self.two_legged = two_legged
-
-    def is_authenticated(self, request):
-        oauth_request = get_oauth_request(request)
-
-        if self.two_legged:
-            return self._authenticate_two_legged(request, oauth_request)
-        else:
-            return self._authenticate_three_legged(request, oauth_request)
-
-    def _authenticate_two_legged(self, request, oauth_request):
-        missing_params = require_params(oauth_request)
-        if missing_params is not None:
-            return False
-
-        try:
-            consumer = store.get_consumer(request, oauth_request, oauth_request['oauth_consumer_key'])
-        except InvalidConsumerError:
-            return False
-
-        if not verify_oauth_request(request, oauth_request, consumer):
-            return False
-
-        request.user = store.get_user_for_consumer(request, oauth_request, consumer)
-        request.consumer = consumer
-        request.throttle_extra = consumer.key
-
-        return True
-        
-    def _authenticate_three_legged(self, request, oauth_request):
-        missing_params = require_params(oauth_request, ('oauth_token',))
-        if missing_params is not None:
-            return False
-
-        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

piston/authentication/oauth/forms.py

-from django import forms
-
-
-class AuthorizeRequestTokenForm(forms.Form):
-    oauth_token = forms.CharField(widget=forms.HiddenInput)
-    authorize_access = forms.BooleanField(required=True)

piston/authentication/oauth/store/__init__.py

-from django.conf import settings
-from django.core.exceptions import ImproperlyConfigured
-from django.utils import importlib
-
-
-class Error(Exception):
-    """Base class for Store exceptions."""
-
-
-class InvalidConsumerError(Error):
-    """Invalid consumer."""
-
-
-class InvalidTokenError(Error):
-    """Invalid token."""
-
-
-class Store(object):
-    """
-    The Store class is the backbone of piston's OAuth implementation. It is used
-    by the views and the authentication backend to get consumers and tokens, and
-    to create tokens. The following terms are used in the documentation of the
-    API:
-
-    Consumer:
-        A class defining at minimum `key` and `secret` attributes. Both of these
-        attributes must be either str or unicode.
-
-    Token:
-        A class defining at minimum `key` and `secret` attributes. Both of these
-        attributes must be either str or unicode.
-
-    User:
-        A `django.contrib.auth.models.User` instance.
-
-    Any API that takes a consumer or token will be passed a Consumer or Token
-    instance it itself returned at an earlier stage from one of the methods that
-    take a key and return a Consumer or Token. This means if your store
-    implementation uses tokens that keep a reference to its Consumer on the
-    Token itself, `get_consumer_for_request_token` can simply return
-    `request_token.consumer`.
-    """
-    def get_consumer(self, request, oauth_request, consumer_key):
-        """
-        Return the Consumer for `consumer_key` or raise `InvalidConsumerError`.
-
-        `request`: The Django request object.
-        `oauth_request`: The `oauth2.Request` object.
-        `consumer_key`: The consumer key.
-        """
-        raise NotImplementedError
-
-    def get_consumer_for_request_token(self, request, oauth_request, request_token):
-        """
-        Return the Consumer associated with the `request_token` Token.
-
-        `request`: The Django request object.
-        `oauth_request`: The `oauth2.Request` object.
-        `request_token`: The request token to get the consumer for.
-        """
-        raise NotImplementedError
-
-    def get_consumer_for_access_token(self, request, oauth_request, access_token):
-        """
-        Return the Consumer associated with the `access_token` Token.
-
-        `request`: The Django request object.
-        `oauth_request`: The `oauth2.Request` object.
-        `access_token`: The access Token to get the consumer for.
-        """
-        raise NotImplementedError
-
-    def create_request_token(self, request, oauth_request, consumer, callback):
-        """
-        Generate and return a Token.
-
-        `request`: The Django request object.
-        `oauth_request`: The `oauth2.Request` object.
-        `consumer`: The Consumer that made the request.
-        """
-        raise NotImplementedError
-
-    def get_request_token(self, request, oauth_request, request_token_key):
-        """
-        Return the Token for `request_token_key` or raise `InvalidTokenError`.
-
-        `request`: The Django request object.
-        `oauth_request`: The `oauth2.Request` object.
-        `consumer`: The Consumer that made the request.
-        `request_token_key`: The request token key.
-        """
-        raise NotImplementedError
-
-    def authorize_request_token(self, request, oauth_request, request_token):
-        """
-        Authorize the `request_token` Token and return it.
-
-        `request`: The Django request object.
-        `oauth_request`: The `oauth2.Request` object.
-        `request_token`: The request token to authorize.
-        """
-        raise NotImplementedError
-
-    def create_access_token(self, request, oauth_request, consumer, request_token):
-        """
-        Generate and return a Token.
-
-        `request`: The Django request object.
-        `oauth_request`: The `oauth2.Request` object.
-        `consumer`: The Consumer that made the request.
-        `request_token`: The Token used to make the request.
-        """
-        raise NotImplementedError
-
-    def get_access_token(self, request, oauth_request, consumer, access_token_key):
-        """
-        Return the Token for `access_token_key` or raise `InvalidTokenError`.
-
-        `request`: The Django request object.
-        `oauth_request`: The `oauth2.Request` object.
-        `consumer`: The Consumer that made the request.
-        `access_token_key`: The token key used to make the request.
-        """
-        raise NotImplementedError
-
-    def get_user_for_access_token(self, request, oauth_request, access_token):
-        """
-        Return the associated User for `access_token`.
-
-        `request`: The Django request object.
-        `oauth_request`: The `oauth2.Request` object.
-        `consumer`: The Consumer that made the request.
-        `access_token`: The Token used to make the request.
-        """
-        raise NotImplementedError
-
-    def get_user_for_consumer(self, request, oauth_request, consumer):
-        """
-        Return the associated User for `consumer`.
-        
-        `request`: The Django request object.
-        `oauth_request`: The `oauth2.Request` object.
-        `consumer`: The Consumer that made the request.
-        """
-        raise NotImplementedError
-
-    def check_nonce(self, request, oauth_request, nonce):
-        """
-        Return `True` if the nonce has not yet been used, `False` otherwise.
-
-        `request`: The Django request object.
-        `oauth_request`: The `oauth2.Request` object.
-        `nonce`: The nonce to check.
-        """
-        raise NotImplementedError
-
-
-def get_store(path='piston.authentication.oauth.store.db.ModelStore'):
-    """
-    Load the piston oauth store. Should not be called directly unless testing.
-    """
-    path = getattr(settings, 'PISTON_OAUTH_STORE', path)
-
-    try:
-        module, attr = path.rsplit('.', 1)
-        store_class = getattr(importlib.import_module(module), attr)
-    except ValueError:
-        raise ImproperlyConfigured('Invalid piston oauth store string: "%s"' % path)
-    except ImportError, e:
-        raise ImproperlyConfigured('Error loading piston oauth store module "%s": "%s"' % (module, e))
-    except AttributeError:
-        raise ImproperlyConfigured('Module "%s" does not define a piston oauth store named "%s"' % (module, attr))
-
-    return store_class()
-
-
-store = get_store()

piston/authentication/oauth/store/db.py

-import oauth2 as oauth
-
-from piston.authentication.oauth.store import InvalidConsumerError, InvalidTokenError, Store
-from piston.models import Nonce, Token, Consumer, VERIFIER_SIZE
-
-
-class ModelStore(Store):
-    """
-    Store implementation using the Django models defined in `piston.models`.
-    """
-    def get_consumer(self, request, oauth_request, consumer_key):
-        try:
-            return Consumer.objects.get(key=consumer_key)
-        except Consumer.DoesNotExist:
-            raise InvalidConsumerError()
-
-    def get_consumer_for_request_token(self, request, oauth_request, request_token):
-        return request_token.consumer
-
-    def get_consumer_for_access_token(self, request, oauth_request, access_token):
-        return access_token.consumer
-
-    def create_request_token(self, request, oauth_request, consumer, callback):
-        token = Token.objects.create_token(
-            token_type=Token.REQUEST,
-            consumer=Consumer.objects.get(key=oauth_request['oauth_consumer_key']),
-            timestamp=oauth_request['oauth_timestamp']
-        )
-        token.set_callback(callback)
-        token.save()
-
-        return token
-
-    def get_request_token(self, request, oauth_request, request_token_key):
-        try:
-            return Token.objects.get(key=request_token_key, token_type=Token.REQUEST)
-        except Token.DoesNotExist:
-            raise InvalidTokenError()
-
-    def authorize_request_token(self, request, oauth_request, request_token):
-        request_token.is_approved = True
-        request_token.user = request.user
-        request_token.verifier = oauth.generate_verifier(VERIFIER_SIZE)
-        request_token.save()
-        return request_token
-
-    def create_access_token(self, request, oauth_request, consumer, request_token):
-        access_token = Token.objects.create_token(
-            token_type=Token.ACCESS,
-            timestamp=oauth_request['oauth_timestamp'],
-            consumer=Consumer.objects.get(key=consumer.key),
-            user=request_token.user,
-        )
-        request_token.delete()
-        return access_token
-
-    def get_access_token(self, request, oauth_request, consumer, access_token_key):
-        try:
-            return Token.objects.get(key=access_token_key, token_type=Token.ACCESS)
-        except Token.DoesNotExist:
-            raise InvalidTokenError()
-
-    def get_user_for_access_token(self, request, oauth_request, access_token):
-        return access_token.user
-
-    def get_user_for_consumer(self, request, oauth_request, consumer):
-        return consumer.user
-
-    def check_nonce(self, request, oauth_request, nonce):
-        nonce, created = Nonce.objects.get_or_create(
-            consumer_key=oauth_request['oauth_consumer_key'],
-            token_key=oauth_request.get('oauth_token', ''),
-            key=nonce
-        )
-        return created

piston/authentication/oauth/urls.py

-from django.conf.urls.defaults import *
-
-
-urlpatterns = patterns('piston.authentication.oauth.views',
-    (r'^get_request_token', 'get_request_token'),
-    (r'^authorize_request_token', 'authorize_request_token'),
-    (r'^get_access_token', 'get_access_token'),
-)

piston/authentication/oauth/utils.py

-import oauth2 as oauth
-from django.contrib.auth.models import User
-from django.http import HttpResponseBadRequest
-
-
-def get_oauth_request(request):
-    """ Converts a Django request object into an `oauth2.Request` object. """
-    headers = {}
-    if 'HTTP_AUTHORIZATION' in request.META:
-        headers['Authorization'] = request.META['HTTP_AUTHORIZATION']
-    return oauth.Request.from_request(request.method, request.build_absolute_uri(request.path), headers, dict(request.REQUEST))
-
-
-def verify_oauth_request(request, oauth_request, consumer, token=None):
-    """ Helper function to verify requests. """
-    from piston.authentication.oauth.store import store
-
-    # Check nonce
-    if not store.check_nonce(request, oauth_request, oauth_request['oauth_nonce']):
-        return False
-
-    # Verify request
-    try:
-        oauth_server = oauth.Server()
-        oauth_server.add_signature_method(oauth.SignatureMethod_HMAC_SHA1())
-        oauth_server.add_signature_method(oauth.SignatureMethod_PLAINTEXT())
-
-        # Ensure the passed keys and secrets are ascii, or HMAC will complain.
-        consumer = oauth.Consumer(consumer.key.encode('ascii', 'ignore'), consumer.secret.encode('ascii', 'ignore'))
-        if token is not None:
-            token = oauth.Token(token.key.encode('ascii', 'ignore'), token.secret.encode('ascii', 'ignore'))
-
-        oauth_server.verify_request(oauth_request, consumer, token)
-    except oauth.Error:
-        return False
-
-    return True
-
-
-def require_params(oauth_request, parameters=[]):
-    """ Ensures that the request contains all required parameters. """
-    params = [
-        'oauth_consumer_key',
-        'oauth_nonce',
-        'oauth_signature',
-        'oauth_signature_method',
-        'oauth_timestamp'
-    ]
-    params.extend(parameters)
-
-    try:
-        missing = list(param for param in params if param not in oauth_request)
-    except:
-        missing = params
-        
-    if missing:
-        return HttpResponseBadRequest('Missing OAuth parameters: %s' % (', '.join(missing)))
-
-    return None

piston/authentication/oauth/views.py

-from urllib import urlencode
-
-import oauth2 as oauth
-from django.contrib.auth.decorators import login_required
-from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseRedirect
-from django.shortcuts import render_to_response
-from django.template import RequestContext
-from django.views.decorators.csrf import csrf_exempt
-
-from piston.authentication.oauth.forms import AuthorizeRequestTokenForm
-from piston.authentication.oauth.store import store, InvalidConsumerError, InvalidTokenError
-from piston.authentication.oauth.utils import verify_oauth_request, get_oauth_request, require_params
-
-
-@csrf_exempt
-def get_request_token(request):
-    oauth_request = get_oauth_request(request)
-
-    missing_params = require_params(oauth_request, ('oauth_callback',))
-    if missing_params is not None:
-        return missing_params
-
-    try:
-        consumer = store.get_consumer(request, oauth_request, oauth_request['oauth_consumer_key'])
-    except InvalidConsumerError:
-        return HttpResponseBadRequest('Invalid Consumer.')
-
-    if not verify_oauth_request(request, oauth_request, consumer):
-        return HttpResponseBadRequest('Could not verify OAuth request.')
-
-    request_token = store.create_request_token(request, oauth_request, consumer, oauth_request['oauth_callback'])
-
-    ret = urlencode({
-        'oauth_token': request_token.key,
-        'oauth_token_secret': request_token.secret,
-        'oauth_callback_confirmed': 'true'
-    })
-    return HttpResponse(ret, content_type='application/x-www-form-urlencoded')
-
-
-@login_required
-def authorize_request_token(request, form_class=AuthorizeRequestTokenForm, template_name='piston/oauth/authorize.html', verification_template_name='piston/oauth/authorize_verification_code.html'):
-    if 'oauth_token' not in request.REQUEST:
-        return HttpResponseBadRequest('No request token specified.')
-
-    oauth_request = get_oauth_request(request)
-
-    try:
-        request_token = store.get_request_token(request, oauth_request, request.REQUEST['oauth_token'])
-    except InvalidTokenError:
-        return HttpResponseBadRequest('Invalid request token.')
-
-    consumer = store.get_consumer_for_request_token(request, oauth_request, request_token)
-
-    if request.method == 'POST':
-        form = form_class(request.POST)
-        if form.is_valid() and form.cleaned_data['authorize_access']:
-            request_token = store.authorize_request_token(request, oauth_request, request_token)
-            if request_token.callback is not None and request_token.callback != 'oob':
-                return HttpResponseRedirect('%s&%s' % (request_token.get_callback_url(), urlencode({'oauth_token': request_token.key})))
-            else:
-                return render_to_response(verification_template_name, {'consumer': consumer, 'verification_code': request_token.verifier}, RequestContext(request))
-    else:
-        form = form_class(initial={'oauth_token': request_token.key})
-
-    return render_to_response(template_name, {'consumer': consumer, 'form': form}, RequestContext(request))
-
-
-@csrf_exempt
-def get_access_token(request):
-    oauth_request = get_oauth_request(request)
-
-    missing_params = require_params(oauth_request, ('oauth_token', 'oauth_verifier'))
-    if missing_params is not None:
-        return missing_params
-
-    try:
-        consumer = store.get_consumer(request, oauth_request, oauth_request['oauth_consumer_key'])
-        request_token = store.get_request_token(request, oauth_request, oauth_request['oauth_token'])
-    except InvalidTokenError:
-        return HttpResponseBadRequest('Invalid consumer.')
-    except InvalidConsumerError:
-        return HttpResponseBadRequest('Invalid request token.')
-
-    if not verify_oauth_request(request, oauth_request, consumer, request_token):
-        return HttpResponseBadRequest('Could not verify OAuth request.')
-
-    if oauth_request.get('oauth_verifier', None) != request_token.verifier:
-        return HttpResponseBadRequest('Invalid OAuth verifier.')
-
-    access_token = store.create_access_token(request, oauth_request, consumer, request_token)
-
-    ret = urlencode({
-        'oauth_token': access_token.key,
-        'oauth_token_secret': access_token.secret
-    })
-    return HttpResponse(ret, content_type='application/x-www-form-urlencoded')

piston/fixtures/oauth.json

-[
-    {
-        "pk": 1, 
-        "model": "piston.consumer", 
-        "fields": {
-            "status": "accepted", 
-            "name": "Piston Test Consumer", 
-            "secret": "T5XkNMkcjffDpC9mNQJbyQnJXGsenYbz", 
-            "user": 2, 
-            "key": "8aZSFj3W54h8J8sCpx", 
-            "description": "A test consumer record for Piston unit tests."
-        }
-    },
-    {
-        "pk": 1, 
-        "model": "piston.token", 
-        "fields": {
-            "is_approved": true, 
-            "timestamp": 1249347414, 
-            "token_type": 2, 
-            "secret": "qSWZq36t7yvkBquetYBkd8JxnuCu9jKk", 
-            "user": 2, 
-            "key": "Y7358vL5hDBbeP3HHL", 
-            "consumer": 1
-        }
-    }
-]

piston/managers.py

-from django.db import models
-from django.contrib.auth.models import User
-
-KEY_SIZE = 18
-SECRET_SIZE = 32
-
-class KeyManager(models.Manager):
-    '''Add support for random key/secret generation
-    '''
-    def generate_random_codes(self):
-        key = User.objects.make_random_password(length=KEY_SIZE)
-        secret = User.objects.make_random_password(length=SECRET_SIZE)
-
-        while self.filter(key__exact=key, secret__exact=secret).count():
-            secret = User.objects.make_random_password(length=SECRET_SIZE)
-
-        return key, secret
-
-
-class ConsumerManager(KeyManager):
-    def create_consumer(self, name, description=None, user=None):
-        """
-        Shortcut to create a consumer with random key/secret.
-        """
-        consumer, created = self.get_or_create(name=name)
-
-        if user:
-            consumer.user = user
-
-        if description:
-            consumer.description = description
-
-        if created:
-            consumer.key, consumer.secret = self.generate_random_codes()
-            consumer.save()
-
-        return consumer
-
-    _default_consumer = None
-
-class ResourceManager(models.Manager):
-    _default_resource = None
-
-    def get_default_resource(self, name):
-        """
-        Add cache if you use a default resource.
-        """
-        if not self._default_resource:
-            self._default_resource = self.get(name=name)
-
-        return self._default_resource        
-
-class TokenManager(KeyManager):
-    def create_token(self, consumer, token_type, timestamp, user=None):
-        """
-        Shortcut to create a token with random key/secret.
-        """
-        token, created = self.get_or_create(consumer=consumer, 
-                                            token_type=token_type, 
-                                            timestamp=timestamp,
-                                            user=user)
-
-        if created:
-            token.key, token.secret = self.generate_random_codes()
-            token.save()
-
-        return token
-        

piston/models.py

-import urllib, time, urlparse
-
-# Django imports
-from django.db.models.signals import post_save, pre_delete
-from django.db import models
-from django.contrib.auth.models import User
-from django.core.mail import send_mail, mail_admins
-
-# Piston imports
-from managers import TokenManager, ConsumerManager, ResourceManager
-from signals import consumer_post_save, consumer_pre_delete
-
-KEY_SIZE = 18
-SECRET_SIZE = 32
-VERIFIER_SIZE = 10
-
-CONSUMER_STATES = (
-    ('pending', 'Pending'),
-    ('accepted', 'Accepted'),
-    ('canceled', 'Canceled'),
-    ('rejected', 'Rejected')
-)
-
-def generate_random(length=SECRET_SIZE):
-    return User.objects.make_random_password(length=length)
-
-class Nonce(models.Model):
-    token_key = models.CharField(max_length=KEY_SIZE)
-    consumer_key = models.CharField(max_length=KEY_SIZE)
-    key = models.CharField(max_length=255)
-    
-    def __unicode__(self):
-        return u"Nonce %s for %s" % (self.key, self.consumer_key)
-
-
-class Consumer(models.Model):
-    name = models.CharField(max_length=255)
-    description = models.TextField()
-
-    key = models.CharField(max_length=KEY_SIZE)
-    secret = models.CharField(max_length=SECRET_SIZE)
-
-    status = models.CharField(max_length=16, choices=CONSUMER_STATES, default='pending')
-    user = models.ForeignKey(User, null=True, blank=True, related_name='consumers')
-
-    objects = ConsumerManager()
-        
-    def __unicode__(self):
-        return u"Consumer %s with key %s" % (self.name, self.key)
-
-    def generate_random_codes(self):
-        """
-        Used to generate random key/secret pairings. Use this after you've
-        added the other data in place of save(). 
-
-        c = Consumer()
-        c.name = "My consumer" 
-        c.description = "An app that makes ponies from the API."
-        c.user = some_user_object
-        c.generate_random_codes()
-        """
-        key = User.objects.make_random_password(length=KEY_SIZE)
-        secret = generate_random(SECRET_SIZE)
-
-        while Consumer.objects.filter(key__exact=key, secret__exact=secret).count():
-            secret = generate_random(SECRET_SIZE)
-
-        self.key = key
-        self.secret = secret
-        self.save()
-
-
-class Token(models.Model):
-    REQUEST = 1
-    ACCESS = 2
-    TOKEN_TYPES = ((REQUEST, u'Request'), (ACCESS, u'Access'))
-    
-    key = models.CharField(max_length=KEY_SIZE)
-    secret = models.CharField(max_length=SECRET_SIZE)
-    verifier = models.CharField(max_length=VERIFIER_SIZE)
-    token_type = models.IntegerField(choices=TOKEN_TYPES)
-    timestamp = models.IntegerField(default=long(time.time()))
-    is_approved = models.BooleanField(default=False)
-    
-    user = models.ForeignKey(User, null=True, blank=True, related_name='tokens')
-    consumer = models.ForeignKey(Consumer)
-    
-    callback = models.CharField(max_length=255, null=True, blank=True)
-    callback_confirmed = models.BooleanField(default=False)
-    
-    objects = TokenManager()
-    
-    def __unicode__(self):
-        return u"%s Token %s for %s" % (self.get_token_type_display(), self.key, self.consumer)
-
-    def to_string(self, only_key=False):
-        token_dict = {
-            'oauth_token': self.key, 
-            'oauth_token_secret': self.secret,
-            'oauth_callback_confirmed': 'true',
-        }
-
-        if self.verifier:
-            token_dict.update({ 'oauth_verifier': self.verifier })
-
-        if only_key:
-            del token_dict['oauth_token_secret']
-
-        return urllib.urlencode(token_dict)
-
-    def generate_random_codes(self):
-        key = User.objects.make_random_password(length=KEY_SIZE)
-        secret = generate_random(SECRET_SIZE)
-
-        while Token.objects.filter(key__exact=key, secret__exact=secret).count():
-            secret = generate_random(SECRET_SIZE)
-
-        self.key = key
-        self.secret = secret
-        self.save()
-        
-    # -- OAuth 1.0a stuff
-
-    def get_callback_url(self):
-        if self.callback and self.verifier:
-            # Append the oauth_verifier.
-            parts = urlparse.urlparse(self.callback)
-            scheme, netloc, path, params, query, fragment = parts[:6]
-            if query:
-                query = '%s&oauth_verifier=%s' % (query, self.verifier)
-            else:
-                query = 'oauth_verifier=%s' % self.verifier
-            return urlparse.urlunparse((scheme, netloc, path, params,
-                query, fragment))
-        return self.callback
-    
-    def set_callback(self, callback):
-        if callback != "oob": # out of band, says "we can't do this!"
-            self.callback = callback
-            self.callback_confirmed = True
-            self.save()
-
-
-# Attach our signals
-post_save.connect(consumer_post_save, sender=Consumer)
-pre_delete.connect(consumer_pre_delete, sender=Consumer)

piston/signals.py

-# Django imports
-import django.dispatch 
-
-# Piston imports
-from utils import send_consumer_mail
-
-def consumer_post_save(sender, instance, created, **kwargs):
-    send_consumer_mail(instance)
-
-def consumer_pre_delete(sender, instance, **kwargs):
-    instance.status = 'canceled'
-    send_consumer_mail(instance)
-
-
 import django.test as test
 from django.utils.http import urlencode
 
-# Piston imports
-from piston.models import Consumer, Token
-
 # 3rd/Python party imports
 import httplib2, urllib, cgi
 
 
 # Piston imports
 from test import TestCase
-from models import Consumer
 from handler import BaseHandler
 from utils import rc
 from resource import Resource
 
-class ConsumerTest(TestCase):
-    fixtures = ['models.json']
-
-    def setUp(self):
-        self.consumer = Consumer()
-        self.consumer.name = "Piston Test Consumer"
-        self.consumer.description = "A test consumer for Piston."
-        self.consumer.user = User.objects.get(pk=3)
-        self.consumer.generate_random_codes()
-
-    def _pre_test_email(self):
-        template = "piston/mails/consumer_%s.txt" % self.consumer.status
-        try:
-            loader.render_to_string(template, {
-                'consumer': self.consumer,
-                'user': self.consumer.user
-            })
-            return True
-        except TemplateDoesNotExist:
-            """
-            They haven't set up the templates, which means they might not want
-            these emails sent.
-            """
-            return False
-
-    def test_create_pending(self):
-        """ Ensure creating a pending Consumer sends proper emails """
-        # Verify if the emails can be sent
-        if not self._pre_test_email():
-            return
-
-        # If it's pending we should have two messages in the outbox; one
-        # to the consumer and one to the site admins.
-        if len(settings.ADMINS):
-            self.assertEquals(len(mail.outbox), 2)
-        else:
-            self.assertEquals(len(mail.outbox), 1)
-
-        expected = "Your API Consumer for example.com is awaiting approval."
-        self.assertEquals(mail.outbox[0].subject, expected)
-
-    def test_delete_consumer(self):
-        """ Ensure deleting a Consumer sends a cancel email """
-
-        # Clear out the outbox before we test for the cancel email.
-        mail.outbox = []
-
-        # Delete the consumer, which should fire off the cancel email.
-        self.consumer.delete()
-
-        # Verify if the emails can be sent
-        if not self._pre_test_email():
-            return
-
-        self.assertEquals(len(mail.outbox), 1)
-        expected = "Your API Consumer for example.com has been canceled."
-        self.assertEquals(mail.outbox[0].subject, expected)
-
-
 class CustomResponseWithStatusCodeTest(TestCase):
      """
      Test returning content to be formatted and a custom response code from a 
     return wrap
 
 require_extended = require_mime('json', 'yaml', 'xml', 'pickle')
-    
-def send_consumer_mail(consumer):
-    """
-    Send a consumer an email depending on what their status is.
-    """
-    if not getattr(settings, 'PISTON_OAUTH_SEND_STATUS_EMAILS', True):
-        return
-
-    try:
-        subject = settings.PISTON_OAUTH_EMAIL_SUBJECTS[consumer.status]
-    except AttributeError:
-        subject = "Your API Consumer for %s " % Site.objects.get_current().name
-        if consumer.status == "accepted":
-            subject += "was accepted!"
-        elif consumer.status == "canceled":
-            subject += "has been canceled."
-        elif consumer.status == "rejected":
-            subject += "has been rejected."
-        else: 
-            subject += "is awaiting approval."
-
-    template = "piston/mails/consumer_%s.txt" % consumer.status    
-    
-    try:
-        body = loader.render_to_string(template, 
-            { 'consumer' : consumer, 'user' : consumer.user })
-    except TemplateDoesNotExist:
-        """ 
-        They haven't set up the templates, which means they might not want
-        these emails sent.
-        """
-        return 
-
-    try:
-        sender = settings.PISTON_FROM_EMAIL
-    except AttributeError:
-        sender = settings.DEFAULT_FROM_EMAIL
-
-    if consumer.user:
-        send_mail(_(subject), body, sender, [consumer.user.email], fail_silently=True)
-
-    if consumer.status == 'pending' and len(settings.ADMINS):
-        mail_admins(_(subject), body, fail_silently=True)
-
-    if settings.DEBUG and consumer.user:
-        print "Mail being sent, to=%s" % consumer.user.email
-        print "Subject: %s" % _(subject)
-        print body
-

tests/test_project/apps/testapp/tests.py

 from django.utils import simplejson
 from django.conf import settings
 
-from piston.models import Consumer, Token
-
 try:
     import yaml
 except ImportError:
         self.user.delete()
 
 
-
-class OAuthTests(MainTests):
-    signature_method = oauth.SignatureMethod_HMAC_SHA1()
-    callback_url = 'http://example.com/cb'
-    request_token_url = 'http://testserver/api/oauth/get_request_token'
-    authorize_url = 'http://testserver/api/oauth/authorize_request_token'
-    access_token_url = 'http://testserver/api/oauth/get_access_token'
-    two_legged_api_url = 'http://testserver/api/oauth/two_legged_api'
-    three_legged_api_url = 'http://testserver/api/oauth/three_legged_api'
-
-    def setUp(self):
-        super(OAuthTests, self).setUp()
-        self.consumer = Consumer.objects.create_consumer('Test Consumer')
-        self.consumer.status = 'accepted'
-        self.consumer.save()
-
-    def tearDown(self):
-        super(OAuthTests, self).tearDown()
-        #self.consumer.delete()
-
-    def test_get_request_token(self, callback='oob'):
-        request = oauth.Request.from_consumer_and_token(self.consumer, None, 'GET', self.request_token_url, {'oauth_callback': callback})
-        request.sign_request(self.signature_method, self.consumer, None)
-
-        response = self.client.get(self.request_token_url, request)
-        self.assertEquals(response.status_code, 200)
-
-        params = dict(urlparse.parse_qsl(response.content))
-        return oauth.Token(params['oauth_token'], params['oauth_token_secret'])
-
-    def authorize_request_token(self, request_token_key):
-        self.client.login(username='admin', password='admin')
-        return self.client.post(self.authorize_url, {'oauth_token': request_token_key, 'authorize_access': None})
-
-    def test_authorize_request_token_without_callback(self):
-        request_token = self.test_get_request_token('oob')
-        response = self.authorize_request_token(request_token.key)
-
-        self.assertEquals(response.status_code, 200)
-
-    def test_authorize_request_token_with_callback(self):
-        request_token = self.test_get_request_token(self.callback_url)
-        response = self.authorize_request_token(request_token.key)
-
-        self.assertEquals(response.status_code, 302)
-        self.assert_(response['Location'].startswith(self.callback_url))
-
-    def test_get_access_token(self):
-        request_token = self.test_get_request_token(self.callback_url)
-        response = self.authorize_request_token(request_token.key)
-        params = dict(urlparse.parse_qsl(response['Location'][len(self.callback_url)+1:]))
-        
-        request_token.set_verifier(params['oauth_verifier'])
-        
-        request = oauth.Request.from_consumer_and_token(self.consumer, request_token, 'POST', self.access_token_url)
-        request.sign_request(self.signature_method, self.consumer, request_token)
-
-        response = self.client.post(self.access_token_url, request)
-        self.assertEquals(response.status_code, 200)
-        
-        params = dict(urlparse.parse_qsl(response.content))
-        return oauth.Token(params['oauth_token'], params['oauth_token_secret'])
-
-    def test_two_legged_api(self):
-        request = oauth.Request.from_consumer_and_token(self.consumer, None, 'GET', self.two_legged_api_url, {'msg': 'expected response'})
-        request.sign_request(self.signature_method, self.consumer, None)
-
-        response = self.client.get(self.two_legged_api_url, request)
-        self.assertEquals(response.status_code, 200)
-        self.assert_('expected response' in response.content)
-
-    def test_three_legged_api(self):
-        access_token = self.test_get_access_token()
-
-        request = oauth.Request.from_consumer_and_token(self.consumer, access_token, 'GET', self.three_legged_api_url, {'msg': 'expected response'})
-        request.sign_request(self.signature_method, self.consumer, access_token)
-
-        response = self.client.get(self.three_legged_api_url, request)
-        self.assertEquals(response.status_code, 200)
-        self.assert_('expected response' in response.content)
-
-
 class BasicAuthTest(MainTests):
 
     def test_invalid_auth_header(self):
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.