Skip to content
This repository has been archived by the owner on Sep 23, 2020. It is now read-only.

Commit

Permalink
Remote Nimbus User creation (local functionality),
Browse files Browse the repository at this point in the history
mostly working by way of their correspoding Unit tests.
  • Loading branch information
clemesha-ooi committed Jan 29, 2010
1 parent 0e13f00 commit 0014e6d
Show file tree
Hide file tree
Showing 8 changed files with 99 additions and 52 deletions.
8 changes: 8 additions & 0 deletions web/src/python/README
@@ -0,0 +1,8 @@
TODO: should this file go here?


Running tests
-------------

Example: test only the "nimbus" app test:
$ python nimbusweb/portal/manage.py test nimbus --pythonpath="."
5 changes: 4 additions & 1 deletion web/src/python/nimbusrest/connection.py
Expand Up @@ -16,7 +16,10 @@
from urlparse import urljoin from urlparse import urljoin


import httplib2 import httplib2
import json try:
import json
except ImportError:
import simplejson as json


from nimbusrest.error import NimbusServerError, NotFoundError from nimbusrest.error import NimbusServerError, NotFoundError


Expand Down
5 changes: 4 additions & 1 deletion web/src/python/nimbusrest/error.py
Expand Up @@ -16,7 +16,10 @@
Nimbus exception types. Subclassed for specific errors Nimbus exception types. Subclassed for specific errors
""" """


import json try:
import json
except ImportError:
import simplejson as json


class NimbusClientError(Exception): class NimbusClientError(Exception):
""" """
Expand Down
12 changes: 1 addition & 11 deletions web/src/python/nimbusweb/portal/nimbus/adminops.py
Expand Up @@ -152,17 +152,7 @@ def _newuser(newuserform, request_files):
# filled in to help the user re-enter content when there is an error. # filled in to help the user re-enter content when there is an error.
return (None, noerror_flash_msg, None) return (None, noerror_flash_msg, None)


def nimbus_user_create(user_instance):
"""Use the Nimbus API to register a new Nimbus User.
"""
from nimbusrest.connection import Connection
service_uri = settings.NIMBUS_SERVICE_URI
conn = Connection(service_uri) #, nimbus_key, nimbus_secret)
body = {"username":user_instance.username} #XXX what else is needed?
response = conn.post_json("/user/create", body) #let caller handle errors
return response


def ok_token_attempt(ipaddress, maxcount): def ok_token_attempt(ipaddress, maxcount):
"""Return False if this IP has submitted too many tokens""" """Return False if this IP has submitted too many tokens"""
try: try:
Expand Down
25 changes: 3 additions & 22 deletions web/src/python/nimbusweb/portal/nimbus/models.py
@@ -1,6 +1,6 @@
from django.db import models from django.db import models
from django.contrib.auth.models import User, UserManager from django.contrib.auth.models import User, UserManager
import adminops import remote


class TokenFailure(models.Model): class TokenFailure(models.Model):
ip = models.IPAddressField(primary_key=True) ip = models.IPAddressField(primary_key=True)
Expand All @@ -26,30 +26,11 @@ class UserProfile(models.Model):
certkey_time = models.DateTimeField(auto_now=False, null=True) certkey_time = models.DateTimeField(auto_now=False, null=True)
query_id = models.TextField(null=True) query_id = models.TextField(null=True)
query_secret = models.TextField(null=True) query_secret = models.TextField(null=True)
nimbus_userid = models.TextField(null=True)


# register userprofile with the django auth system # register userprofile with the django auth system
def user_post_save(sender, instance, **kwargs): def user_post_save(sender, instance, **kwargs):
profile, new = UserProfile.objects.get_or_create(user=instance) profile, new = UserProfile.objects.get_or_create(user=instance)
models.signals.post_save.connect(user_post_save, User) models.signals.post_save.connect(user_post_save, User)



models.signals.post_save.connect(remote.nimbus_user_create, User)
def complete_nimbus_user_create(sender, instance, **kwargs):
"""Save response data from a successful `Nimbus User`
creation attempt, or, in the case of failure, remove
the recently created `Django User` and send failure
message back to User create Form.
"""
print "complete_nimbus_user_create => ", sender, instance, kwargs
# only attempt to create Nimbus User on Django User creation.
if kwargs.get('created'):
try:
response = adminops.nimbus_user_create(instance)
except:
#Nimbus User failed to be created, delete Django User
instance.delete() #XXX how to handle this?
raise #forms.Error("Failed to create Nimbus user at '%s'" % settings.NIMBUS_SERVICE_URI)
up = UserProfile(user=instance)
up.registration_complete = True
#XXX what other data in "response" needs to be saved in UserProfile??

models.signals.post_save.connect(complete_nimbus_user_create, User)
42 changes: 42 additions & 0 deletions web/src/python/nimbusweb/portal/nimbus/remote.py
@@ -0,0 +1,42 @@
import sys
from django.conf import settings
from nimbusrest.connection import Connection
import models

def nimbus_user_create_remote(user_instance, path="/users/create", nimbus_key=None, nimbus_secret=None):
"""Use the Nimbus API to register a new Nimbus User.
`user_instance` is a `Django User` instance.
"""
service_uri = getattr(settings, "NIMBUS_SERVICE_URI", "http://some.sensible.default/")
conn = Connection(service_uri, nimbus_key, nimbus_secret)
body = {"username":user_instance.username} #XXX what else is needed?
response = conn.post_json(path, body) #let caller handle errors
return response

def nimbus_user_create(sender, instance, **kwargs):
"""Django User model `post_save` function.
Save response data from a successful `Nimbus User`
creation attempt, or, in the case of failure, remove
the recently created `Django User` and send failure
message back to User create Form.
"""
print "complete_nimbus_user_create => ", sender, instance, kwargs
remote_user_creator = kwargs.get("remote_user_creator")
if remote_user_creator is None:
remote_user_creator = nimbus_user_create_remote
# only attempt to create Nimbus User on Django User creation.
if kwargs.get('created'):
response = remote_user_creator(instance)
try:
response = remote_user_creator(instance)
except:
#Nimbus User failed to be created, delete Django User
instance.delete() #XXX how to handle this?
raise Exception(sys.exc_type)
up = models.UserProfile.objects.get(user=instance)
up.nimbus_userid = response["nimbus_userid"]
up.save()
return True

52 changes: 36 additions & 16 deletions web/src/python/nimbusweb/portal/nimbus/tests.py
@@ -1,23 +1,43 @@
""" import unittest
This file demonstrates two different styles of tests (one doctest and one from django.test import TestCase
unittest). These will both pass when you run "manage.py test".


Replace these with more appropriate tests for your application. from django.contrib.auth.models import User
"""


from django.test import TestCase import remote


class SimpleTest(TestCase): class FakeUser(object):
def test_basic_addition(self): username = "test_username"
""" email = "test@example.com"
Tests that 1 + 1 always equals 2. password = "test_password"

class CreateNimbusUserTest(unittest.TestCase):

def setUp(self):
#self.user = User.objects.create_user("test_username", "test@email.com", "test_password")
#creating a real user kicks off a real 'models.signals.post_save.connect'! So do this:
self.user = FakeUser()
self.ok_resp = {"nimbus_userid":"abc123"} #, "state":"created"}

def _fake_remote_user_creator(self, user_instance, fail=False):
"""Creator real request, fake response and failure states.
Get necessary data from `user_instance` to form a correct
request to create a remote Nimbus User.
""" """
self.failUnlessEqual(1 + 1, 2) if not fail:
return self.ok_resp
else:
raise Exception("fake error in '_fake_remote_user_creator'")


__test__ = {"doctest": """ def test_create_user(self):
Another way to test that 1 + 1 is equal to 2. """
"""
passthrough = lambda x:x
created = remote.nimbus_user_create(passthrough, self.user, created=True,
remote_user_creator=self._fake_remote_user_creator)
self.assertEquals(created, True)


>>> 1 + 1 == 2 def test_create_user_failed(self):
True #test that User rollback is successful.
"""} pass


2 changes: 1 addition & 1 deletion web/src/python/nimbusweb/portal/settings.py
Expand Up @@ -63,7 +63,7 @@
'django.contrib.contenttypes', 'django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.sessions',
'django.contrib.sites', 'django.contrib.sites',
'cpserver', #'cpserver',
'nimbusweb.portal.nimbus', 'nimbusweb.portal.nimbus',
) )


Expand Down

0 comments on commit 0014e6d

Please sign in to comment.