示例#1
0
    def create(self, request, **kwargs):
        #print "@ create account"
        self.method_check(request, allowed=['post'])
        
        backend = get_backend('registration.backends.default.DefaultBackend')
        postData = simplejson.loads(request.raw_post_data)

        args = {'username':postData['username'],
                'email' : postData['email'],
                'password1' : postData['password']}
        
        if User.objects.filter(email=postData['email']).count() > 0:
            return self.create_response(request,{
                    'status': SYSTEM_ERROR,
                    'error': 'duplicate email'})
        
        #print "post data"
        #print args
        #print "trying to create account"
        newUser = backend.register(request,**args)
        
        #print "user created"
        if newUser:
            return self.create_response(request,{'status': OK,
                'message': 'Please check your email !!'})

        else:
            return self.create_response(request,{'status': SYSTEM_ERROR,
                                    'error': 'Something is wrong >:/ '})
示例#2
0
文件: views.py 项目: oraclebill/dsusa
def setup_and_activate(request, activation_key, backend,
                       form_class=UserCreationForm,
                       template_name='registration/setup_new_user.html',
                       fail_template_name='registration/activate.html',
                       success_url=None):

    backend = get_backend(backend)
    profile = get_object_or_404(RegistrationProfile, activation_key=activation_key)
    if not backend.can_activate(activation_key):
        return render_to_response(fail_template_name,
                                  context_instance=RequestContext(request))

    if request.method == 'POST':
        form = form_class(request.POST, request.FILES, instance=profile.user)
        if form.is_valid():
            form.save()
            account = backend.activate(request, activation_key)
            if success_url:
                return redirect(success_url)
            to, args, kwargs = backend.post_activation_redirect(request, account)
            return redirect(to, *args, **kwargs)
    else:
        # do not prepopulate form with generated user data
        form = form_class()

    return render_to_response(template_name, {'form': form},
                              context_instance=RequestContext(request))
示例#3
0
文件: views.py 项目: arn0601/lessnlab
def registerStudent(request, backend, success_url=None, form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None):
    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)
    if form_class is None:
        form_class = backend.get_form_class(request)
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = backend.register(request, **form.cleaned_data)
            print new_user.first_name
            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        form = form_class()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              {'form': form},
                              context_instance=context)
示例#4
0
def send_post_notification_email(post, event, request):
    """
    Send blog post events notification email.
    """
    
    # get the current site
    if Site._meta.installed:
        site = Site.objects.get_current()
    else:
        site = RequestSite(request)

    subject = render_to_string(POST_EVENTS[event]['subject_template'], {
        'site': site,
        'post': post,
    })

    # no newlines
    subject = ''.join(subject.splitlines())

    message = render_to_string(POST_EVENTS[event]['email_template'], {
        'site': site,
        'post': post,
    })

    if POST_EVENTS[event]['receiver'] == 'moderators':
        backend = get_backend('default')
        moderators = (x[1] for x in backend.get_moderators(request))
        send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, moderators)
    if POST_EVENTS[event]['receiver'] == 'author':
        send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, (post.author.email,))
示例#5
0
    def test_get_backend(self):
        """
        Verify that ``get_backend()`` returns the correct value when
        passed a valid backend.

        """
        self.failUnless(isinstance(get_backend("registration.backends.default.DefaultBackend"), DefaultBackend))
示例#6
0
def register(request, backend, success_url=None, form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None):

    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)
    if form_class is None:
        form_class = backend.get_form_class(request)

    if request.method == 'POST':
        data = request.POST.copy() # so we can manipulate data
        form = form_class(data, files=request.FILES)
        if form.is_valid():
            # random username
            form.cleaned_data['username'] = ''.join([choice(letters) for i in xrange(30)])
            new_user = backend.register(request, **form.cleaned_data)
            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        form = form_class()

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              {'form': form},
                              context_instance=context)
示例#7
0
def moderate_list(request, backend='default', template_name='registration/registration_moderate_list.html'):
    backend = get_backend(backend)
    profiles = backend.get_unmoderated_profiles(request)

    return render(request, template_name, {
        'profiles': profiles,
    })
示例#8
0
def accept_email_invite(request, activation_key):
    inv = get_object_or_404 (Invitation, reg_activation_key=activation_key)
    logging.debug("BBM: accept_email_invite view found invite %s." % str(inv))
    
    if request.method == 'POST':
        pw_form = EmailInviteAcceptForm(request.POST)
        if pw_form.is_valid():
            from registration.backends import get_backend
            reg_backend = get_backend(settings.REGISTRATION_BACKEND)
            u = reg_backend.activate(request, activation_key)
            if not u:
                logging.debug('BBM was unable to activate user with activation key %s' % (activation_key))
                messages.error(request, 'Sorry we were unable to activate your user, please try again and contact us if the problem persists')
                return HttpResponseRedirect(reverse('home'))
            else:
                logging.debug('BBM attempting to set password to %s for user %s' % (pw_form.data['password1'], u.username))
                u.set_password(pw_form.data['password1'])
                u.save()
                #authenticate the user and log them in
                auth_user = authenticate(username=u.email, password=pw_form.data['password1'])
                if auth_user is not None:
                    logging.debug('BBM: new invited user %s authenticated' % auth_user.username)
                    #accept invite
                    inv.accept_invitation()
                    login(request, auth_user)
                    messages.info(request, "Thank you %s, your account has been activated and invitation accepted" % auth_user.first_name)
                    return HttpResponseRedirect(reverse('welcome'))
                else:
                    messages.error(request, "Your username and/or password were not recognised, please try again.")
    else:
        pw_form=EmailInviteAcceptForm()
        
    return render_to_response('groupmanager/accept_email_invite.html', {'invite': inv, 'pw_form': pw_form}, context_instance=RequestContext(request))
示例#9
0
def _register_user(request, facebook, profile_callback=None):
    """
    Creates a new user and authenticates
    The registration form handles the registration and validation
    Other data on the user profile is updates afterwards
    """
    if not facebook.is_authenticated():
        raise ValueError("Facebook needs to be authenticated for connect flows")

    from registration.forms import RegistrationFormUniqueEmail

    new_reg_module = True
    try:
        from registration.backends import get_backend
    except ImportError:
        new_reg_module = False

    form_class = RegistrationFormUniqueEmail
    facebook_data = facebook.facebook_registration_data()

    data = request.POST.copy()
    for k, v in facebook_data.items():
        if not data.get(k):
            data[k] = v

    if request.REQUEST.get("force_registration_hard"):
        data["email"] = data["email"].replace("@", "+%s@" % randint(0, 100000))

    form = form_class(data=data, files=request.FILES, initial={"ip": request.META["REMOTE_ADDR"]})

    if not form.is_valid():
        error = facebook_exceptions.IncompleteProfileError(
            "Facebook data %s " "gave error %s" % (facebook_data, form.errors)
        )
        error.form = form
        raise error

    if new_reg_module:
        # support for the newer implementation
        try:
            from django.conf import settings

            backend = get_backend(settings.REGISTRATION_BACKEND)
        except:
            raise ValueError("Cannot get django-registration backend from " "settings.REGISTRATION_BACKEND")
        new_user = backend.register(request, **form.cleaned_data)
    else:
        new_user = form.save(profile_callback=profile_callback)

    # update some extra data not yet done by the form
    new_user = _update_user(new_user, facebook)

    # IS this the correct way for django 1.3? seems to require the backend
    # attribute for some reason
    new_user.backend = "django_facebook.auth_backends.FacebookBackend"
    auth.login(request, new_user)

    return new_user
示例#10
0
def invite_email(request, group_id):
    """
    just a wrapper for emailregiatration backend register view which is a clone of the default registration backend
    but extended to add new users into the appropriate group.
    """
    #TODO: currently supports 1 email invite at a time need to make multiple
    #TODO: capture email text in invite message in when it is editable

    g = get_object_or_404(Group, pk=group_id)

    if request.method == 'POST':
        if g.is_organiser(request.user) or (g.is_member(request.user) and g.is_mem_get_mem) or g.is_open: #check we are the organiser or the group allows others to invite
            next_url=request.POST.get('next', None) #establish where to go next from a next field in the submitted form
            logging.debug("GM: attempting to invite a new email invited member and add to group %s then redirect to %s" % (g.name,next_url))
            user_form = EmailInvitationForm(request.POST)
            #check if this person already exists as a user. If so just invite them.
            if user_form.is_valid():
                try:
                    logging.debug("GM: testing duplicate user by email address %s" % (user_form.data['email']))
                    u = User.objects.filter(email=user_form.data['email'])
                except ObjectDoesNotExist:
                    from registration.backends import get_backend
                    backend = get_backend('emailregistration.backends.registration.InviteEmailRegBackend') #use custom invite backend to send invitation emails
                    #create a new inactive user and send them an activation email
                    u = backend.register(request, **user_form.cleaned_data)
                    messages.info(request, 'Sucessfully invited %s at address %s to join this group.' % (user_form.data['first_name'], user_form.data['email']))
                    #get the activation key from the new inactive user registration profile to put in the invite as a reference
                    from registration.models import RegistrationProfile
                    p = RegistrationProfile.objects.get(user=u)
                    #create the invitation in the db
                    inv = Invitation.objects.create(group_id=g.id, inviter_id=request.user.id, invitee_id=u.id, reg_activation_key=p.activation_key)
                    logging.debug("RM: create invite to group %s from %s to %s" % (g.id, request.user.id, u.id))

                else: #user already exists (by email) so create the invitation in the db no new user no activation key
                    inv = Invitation.objects.create(group_id=g.id, inviter_id=request.user.id, invitee_id=u.id, reg_activation_key='existing user invited')
                    messages.info(request, '%s at address %s is already a user of %s and will receive an invitation to joint this group.' % (u.first_name, u.email, settings.SITE_NAME))
                    logging.debug("RM: create invite to group %s from %s to %s" % (g.id, request.user.id, u.id))
                    #TODO: notify them of the new invite by email

            else: #invalid form re-render the template, show form errors
                logging.debug("GM: Failed to add new email invite user to group %s because posted form was invalid." % (g.name))
                return render_to_response("groupmanager/invite_email_form.html",{'group_id': group_id, 'form':user_form },context_instance=RequestContext(request))

            if settings.AUTO_ACCEPT:  #automatically accept the invite (ie. don't wait for the invitee to do so)
                inv.accept_invitation()

        else: #user doesn't have permission to invite into the group
            logging.error("GM: invite_email_member received request to invite users from user without correct permissions.")
            messages.error(request, 'You do not have permission to invite users to that group. If this problem persists please let us know.')

    else: #its a GET so just render the template
        user_form = EmailInvitationForm()
        return render_to_response("groupmanager/invite_email_form.html",{'group_id': group_id, 'form':user_form },context_instance=RequestContext(request))

    if next_url:
        return HttpResponseRedirect(next_url)
    return HttpResponseRedirect(reverse('group_home', args=[g.id]))
示例#11
0
文件: views.py 项目: cephey/openby
    def get(self, request, backend, *args, **kwargs):
        backend = get_backend(backend)
        account = backend.activate(request, **kwargs)

        if account or request.user.is_authenticated():
            return redirect(settings.LOGIN_REDIRECT_URL)
        else:
            # ошибка активации
            context = RequestContext(request)
            return self.render_to_response(context)
示例#12
0
def register_test_cookie(request, backend, success_url=None, form_class=None,
                         disallowed_url='registration_disallowed',
                         template_name='registration/registration_form.html',
                         extra_context=None):
    """
    Регистрация пользователя.
    Создано основе стандартного представления register из django-registration
    путем добавления в начале проверки включенности cookies в браузере,
    и фокусов с формой в зависимости от статуса регистрирующегося.
    """
    if request.method == 'POST':
        if request.session.test_cookie_worked():
            request.session.delete_test_cookie()
        else:
            return TemplateResponse(request, 'cookies.html')

    request.session.set_test_cookie()
    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)

    if request.method == 'POST':
        status = int(request.POST.get("status", u"0"))
        if status == 1:  # интересующийся гражданин.
            form = RegistrationFormShort(data=request.POST,
                files=request.FILES)
        else:  # представитель организации.
            form = RegistrationFormFull(data=request.POST, files=request.FILES)

        if form.is_valid():
            new_user = backend.register(request, **form.cleaned_data)
            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(request,
                    new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
        else:
            if status == 1:
                form = RegistrationFormFull(data=request.POST,
                                            files=request.FILES)
    else:
        form = RegistrationFormFull()

    if extra_context is None:
        extra_context = {}

    extra_context.update({'required_error':
                              Field.default_error_messages['required']})

    context = {'form': form}
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return TemplateResponse(request, template_name, context)
示例#13
0
def _register_user(request, facebook, profile_callback=None):
    if not facebook.is_authenticated():
        raise ValueError, 'Facebook needs to be authenticated for connect flows'
    
    from registration.forms import RegistrationFormUniqueEmail
    import registration
    new_reg_module = hasattr(registration, 'backends')
    
    if new_reg_module:
        from registration.backends import get_backend
        
    form_class = RegistrationFormUniqueEmail
    facebook_data = facebook.facebook_registration_data()

    data = request.POST.copy()
    for k, v in facebook_data.items():
        if not data.get(k):
            data[k] = v
    
    if request.REQUEST.get('force_registration_hard'):
        data['email'] = data['email'].replace('@', '+%s@' % randint(0, 100000))

    form = form_class(data=data, files=request.FILES,
        initial={'ip': request.META['REMOTE_ADDR']})

    if not form.is_valid():
        error = facebook_exceptions.IncompleteProfileError('Facebook data %s gave error %s' % (facebook_data, form.errors))
        error.form = form
        raise error

    if new_reg_module:
        #support for the newer implementation
        try:
            from django.conf import settings
            backend = get_backend(settings.REGISTRATION_BACKEND)
        except:
            raise ValueError, 'Cannot get django-registration backend from settings.REGISTRATION_BACKEND'
        new_user = backend.register(request, **form.cleaned_data)
    else:
        new_user = form.save(profile_callback=profile_callback)
    
    profile = new_user.get_profile()
    profile.date_of_birth = facebook_data.get('date_of_birth')
    if hasattr(profile, 'raw_data'):
        serialized_fb_data = json.dumps(facebook.facebook_profile_data())
        profile.raw_data = serialized_fb_data
    profile.save()
        
    auth.login(request, new_user)
    
    
    

    return new_user
 def get(self, request, backend, template_name=None, success_url=None, form_class=None,
          disallowed_url='registration_disallowed', extra_context=None):
     if template_name is not None:
         self.template_name = template_name
     backend = get_backend(backend)
     if not backend.registration_allowed(request):
         return redirect(disallowed_url)
     if form_class is None:
         form_class = backend.get_form_class(request)
     form = form_class()
     context = self._add_extra_context(request, form, extra_context)
     return self.render_to_response(context)
示例#15
0
def login(request):
    error_messages = []

    #grab the redirect URL if set
    redirect = request.GET.get('next') or request.POST.get('redirect', '')

    #Create login and registration forms
    login_form = SigninForm()
    registration_form = CreateAccountForm()
    
    if request.method == 'POST':
        #Existing user is logging in
        if request.POST.has_key('login'):

            login_form = SigninForm(data=request.POST)
            if login_form.is_valid():
                user = auth.authenticate(username=request.POST['user_or_email'], password=request.POST['password'])

                #Log in
                auth.login(request, user)

                #set session timeout
                if request.POST.has_key('remember_me'):
                    request.session.set_expiry(settings.SESSION_TIMEOUT)

                if redirect:
                    return HttpResponseRedirect(redirect)
                else:
                    return HttpResponseRedirect(reverse('frontpage'))

        #New user is registering
        elif request.POST.has_key('register'):

            registration_form = CreateAccountForm(data=request.POST)

            if registration_form.is_valid():
                backend = get_backend(settings.REGISTRATION_BACKEND)             
                new_user = backend.register(request, **registration_form.cleaned_data)

                #sign straight in
                signed_in_user = auth.authenticate(username=request.POST['username'], password=request.POST['password1'])
                auth.login(request, signed_in_user)                

                #redirect
                if redirect:
                    return HttpResponseRedirect(redirect)
                else:
                    return HttpResponseRedirect(reverse('frontpage'))

    return render_to_response('registration/extended_login.html', {'registration_form': registration_form,
                                                                   'login_form': login_form, 
                                                                   'error_messages': error_messages,  
                                                                   'redirect': redirect}, context_instance = RequestContext(request))
示例#16
0
def invited_register(request, backend, invitation_key, success_url=None,
            form_class=RegistrationForm,
            disallowed_url='registration_disallowed',
            post_registration_redirect=None,
            template_name='registration/registration_form.html',
            wrong_template_name='invitations/wrong_invitation_key.html',
            extra_context=None):
    extra_context = extra_context is not None and extra_context.copy() or {}
    if getattr(settings, 'INVITE_MODE', False):
        if invitation_key:
            extra_context.update({'invitation_key': invitation_key})
            # if key is valid
            if is_key_valid(invitation_key):
                key_object = get_key(invitation_key)
                # if email is assigned to an access content_object 
                # but not user - if user is assigned then this invitation has
                # already been accepted
                if ((key_object.content_object and \
                        key_object.content_object.email) and not \
                        key_object.content_object.user):

                    extra_context.update(
                            {'email': key_object.content_object.email})

                    if request.POST:
                        backend = get_backend(backend)
                        form = form_class(data=request.POST, files=request.FILES)
                        if form.is_valid():
                            new_user = backend.register(request, **extra_context)
                            to, args, kwargs = backend.post_registration_redirect(
                                    request,
                                    new_user,
                                    invitation_key=invitation_key)

                            messages.success(request, _("You've been registered and logged in."))                            
                            return redirect(to, *args, **kwargs)
                    else:
                        form = form_class()
                    extra_context.update({'form': form})

                    return render(request, template_name, extra_context)

                #return registration_register(request, backend, success_url,
                #                            form_class, disallowed_url,
                #                            template_name, extra_context)
            extra_context.update({'invalid_key': True})
        else:
            extra_context.update({'no_key': True})
        return render(request, wrong_template_name, extra_context)
    else:
        return registration_register(request, backend, success_url, form_class,
                                     disallowed_url, template_name, extra_context)
示例#17
0
def get_registration_backend():
    '''
    Ensures compatability with the new and old version of django registration
    '''
    backend = None
    try:        
        #support for the newer implementation
        from registration.backends import get_backend
        try:
            backend = get_backend(settings.REGISTRATION_BACKEND)
        except:
            raise ValueError, 'Cannot get django-registration backend from settings.REGISTRATION_BACKEND'
    except ImportError, e:
        backend = None
示例#18
0
文件: views.py 项目: cephey/openby
    def post(self, request, backend, extra_context=None):
        backend = get_backend(backend)

        form_class = backend.get_register_form_class(request)
        form = form_class(data=request.POST)

        result = {'success': False, 'errors': []}
        if form.is_valid():
            backend.register(request, **form.cleaned_data)
            result = reg_success(request)
        else:
            result['errors'] = form.errors

        return result
示例#19
0
def register(request, backend, success_url=None, form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None):


    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)
    if form_class is None:
        form_class = backend.get_form_class(request)

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = backend.register(request, **form.cleaned_data)
            form.save(new_user)

            # need to login the user now also
            user = authenticate(username=form.cleaned_data['username'],
                                password=form.cleaned_data['password1'])
            login(request, user)

            if success_url is None:
                return redirect(settings.REGISTRATION_SUCCESS_URL)
            else:
                return redirect(success_url)

            # MRT CHANGED THE ABOVE
            # save the addtional fields to the user
            '''
            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
            '''
    else:
        form = form_class()

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              {'form': form},
                              context_instance=context)
示例#20
0
def verify(request, **kwargs):

    backend = 'whwn.register.RegistrationBackend'
    backend = get_backend(backend)
    user = backend.activate(request, **kwargs)

    if user:
        backend.post_activation_redirect(request, user)
        user.backend = 'django.contrib.auth.backends.ModelBackend'
        login(request, user)

            
        return redirect(reverse('inventory_list'))
    else:
        return redirect(reverse('home'))
示例#21
0
def create_user(request, post_data, files):
    """Create new user from a distutil client request"""
    form = RegistrationForm({"username": post_data["name"],
                             "email": post_data["email"],
                             "password1": post_data["password"],
                             "password2": post_data["password"]})
    if not form.is_valid():
        # Dist Utils requires error msg in HTTP status: "HTTP/1.1 400 msg"
        # Which is HTTP/WSGI incompatible, so we're just returning a empty 400.
        return HttpResponseBadRequest()

    backend = get_backend("registration.backends.default.DefaultBackend")
    if not backend.registration_allowed(request):
        return HttpResponseBadRequest()
    new_user = backend.register(request, **form.cleaned_data)
    return HttpResponse("OK\n", status=200, mimetype='text/plain')
示例#22
0
def moderate(request, backend='default', template_name='registration/registration_moderate.html', **kwargs):
    backend = get_backend(backend)
    profile = backend.get_profile(request, **kwargs)
    form_class = backend.get_moderation_form_class(request)

    if request.method == 'POST':
        form = form_class(request.POST)

        if form.is_valid():
            backend.moderate(request, form, profile, **kwargs)
            return redirect(backend.post_moderation_redirect(request, profile))
    else:
        form = form_class()

    return render(request, template_name, {
        'form': form,
        'profile': profile,
    })
 def post(self, request, backend, template_name=None, success_url=None, form_class=None,
          disallowed_url='registration_disallowed', extra_context=None):
     if template_name is not None:
         self.template_name = template_name
     backend = get_backend(backend)
     if not backend.registration_allowed(request):
         return redirect(disallowed_url)
     if form_class is None:
         form_class = backend.get_form_class(request)
     form = form_class(data=request.POST, files=request.FILES)
     if form.is_valid():
         new_user = backend.register(request, **form.cleaned_data)
         if success_url is None:
             to, args, kwargs = backend.post_registration_redirect(request, new_user)
             return redirect(to, *args, **kwargs)
         else:
             return redirect(success_url)
     context = self._add_extra_context(request, form, extra_context)
     return self.render_to_response(context)
示例#24
0
def verify(request, backend='default', template_name='registration/registration_verify.html', **kwargs):
    backend = get_backend(backend)
    profile = backend.get_profile(request, **kwargs)

    if profile:
        # check to see if moderation for this profile is required and whether or
        # not it is a verified account.
        if backend.moderation_required(request, profile):
            moderation_required = True
            backend.verify(request, profile, **kwargs)
        else:
            moderation_required = False
            # attempt to activate this user
            backend.activate(request, profile, **kwargs)

    return render(request, template_name, {
        'profile': profile,
        'moderation_required': moderation_required,
    })
示例#25
0
def register(request, backend, success_url=None, form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None):
    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)
    if form_class is None:
        form_class = backend.get_form_class(request)

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = backend.register(request, **form.cleaned_data)

            # Custom code, creating player here ourselves
            player = Player.objects.create(user=new_user) # Default role is player
    
            player.update_unsubscribe_hash()
            player.pseudonym = form.cleaned_data.get('pseudonym')
            player.save()

            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        form = form_class()
    
    if extra_context is None:
        extra_context = {}

    context = RequestContext(request)
    
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              {'form': form},
                              context_instance=context)
示例#26
0
def register(request, backend='default', template_name='registration/registration_form.html'):
    backend = get_backend(backend)

    # determine is registration is currently allowed. the ``request`` object
    # is passed which can be used to selectively disallow registration based on
    # the user-agent
    if not backend.registration_allowed(request):
        return redirect(*backend.registration_closed_redirect(request))

    form_class = backend.get_registration_form_class(request)

    if request.method == 'POST':
        form = form_class(request.POST, request.FILES)

        if form.is_valid():
            user = backend.register(request, form)
            return redirect(backend.post_registration_redirect(request, user))
    else:
        form = form_class()

    return render(request, template_name, {'form': form})
def resend_by_username(request, backend, username, success_url=None, form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None):
    """ Resend the activation key based on the username """

    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)

    # TODO: Need to fetch the RegistrationProfile object for this user
    #       then do user_regprofile.send_activation_email(site)
    #       then render an HTML page saying "activation email resent"

    if Site._meta.installed:
        site = Site.objects.get_current()
    else:
        site = RequestSite(request)
    # NOTE: user is a FK to the User table, we need user.name or user.username or something like that.
    try:
        user_regprofile = RegistrationProfile.objects.get(user__username=username)
        user_regprofile.send_activation_email(site)
    except:
        # user doesn't exist
        pass

    # Now we need to tell the web user what's happened: email sent, or user not found

    # TODO: what is below won't work properly.
    form = form_class()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
                              {'form': form},
                              context_instance=context)
示例#28
0
def resend(request, backend,
             disallowed_url='registration_disallowed',
             template_name='registration/resend_activation_form.html',
             extra_context=None):
    """
    Allow a new user to request a new activation e-mail be sent

    The actual resend of the account activation E-mail will be delegated
    to the backend specified by the ``backend`` keyword argument.
    
    """
    # Determine parameters backend and form class
    backend = get_backend(backend)
    form_class = backend.get_resend_form_class(request)

    # Handle the resend request using the backend
    resend_msg = ''
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            email = form.cleaned_data['email']
            if backend.resend(request, email):
                resend_msg = 'Activation E-mail resent to ' + email
            else:
                resend_msg = 'No inactive account for ' + email
    else:
        form = form_class()
    
    # Add any extra context items
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    # Render response 
    return render_to_response(template_name,
                              { 'form': form, 'resend_msg': resend_msg },
                              context_instance=context)
示例#29
0
文件: views.py 项目: Noyer/ExmoNew
def activate_redirect(request, backend,
             template_name='registration/activate.html',
             success_url=None, extra_context=None, **kwargs):
    """
    Вью на основании registration, добавлен редирект на страницу
    логина, если backend.activate() возвращает False
    """

    # Проверка наличия ключа активации и является ли он 160-битным значением
    # в шестнадцатеричной форме записи
    activation_key = kwargs.get('activation_key')
    hex_pattern = re.compile(r'^[0-9a-f]{40}$')
    is_hex = re.search(hex_pattern, activation_key)
    if activation_key and is_hex:
        backend = get_backend(backend)
        account = backend.activate(request, **kwargs)

        if account:
            # успех
            if success_url is None:
                to, args, kwargs = backend.post_activation_redirect(request,
                                                                    account)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)

        # если ключ правильный, но пользователь уже активирован
        return redirect('exmo2010:auth_login')

    # если ключ активации неправильный
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name,
        kwargs,
        context_instance=context)
示例#30
0
def signup(request, backend, success_url=None, extra_context=None):
    disallowed_url = 'registration_disallowed'
    backend = get_backend(backend)

    if not backend.registration_allowed(request):
        return redirect(disallowed_url)

    if request.method == 'POST':
        user_form = UserForm(request.POST)
        signup_form = SignupForm(request.POST)

        if user_form.is_valid() and signup_form.is_valid():
            new_user = backend.register(request, **user_form.cleaned_data)
            profile = signup_form.save(commit=False)
            profile.user = new_user
            profile.save()
            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        user_form = UserForm()
        signup_form = SignupForm()
    
    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(
        'signup.html',
        {
            'user_form': user_form,
            'signup_form': signup_form
        },
        context_instance=context)
示例#31
0
def assign_user_to_group(sender, user, password, is_generated, request, **kwargs):
  backend = get_backend()
  g = Group.objects.get(name='research')
  g.user_set.add(user)
示例#32
0
    form = form_class(data=data,
                      files=request.FILES,
                      initial={'ip': request.META['REMOTE_ADDR']})

    if not form.is_valid():
        error = facebook_exceptions.IncompleteProfileError(
            'Facebook data %s gave error %s' % (facebook_data, form.errors))
        error.form = form
        raise error

    if new_reg_module:
        #support for the newer implementation
        try:
            from django.conf import settings
            backend = get_backend(settings.REGISTRATION_BACKEND)
        except:
            raise ValueError, 'Cannot get django-registration backend from settings.REGISTRATION_BACKEND'
        new_user = backend.register(request, **form.cleaned_data)
    else:
        new_user = form.save(profile_callback=profile_callback)

    #update some extra data not yet done by the form
    new_user = _update_user(new_user, facebook)

    #IS this the correct way for django 1.3? seems to require the backend attribute for some reason
    new_user.backend = 'django_facebook.auth_backends.FacebookBackend'
    auth.login(request, new_user)

    return new_user
示例#33
0
def activate(request, backend,
             template_name='registration/activate.html',
             success_url=None, extra_context=None, **kwargs):
    """
    Activate a user's account.

    The actual activation of the account will be delegated to the
    backend specified by the ``backend`` keyword argument (see below);
    the backend's ``activate()`` method will be called, passing any
    keyword arguments captured from the URL, and will be assumed to
    return a ``User`` if activation was successful, or a value which
    evaluates to ``False`` in boolean context if not.

    Upon successful activation, the backend's
    ``post_activation_redirect()`` method will be called, passing the
    ``HttpRequest`` and the activated ``User`` to determine the URL to
    redirect the user to. To override this, pass the argument
    ``success_url`` (see below).

    On unsuccessful activation, will render the template
    ``registration/activate.html`` to display an error message; to
    override thise, pass the argument ``template_name`` (see below).

    **Arguments**

    ``backend``
        The dotted Python import path to the backend class to
        use. Required.

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context. Optional.

    ``success_url``
        The name of a URL pattern to redirect to on successful
        acivation. This is optional; if not specified, this will be
        obtained by calling the backend's
        ``post_activation_redirect()`` method.

    ``template_name``
        A custom template to use. This is optional; if not specified,
        this will default to ``registration/activate.html``.

    ``\*\*kwargs``
        Any keyword arguments captured from the URL, such as an
        activation key, which will be passed to the backend's
        ``activate()`` method.

    **Context:**

    The context will be populated from the keyword arguments captured
    in the URL, and any extra variables supplied in the
    ``extra_context`` argument (see above).

    **Template:**

    registration/activate.html or ``template_name`` keyword argument.

    """
    backend = get_backend(backend)
    account = backend.activate(request, **kwargs)

    if account:
        if success_url is None:
            to, args, kwargs = backend.post_activation_redirect(request, account)
            return redirect(to, *args, **kwargs)
        else:
            return redirect(success_url)

    if extra_context is None:
        extra_context = {}
    context = {}
    for key, value in list(extra_context.items()):
        context[key] = callable(value) and value() or value

    return render(request, template_name,
                              kwargs,
                              context=context)
示例#34
0
    def get(self, request, backend, *args, **kwargs):
        backend = get_backend(backend)
        backend.logout(request)

        return redirect(request.META.get('HTTP_REFERER', '/'))
示例#35
0
def register(request,
             backend,
             success_url=None,
             form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None):

    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)
    if settings.CLOSED_BETA_ACTIVE and \
        request.session.get('invitation_code','') != '':
        form_class = backend.get_invitation_form_class(request)
    else:
        form_class = backend.get_form_class(request)

    invitation_error = None
    invitation_instance = None

    if settings.CLOSED_BETA_ACTIVE:
        success_url = 'registration_activation_complete'
        if request.session.get('invitation_code', '') == '':
            request.session['invitation_code'] = request.GET.get('code', '')
        else:
            if request.GET.get('code', ''):
                request.session['invitation_code'] = request.GET.get(
                    'code', '')
        try:
            invitation_instance = \
                Invitation.objects.get(code=request.session['invitation_code'])
        except Invitation.DoesNotExist:
            pass

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        invitation_flag = True

        if settings.CLOSED_BETA_ACTIVE and \
                request.session.get('invitation_code', '') != '' and \
                form.is_valid():

            invitation_flag = False
            if invitation_instance:
                invitation_flag = True
                invitation_instance.used = True
                invitation_instance.save()
            else:
                invitation_error = 'Invitation does not Exist'

        if form.is_valid() and invitation_flag:
            if settings.CLOSED_BETA_ACTIVE:
                new_user = backend.register(
                    request,
                    first_name=form.cleaned_data['first_name'],
                    last_name=form.cleaned_data['last_name'],
                    email=invitation_instance.email,
                    password1=form.cleaned_data['password1'])
                #Login
                user = authenticate(username=invitation_instance.email,
                                    password=form.cleaned_data['password1'])
                login(request, user)
                #Sending invitation mail
                template = "mails/welcome.html"
                context = {}
                context['STATIC_PREFIX'] = settings.STATIC_PREFIX
                context['user'] = user
                message = render_to_string(template, context)
                msg = EmailMessage(strings.WELCOME_MESSAGE, message,
                                   settings.EMAIL_HOST_USER, [user.email])
                msg.content_subtype = "html"
                msg.send()
                #Generate reverse for profile
                #                success_url = reverse('show_user_profile_info',
                #                           kwargs={'user_id':user.id}
                #                          )
                success_url = reverse('mycircuits')
            else:
                new_user = backend.register(request, **form.cleaned_data)

            if request.session.get('invitation_code', None):
                del request.session['invitation_code']
            else:
                pass
            if success_url is None:
                to, args, kwargs = \
                    backend.post_registration_redirect(request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        form = form_class()

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    template_context = {'form': form}
    if settings.CLOSED_BETA_ACTIVE:
        template_context['invitation_error'] = invitation_error
        template_context['invitation_instance'] = invitation_instance
        template_context['invitation_code'] = request.session[
            'invitation_code']
        template_context['closed_beta'] = settings.CLOSED_BETA_ACTIVE

    return render(request,
                  template_name,
                  template_context,
                  context_instance=context)
示例#36
0
def activate(request,
             backend,
             form_class=None,
             activation_method=None,
             template_name='registration/activate.html',
             success_url=None,
             extra_context=None,
             **kwargs):
    """
    Activate a user's account.

    The actual activation of the account will be delegated to the
    backend specified by the ``backend`` keyword argument (see below);
    the backend's ``activate()`` method will be called, passing any
    keyword arguments captured from the URL, the request and the instance
    of the form gotten from ``get_activation_form`` backend (if any). If
    activation form is defined ``activate`` will be called only after form
    is valid. Once ``activate`` is called,it will be assumed to return a
    two-tuple (``User``, ``None``) if activation was successful, or
    (falsy_value, error_message) value if not.

    Upon successful activation, the backend's
    ``post_activation_redirect()`` method will be called, passing the
    ``HttpRequest`` and the activated ``User`` to determine the URL to
    redirect the user to. To override this, pass the argument
    ``success_url`` (see below).

    On unsuccessful activation, will render the template
    ``registration/activate.html`` to display an error message; to
    override thise, pass the argument ``template_name`` (see below).

    **Arguments**

    ``backend``
        The dotted Python import path to the backend class to
        use. Required.

    ``form_class``
        The activation form class.

    ``activation_method``
        The callback actually performing the activation. Default value is
        ``None``, so it will be taken from ``ACTIVATION_METHOD`` setting.

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context. Optional.

    ``success_url``
        The name of a URL pattern to redirect to on successful
        acivation. This is optional; if not specified, this will be
        obtained by calling the backend's
        ``post_activation_redirect()`` method.
    
    ``template_name``
        A custom template to use. This is optional; if not specified,
        this will default to ``registration/activate.html``.

    ``\*\*kwargs``
        Any keyword arguments captured from the URL, such as an
        activation key, which will be passed to the backend's
        ``activate()`` method.
    
    **Context:**
    
    The context will be populated from the keyword arguments captured
    in the URL, and any extra variables supplied in the
    ``extra_context`` argument (see above). In addition if a activation
    form (see aboce again) is defined will be added ``form`` to context
    containing current instance.
    
    **Template:**
    
    registration/activate.html or ``template_name`` keyword argument.
    
    """
    backend = get_backend(backend,
                          activation_method=activation_method,
                          **kwargs)
    if form_class is None:
        activation_form = backend.get_activation_form_class(request)
    if request.method == 'POST':
        form = activation_form and activation_form(data=request.POST,
                                                   files=request.FILES)
        kwargs['form'] = form
        if not form or form.is_valid():
            account, errors = backend.activate(request, **kwargs)

            if account:
                if success_url is None:
                    to, args, kwargs = backend.post_activation_redirect(
                        request, account)
                    return redirect(to, *args, **kwargs)
                else:
                    return redirect(success_url)
            if errors:
                form._errors['__all__'] = errors

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    if activation_form is not None and 'form' not in kwargs:
        kwargs['form'] = activation_form()

    return render_to_response(template_name, kwargs, context_instance=context)
 def __init__(self, *args, **kwargs):
     self.backend = get_backend()
     super(ActivationView, self).__init__(*args, **kwargs)
示例#38
0
文件: views.py 项目: Applaud/server
def register(request,
             backend,
             success_url=None,
             form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None,
             **kwargs):
    """
    Allow a new user to register an account.

    The actual registration of the account will be delegated to the
    backend specified by the ``backend`` keyword argument (see below);
    it will be used as follows:

    1. The backend's ``registration_allowed()`` method will be called,
       passing the ``HttpRequest``, to determine whether registration
       of an account is to be allowed; if not, a redirect is issued to
       the view corresponding to the named URL pattern
       ``registration_disallowed``. To override this, see the list of
       optional arguments for this view (below).

    2. The form to use for account registration will be obtained by
       calling the backend's ``get_form_class()`` method, passing the
       ``HttpRequest``. To override this, see the list of optional
       arguments for this view (below).

    3. If valid, the form's ``cleaned_data`` will be passed (as
       keyword arguments, and along with the ``HttpRequest``) to the
       backend's ``register()`` method, which should return the new
       ``User`` object.

    4. Upon successful registration, the backend's
       ``post_registration_redirect()`` method will be called, passing
       the ``HttpRequest`` and the new ``User``, to determine the URL
       to redirect the user to. To override this, see the list of
       optional arguments for this view (below).
    
    **Required arguments**
    
    None.
    
    **Optional arguments**

    ``backend``
        The dotted Python import path to the backend class to use.

    ``disallowed_url``
        URL to redirect to if registration is not permitted for the
        current ``HttpRequest``. Must be a value which can legally be
        passed to ``django.shortcuts.redirect``. If not supplied, this
        will be whatever URL corresponds to the named URL pattern
        ``registration_disallowed``.
    
    ``form_class``
        The form class to use for registration. If not supplied, this
        will be retrieved from the registration backend.
    
    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``success_url``
        URL to redirect to after successful registration. Must be a
        value which can legally be passed to
        ``django.shortcuts.redirect``. If not supplied, this will be
        retrieved from the registration backend.
        
    ``template_name``
        A custom template to use. If not supplied, this will default
        to ``registration/registration_form.html``.
    
    **Context:**
    
    ``form``
        The registration form.
    
    Any extra variables supplied in the ``extra_context`` argument
    (see above).
    
    **Template:**
    
    registration/registration_form.html or ``template_name`` keyword
    argument.
    
    """
    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)
    if form_class is None:
        form_class = backend.get_form_class(request)

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)

        if form.is_valid():
            new_user = backend.register(request, **form.cleaned_data)
            # django-registration does not take care of names. Do it here.
            new_user.first_name = request.POST['first_name']
            new_user.last_name = request.POST['last_name']
            new_user.save()

            # Each user (business, emp or enduser) has an inbox, associated with the User model
            inbox = applaud_models.Inbox(user=new_user)
            inbox.save()

            # Welcome message
            message = applaud_models.MessageItem(
                text=
                "Welcome to the Apatapa family! We're happatapy to have you here",
                date_created=datetime.utcnow().replace(tzinfo=utc),
                inbox=inbox,
                subject='Oh Hello!',
                sender=User.objects.get(pk=1))
            message.save()

            # This section modified by Luke & Peter on Tue Jun 19 21:26:42 UTC 2012
            # This section modified again by Jack and Shahab on Thu June 21
            if 'profile_type' in kwargs:

                # We are registering a business
                if kwargs['profile_type'] is 'business':
                    profile = applaud_models.BusinessProfile(
                        latitude=request.POST['latitude'],
                        longitude=request.POST['longitude'],
                        address=request.POST['address'],
                        phone=request.POST['phone'],
                        business_name=request.POST['business_name'],
                        user=new_user,
                        goog_id=request.POST['goog_id'],
                        first_time=True)

                    profile.save()

                    # Create a generic rating profile
                    rp = applaud_models.RatingProfile(title="Employee",
                                                      dimensions=['rating'],
                                                      business=profile)
                    rp.save()

                #We know that we're registering an employee
                elif kwargs['profile_type'] is 'employee':

                    #First, determine which business this employee works for
                    business_profile = applaud_models.BusinessProfile.objects.get(
                        goog_id=kwargs['goog_id'])
                    # There is only one rating profile at this point.
                    rp = business_profile.ratingprofile_set.all()[0]
                    profile = applaud_models.EmployeeProfile(
                        business=business_profile,
                        user=new_user,
                        rating_profile=rp,
                        first_time=True)
                    profile.save()

                # Registering an end-user
                elif kwargs['profile_type'] is 'user':

                    profile = applaud_models.UserProfile(user=new_user,
                                                         first_time=True)

                    # Give a random profile picture
                    which = int(random.random() * 6) + 1
                    profile.default_picture = which
                    profile.save()
            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(
                    request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        form = form_class()

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():

        context[key] = callable(value) and value() or value

    return render_to_response(
        template_name,
        {'form': form},
        # context
        context_instance=RequestContext(request))
示例#39
0
 def test_get_backend(self):
     backend = get_backend(
         'registration.backends.default.DefaultRegistrationBackend')
     self.failUnless(isinstance(backend, DefaultRegistrationBackend))
示例#40
0
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.views import login
from django.views.decorators.cache import never_cache
from django.contrib.auth import login as auth_login
from django.conf import settings
from c2g.util import upgrade_to_https_and_downgrade_upon_redirect
from django.views.decorators.debug import sensitive_post_parameters

import json
import settings
import os.path

import logging
logger = logging.getLogger("foo")

backend = get_backend('registration.backends.simple.SimpleBackend')
form_class = RegistrationFormUniqueEmail


@upgrade_to_https_and_downgrade_upon_redirect
def preview(request, course_prefix, course_suffix):
    """
    Much code borrowed from registration.views.register
    """
    if request.common_page_data['is_course_admin']:
        return redirect(
            'http://' + request.get_host() +
            reverse('courses.views.main', args=[course_prefix, course_suffix]))

    if request.common_page_data['is_course_member'] and not request.common_page_data['course'].preview_only_mode and \
       date.today() >= request.common_page_data['course'].calendar_start :
示例#41
0
def register(request,
             backend,
             success_url=None,
             form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register an account.

    The actual registration of the account will be delegated to the
    backend specified by the ``backend`` keyword argument (see below);
    it will be used as follows:

    1. The backend's ``registration_allowed()`` method will be called,
       passing the ``HttpRequest``, to determine whether registration
       of an account is to be allowed; if not, a redirect is issued to
       the view corresponding to the named URL pattern
       ``registration_disallowed``. To override this, see the list of
       optional arguments for this view (below).

    2. The form to use for account registration will be obtained by
       calling the backend's ``get_form_class()`` method, passing the
       ``HttpRequest``. To override this, see the list of optional
       arguments for this view (below).

    3. If valid, the form's ``cleaned_data`` will be passed (as
       keyword arguments, and along with the ``HttpRequest``) to the
       backend's ``register()`` method, which should return the new
       ``User`` object.

    4. Upon successful registration, the backend's
       ``post_registration_redirect()`` method will be called, passing
       the ``HttpRequest`` and the new ``User``, to determine the URL
       to redirect the user to. To override this, see the list of
       optional arguments for this view (below).

    **Required arguments**

    None.

    **Optional arguments**

    ``backend``
        The dotted Python import path to the backend class to use.

    ``disallowed_url``
        URL to redirect to if registration is not permitted for the
        current ``HttpRequest``. Must be a value which can legally be
        passed to ``django.shortcuts.redirect``. If not supplied, this
        will be whatever URL corresponds to the named URL pattern
        ``registration_disallowed``.

    ``form_class``
        The form class to use for registration. If not supplied, this
        will be retrieved from the registration backend.

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``success_url``
        URL to redirect to after successful registration. Must be a
        value which can legally be passed to
        ``django.shortcuts.redirect``. If not supplied, this will be
        retrieved from the registration backend.

    ``template_name``
        A custom template to use. If not supplied, this will default
        to ``registration/registration_form.html``.

    **Context:**

    ``form``
        The registration form.

    Any extra variables supplied in the ``extra_context`` argument
    (see above).

    **Template:**

    registration/registration_form.html or ``template_name`` keyword
    argument.

    """
    if not config.ENABLE_SIGNUP:
        raise Http404

    if config.ACTIVATE_AFTER_REGISTRATION:
        success_url = settings.SITE_ROOT

    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)
    if form_class is None:
        form_class = backend.get_form_class(request)

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = backend.register(request, **form.cleaned_data)
            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(
                    request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        userid = request.GET.get('userid', '')
        form = form_class(initial={'userid': userid})

    if extra_context is None:
        extra_context = {}
    from django.template import RequestContext
    context = {}
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    src = request.GET.get('src', '')
    if src:
        form = form_class(initial={'email': src})

    context['form'] = form
    context['min_len'] = config.USER_PASSWORD_MIN_LENGTH
    context['strong_pwd_required'] = config.USER_STRONG_PASSWORD_REQUIRED
    context['level'] = config.USER_PASSWORD_STRENGTH_LEVEL

    login_bg_image_path = get_login_bg_image_path()
    context['login_bg_image_path'] = login_bg_image_path

    return render(request, template_name, context)
class RegistrationAdmin(admin.ModelAdmin):
    """Admin class of RegistrationProfile

    Admin users can accept/reject registration and activate user in Django
    Admin page.

    If ``REGISTRATION_SUPPLEMENT_CLASS`` is specified, admin users can see the
    summary of the supplemental information in list view and detail of it in
    change view.

    ``RegistrationProfile`` is not assumed to handle by hand thus
    adding/changing/deleting is not accepted even in Admin page.
    ``RegistrationProfile`` only can be accepted/rejected or activated.
    To prevent these disallowed functions, the special AdminForm called
    ``RegistrationAdminForm`` is used.
    Its ``save`` method is overridden and it actually does not save the
    instance.
    It just call ``accept``, ``reject`` or ``activate`` method of current
    registration backend. So you don't want to override the ``save`` method of
    the form.

    """
    list_display = ('user', 'get_status_display', 'activation_key_expired',
                    'display_supplement_summary')
    raw_id_fields = ['user']
    search_fields = ('user__username', 'user__first_name', 'user__last_name')
    list_filter = ('_status', )

    form = RegistrationAdminForm
    backend = get_backend()

    readonly_fields = ('user', '_status')

    actions = ('accept_users', 'reject_users', 'force_activate_users',
               'resend_acceptance_email')

    def __init__(self, model, admin_site):
        super(RegistrationAdmin, self).__init__(model, admin_site)
        if not hasattr(super(RegistrationAdmin, self), 'get_inline_instances'):
            # Django 1.3 doesn't have ``get_inline_instances`` method but
            # ``inline_instances`` was generated in ``__init__`` thus
            # update the attribute
            self.inline_instances = self.get_inline_instances(None)

    def has_add_permission(self, request):
        """registration profile should not be created by hand"""
        return False

    def has_delete_permission(self, request, obj=None):
        """registration profile should not be created by hand"""
        return False

    def has_accept_permission(self, request, obj):
        """whether the user has accept permission"""
        if not settings.REGISTRATION_USE_OBJECT_PERMISSION:
            obj = None
        return request.user.has_perm('registration.accept_registration', obj)

    def has_reject_permission(self, request, obj):
        """whether the user has reject permission"""
        if not settings.REGISTRATION_USE_OBJECT_PERMISSION:
            obj = None
        return request.user.has_perm('registration.reject_registration', obj)

    def has_activate_permission(self, request, obj):
        """whether the user has activate permission"""
        if not settings.REGISTRATION_USE_OBJECT_PERMISSION:
            obj = None
        return request.user.has_perm('registration.activate_user', obj)

    def get_actions(self, request):
        """get actions displaied in admin site

        RegistrationProfile should not be deleted in admin site thus
        'delete_selected' is disabled in default.

        Each actions has permissions thus delete the action if the accessed
        user doesn't have appropriate permission.

        """
        actions = super(RegistrationAdmin, self).get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        if not request.user.has_perm('registration.accept_registration'):
            del actions['accept_users']
        if not request.user.has_perm('registration.reject_registration'):
            del actions['reject_users']
        if not request.user.has_perm('registration.accept_registration') or \
           not request.user.has_perm('registration.activate_user'):
            del actions['force_activate_users']
        return actions

    def accept_users(self, request, queryset):
        """Accept the selected users, if they are not already accepted"""
        for profile in queryset:
            self.backend.accept(profile, request=request, force=True)

    accept_users.short_description = _(
        "(Re)Accept registrations of selected users")

    def reject_users(self, request, queryset):
        """Reject the selected users, if they are not already accepted"""
        for profile in queryset:
            self.backend.reject(profile, request=request)

    reject_users.short_description = _(
        "Reject registrations of selected users")

    def force_activate_users(self, request, queryset):
        """Activates the selected users, if they are not already activated"""
        for profile in queryset:
            self.backend.accept(profile, request=request, send_email=False)
            self.backend.activate(profile.activation_key, request=request)

    force_activate_users.short_description = _(
        "Activate selected users forcibly")

    def resend_acceptance_email(self, request, queryset):
        """Re-sends acceptance emails for the selected users

        Note that this will *only* send acceptance emails for users
        who are eligible to activate; emails will not be sent to users
        whose activation keys have expired or who have already
        activated or rejected.

        """
        site = get_site(request)
        for profile in queryset:
            if not profile.activation_key_expired():
                if profile.status != 'rejected':
                    profile.send_acceptance_email(site=site)

    resend_acceptance_email.short_description = _(
        "Re-send acceptance emails to selected users")

    def display_supplement_summary(self, obj):
        """Display supplement summary

        Display ``__unicode__`` method result of
        ``REGISTRATION_SUPPLEMENT_CLASS``
        ``Not available`` when ``REGISTRATION_SUPPLEMENT_CLASS`` is not
        specified

        """
        if obj.supplement:
            return force_text(obj.supplement)
        return _('Not available')

    display_supplement_summary.short_description = _(
        'A summary of supplemental information')

    def display_activation_key(self, obj):
        """Display activation key with link

        Note that displaying activation key is not recommended in security
        reason.
        If you really want to use this method, create your own subclass and
        re-register to admin.site

        Even this is a little bit risky, it is really useful for developping
        (without checking email, you can activate any user you want) thus
        I created but turned off in default :-p

        """
        if obj.status == 'accepted':
            activation_url = reverse(
                'registration_activate',
                kwargs={'activation_key': obj.activation_key})
            return mark_safe('<a href="%s">%s</a>' %
                             (activation_url, obj.activation_key))
        return _('Not available')

    display_activation_key.short_description = _('Activation key')
    display_activation_key.allow_tags = True

    def get_inline_instances(self, request, obj=None):
        """
        return inline instances with registration supplement inline instance
        """
        inline_instances = []
        supplement_class = self.backend.get_supplement_class()
        if supplement_class:
            kwargs = {
                'extra': 1,
                'max_num': 1,
                'can_delete': False,
                'model': supplement_class,
            }
            inline_base = get_supplement_admin_inline_base_class()
            inline_form = type(str("RegistrationSupplementInlineAdmin"),
                               (inline_base, ), kwargs)
            inline_instances = [inline_form(self.model, self.admin_site)]
        supercls = super(RegistrationAdmin, self)
        if hasattr(supercls, 'get_inline_instances'):
            if django.VERSION >= (1, 5):
                inline_instances.extend(
                    supercls.get_inline_instances(request, obj))
            else:
                # Django 1.4 cannot handle obj
                inline_instances.extend(
                    supercls.get_inline_instances(request, ))
        else:
            # Django 1.3
            for inline_class in self.inlines:
                inline_instance = inline_class(self.model, self.admin_site)
                inline_instances.append(inline_instance)
        return inline_instances

    def get_object(self, request, object_id, from_field=None):
        """add ``request`` instance to model instance and return

        To get ``request`` instance in form, ``request`` instance is stored
        in the model instance.

        """
        if django.VERSION < (1, 8, 0):
            obj = super(RegistrationAdmin, self).get_object(request, object_id)
        else:
            # Note:
            #   from_field was introduced from django 1.8
            obj = super(RegistrationAdmin,
                        self).get_object(request, object_id, from_field)
        if obj:
            attr_name = settings._REGISTRATION_ADMIN_REQ_ATTR_NAME_IN_MODEL_INS
            setattr(obj, attr_name, request)
        return obj

    @csrf_protect_m
    @transaction_atomic
    def change_view(self, request, object_id, form_url='', extra_context=None):
        """called for change view

        Check permissions of the admin user for ``POST`` request depends on
        what action is requested and raise PermissionDenied if the action is
        not accepted for the admin user.

        """
        obj = self.get_object(request, unquote(object_id))

        # Permissin check
        if request.method == 'POST':
            #
            # Note:
            #   actions will be treated in form.save() method.
            #   in general, activate action will remove the profile because
            #   the profile is no longer required after the activation
            #   but if I remove the profile in form.save() method, django admin
            #   will raise IndexError thus I passed `no_profile_delete = True`
            #   to activate with backend in form.save() method.
            #
            action_name = request.POST.get('action_name')
            if (action_name == 'accept'
                    and not self.has_accept_permission(request, obj)):
                raise PermissionDenied
            elif (action_name == 'reject'
                  and not self.has_reject_permission(request, obj)):
                raise PermissionDenied
            elif (action_name == 'activate'
                  and not self.has_activate_permission(request, obj)):
                raise PermissionDenied
            elif action_name == 'force_activate' and (
                    not self.has_accept_permission(request, obj)
                    or not self.has_activate_permission(request, obj)):
                raise PermissionDenied

        if django.VERSION < (
                1,
                4,
        ):
            response = super(RegistrationAdmin,
                             self).change_view(request, object_id,
                                               extra_context)
        else:
            response = super(RegistrationAdmin,
                             self).change_view(request, object_id, form_url,
                                               extra_context)

        if (request.method == 'POST'
                and action_name in ('activate', 'force_activate')):
            # if the requested data is valid then response will be an instance
            # of ``HttpResponseRedirect`` otherwise ``TemplateResponse``
            if isinstance(response, HttpResponseRedirect):
                obj.delete()
        return response
示例#43
0
def register(request,
             backend,
             success_url=None,
             form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register an account.

    The actual registration of the account will be delegated to the
    backend specified by the ``backend`` keyword argument (see below);
    it will be used as follows:

    1. The backend's ``registration_allowed()`` method will be called,
       passing the ``HttpRequest``, to determine whether registration
       of an account is to be allowed; if not, a redirect is issued to
       the view corresponding to the named URL pattern
       ``registration_disallowed``. To override this, see the list of
       optional arguments for this view (below).

    2. The form to use for account registration will be obtained by
       calling the backend's ``get_form_class()`` method, passing the
       ``HttpRequest``. To override this, see the list of optional
       arguments for this view (below).

    3. If valid, the form's ``cleaned_data`` will be passed (as
       keyword arguments, and along with the ``HttpRequest``) to the
       backend's ``register()`` method, which should return the new
       ``User`` object.

    4. Upon successful registration, the backend's
       ``post_registration_redirect()`` method will be called, passing
       the ``HttpRequest`` and the new ``User``, to determine the URL
       to redirect the user to. To override this, see the list of
       optional arguments for this view (below).
    
    **Required arguments**
    
    None.
    
    **Optional arguments**

    ``backend``
        The dotted Python import path to the backend class to use.

    ``disallowed_url``
        URL to redirect to if registration is not permitted for the
        current ``HttpRequest``. Must be a value which can legally be
        passed to ``django.shortcuts.redirect``. If not supplied, this
        will be whatever URL corresponds to the named URL pattern
        ``registration_disallowed``.
    
    ``form_class``
        The form class to use for registration. If not supplied, this
        will be retrieved from the registration backend.
    
    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``success_url``
        URL to redirect to after successful registration. Must be a
        value which can legally be passed to
        ``django.shortcuts.redirect``. If not supplied, this will be
        retrieved from the registration backend.
    
    ``template_name``
        A custom template to use. If not supplied, this will default
        to ``registration/registration_form.html``.
    
    **Context:**
    
    ``form``
        The registration form.
    
    Any extra variables supplied in the ``extra_context`` argument
    (see above).
    
    **Template:**
    
    registration/registration_form.html or ``template_name`` keyword
    argument.
    
    """

    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)
    if form_class is None:
        form_class = backend.get_form_class(request)

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            #logger.info(form.cleaned_data['first_name'])
            new_user = backend.register(request, **form.cleaned_data)
            #register the user in class based on course_prefix course_suffix
            num_classes = 0
            try:
                course = Course.objects.get(
                    handle=request.POST.get('course_prefix') + "--" +
                    request.POST.get('course_suffix'),
                    mode='draft')
                if not course.preenroll_only:
                    course.student_group.user_set.add(new_user)
                    course_main = reverse(
                        'courses.views.main',
                        args=[
                            request.POST.get('course_prefix'),
                            request.POST.get('course_suffix')
                        ])
                    num_classes += 1
            except Course.DoesNotExist:
                pass

            #register the user based on invites
            invites = StudentInvitation.objects.filter(email=new_user.email)
            for invite in invites:
                invite.course.student_group.user_set.add(new_user)
                course_main = reverse(
                    'courses.views.main',
                    args=[invite.course.prefix, invite.course.suffix])
                invite.delete()
                num_classes += 1

            #now determine where to redirect
            if num_classes > 1:
                return redirect('accounts_profile')
            elif num_classes == 1:
                return redirect(course_main)

            #default redirects
            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(
                    request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        form = form_class(
            initial={
                'course_prefix': request.GET.get('pre'),
                'course_suffix': request.GET.get('post'),
                'invite': request.GET.get('invite'),
                'username': request.GET.get('invite'),
                'email': request.GET.get('invite'),
            })

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    prefill_username = False
    if request.GET.get('invite'):
        prefill_username = True

    return render_to_response(template_name, {
        'form': form,
        'prefill_username': prefill_username
    },
                              context_instance=context)
示例#44
0
def register(request,
             backend,
             success_url=None,
             form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register an account.

    The actual registration of the account will be delegated to the
    backend specified by the ``backend`` keyword argument (see below);
    it will be used as follows:

    1. The backend's ``registration_allowed()`` method will be called,
       passing the ``HttpRequest``, to determine whether registration
       of an account is to be allowed; if not, a redirect is issued to
       the view corresponding to the named URL pattern
       ``registration_disallowed``. To override this, see the list of
       optional arguments for this view (below).

    2. The form to use for account registration will be obtained by
       calling the backend's ``get_form_class()`` method, passing the
       ``HttpRequest``. To override this, see the list of optional
       arguments for this view (below).

    3. If valid, the form's ``cleaned_data`` will be passed (as
       keyword arguments, and along with the ``HttpRequest``) to the
       backend's ``register()`` method, which should return the new
       ``User`` object.

    4. Upon successful registration, the backend's
       ``post_registration_redirect()`` method will be called, passing
       the ``HttpRequest`` and the new ``User``, to determine the URL
       to redirect the user to. To override this, see the list of
       optional arguments for this view (below).

    **Required arguments**

    None.

    **Optional arguments**

    ``backend``
        The dotted Python import path to the backend class to use.

    ``disallowed_url``
        URL to redirect to if registration is not permitted for the
        current ``HttpRequest``. Must be a value which can legally be
        passed to ``django.shortcuts.redirect``. If not supplied, this
        will be whatever URL corresponds to the named URL pattern
        ``registration_disallowed``.

    ``form_class``
        The form class to use for registration. If not supplied, this
        will be retrieved from the registration backend.

    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``success_url``
        URL to redirect to after successful registration. Must be a
        value which can legally be passed to
        ``django.shortcuts.redirect``. If not supplied, this will be
        retrieved from the registration backend.

    ``template_name``
        A custom template to use. If not supplied, this will default
        to ``registration/registration_form.html``.

    **Context:**

    ``form``
        The registration form.

    Any extra variables supplied in the ``extra_context`` argument
    (see above).

    **Template:**

    registration/registration_form.html or ``template_name`` keyword
    argument.

    """
    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)
    if form_class is None:
        form_class = backend.get_form_class(request)

    do_subscribe = request.REQUEST.get("email_subscribe") == "on"

    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        org_form = OrganizationForm(data=request.POST, instance=Organization())

        # Could register
        if form.is_valid() and org_form.is_valid():
            assert form.cleaned_data.get("username") == form.cleaned_data.get(
                "email"), "Should be set equal in the call to clean()"

            try:
                # Create the user
                new_user = backend.register(request, **form.cleaned_data)

                # Add an org.  Must create org before adding user.
                org_form.instance.owner = new_user
                org_form.save()
                org = org_form.instance
                org.add_member(new_user)

                # Now add a zone, and link to the org
                zone = Zone(name=org_form.instance.name + " Sharing Network")
                zone.save()
                org.add_zone(zone)

                # Finally, try and subscribe the user to the mailing list
                # (silently; don't return anything to the user)
                if do_subscribe:
                    contact_subscribe(
                        request, form.cleaned_data['email'])  # no "return"
                org.save()

                if success_url is None:
                    to, args, kwargs = backend.post_registration_redirect(
                        request, new_user)
                    return redirect(to, *args, **kwargs)
                else:
                    return redirect(success_url)

            except IntegrityError as e:
                if e.message == 'column username is not unique':
                    form._errors['__all__'] = _(
                        "An account with this email address has already been created.  Please login at the link above."
                    )
                else:
                    raise e

    # GET, not POST
    else:
        form = form_class()
        org_form = OrganizationForm()

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(
        template_name,
        {
            'form': form,
            "org_form": org_form,
            "subscribe": do_subscribe,
        },
        context_instance=context,
    )
示例#45
0
def register(request,
             backend,
             success_url=None,
             form_class=None,
             disallowed_url='registration_disallowed',
             template_name='registration/registration_form.html',
             extra_context=None):
    """
    Allow a new user to register an account.

    The actual registration of the account will be delegated to the
    backend specified by the ``backend`` keyword argument (see below);
    it will be used as follows:

    1. The backend's ``registration_allowed()`` method will be called,
       passing the ``HttpRequest``, to determine whether registration
       of an account is to be allowed; if not, a redirect is issued to
       the view corresponding to the named URL pattern
       ``registration_disallowed``. To override this, see the list of
       optional arguments for this view (below).

    2. The form to use for account registration will be obtained by
       calling the backend's ``get_form_class()`` method, passing the
       ``HttpRequest``. To override this, see the list of optional
       arguments for this view (below).

    3. If valid, the form's ``cleaned_data`` will be passed (as
       keyword arguments, and along with the ``HttpRequest``) to the
       backend's ``register()`` method, which should return the new
       ``User`` object.

    4. Upon successful registration, the backend's
       ``post_registration_redirect()`` method will be called, passing
       the ``HttpRequest`` and the new ``User``, to determine the URL
       to redirect the user to. To override this, see the list of
       optional arguments for this view (below).
    
    **Required arguments**
    
    None.
    
    **Optional arguments**

    ``backend``
        The dotted Python import path to the backend class to use.

    ``disallowed_url``
        URL to redirect to if registration is not permitted for the
        current ``HttpRequest``. Must be a value which can legally be
        passed to ``django.shortcuts.redirect``. If not supplied, this
        will be whatever URL corresponds to the named URL pattern
        ``registration_disallowed``.
    
    ``form_class``
        The form class to use for registration. If not supplied, this
        will be retrieved from the registration backend.
    
    ``extra_context``
        A dictionary of variables to add to the template context. Any
        callable object in this dictionary will be called to produce
        the end result which appears in the context.

    ``success_url``
        URL to redirect to after successful registration. Must be a
        value which can legally be passed to
        ``django.shortcuts.redirect``. If not supplied, this will be
        retrieved from the registration backend.
    
    ``template_name``
        A custom template to use. If not supplied, this will default
        to ``registration/registration_form.html``.
    
    **Context:**
    
    ``form``
        The registration form.
    
    Any extra variables supplied in the ``extra_context`` argument
    (see above).
    
    **Template:**
    
    registration/registration_form.html or ``template_name`` keyword
    argument.
    
    """
    backend = get_backend(backend)
    if not backend.registration_allowed(request):
        return redirect(disallowed_url)
    if form_class is None:
        form_class = backend.get_form_class(request)

    if request.method == 'POST':
        form = form_class(request, data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = backend.register(request, **form.cleaned_data)
            if success_url is None:
                to, args, kwargs = backend.post_registration_redirect(
                    request, new_user)
                return redirect(to, *args, **kwargs)
            else:
                return redirect(success_url)
    else:
        form = form_class(request)

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value

    return render_to_response(template_name, {'form': form},
                              context_instance=context)
示例#46
0
文件: forms.py 项目: langcog/web-cdi
class RegistrationAdminForm(forms.ModelForm):

    """A special form for handling ``RegistrationProfile``

    This form handle ``RegistrationProfile`` correctly in ``save()``
    method. Because ``RegistrationProfile`` is not assumed to handle
    by hands, instance modification by hands is not allowed. Thus subclasses
    should feel free to add any additions they need, but should avoid
    overriding a ``save()`` method.

    """
    registration_backend = get_backend()

    UNTREATED_ACTIONS = (
        ('accept', _('Accept this registration')),
        ('reject', _('Reject this registration')),
        ('force_activate', _(
            'Activate the associated user of this registration forcibly')),
    )
    ACCEPTED_ACTIONS = (
        ('accept', _('Re-accept this registration')),
        ('activate',
         _('Activate the associated user of this registration')),
    )
    REJECTED_ACTIONS = (
        ('accept', _('Accept this registration')),
        ('force_activate', _(
            'Activate the associated user of this registration forcibly')),
    )

    action_name = forms.ChoiceField(label=_('Action'))
    message = forms.CharField(label=_('Message'),
                              widget=forms.Textarea, required=False,
                              help_text=_(
        'You can use the value of this field in templates for acceptance, '
        'rejection, and activation email with "{{ message }}". '
        'It is displayed in rejection email as "Rejection reasons" in '
        'default templates.'
    ))

    class Meta:
        model = RegistrationProfile
        exclude = ('user', '_status')

    def __init__(self, *args, **kwargs):
        super(RegistrationAdminForm, self).__init__(*args, **kwargs)
        # dynamically set choices of _status field
        if self.instance._status == 'untreated':
            self.fields['action_name'].choices = self.UNTREATED_ACTIONS
        elif self.instance._status == 'accepted':
            self.fields['action_name'].choices = self.ACCEPTED_ACTIONS
        elif self.instance._status == 'rejected':
            self.fields['action_name'].choices = self.REJECTED_ACTIONS

    def clean_action(self):
        """clean action value

        Insted of raising AttributeError, validate the current registration
        profile status and the requested action and then raise ValidationError

        """
        action_name = self.cleaned_data['action_name']
        if action_name == 'reject':
            if self.instance._status == 'accepted':
                raise ValidationError(_(
                    "You cannot reject a previously accepted registration."))
        elif action_name == 'activate':
            if self.instance._status != 'accepted':
                raise ValidationError(_(
                    "You cannot activate a user whose registration has not "
                    "been accepted yet."))
        elif action_name != 'force_activate':
            # with using django admin page, the code below never be called.
            raise ValidationError(
                "Unknown action_name '%s' was requested." % action_name)
        return self.cleaned_data['action_name']

    def save(self, commit=True):
        """Call appropriate action via current registration backend

        Insted of modifing the registration profile, this method call current
        registration backend's accept/reject/activate method as requested.

        """
        fail_message = 'update' if self.instance.pk else 'create'
        opts = self.instance._meta
        if self.errors:
            raise ValueError("The %s chould not be %s because the data did'nt"
                             "validate." % (opts.object_name, fail_message))
        action_name = self.cleaned_data['action_name']
        message = self.cleaned_data['message']
        # this is a bit hack. to get request instance in form instance,
        # RegistrationAdmin save its request to bundle model instance
        _request = getattr(
            self.instance,
            settings._REGISTRATION_ADMIN_REQ_ATTR_NAME_IN_MODEL_INS
        )
        if action_name == 'accept':
            self.registration_backend.accept(
                self.instance, _request, message=message,
                force=True,
            )
        elif action_name == 'reject':
            self.registration_backend.reject(
                self.instance, _request, message=message)
        elif action_name == 'activate':
            # DO NOT delete profile otherwise Django Admin will raise
            # IndexError
            self.registration_backend.activate(
                self.instance.activation_key, _request, message=message,
                no_profile_delete=True,
            )
        elif action_name == 'force_activate':
            self.registration_backend.accept(
                self.instance, _request, send_email=False)
            # DO NOT delete profile otherwise Django Admin will raise
            # IndexError
            self.registration_backend.activate(
                self.instance.activation_key, _request, message=message,
                no_profile_delete=True,
            )
        else:
            raise AttributeError(
                'Unknwon action_name "%s" was requested.' % action_name)
        if action_name not in ('activate', 'force_activate'):
            new_instance = self.instance.__class__.objects.get(
                pk=self.instance.pk)
        else:
            new_instance = self.instance
            # the instance has been deleted by activate method however
            # ``save()`` method will be called, thus set mock save method
            new_instance.save = lambda *args, **kwargs: new_instance
        return new_instance

    # this form doesn't have ``save_m2m()`` method and it is required
    # in default ModelAdmin class to use. thus set mock save_m2m method
    save_m2m = lambda x: x
 def handle(self, **options):
     backend = get_backend(options['backend'])
     backend.delete_expired_users()