Exemple #1
0
def register_admin_does_all(request):
    if request.method == 'POST': # If the form has been submitted...
        form = AdminRegistersUserForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            try:
                new_user = User()
                new_user.first_name = form.cleaned_data['first_name']
                new_user.last_name  = form.cleaned_data['last_name']
                new_user.username = form.cleaned_data['username']
                new_user.email = form.cleaned_data['email']
                new_user.set_password(form.cleaned_data['password_1'])
                new_user.is_staff = False # Can't log in to admin site
                new_user.is_active = form.cleaned_data['is_active']
                new_user.is_superuser = False           
                new_user.last_login =  datetime.datetime(1970,1,1)
                # date_joined is used to determine expiration of the invitation key - I'd like to
                # munge it back to 1970, but can't because it makes all keys look expired.
                new_user.date_joined = datetime.datetime.utcnow()
                new_user.save()
                    
                # Membership     
                ct = ContentType.objects.get_for_model(User)
                mem = Membership()
                
                # Domain that the current logged-on admin is in 
                mem.domain = request.user.selected_domain         
                mem.member_type = ct
                mem.member_id = new_user.id
                mem.is_active = form.cleaned_data['is_active_member'] 
                mem.save()      
                
                # domain admin?
                if form.cleaned_data['is_domain_admin']:
                    new_user.add_row_perm(request.user.selected_domain, Permissions.ADMINISTRATOR)
                
                _send_user_registration_email(new_user.email, request.user.selected_domain.name, 
                                              new_user.username, form.cleaned_data['password_1'])                                 
            except:
                transaction.rollback()                
                vals = {'error_msg':'There was a problem with your request',
                        'error_details':sys.exc_info(),
                        'show_homepage_link': 1 }
                return render_to_response('error.html', vals, context_instance = RequestContext(request))                   
            else:
                transaction.commit()  
                return HttpResponseRedirect( reverse('registration_activation_complete', kwargs={'caller':'admin', 'account':new_user.username}) ) # Redirect after POST                
    else:
        form = AdminRegistersUserForm() # An unbound form
   
    return render_to_response('domain/user_registration/registration_admin_does_all_form.html', {'form': form}, context_instance = RequestContext(request)) 

########################################################################################################
Exemple #2
0
def create_user_and_domain(username='******', 
                           password='******',
                           domain_name='mockdomain'):
    """Creates a domain 'mockdomain' and a web user with name/pw 
       'brian'/'test'.  Returns these two objects in a tuple 
       as (domain, user).  The parameters are configurable."""
    try:
        domain = Domain.objects.get(name=domain_name)
        print "WARNING: tried to create domain %s but it already exists!" % domain_name
        print "Are all your tests cleaning up properly?"
    except Domain.DoesNotExist:
        # this is the normal case
        domain = Domain(name=domain_name, is_active=True)
        domain.save()
    
    try:
        user = User.objects.get(username=username)
        print "WARNING: tried to create user %s but it already exists!" % username
        print "Are all your tests cleaning up properly?"
        # update the pw anyway
        user.password = _get_salted_pw(password)
        user.save()
    except User.DoesNotExist:
        user = User()
        user.username = username
        # here, we mimic what the django auth system does
        # only we specify the salt to be 12345
        user.password = _get_salted_pw(password)
        
        user.save()
        
        # update the domain mapping using the Membership object
        mem = Membership()
        mem.domain = domain         
        mem.member_type = ContentType.objects.get_for_model(User)
        mem.member_id = user.id
        mem.is_active = True
        mem.save()
                
    return (user, domain)
Exemple #3
0
    def register(self, request, **kwargs):
        """
        Given an email address, create a dummy user account, with a 
        nonsense username and password. They'll be filled out properly
        by the user when he/she responds to the invitation email.

        Along with the new ``User`` object, a new
        ``registration.models.RegistrationProfile`` will be created,
        tied to that ``User``, containing the activation key which
        will be used for this account. That dummy user will be given
        a membership in the domain to which the active admin (the 
        user who is sending the invitation) belongs.

        An email will be sent to the supplied email address; this
        email should contain an activation link. The email will be
        rendered using two templates. See the documentation for
        ``RegistrationProfile.send_activation_email()`` for
        information about these templates and the contexts provided to
        them.

        After the ``User`` and ``RegistrationProfile`` are created and
        the activation email is sent, the signal
        ``registration.signals.user_registered`` will be sent, with
        the new ``User`` as the keyword argument ``user`` and the
        class of this backend as the sender.

        """
        
        email = kwargs['email']
        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)
        
        username_max_len = User._meta.get_field('username').max_length
        username = uuid.uuid1().hex[:username_max_len]
        password = uuid.uuid1().hex # will be cut down to db field size during hashing        
    
        # Can't call create_inactive_user, because that has a commit_on_success
        # transaction wrapper. That won't work here; only the outermost function
        # (this one) can call commit or rollback. So, we'll manually carry out the
        # requisite steps: create user, create registration profile, create domain
        # membership
        
        try:
            new_user = User()
            new_user.first_name = 'unregistered'
            new_user.last_name  = 'unregistered'
            new_user.username = username
            new_user.email = email        
            new_user.set_password(password)
            new_user.is_staff = False # Can't log in to admin site
            new_user.is_active = False # Activated upon receipt of confirmation
            new_user.is_superuser = True # For now make people superusers because permissions are a pain
            new_user.last_login =  datetime.datetime(1970,1,1)
            # date_joined is used to determine expiration of the invitation key - I'd like to
            # munge it back to 1970, but can't because it makes all keys look expired.
            new_user.date_joined = datetime.datetime.utcnow()
            new_user.save()
                
            # Membership     
            ct = ContentType.objects.get_for_model(User)
            mem = Membership()
            # Domain that the current logged-on admin is in
            mem.domain = request.user.selected_domain         
            mem.member_type = ct
            mem.member_id = new_user.id
            mem.is_active = True # Unlike domain and account, the membership is valid from the start
            mem.save()        
    
            # Registration profile   
            registration_profile = RegistrationProfile.objects.create_profile(new_user)
            
            registration_profile.send_activation_email(site)
            
        except:
            transaction.rollback()                
            vals = {'error_msg':'There was a problem with your request',
                    'error_details':sys.exc_info(),
                    'show_homepage_link': 1 }
            return render_to_response('error.html', vals, context_instance = RequestContext(request))                   
        else:
            transaction.commit()  
                         
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user
Exemple #4
0
def _create_new_domain_request( request, kind, form, now ):
            
    dom_req = RegistrationRequest()
    dom_req.tos_confirmed = form.cleaned_data['tos_confirmed']
    dom_req.request_time = now
    dom_req.request_ip = request.META['REMOTE_ADDR']                
    dom_req.activation_guid = uuid.uuid1().hex         
 
    dom_is_active = False
    if kind == 'existing_user':
        dom_req.confirm_time = datetime.datetime.now()
        dom_req.confirm_ip = request.META['REMOTE_ADDR']     
        dom_is_active = True  
     
    # Req copies domain_id at initial assignment of Domain to req; does NOT get the ID from the 
    # copied Domain object just prior to Req save. Thus, we need to save the new domain before copying 
    # it over to the req, so the Domain will have a valid id 
    d = Domain(name = form.cleaned_data['domain_name'], is_active=dom_is_active)
    d.save()                                
    dom_req.domain = d                
                     
    ############# User     
    if kind == 'existing_user':   
        new_user = request.user
    else:        
        new_user = User()
        new_user.first_name = form.cleaned_data['first_name']
        new_user.last_name  = form.cleaned_data['last_name']
        new_user.username = form.cleaned_data['username']
        new_user.email = form.cleaned_data['email']
        assert(form.cleaned_data['password_1'] == form.cleaned_data['password_2'])
        new_user.set_password(form.cleaned_data['password_1'])                                                        
        new_user.is_staff = False # Can't log in to admin site
        new_user.is_active = False # Activated upon receipt of confirmation
        new_user.is_superuser = False           
        new_user.last_login = datetime.datetime(1970,1,1)
        new_user.date_joined = now
        # As above, must save to get id from db before giving to request
        new_user.save()
   
    dom_req.new_user = new_user

    # new_user must become superuser in the new domain 
    new_user.add_row_perm(d, Permissions.ADMINISTRATOR)
     
    ############# Membership
    ct = ContentType.objects.get_for_model(User)
    mem = Membership()
    mem.domain = d          
    mem.member_type = ct
    mem.member_id = new_user.id
    mem.is_active = True # Unlike domain and account, the membership is valid from the start
    mem.save()
                                                 
    # Django docs say "use is_authenticated() to see if you have a valid user"
    # request.user is an AnonymousUser if not, and that always returns False                
    if request.user.is_authenticated():
        dom_req.requesting_user = request.user
                     
    dom_req.save()        
    return dom_req