Permalink
Browse files

New User creation now working, using all 3 create methods, (in rough,…

… first-pass form).
  • Loading branch information...
1 parent 4018659 commit 7246cf4b8b496121ff873d48361edad233627d2b @clemesha-ooi clemesha-ooi committed Feb 20, 2010
@@ -29,5 +29,12 @@ class UserProfile(models.Model):
query_secret = models.TextField(null=True)
nimbus_userid = models.TextField(null=True)
-if sys.argv.count("test") != 1: #are we running tests? better way?
- models.signals.post_save.connect(remote.nimbus_user_create, User)
+
+def user_post_save(sender, instance, **kwargs):
+ profile, new = UserProfile.objects.get_or_create(user=instance)
+models.signals.post_save.connect(user_post_save, User)
+
+def user_post_delete(sender, instance, **kwargs):
+ profile = UserProfile.objects.get_or_create(user=instance)
+ profile.delete()
+models.signals.post_delete.connect(user_post_delete, User)
@@ -5,7 +5,7 @@
import sys
here = lambda x: os.path.join(os.path.abspath(os.path.dirname(__file__)), x)
-WEBDIR = here("../../../../") #uh, ok?
+WEBDIR = here("../../../../")
# ------------------------------------------------------------------------------
@@ -0,0 +1,79 @@
+import os
+import sys
+import string
+from datetime import datetime
+from random import Random
+
+from django.contrib.auth.models import User
+from django.db import IntegrityError
+from django.conf import settings
+
+from dateutil.relativedelta import *
+from nimbusrest.admin.connection import AdminConnection
+
+
+def create_user(dn, username, email, firstname, lastname):
+ """
+ Returns (error_text, new_user, success_token)
+ """
+ password = _generate_initial_password()
+ try:
+ user = User.objects.create_user(username, email, password)
+ except IntegrityError:
+ return ("Username is taken already", user, None)
+ user.first_name = firstname
+ user.last_name = lastname
+ user.save()
+
+ user.dn = dn #XXX hack
+ nimbus_user = nimbus_user_create_remote(user)
+ print "[create_user] nimbus_user => ", nimbus_user
+ token = _generate_login_key()
+ _insert_user_profile_data(user, token=token)
+ return (None, user, token)
+
+
+def _insert_user_profile_data(user, token=None, cert=None, key=None, query_id=None, query_secret=None):
+ """
+ 'user' is a Django User instance.
+ """
+ profile = user.get_profile()
+ profile.initial_login_key = token
+ profile.cert = cert
+ profile.certkey = key
+ profile.query_id = query_id
+ profile.query_secret = query_secret
+ now = datetime.now()
+ expire_hours = int(settings.NIMBUS_TOKEN_EXPIRE_HOURS)
+ profile.login_key_expires = now + relativedelta(hours=+expire_hours)
+ profile.save()
+ return profile
+
+
+def nimbus_user_create_remote(user_instance):
+ """Use the Nimbus API to register a new Nimbus User.
+
+ `user_instance` is a `Django User` instance.
+ """
+ nimbus_key = getattr(settings, "NIMBUS_KEY", "testadmin")
+ nimbus_secret = getattr(settings, "NIMBUS_SECRET", "secret")
+ service_uri = getattr(settings, "NIMBUS_SERVICE_URI", "https://localhost:4443/admin")
+ conn = AdminConnection(service_uri, nimbus_key, nimbus_secret)
+ nimbus_user = conn.add_user(user_instance)
+ return nimbus_user
+
+
+def _generate_initial_password():
+ okchars = string.letters + string.digits + "!@%^_&*+-"
+ okchars += okchars
+ password = ''.join( Random().sample(okchars, 50))
+ # double check what we're getting from foreign function
+ if len(password) < 50:
+ raise Exception("Could not create initial password") #XXX
+ return password
+
+def _generate_login_key():
+ okchars = string.letters + string.digits + "_+-"
+ okchars += okchars
+ token = ''.join(Random().sample(okchars, 80)).replace(" ", "_")
+ return token
@@ -6,9 +6,8 @@ class NewUserForm(forms.Form):
lastname = forms.CharField()
email = forms.EmailField()
-class CertKeyForm(NewUserForm):
+class CertForm(NewUserForm):
cert = forms.FileField()
- key = forms.FileField()
class DNForm(NewUserForm):
DN = forms.CharField()
@@ -1,19 +1,10 @@
from django.conf import settings
from nimbusweb.setup.ezpz_ca import EzPzCA
-def create_nimbus_user_stub(dn):
- nimbus_userid = "test_nimbus_userid - dn =>", dn
- return nimbus_userid
-create_nimbus_user = create_nimbus_user_stub
-
def extract_dn(cert):
ezpz = EzPzCA(settings.NIMBUS_CADIR, settings.WEBDIR)
- (DN, cert, key) = ezpz.get_cert_dn(cert)
- return (DN, cert, key)
-
-
-autocreate_cert_stub = lambda x: ("test_dn", "test_cert", "test_key")
-autocreate_cert = autocreate_cert_stub
+ DN = ezpz.get_cert_dn(cert)
+ return DN
def autocreate_cert(cn):
"""Create a cert using local CA functionality.
@@ -1,12 +1,16 @@
+import sys
+
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponseRedirect
+from django.conf import settings
-import util
-from forms import CertKeyForm, DNForm, AutoCreateForm
+from util import extract_dn, autocreate_cert
+from create import create_user
+from forms import CertForm, DNForm, AutoCreateForm
USER_CREATE_METHODS = (
- ("certkey", "Provide User's Cert and Key files", "The DN will be extracted from upload keys to create a new User."),
+ ("cert", "Provide User's Cert file", "The DN is extracted from given Cert file, then used to create a new User."),
("dn", "Provide User's DN", "The provided DN will be used to create a new User."),
("autocreate", "Auto-create a Certificate and User", "A new certicate will be created, then used to create a new User.")
)
@@ -17,26 +21,21 @@ def index(request):
@login_required
def method(request, method):
- if method not in ["certkey", "dn", "autocreate"]:
+ if method not in ["cert", "dn", "autocreate"]:
raise Http404
dn = None
- if method == "certkey":
+ if method == "cert":
methodinfo = USER_CREATE_METHODS[0][1]
if request.method == "POST":
- # get cert and key
- form = CertKeyForm(request.POST, request.FILES)
+ form = CertForm(request.POST, request.FILES)
if form.is_valid():
- cert = form.cleaned_data["cert"]
- key = form.cleaned_data["key"]
- print cert, key, type(cert), type(key)
- #TODO get string contents out of cert
- try:
- dn = util.extract_dn(cert)
- except:
- raise Exception("Failed getting DN from cert.") #TODO: better error.
+ certdata = form.cleaned_data["cert"]
+ cert = certdata.read()
+ dn = extract_dn(cert)
+ print "[from 'cert'] dn => ", dn
else:
- form = CertKeyForm()
+ form = CertForm()
if method == "dn":
methodinfo = USER_CREATE_METHODS[1][1]
@@ -55,7 +54,7 @@ def method(request, method):
if form.is_valid():
cn = form.cleaned_data["username"] #username is used as the CN (common name)
try:
- (dn, cert, key) = util.autocreate_cert(cn)
+ (dn, cert, key) = autocreate_cert(cn)
except:
raise Exception("Failed autocreating new cert and key.") #TODO: better error.
else:
@@ -67,20 +66,29 @@ def method(request, method):
firstname = form.cleaned_data["firstname"]
lastname = form.cleaned_data["lastname"]
email = form.cleaned_data["email"]
- nimbus_userid = util.create_nimbus_user(dn) #if this fails, new User is deleted.
- #TODO save 'nimbus_userid' to UserProfile here, or does util.create_nimbus_user do it?
- print "=== final data ==> ", username, firstname, lastname, email, nimbus_userid
- #TODO: use 'nimbus.adminops._newuser(newuserform, request_files)' here:
- unique_new_user_token="abc123"
- return HttpResponseRedirect("/usercreate/success?token="+unique_new_user_token)
+ (error, new_user, token) = create_user(dn, username, email, firstname, lastname)
+ if error:
+ raise Exception(error)
+ return HttpResponseRedirect("/usercreate/success?token="+token)
except:
- raise Exception("Failed creating Nimbus User")
+ new_user.delete() #roll back newly create User and UserProfile
+ exception_type = sys.exc_type
+ try:
+ exceptname = exception_type.__name__
+ except AttributeError:
+ exceptname = exception_type
+ name = str(exceptname)
+ err = str(sys.exc_value)
+ errmsg = "Problem creating User: '%s: %s'" % (name, err)
+ raise Exception(errmsg)
return render_to_response('usercreate/method.html', {"form":form, "method":method, "methodinfo":methodinfo})
@login_required
def success(request):
token = request.GET.get("token")
- url = "http://localhost:1443/register/"#settings.APP_URL
+ baseurl = getattr(settings, "NIMBUS_PRINT_URL", "http://.../nimbus/")
+ basepath = getattr(settings, "NIMBUS_PRINT_PATH", "register/token/")
+ url = baseurl+basepath
return render_to_response('usercreate/success.html', {"url":url, "token":token})

0 comments on commit 7246cf4

Please sign in to comment.