Alexis Metaireau avatar Alexis Metaireau committed 7c12111

views now uses models neither than django settings. Allows multiple oauth server flow with the same app

Comments (0)

Files changed (4)

oauthclient/management/__init__.py

                 call_command("oauthcreatetoken", interactive=True)
             break
 
-signals.post_syncdb.connect(create_oauth_token, sender=oauthclient_app,
-    dispatch_uid="oauthclient.management.create_oauth_token")
+#signals.post_syncdb.connect(create_oauth_token, sender=oauthclient_app,
+#    dispatch_uid="oauthclient.management.create_oauth_token")

oauthclient/management/commands/oauthcreatetoken.py

                 'idea is to enter the name of the service, or the OAuth' \
                 'server.'),
         make_option('--key', dest='key', default=None, 
-            help='Specify the OAuth token key to use'),
+            help='Specify the OAuth token key.'),
         make_option('--secret', dest='secret', default=None,
-            help='Specify the OAuth token secret to user'), 
+            help='Specify the OAuth token secret.'), 
         make_option('--serverurl', dest='serverurl', default=None, 
-            help='Specify the OAuth server root url to use'),
+            help='Specify the OAuth server root url.'),
         make_option('--request-token-url', dest='request_token_url',
             default='/oauth/request_token/', 
             help='Specify the request token url'),

oauthclient/models.py

 from django.db import models
+import oauth2
 
 KEY_SIZE = SECRET_SIZE = 16
 
     server_url = models.URLField(verify_exists = False)
     request_token_url = models.CharField(max_length=300)
     access_token_url = models.CharField(max_length=300)
-    authorize_url = models.CharField(max_length=300) 
+    authorize_url = models.CharField(max_length=300)
+
+    def get_request_token_url(self):
+        return self.server_url + self.request_token_url
+
+    def get_access_token_url(self):
+        return self.server_url + self.access_token_url
+    
+    def get_authorize_url(self):
+        return self.server_url + self.authorize_url
+
 
 class Token(models.Model):
     """Define a couple key-secret provided by the oauth server for this
     secret = models.CharField(max_length=SECRET_SIZE, null=True, blank=True)
     server = models.ForeignKey(OAuthServer)
     last_modification = models.DateField(auto_now=True)
+
+    def _get_consumer(self):
+        """Return a consumer object, configured with settings values.
+        
+        """
+        return oauth2.Consumer(self.key, self.secret)
     
     class Meta:
         get_latest_by = 'last_modification'

oauthclient/views.py

 # django imports
 from django.shortcuts import render_to_response as render, redirect
-from django.conf import settings
 from django.contrib.sites.models import Site
 from django.core.urlresolvers import reverse
 
 
 #oauthclient import
 from utils import is_oauthenticated
+from models import Token, OAuthServer
 
-def _get_consumer():
-    """Return a consumer object, configured with settings values.
-    
-    """
-    return oauth2.Consumer(settings.OAUTH_CONSUMER_TOKEN, settings.OAUTH_CONSUMER_SECRET)
-        
-def get_request_token(request):
+def get_request_token(request, identifier):
     """First and second step of the three-legged OAuth flow:
     
     Request a request token to the OAuth server, and redirect the user on the
-    BisonVert website, to authorize user access.
+    OAuth server, to authorize user access.
     
     Once this done, the server redirect the user on the access_token_ready
     view.
     
     """
-    client = oauth2.Client(_get_consumer())
-    resp, content = client.request(settings.OAUTH_REQUEST_TOKEN_URL, "GET")
+    token = Token.objects.get(identifier=identifier)
+    client = oauth2.Client(token.get_consumer())
+    resp, content = client.request(token.server.get_request_token_url(), "GET")
+
     if resp['status'] != '200':
         raise Exception("Invalid response %s." % resp['status'])    
 
         raise Exception("Invalid response: oauth_token and oauth_token_secret have to be present in the OAuth server response")
     
     # store information in session
-    request.session['request_token'] = request_token['oauth_token']
-    request.session['request_token_secret'] = request_token['oauth_token_secret']
+    request.session[identifier + '_request_token'] = request_token['oauth_token']
+    request.session[identifier + '_request_token_secret'] = request_token['oauth_token_secret']
     
     #redirect the user to the authentication page
-    callback_url = 'http://%s%s' % (Site.objects.get_current().domain, reverse('oauth:access_token_ready'))
+    callback_url = 'http://%s%s' % (Site.objects.get_current().domain,
+        reverse('oauth:access_token_ready', args=[identifier]))
     
-    redirect_url = "%s?oauth_token=%s&oauth_callback=%s" % (settings.OAUTH_AUTHORIZE_URL, request_token['oauth_token'], callback_url)
+    redirect_url = "%s?oauth_token=%s&oauth_callback=%s" %
+        (token.server.get_authorize_url(), request_token['oauth_token'], callback_url)
     if 'next' in request.GET:
         request.session['next'] = request.GET['next']
     request.session.save()
     return redirect(redirect_url)
     
-def access_token_ready(request):
+def access_token_ready(request, identifier):
     """Last step of the OAuth three-legged flow.
-    The user is redirected here once the user has validated or not the 
-    application to access private informations.
+
+    The user is redirected here once he allowed (or not) the application to 
+    access private informations.
     
     Echange a valid request token against a valid access token. If a valid 
     access token is given, store it in session.
     
     """
-    if not 'request_token' and 'request_token_secret' in request.session:
-        raise Exception('request_token and request_token_secret are not present in session.')
+    if not identifier+'_request_token' and identifier+'_request_token_secret' in request.session:
+        raise Exception('%s_request_token and %s_request_token_secret are not' \
+            'present in session.' % (identifier, identifier))
     
     if ('error' in request.GET):
         return render('error.html', {
     if not 'oauth_verifier' in request.GET:
         raise Exception('oauth_verifier must be present in request.GET')
     
+    token = Token.objects.get(identifier=identifier)
+
     # Echange the request token against a access token.
-    token = oauth2.Token(request.session['request_token'],
-        request.session['request_token_secret'])
-    token.set_verifier(request.GET['oauth_verifier'])
-    client = oauth2.Client(_get_consumer(), token)
-    resp, content = client.request(settings.OAUTH_ACCESS_TOKEN_URL , "POST")
+    request_token = oauth2.Token(request.session[identifier + '_request_token'],
+        request.session[identifier + '_request_token_secret'])
+    request_token.set_verifier(request.GET['oauth_verifier'])
+    client = oauth2.Client(_get_consumer(), request_token)
+    resp, content = client.request(token.server.get_access_token_url() , "POST")
     access_token = dict(urlparse.parse_qsl(content))
     
     # test if access token is valid. 
     if not ('oauth_token' and 'oauth_token_secret' in access_token):
         raise Exception('oauth_token and oauth_token_secret must be present in the OAuth server response')
         
-    request.session['oauth_token'] = access_token['oauth_token']
-    request.session['oauth_token_secret'] = access_token['oauth_token_secret']
+    request.session[identifier + '_oauth_token'] = access_token['oauth_token']
+    request.session[identifier + '_oauth_token_secret'] = access_token['oauth_token_secret']
 
     if 'next' in request.session:
         return redirect(request.session['next'])
         
     return render('authenticated.html', {})
     
-def logout(request):
+def logout(request, identifier):
     """Destruct the active session oauth related keys.
     
     """
     for key in ('oauth_token', 'oauth_token_secret', 
         'request_token', 'request_token_secret'):
-        if request.session[key]:
-            del request.session[key]
+        if request.session[identifier + '_' + key]:
+            del request.session[identifier + '_' + key]
             
     return render('logout.html', {})
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.