Skip to content
Browse files

Removes verifier--destroy what I don't understand.

  • Loading branch information...
1 parent c16d1d7 commit 1cc9dc28be67d1d40434a417a52fae006ce0df31 @davedash davedash committed Aug 31, 2010
Showing with 48 additions and 80 deletions.
  1. +1 −0 .gitignore
  2. +31 −32 piston/authentication.py
  3. +1 −36 piston/forms.py
  4. +15 −12 piston/oauth.py
View
1 .gitignore
@@ -0,0 +1 @@
+*.egg-info
View
63 piston/authentication.py
@@ -26,7 +26,7 @@ def is_authenticated(self, request):
class HttpBasicAuthentication(object):
"""
Basic HTTP authenticater. Synopsis:
-
+
Authentication handlers must implement two methods:
- `is_authenticated`: Will be called when checking for
authentication. Receives a `request` object, please
@@ -46,7 +46,7 @@ def is_authenticated(self, request):
if not auth_string:
return False
-
+
try:
(authmeth, auth) = auth_string.split(" ", 1)
@@ -57,12 +57,12 @@ def is_authenticated(self, request):
(username, password) = auth.split(':', 1)
except (ValueError, binascii.Error):
return False
-
+
request.user = self.auth_func(username=username, password=password) \
or AnonymousUser()
-
+
return not request.user in (False, None, AnonymousUser())
-
+
def challenge(self):
resp = HttpResponse("Authorization Required")
resp['WWW-Authenticate'] = 'Basic realm="%s"' % self.realm
@@ -78,7 +78,7 @@ def __init__(self, realm, username, password):
self.password = password
super(HttpBasicSimple, self).__init__(auth_func=self.hash, realm=realm)
-
+
def hash(self, username, password):
if username == self.user.username and password == self.password:
return self.user
@@ -122,17 +122,17 @@ def initialize_server_request(request):
request.META['Authorization'] = request.META.get('HTTP_AUTHORIZATION', '')
oauth_request = oauth.OAuthRequest.from_request(
- request.method, request.build_absolute_uri(),
+ request.method, request.build_absolute_uri(),
headers=request.META, parameters=params,
query_string=request.environ.get('QUERY_STRING', ''))
-
+
if oauth_request:
oauth_server = oauth.OAuthServer(oauth_datastore(oauth_request))
oauth_server.add_signature_method(oauth.OAuthSignatureMethod_PLAINTEXT())
oauth_server.add_signature_method(oauth.OAuthSignatureMethod_HMAC_SHA1())
else:
oauth_server = None
-
+
return oauth_server, oauth_request
def send_oauth_error(err=None):
@@ -152,7 +152,7 @@ def send_oauth_error(err=None):
def oauth_request_token(request):
oauth_server, oauth_request = initialize_server_request(request)
-
+
if oauth_server is None:
return INVALID_PARAMS_RESPONSE
try:
@@ -176,20 +176,20 @@ def oauth_auth_view(request, token, callback, params):
@login_required
def oauth_user_auth(request):
oauth_server, oauth_request = initialize_server_request(request)
-
+
if oauth_request is None:
return INVALID_PARAMS_RESPONSE
-
+
try:
token = oauth_server.fetch_request_token(oauth_request)
except oauth.OAuthError, err:
return send_oauth_error(err)
-
+
try:
callback = oauth_server.get_callback(oauth_request)
except:
callback = None
-
+
if request.method == "GET":
params = oauth_request.get_normalized_parameters()
@@ -206,48 +206,47 @@ def oauth_user_auth(request):
args = '?'+token.to_string(only_key=True)
else:
args = '?error=%s' % 'Access not granted by user.'
- print "FORM ERROR", form.errors
-
+
if not callback:
callback = getattr(settings, 'OAUTH_CALLBACK_VIEW')
return get_callable(callback)(request, token)
-
+
response = HttpResponseRedirect(callback+args)
-
+
except oauth.OAuthError, err:
response = send_oauth_error(err)
else:
response = HttpResponse('Action not allowed.')
-
+
return response
def oauth_access_token(request):
oauth_server, oauth_request = initialize_server_request(request)
-
+
if oauth_request is None:
return INVALID_PARAMS_RESPONSE
-
+
try:
- token = oauth_server.fetch_access_token(oauth_request)
+ token = oauth_server.fetch_access_token(oauth_request, required=True)
return HttpResponse(token.to_string())
except oauth.OAuthError, err:
return send_oauth_error(err)
INVALID_PARAMS_RESPONSE = send_oauth_error(oauth.OAuthError('Invalid request parameters.'))
-
+
class OAuthAuthentication(object):
"""
OAuth authentication. Based on work by Leah Culver.
"""
def __init__(self, realm='API'):
self.realm = realm
self.builder = oauth.build_authenticate_header
-
+
def is_authenticated(self, request):
"""
Checks whether a means of specifying authentication
is provided, and if so, if it is a valid token.
-
+
Read the documentation on `HttpBasicAuthentication`
for more information about what goes on here.
"""
@@ -263,14 +262,14 @@ def is_authenticated(self, request):
request.consumer = consumer
request.throttle_extra = token.consumer.id
return True
-
+
return False
-
+
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
@@ -290,7 +289,7 @@ def challenge(self):
response.content = tmpl
return response
-
+
@staticmethod
def is_valid_request(request):
"""
@@ -302,14 +301,14 @@ def is_valid_request(request):
must_have = [ 'oauth_'+s for s in [
'consumer_key', 'token', 'signature',
'signature_method', 'timestamp', 'nonce' ] ]
-
+
is_in = lambda l: all([ (p in l) for p in must_have ])
auth_params = request.META.get("HTTP_AUTHORIZATION", "")
req_params = request.REQUEST
-
+
return is_in(auth_params) or is_in(req_params)
-
+
@staticmethod
def validate_token(request, check_timestamp=True, check_nonce=True):
oauth_server, oauth_request = initialize_server_request(request)
View
37 piston/forms.py
@@ -5,7 +5,7 @@
class Form(forms.Form):
pass
-
+
class ModelForm(forms.ModelForm):
"""
Subclass of `forms.ModelForm` which makes sure
@@ -25,38 +25,3 @@ class OAuthAuthenticationForm(forms.Form):
oauth_token = forms.CharField(widget=forms.HiddenInput)
oauth_callback = forms.CharField(widget=forms.HiddenInput, required=False)
authorize_access = forms.BooleanField(required=True)
- csrf_signature = forms.CharField(widget=forms.HiddenInput)
-
- def __init__(self, *args, **kwargs):
- forms.Form.__init__(self, *args, **kwargs)
-
- self.fields['csrf_signature'].initial = self.initial_csrf_signature
-
- def clean_csrf_signature(self):
- sig = self.cleaned_data['csrf_signature']
- token = self.cleaned_data['oauth_token']
-
- sig1 = OAuthAuthenticationForm.get_csrf_signature(settings.SECRET_KEY, token)
-
- if sig != sig1:
- raise forms.ValidationError("CSRF signature is not valid")
-
- return sig
-
- def initial_csrf_signature(self):
- token = self.initial['oauth_token']
- return OAuthAuthenticationForm.get_csrf_signature(settings.SECRET_KEY, token)
-
- @staticmethod
- def get_csrf_signature(key, token):
- # Check signature...
- try:
- import hashlib # 2.5
- hashed = hmac.new(key, token, hashlib.sha1)
- except:
- import sha # deprecated
- hashed = hmac.new(key, token, sha)
-
- # calculate the digest base 64
- return base64.b64encode(hashed.digest())
-
View
27 piston/oauth.py
@@ -87,7 +87,7 @@ def __init__(self, key, secret):
class OAuthToken(object):
"""OAuthToken is a data type that represents an End User via either an access
or request token.
-
+
key -- the token
secret -- the token secret
@@ -133,7 +133,7 @@ def to_string(self):
if self.callback_confirmed is not None:
data['oauth_callback_confirmed'] = self.callback_confirmed
return urllib.urlencode(data)
-
+
def from_string(s):
""" Returns a token from something like:
oauth_token_secret=xxx&oauth_token=xxx
@@ -157,11 +157,11 @@ class OAuthRequest(object):
"""OAuthRequest represents the request and can be serialized.
OAuth parameters:
- - oauth_consumer_key
+ - oauth_consumer_key
- oauth_token
- oauth_signature_method
- - oauth_signature
- - oauth_timestamp
+ - oauth_signature
+ - oauth_timestamp
- oauth_nonce
- oauth_version
- oauth_verifier
@@ -405,24 +405,27 @@ def fetch_request_token(self, oauth_request):
token = self.data_store.fetch_request_token(consumer, callback)
return token
- def fetch_access_token(self, oauth_request):
+ def fetch_access_token(self, oauth_request, required=False):
"""Processes an access_token request and returns the
access token on success.
"""
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
- verifier = self._get_verifier(oauth_request)
# Get the request token.
token = self._get_token(oauth_request, 'request')
self._check_signature(oauth_request, consumer, token)
- new_token = self.data_store.fetch_access_token(consumer, token, verifier)
+ new_token = self.data_store.fetch_access_token(consumer, token, '')
+
+ if required and not new_token:
+ raise OAuthError('Valid token not present.')
return new_token
def verify_request(self, oauth_request):
"""Verifies an api call and checks all the parameters."""
# -> consumer and token
version = self._get_version(oauth_request)
consumer = self._get_consumer(oauth_request)
+
# Get the access token.
token = self._get_token(oauth_request, 'access')
self._check_signature(oauth_request, consumer, token)
@@ -436,7 +439,7 @@ def authorize_token(self, token, user):
def get_callback(self, oauth_request):
"""Get the callback URL."""
return oauth_request.get_parameter('oauth_callback')
-
+
def build_authenticate_header(self, realm=''):
"""Optional support for the authenticate header."""
return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
@@ -482,7 +485,7 @@ def _get_token(self, oauth_request, token_type='access'):
if not token:
raise OAuthError('Invalid %s token: %s' % (token_type, token_field))
return token
-
+
def _get_verifier(self, oauth_request):
return oauth_request.get_parameter('oauth_verifier')
@@ -601,7 +604,7 @@ class OAuthSignatureMethod_HMAC_SHA1(OAuthSignatureMethod):
def get_name(self):
return 'HMAC-SHA1'
-
+
def build_signature_base_string(self, oauth_request, consumer, token):
sig = (
escape(oauth_request.get_normalized_http_method()),
@@ -647,4 +650,4 @@ def build_signature_base_string(self, oauth_request, consumer, token):
def build_signature(self, oauth_request, consumer, token):
key, raw = self.build_signature_base_string(oauth_request, consumer,
token)
- return key
+ return key

0 comments on commit 1cc9dc2

Please sign in to comment.
Something went wrong with that request. Please try again.