Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

oauth example

  • Loading branch information...
commit 9d36100dff6909185c08f809e9a542ea22f6a7dc 1 parent 16a281b
Benoit Chesneau authored
2  .gitignore
@@ -9,4 +9,4 @@ dist
9 9 build
10 10 doc/build/doctrees
11 11 doc/build/html
12   -examples/oauth/oauth.db
  12 +examples/testoauth/oauth.db
0  example/testoauth/__init__.py
No changes.
11 example/testoauth/manage.py
... ... @@ -0,0 +1,11 @@
  1 +#!/usr/bin/env python
  2 +from django.core.management import execute_manager
  3 +try:
  4 + import settings # Assumed to be in the same directory.
  5 +except ImportError:
  6 + import sys
  7 + 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__)
  8 + sys.exit(1)
  9 +
  10 +if __name__ == "__main__":
  11 + execute_manager(settings)
0  example/testoauth/protected/__init__.py
No changes.
10 example/testoauth/protected/resource.py
... ... @@ -0,0 +1,10 @@
  1 +from webmachine import Resource
  2 +from webmachine.auth.oauth import Oauth
  3 +
  4 +class Protected(Resource):
  5 +
  6 + def to_html(self, req, resp):
  7 + return "<html><p>I'm protected you know.</p></html>"
  8 +
  9 + def is_authorized(self, req, resp):
  10 + return Oauth().authorized(req, resp)
98 example/testoauth/settings.py
... ... @@ -0,0 +1,98 @@
  1 +# Django settings for oauth project.
  2 +
  3 +DEBUG = True
  4 +TEMPLATE_DEBUG = DEBUG
  5 +
  6 +ADMINS = (
  7 + # ('Your Name', 'your_email@domain.com'),
  8 +)
  9 +
  10 +MANAGERS = ADMINS
  11 +
  12 +DATABASES = {
  13 + 'default': {
  14 + 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
  15 + 'NAME': 'oauth.db', # Or path to database file if using sqlite3.
  16 + 'USER': '', # Not used with sqlite3.
  17 + 'PASSWORD': '', # Not used with sqlite3.
  18 + 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
  19 + 'PORT': '', # Set to empty string for default. Not used with sqlite3.
  20 + }
  21 +}
  22 +
  23 +# Local time zone for this installation. Choices can be found here:
  24 +# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
  25 +# although not all choices may be available on all operating systems.
  26 +# On Unix systems, a value of None will cause Django to use the same
  27 +# timezone as the operating system.
  28 +# If running in a Windows environment this must be set to the same as your
  29 +# system time zone.
  30 +TIME_ZONE = 'Europe/Paris'
  31 +
  32 +# Language code for this installation. All choices can be found here:
  33 +# http://www.i18nguy.com/unicode/language-identifiers.html
  34 +LANGUAGE_CODE = 'en-us'
  35 +
  36 +SITE_ID = 1
  37 +
  38 +# If you set this to False, Django will make some optimizations so as not
  39 +# to load the internationalization machinery.
  40 +USE_I18N = True
  41 +
  42 +# If you set this to False, Django will not format dates, numbers and
  43 +# calendars according to the current locale
  44 +USE_L10N = True
  45 +
  46 +# Absolute path to the directory that holds media.
  47 +# Example: "/home/media/media.lawrence.com/"
  48 +MEDIA_ROOT = ''
  49 +
  50 +# URL that handles the media served from MEDIA_ROOT. Make sure to use a
  51 +# trailing slash if there is a path component (optional in other cases).
  52 +# Examples: "http://media.lawrence.com", "http://example.com/media/"
  53 +MEDIA_URL = ''
  54 +
  55 +# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
  56 +# trailing slash.
  57 +# Examples: "http://foo.com/media/", "/media/".
  58 +ADMIN_MEDIA_PREFIX = '/media/'
  59 +
  60 +# Make this unique, and don't share it with anybody.
  61 +SECRET_KEY = '#i=e163$15)prr-_mpo!po085%jtan0y0%yd8gx++wz0fy(qg%'
  62 +
  63 +# List of callables that know how to import templates from various sources.
  64 +TEMPLATE_LOADERS = (
  65 + 'django.template.loaders.filesystem.Loader',
  66 + 'django.template.loaders.app_directories.Loader',
  67 +# 'django.template.loaders.eggs.Loader',
  68 +)
  69 +
  70 +MIDDLEWARE_CLASSES = (
  71 + 'django.middleware.common.CommonMiddleware',
  72 + 'django.contrib.sessions.middleware.SessionMiddleware',
  73 + 'django.middleware.csrf.CsrfViewMiddleware',
  74 + 'django.contrib.auth.middleware.AuthenticationMiddleware',
  75 + 'django.contrib.messages.middleware.MessageMiddleware',
  76 +)
  77 +
  78 +ROOT_URLCONF = 'testoauth.urls'
  79 +
  80 +TEMPLATE_DIRS = (
  81 + # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
  82 + # Always use forward slashes, even on Windows.
  83 + # Don't forget to use absolute paths, not relative paths.
  84 +)
  85 +
  86 +INSTALLED_APPS = (
  87 + 'django.contrib.auth',
  88 + 'django.contrib.contenttypes',
  89 + 'django.contrib.sessions',
  90 + 'django.contrib.sites',
  91 + 'django.contrib.messages',
  92 + # Uncomment the next line to enable the admin:
  93 + # 'django.contrib.admin',
  94 + # Uncomment the next line to enable admin documentation:
  95 + # 'django.contrib.admindocs',
  96 + 'webmachine',
  97 + 'testoauth.protected'
  98 +)
23 example/testoauth/urls.py
... ... @@ -0,0 +1,23 @@
  1 +from django.conf.urls.defaults import *
  2 +from webmachine.auth import oauth_res
  3 +
  4 +from testoauth.protected.resource import Protected
  5 +
  6 +# Uncomment the next two lines to enable the admin:
  7 +# from django.contrib import admin
  8 +# admin.autodiscover()
  9 +
  10 +
  11 +urlpatterns = patterns('',
  12 + # Example:
  13 + # (r'^oauth/', include('oauth.foo.urls')),
  14 +
  15 + # Uncomment the admin/doc line below to enable admin documentation:
  16 + # (r'^admin/doc/', include('django.contrib.admindocs.urls')),
  17 +
  18 + # Uncomment the next line to enable the admin:
  19 + # (r'^admin/', include(admin.site.urls)),
  20 +
  21 + (r'auth', oauth_res.OauthResource().get_urls()),
  22 + (r'$^', Protected()),
  23 +)
3  webmachine/auth/base.py
@@ -5,7 +5,8 @@
5 5
6 6 import binascii
7 7
8   -from django.contrib.auth import authenticate, AnonymousUser
  8 +from django.contrib.auth import authenticate
  9 +from django.contrib.auth.models import AnonymousUser
9 10
10 11 from webmachine.exc import HTTPClientError
11 12
9 webmachine/auth/oauth.py
@@ -8,7 +8,7 @@
8 8 from django.utils.importlib import import_module
9 9
10 10 try:
11   - from restkit.utils import oauth2
  11 + from restkit.util import oauth2
12 12 except ImportError:
13 13 try:
14 14 import oauth2
@@ -19,11 +19,12 @@
19 19 from webmachine.const import TOKEN_REQUEST, TOKEN_ACCESS
20 20
21 21
22   -def load_oauth_datastore(self):
  22 +def load_oauth_datastore():
23 23 datastore = getattr(settings, 'OAUTH_DATASTORE',
24 24 'webmachine.auth.oauth_store.DataStore')
25 25 i = datastore.rfind('.')
26 26 module, clsname = datastore[:i], datastore[i+1:]
  27 + print module
27 28 try:
28 29 mod = import_module(module)
29 30 except ImportError:
@@ -124,8 +125,8 @@ def __init__(self, realm="OAuth"):
124 125 oauth_datastore = load_oauth_datastore()
125 126 self.realm = realm
126 127 self.oauth_server = OAuthServer(oauth_datastore())
127   - self.oauth_server.add_signature_method(oauth2.OAuthSignatureMethod_PLAINTEXT())
128   - self.oauth_server.add_signature_method(oauth2.OAuthSignatureMethod_HMAC_SHA1())
  128 + self.oauth_server.add_signature_method(oauth2.SignatureMethod_PLAINTEXT())
  129 + self.oauth_server.add_signature_method(oauth2.SignatureMethod_HMAC_SHA1())
129 130
130 131 def authorized(self, req, resp):
131 132 params = {}
4 webmachine/auth/oauth_res.py
@@ -6,7 +6,7 @@
6 6 from django.template import loader, RequestContext
7 7
8 8 try:
9   - from restkit.utils import oauth2
  9 + from restkit.util import oauth2
10 10 except ImportError:
11 11 try:
12 12 import oauth2
@@ -17,7 +17,7 @@
17 17 from webmachine.resource import Resource
18 18
19 19
20   -class Oauth(Resource):
  20 +class OauthResource(Resource):
21 21
22 22 def __init__(self, realm='OAuth',
23 23 auth_template='webmachine/authorize_token.html',
4 webmachine/forms.py
@@ -7,7 +7,7 @@
7 7 try:
8 8 import hashlib
9 9 _sha = hashlib.sha1
10   -except ImportError
  10 +except ImportError:
11 11 import sha
12 12 _sha = sha
13 13
@@ -31,7 +31,7 @@ def clean_csrf_signature(self):
31 31 token = self.cleaned_data['oauth_token']
32 32
33 33 sig1 = OAuthAuthenticationForm.get_csrf_signature(settings.SECRET_KEY,
34   - token
  34 + token)
35 35 if sig != sig1:
36 36 raise forms.ValidationError("CSRF signature is not valid")
37 37
5 webmachine/util/__init__.py
@@ -30,6 +30,11 @@ def generate_timestamp():
30 30 """Get seconds since epoch (UTC)."""
31 31 return int(time.time())
32 32
  33 +def generate_random(length=8):
  34 + """Generate pseudorandom number."""
  35 + return ''.join([str(random.randint(0, 9)) for i in range(length)])
  36 +
  37 +
33 38
34 39 def coerce_put_post(request):
35 40 """

0 comments on commit 9d36100

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