Permalink
Browse files

oauth example

  • Loading branch information...
1 parent 16a281b commit 9d36100dff6909185c08f809e9a542ea22f6a7dc @benoitc committed Nov 11, 2010
View
@@ -9,4 +9,4 @@ dist
build
doc/build/doctrees
doc/build/html
-examples/oauth/oauth.db
+examples/testoauth/oauth.db
No changes.
@@ -0,0 +1,11 @@
+#!/usr/bin/env python
+from django.core.management import execute_manager
+try:
+ import settings # Assumed to be in the same directory.
+except ImportError:
+ import sys
+ sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
+ sys.exit(1)
+
+if __name__ == "__main__":
+ execute_manager(settings)
@@ -0,0 +1,10 @@
+from webmachine import Resource
+from webmachine.auth.oauth import Oauth
+
+class Protected(Resource):
+
+ def to_html(self, req, resp):
+ return "<html><p>I'm protected you know.</p></html>"
+
+ def is_authorized(self, req, resp):
+ return Oauth().authorized(req, resp)
@@ -0,0 +1,98 @@
+# Django settings for oauth project.
+
+DEBUG = True
+TEMPLATE_DEBUG = DEBUG
+
+ADMINS = (
+ # ('Your Name', 'your_email@domain.com'),
+)
+
+MANAGERS = ADMINS
+
+DATABASES = {
+ 'default': {
+ 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
+ 'NAME': 'oauth.db', # Or path to database file if using sqlite3.
+ 'USER': '', # Not used with sqlite3.
+ 'PASSWORD': '', # Not used with sqlite3.
+ 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
+ 'PORT': '', # Set to empty string for default. Not used with sqlite3.
+ }
+}
+
+# Local time zone for this installation. Choices can be found here:
+# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
+# although not all choices may be available on all operating systems.
+# On Unix systems, a value of None will cause Django to use the same
+# timezone as the operating system.
+# If running in a Windows environment this must be set to the same as your
+# system time zone.
+TIME_ZONE = 'Europe/Paris'
+
+# Language code for this installation. All choices can be found here:
+# http://www.i18nguy.com/unicode/language-identifiers.html
+LANGUAGE_CODE = 'en-us'
+
+SITE_ID = 1
+
+# If you set this to False, Django will make some optimizations so as not
+# to load the internationalization machinery.
+USE_I18N = True
+
+# If you set this to False, Django will not format dates, numbers and
+# calendars according to the current locale
+USE_L10N = True
+
+# Absolute path to the directory that holds media.
+# Example: "/home/media/media.lawrence.com/"
+MEDIA_ROOT = ''
+
+# URL that handles the media served from MEDIA_ROOT. Make sure to use a
+# trailing slash if there is a path component (optional in other cases).
+# Examples: "http://media.lawrence.com", "http://example.com/media/"
+MEDIA_URL = ''
+
+# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
+# trailing slash.
+# Examples: "http://foo.com/media/", "/media/".
+ADMIN_MEDIA_PREFIX = '/media/'
+
+# Make this unique, and don't share it with anybody.
+SECRET_KEY = '#i=e163$15)prr-_mpo!po085%jtan0y0%yd8gx++wz0fy(qg%'
+
+# List of callables that know how to import templates from various sources.
+TEMPLATE_LOADERS = (
+ 'django.template.loaders.filesystem.Loader',
+ 'django.template.loaders.app_directories.Loader',
+# 'django.template.loaders.eggs.Loader',
+)
+
+MIDDLEWARE_CLASSES = (
+ 'django.middleware.common.CommonMiddleware',
+ 'django.contrib.sessions.middleware.SessionMiddleware',
+ 'django.middleware.csrf.CsrfViewMiddleware',
+ 'django.contrib.auth.middleware.AuthenticationMiddleware',
+ 'django.contrib.messages.middleware.MessageMiddleware',
+)
+
+ROOT_URLCONF = 'testoauth.urls'
+
+TEMPLATE_DIRS = (
+ # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
+ # Always use forward slashes, even on Windows.
+ # Don't forget to use absolute paths, not relative paths.
+)
+
+INSTALLED_APPS = (
+ 'django.contrib.auth',
+ 'django.contrib.contenttypes',
+ 'django.contrib.sessions',
+ 'django.contrib.sites',
+ 'django.contrib.messages',
+ # Uncomment the next line to enable the admin:
+ # 'django.contrib.admin',
+ # Uncomment the next line to enable admin documentation:
+ # 'django.contrib.admindocs',
+ 'webmachine',
+ 'testoauth.protected'
+)
@@ -0,0 +1,23 @@
+from django.conf.urls.defaults import *
+from webmachine.auth import oauth_res
+
+from testoauth.protected.resource import Protected
+
+# Uncomment the next two lines to enable the admin:
+# from django.contrib import admin
+# admin.autodiscover()
+
+
+urlpatterns = patterns('',
+ # Example:
+ # (r'^oauth/', include('oauth.foo.urls')),
+
+ # Uncomment the admin/doc line below to enable admin documentation:
+ # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
+
+ # Uncomment the next line to enable the admin:
+ # (r'^admin/', include(admin.site.urls)),
+
+ (r'auth', oauth_res.OauthResource().get_urls()),
+ (r'$^', Protected()),
+)
@@ -5,7 +5,8 @@
import binascii
-from django.contrib.auth import authenticate, AnonymousUser
+from django.contrib.auth import authenticate
+from django.contrib.auth.models import AnonymousUser
from webmachine.exc import HTTPClientError
@@ -8,7 +8,7 @@
from django.utils.importlib import import_module
try:
- from restkit.utils import oauth2
+ from restkit.util import oauth2
except ImportError:
try:
import oauth2
@@ -19,11 +19,12 @@
from webmachine.const import TOKEN_REQUEST, TOKEN_ACCESS
-def load_oauth_datastore(self):
+def load_oauth_datastore():
datastore = getattr(settings, 'OAUTH_DATASTORE',
'webmachine.auth.oauth_store.DataStore')
i = datastore.rfind('.')
module, clsname = datastore[:i], datastore[i+1:]
+ print module
try:
mod = import_module(module)
except ImportError:
@@ -124,8 +125,8 @@ def __init__(self, realm="OAuth"):
oauth_datastore = load_oauth_datastore()
self.realm = realm
self.oauth_server = OAuthServer(oauth_datastore())
- self.oauth_server.add_signature_method(oauth2.OAuthSignatureMethod_PLAINTEXT())
- self.oauth_server.add_signature_method(oauth2.OAuthSignatureMethod_HMAC_SHA1())
+ self.oauth_server.add_signature_method(oauth2.SignatureMethod_PLAINTEXT())
+ self.oauth_server.add_signature_method(oauth2.SignatureMethod_HMAC_SHA1())
def authorized(self, req, resp):
params = {}
@@ -6,7 +6,7 @@
from django.template import loader, RequestContext
try:
- from restkit.utils import oauth2
+ from restkit.util import oauth2
except ImportError:
try:
import oauth2
@@ -17,7 +17,7 @@
from webmachine.resource import Resource
-class Oauth(Resource):
+class OauthResource(Resource):
def __init__(self, realm='OAuth',
auth_template='webmachine/authorize_token.html',
View
@@ -7,7 +7,7 @@
try:
import hashlib
_sha = hashlib.sha1
-except ImportError
+except ImportError:
import sha
_sha = sha
@@ -31,7 +31,7 @@ def clean_csrf_signature(self):
token = self.cleaned_data['oauth_token']
sig1 = OAuthAuthenticationForm.get_csrf_signature(settings.SECRET_KEY,
- token
+ token)
if sig != sig1:
raise forms.ValidationError("CSRF signature is not valid")
@@ -30,6 +30,11 @@ def generate_timestamp():
"""Get seconds since epoch (UTC)."""
return int(time.time())
+def generate_random(length=8):
+ """Generate pseudorandom number."""
+ return ''.join([str(random.randint(0, 9)) for i in range(length)])
+
+
def coerce_put_post(request):
"""

0 comments on commit 9d36100

Please sign in to comment.