예제 #1
0
파일: views.py 프로젝트: sergij/roach
def activate(request):
    form = ActivationForm(request.GET or None)
    if form.is_valid():
        activation_key = form.cleaned_data['activation_key']
        reg_backend = RegistrationBackend()
        user = reg_backend.activate(request, activation_key)

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

        try:
            redirect_url = settings.ACTIVATE_REDIRECT_URL
        except AttributeError:
            redirect_url = DEFAULT_ACTIVATE_REDIRECT_URL

        if request.is_ajax():
            return SuccessAjaxFormResponse(request,
                                           type='user', data={'id': user.id})
        else:
            return redirect(redirect_url)

    if request.is_ajax():
        return render_popup(request, 'account/activate.html', {
            'base': 'base_form.html',
            'form_url': reverse('account_activate'),
            'form': form
        })
    else:
        return render(request, 'account/activate.html', {
            'base': 'base.html',
            'form': form
        })
예제 #2
0
파일: views.py 프로젝트: sergij/roach
def register(request):
    form = RegistrationFormUniqueEmail(request.POST or None)
    if form.is_valid():
        reg_backend = RegistrationBackend()
        new_user = reg_backend.register(request, **form.cleaned_data)
        new_user.is_active = True
        new_user.save()
        # login
        new_user.backend = 'django.contrib.auth.backends.ModelBackend'
        auth.login(request, new_user)
        next_page = request.GET.get(REDIRECT_FIELD_NAME,
                                    settings.LOGIN_REDIRECT_URL)
        return redirect(next_page)

    if request.is_ajax():
        return render_popup(
            request, 'account/register.html', {
                'base': 'base_form.html',
                'form_url': reverse('account_register'),
                'form': form
            })
    else:
        return render(request, 'account/register.html', {
            'base': 'base.html',
            'form': form
        })
예제 #3
0
파일: views.py 프로젝트: sergij/roach
def activate(request):
    form = ActivationForm(request.GET or None)
    if form.is_valid():
        activation_key = form.cleaned_data['activation_key']
        reg_backend = RegistrationBackend()
        user = reg_backend.activate(request, activation_key)

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

        try:
            redirect_url = settings.ACTIVATE_REDIRECT_URL
        except AttributeError:
            redirect_url = DEFAULT_ACTIVATE_REDIRECT_URL

        if request.is_ajax():
            return SuccessAjaxFormResponse(request,
                                           type='user',
                                           data={'id': user.id})
        else:
            return redirect(redirect_url)

    if request.is_ajax():
        return render_popup(
            request, 'account/activate.html', {
                'base': 'base_form.html',
                'form_url': reverse('account_activate'),
                'form': form
            })
    else:
        return render(request, 'account/activate.html', {
            'base': 'base.html',
            'form': form
        })
예제 #4
0
    def setUp(self):
        """
        Create an instance of the default backend for use in testing,
        and set ``ACCOUNT_ACTIVATION_DAYS``.

        """
        from registration.backends.default import DefaultBackend
        self.backend = DefaultBackend()
        self.old_activation = getattr(settings, 'ACCOUNT_ACTIVATION_DAYS', None)
        settings.ACCOUNT_ACTIVATION_DAYS = 7
예제 #5
0
def register(request):
    response = {"status": "error"}
    backend = DefaultBackend()
    if backend.registration_allowed(request):
        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)
                response["status"] = "success"
            else:
                response["form_errors"] = form.errors
    return HttpResponse(simplejson.dumps(response), mimetype="application/javascript")
예제 #6
0
    def register(self, request, **kwargs):
        """
        Log the user even if not yet activated : prevents from waiting
        the email and loosing the will to use the website
        """
        new_user = DefaultBackend.register(self, request, **kwargs)

        # Create the band
        band_name = kwargs['band_name']
        band_slug = kwargs['band_slug']
        band_tags = kwargs['band_tags']
        band = Band.objects.create(name=band_name,
                                   slug=band_slug,
                                   genres=band_tags)

        # Add the user into the band
        user_band_roles = kwargs['user_band_roles']
        bandmember = BandMember.objects.create(band=band,
                                               user=new_user,
                                               approved=True,
                                               )

        bandmember.roles = user_band_roles
        bandmember.save()

        # authenticate() always has to be called before login(), and
        # will return the user we just created.
        new_user = authenticate(username=kwargs['username'], password=kwargs['password1'])
        login(request, new_user)

        return new_user
예제 #7
0
def register(request):
    is_registered = False
    if request.method == 'POST':
        form = RegistrationForm(data=request.POST)
        if form.is_valid():
            backend = DefaultBackend()
            new_user = backend.register(request, **form.cleaned_data)
            is_registered = True
        else:
            is_registered = False
    else:
        is_registered = False

    result = {"Status": is_registered}
    response = json.dumps(result)
    return HttpResponse(response)
예제 #8
0
파일: views.py 프로젝트: sergij/roach
def register(request):
    form = RegistrationFormUniqueEmail(request.POST or None)
    if form.is_valid():
        reg_backend = RegistrationBackend()
        new_user = reg_backend.register(request, **form.cleaned_data)
        new_user.is_active = True
        new_user.save()
        # login
        new_user.backend='django.contrib.auth.backends.ModelBackend'
        auth.login(request, new_user)
        next_page = request.GET.get(REDIRECT_FIELD_NAME, settings.LOGIN_REDIRECT_URL)
        return redirect(next_page)

    if request.is_ajax():
        return render_popup(request, 'account/register.html', {
            'base': 'base_form.html',
            'form_url': reverse('account_register'),
            'form': form
        })
    else:
        return render(request, 'account/register.html', {
            'base': 'base.html',
            'form': form
        })
예제 #9
0
class DefaultRegistrationBackendTests(TestCase):
    """
    Test the default registration backend.

    Running these tests successfull will require two templates to be
    created for the sending of activation emails; details on these
    templates and their contexts may be found in the documentation for
    the default backend.

    """
    backend = DefaultBackend()

    def setUp(self):
        """
        Create an instance of the default backend for use in testing,
        and set ``ACCOUNT_ACTIVATION_DAYS`` if it's not set already.

        """
        self.old_activation = getattr(settings, 'ACCOUNT_ACTIVATION_DAYS',
                                      None)
        if self.old_activation is None:
            settings.ACCOUNT_ACTIVATION_DAYS = 7

    def tearDown(self):
        """
        Yank out ``ACCOUNT_ACTIVATION_DAYS`` back out if it wasn't
        originally set.

        """
        if self.old_activation is None:
            settings.ACCOUNT_ACTIVATION_DAYS = self.old_activation

    def test_registration(self):
        """
        Test the registration process: registration creates a new
        inactive account and a new profile with activation key,
        populates the correct account data and sends an activation
        email.

        """
        new_user = self.backend.register(_mock_request(),
                                         username='******',
                                         email='*****@*****.**',
                                         password1='secret')

        # Details of the returned user must match what went in.
        self.assertEqual(new_user.username, 'bob')
        self.failUnless(new_user.check_password('secret'))
        self.assertEqual(new_user.email, '*****@*****.**')

        # New user must not be active.
        self.failIf(new_user.is_active)

        # A registration profile was created, and an activation email
        # was sent.
        self.assertEqual(RegistrationProfile.objects.count(), 1)
        self.assertEqual(len(mail.outbox), 1)

    def test_registration_no_sites(self):
        """
        Test that registration still functions properly when
        ``django.contrib.sites`` is not installed; the fallback will
        be a ``RequestSite`` instance.
        
        """
        Site._meta.installed = False

        new_user = self.backend.register(_mock_request(),
                                         username='******',
                                         email='*****@*****.**',
                                         password1='secret')

        self.assertEqual(new_user.username, 'bob')
        self.failUnless(new_user.check_password('secret'))
        self.assertEqual(new_user.email, '*****@*****.**')

        self.failIf(new_user.is_active)

        self.assertEqual(RegistrationProfile.objects.count(), 1)
        self.assertEqual(len(mail.outbox), 1)

        Site._meta.installed = True

    def test_valid_activation(self):
        """
        Test the activation process: activating within the permitted
        window sets the account's ``is_active`` field to ``True`` and
        resets the activation key.

        """
        valid_user = self.backend.register(_mock_request(),
                                           username='******',
                                           email='*****@*****.**',
                                           password1='swordfish')

        valid_profile = RegistrationProfile.objects.get(user=valid_user)
        activated = self.backend.activate(_mock_request(),
                                          valid_profile.activation_key)
        self.assertEqual(activated.username, valid_user.username)
        self.failUnless(activated.is_active)

        # Fetch the profile again to verify its activation key has
        # been reset.
        valid_profile = RegistrationProfile.objects.get(user=valid_user)
        self.assertEqual(valid_profile.activation_key,
                         RegistrationProfile.ACTIVATED)

    def test_invalid_activation(self):
        """
        Test the activation process: trying to activate outside the
        permitted window fails, and leaves the account inactive.

        """
        expired_user = self.backend.register(_mock_request(),
                                             username='******',
                                             email='*****@*****.**',
                                             password1='secret')

        expired_user.date_joined = expired_user.date_joined - datetime.timedelta(
            days=settings.ACCOUNT_ACTIVATION_DAYS)
        expired_user.save()
        expired_profile = RegistrationProfile.objects.get(user=expired_user)
        self.failIf(
            self.backend.activate(_mock_request(),
                                  expired_profile.activation_key))
        self.failUnless(expired_profile.activation_key_expired())

    def test_allow(self):
        """
        Test that the setting ``REGISTRATION_OPEN`` appropriately
        controls whether registration is permitted.

        """
        old_allowed = getattr(settings, 'REGISTRATION_OPEN', True)
        settings.REGISTRATION_OPEN = True
        self.failUnless(self.backend.registration_allowed(_mock_request()))

        settings.REGISTRATION_OPEN = False
        self.failIf(self.backend.registration_allowed(_mock_request()))
        settings.REGISTRATION_OPEN = old_allowed

    def test_form_class(self):
        """
        Test that the default form class returned is
        ``registration.forms.RegistrationForm``.

        """
        self.failUnless(
            self.backend.get_form_class(_mock_request()) is
            forms.RegistrationForm)

    def test_post_registration_redirect(self):
        """
        Test that the default post-registration redirect is the named
        pattern ``registration_complete``.

        """
        self.assertEqual(
            self.backend.post_registration_redirect(_mock_request(), User()),
            ('registration_complete', (), {}))

    def test_registration_signal(self):
        """
        Test that registering a user sends the ``user_registered``
        signal.
        
        """
        def receiver(sender, **kwargs):
            self.failUnless('user' in kwargs)
            self.assertEqual(kwargs['user'].username, 'bob')
            self.failUnless('request' in kwargs)
            self.failUnless(isinstance(kwargs['request'], WSGIRequest))
            received_signals.append(kwargs.get('signal'))

        received_signals = []
        signals.user_registered.connect(receiver,
                                        sender=self.backend.__class__)

        self.backend.register(_mock_request(),
                              username='******',
                              email='*****@*****.**',
                              password1='secret')

        self.assertEqual(len(received_signals), 1)
        self.assertEqual(received_signals, [signals.user_registered])

    def test_activation_signal_success(self):
        """
        Test that successfully activating a user sends the
        ``user_activated`` signal.
        
        """
        def receiver(sender, **kwargs):
            self.failUnless('user' in kwargs)
            self.assertEqual(kwargs['user'].username, 'bob')
            self.failUnless('request' in kwargs)
            self.failUnless(isinstance(kwargs['request'], WSGIRequest))
            received_signals.append(kwargs.get('signal'))

        received_signals = []
        signals.user_activated.connect(receiver, sender=self.backend.__class__)

        new_user = self.backend.register(_mock_request(),
                                         username='******',
                                         email='*****@*****.**',
                                         password1='secret')
        profile = RegistrationProfile.objects.get(user=new_user)
        self.backend.activate(_mock_request(), profile.activation_key)

        self.assertEqual(len(received_signals), 1)
        self.assertEqual(received_signals, [signals.user_activated])

    def test_activation_signal_failure(self):
        """
        Test that an unsuccessful activation attempt does not send the
        ``user_activated`` signal.
        
        """
        receiver = lambda sender, **kwargs: received_signals.append(
            kwargs.get('signal'))

        received_signals = []
        signals.user_activated.connect(receiver, sender=self.backend.__class__)

        new_user = self.backend.register(_mock_request(),
                                         username='******',
                                         email='*****@*****.**',
                                         password1='secret')
        new_user.date_joined -= datetime.timedelta(
            days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
        new_user.save()
        profile = RegistrationProfile.objects.get(user=new_user)
        self.backend.activate(_mock_request(), profile.activation_key)

        self.assertEqual(len(received_signals), 0)

    def test_email_send_action(self):
        """
        Test re-sending of activation emails via admin action.
        
        """
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        alice = self.backend.register(_mock_request(),
                                      username='******',
                                      email='*****@*****.**',
                                      password1='swordfish')

        admin_class.resend_activation_email(_mock_request(),
                                            RegistrationProfile.objects.all())
        self.assertEqual(len(mail.outbox),
                         2)  # One on registering, one more on the resend.

        RegistrationProfile.objects.filter(user=alice).update(
            activation_key=RegistrationProfile.ACTIVATED)
        admin_class.resend_activation_email(_mock_request(),
                                            RegistrationProfile.objects.all())
        self.assertEqual(
            len(mail.outbox),
            2)  # No additional email because the account has activated.

    def test_activation_action(self):
        """
        Test manual activation of users view admin action.
        
        """
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        alice = self.backend.register(_mock_request(),
                                      username='******',
                                      email='*****@*****.**',
                                      password1='swordfish')

        admin_class.activate_users(_mock_request(),
                                   RegistrationProfile.objects.all())
        self.failUnless(User.objects.get(username='******').is_active)
예제 #10
0
파일: backends.py 프로젝트: 3c7/seahub
class DefaultRegistrationBackendTests(TestCase):
    """
    Test the default registration backend.

    Running these tests successfull will require two templates to be
    created for the sending of activation emails; details on these
    templates and their contexts may be found in the documentation for
    the default backend.

    """
    def setUp(self):
        """
        Create an instance of the default backend for use in testing,
        and set ``ACCOUNT_ACTIVATION_DAYS`` if it's not set already.

        """
        from registration.backends.default import DefaultBackend
        self.backend = DefaultBackend()
        self.old_activation = getattr(settings, 'ACCOUNT_ACTIVATION_DAYS', None)
        if self.old_activation is None:
            settings.ACCOUNT_ACTIVATION_DAYS = 7

    def tearDown(self):
        """
        Yank out ``ACCOUNT_ACTIVATION_DAYS`` back out if it wasn't
        originally set.

        """
        if self.old_activation is None:
            settings.ACCOUNT_ACTIVATION_DAYS = self.old_activation

    def test_registration(self):
        """
        Test the registration process: registration creates a new
        inactive account and a new profile with activation key,
        populates the correct account data and sends an activation
        email.

        """
        new_user = self.backend.register(_mock_request(),
                                         username='******',
                                         email='*****@*****.**',
                                         password1='secret')

        # Details of the returned user must match what went in.
        self.assertEqual(new_user.username, 'bob')
        self.failUnless(new_user.check_password('secret'))
        self.assertEqual(new_user.email, '*****@*****.**')

        # New user must not be active.
        self.failIf(new_user.is_active)

        # A registration profile was created, and an activation email
        # was sent.
        self.assertEqual(RegistrationProfile.objects.count(), 1)
        self.assertEqual(len(mail.outbox), 1)

    def test_registration_no_sites(self):
        """
        Test that registration still functions properly when
        ``django.contrib.sites`` is not installed; the fallback will
        be a ``RequestSite`` instance.
        
        """
        Site._meta.installed = False

        new_user = self.backend.register(_mock_request(),
                                         username='******',
                                         email='*****@*****.**',
                                         password1='secret')

        self.assertEqual(new_user.username, 'bob')
        self.failUnless(new_user.check_password('secret'))
        self.assertEqual(new_user.email, '*****@*****.**')

        self.failIf(new_user.is_active)

        self.assertEqual(RegistrationProfile.objects.count(), 1)
        self.assertEqual(len(mail.outbox), 1)
        
        Site._meta.installed = True

    def test_valid_activation(self):
        """
        Test the activation process: activating within the permitted
        window sets the account's ``is_active`` field to ``True`` and
        resets the activation key.

        """
        valid_user = self.backend.register(_mock_request(),
                                           username='******',
                                           email='*****@*****.**',
                                           password1='swordfish')

        valid_profile = RegistrationProfile.objects.get(user=valid_user)
        activated = self.backend.activate(_mock_request(),
                                          valid_profile.activation_key)
        self.assertEqual(activated.username, valid_user.username)
        self.failUnless(activated.is_active)

        # Fetch the profile again to verify its activation key has
        # been reset.
        valid_profile = RegistrationProfile.objects.get(user=valid_user)
        self.assertEqual(valid_profile.activation_key,
                         RegistrationProfile.ACTIVATED)

    def test_invalid_activation(self):
        """
        Test the activation process: trying to activate outside the
        permitted window fails, and leaves the account inactive.

        """
        expired_user = self.backend.register(_mock_request(),
                                             username='******',
                                             email='*****@*****.**',
                                             password1='secret')

        expired_user.date_joined = expired_user.date_joined - datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS)
        expired_user.save()
        expired_profile = RegistrationProfile.objects.get(user=expired_user)
        self.failIf(self.backend.activate(_mock_request(),
                                          expired_profile.activation_key))
        self.failUnless(expired_profile.activation_key_expired())

    def test_allow(self):
        """
        Test that the setting ``REGISTRATION_OPEN`` appropriately
        controls whether registration is permitted.

        """
        old_allowed = getattr(settings, 'REGISTRATION_OPEN', True)
        settings.REGISTRATION_OPEN = True
        self.failUnless(self.backend.registration_allowed(_mock_request()))

        settings.REGISTRATION_OPEN = False
        self.failIf(self.backend.registration_allowed(_mock_request()))
        settings.REGISTRATION_OPEN = old_allowed

    def test_form_class(self):
        """
        Test that the default form class returned is
        ``registration.forms.RegistrationForm``.

        """
        self.failUnless(self.backend.get_form_class(_mock_request()) is forms.RegistrationForm)

    def test_post_registration_redirect(self):
        """
        Test that the default post-registration redirect is the named
        pattern ``registration_complete``.

        """
        self.assertEqual(self.backend.post_registration_redirect(_mock_request(), User()),
                         ('registration_complete', (), {}))

    def test_registration_signal(self):
        """
        Test that registering a user sends the ``user_registered``
        signal.
        
        """
        def receiver(sender, **kwargs):
            self.failUnless('user' in kwargs)
            self.assertEqual(kwargs['user'].username, 'bob')
            self.failUnless('request' in kwargs)
            self.failUnless(isinstance(kwargs['request'], WSGIRequest))
            received_signals.append(kwargs.get('signal'))

        received_signals = []
        signals.user_registered.connect(receiver, sender=self.backend.__class__)

        self.backend.register(_mock_request(),
                              username='******',
                              email='*****@*****.**',
                              password1='secret')

        self.assertEqual(len(received_signals), 1)
        self.assertEqual(received_signals, [signals.user_registered])

    def test_activation_signal_success(self):
        """
        Test that successfully activating a user sends the
        ``user_activated`` signal.
        
        """
        def receiver(sender, **kwargs):
            self.failUnless('user' in kwargs)
            self.assertEqual(kwargs['user'].username, 'bob')
            self.failUnless('request' in kwargs)
            self.failUnless(isinstance(kwargs['request'], WSGIRequest))
            received_signals.append(kwargs.get('signal'))

        received_signals = []
        signals.user_activated.connect(receiver, sender=self.backend.__class__)

        new_user = self.backend.register(_mock_request(),
                                         username='******',
                                         email='*****@*****.**',
                                         password1='secret')
        profile = RegistrationProfile.objects.get(user=new_user)
        self.backend.activate(_mock_request(), profile.activation_key)

        self.assertEqual(len(received_signals), 1)
        self.assertEqual(received_signals, [signals.user_activated])

    def test_activation_signal_failure(self):
        """
        Test that an unsuccessful activation attempt does not send the
        ``user_activated`` signal.
        
        """
        receiver = lambda sender, **kwargs: received_signals.append(kwargs.get('signal'))

        received_signals = []
        signals.user_activated.connect(receiver, sender=self.backend.__class__)

        new_user = self.backend.register(_mock_request(),
                                         username='******',
                                         email='*****@*****.**',
                                         password1='secret')
        new_user.date_joined -= datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
        new_user.save()
        profile = RegistrationProfile.objects.get(user=new_user)
        self.backend.activate(_mock_request(), profile.activation_key)

        self.assertEqual(len(received_signals), 0)

    def test_email_send_action(self):
        """
        Test re-sending of activation emails via admin action.
        
        """
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)
        
        alice = self.backend.register(_mock_request(),
                                      username='******',
                                      email='*****@*****.**',
                                      password1='swordfish')
        
        admin_class.resend_activation_email(_mock_request(),
                                            RegistrationProfile.objects.all())
        self.assertEqual(len(mail.outbox), 2) # One on registering, one more on the resend.
        
        RegistrationProfile.objects.filter(user=alice).update(activation_key=RegistrationProfile.ACTIVATED)
        admin_class.resend_activation_email(_mock_request(),
                                            RegistrationProfile.objects.all())
        self.assertEqual(len(mail.outbox), 2) # No additional email because the account has activated.

    def test_activation_action(self):
        """
        Test manual activation of users view admin action.
        
        """
        admin_class = RegistrationAdmin(RegistrationProfile, admin.site)

        alice = self.backend.register(_mock_request(),
                                      username='******',
                                      email='*****@*****.**',
                                      password1='swordfish')

        admin_class.activate_users(_mock_request(),
                                   RegistrationProfile.objects.all())
        self.failUnless(User.objects.get(username='******').is_active)