def test_if_valid_on_empty_is_teacher(self):
     form_data = {
         'username': '******',
         'is_teacher': '',
         'password': '******'
     }
     form = AuthenticationForm(data=form_data)
     self.assertTrue(form.is_valid())
Exemple #2
0
def login(request):
    if request.method == 'GET':
        return {'logged_in': request.user.is_authenticated()}

    from users.forms import AuthenticationForm
    form = AuthenticationForm(data=request.POST)
    if form.is_valid():
        auth_login(request, form.get_user())
        return {'ok': True}
    else:
        return {'form_errors': form.errors}
Exemple #3
0
def login(request):
    if request.method == 'GET':
        return {'logged_in': request.user.is_authenticated()}

    from users.forms import AuthenticationForm
    form = AuthenticationForm(data=request.POST)
    if form.is_valid():
        auth_login(request, form.get_user())
        return {'ok': True}
    else:
        return {'form_errors': form.errors}
Exemple #4
0
def handle_signin(request):
    """Helper function that signs a user in."""
    auth.logout(request)
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            auth.login(request, form.get_user())
            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
        return form
    request.session.set_test_cookie()
    return AuthenticationForm()
Exemple #5
0
def handle_login(request, only_active=True):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST, only_active=only_active)
        if form.is_valid():
            auth.login(request, form.get_user())

            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()

        return form

    request.session.set_test_cookie()
    return AuthenticationForm()
Exemple #6
0
def login_view(request):
    if request.method != 'POST':
        form = AuthenticationForm()
    else:
        form = AuthenticationForm(data=request.POST)

        if form.login(request):
            return redirect('home')

    # Render
    context = regular_context(request.user)
    context['form'] = form
    return render(request, 'login.html', context)
Exemple #7
0
def handle_login(request, only_active=True):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST, only_active=only_active)
        if form.is_valid():
            auth.login(request, form.get_user())

            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()

        return form

    request.session.set_test_cookie()
    return AuthenticationForm()
Exemple #8
0
    def test_recaptcha_errors_only(self):
        """Only recaptcha errors should be returned if validation fails.

        We don't want any information on the username/password returned if the
        captcha is incorrect.

        """
        form = AuthenticationForm(
            data={"username": "******", "password": "******", "recaptcha": ""}, use_recaptcha=True
        )
        form.is_valid()

        assert len(form.errors) == 1
        assert "recaptcha" in form.errors
Exemple #9
0
def login(request):
    form = AuthenticationForm()
    if request.method == "POST":
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = authenticate(username=request.POST["username"], password=request.POST["password"])
            if user is not None:
                if user.is_active:
                    django_login(request, user)
                    if user.is_teacher:
                        return redirect("/courses/")
                    else:
                        return redirect("/courses/s")
    return render(request, "login.html", {"form": form})
Exemple #10
0
    def test_recaptcha_errors_only(self):
        """Only recaptcha errors should be returned if validation fails.

        We don't want any information on the username/password returned if the
        captcha is incorrect.

        """
        form = AuthenticationForm(data={'username': '******',
                                        'password': '******',
                                        'recaptcha': ''},
                                  use_recaptcha=True)
        form.is_valid()

        assert len(form.errors) == 1
        assert 'recaptcha' in form.errors
Exemple #11
0
    def test_recaptcha_errors_only(self):
        """Only recaptcha errors should be returned if validation fails.

        We don't want any information on the username/password returned if the
        captcha is incorrect.

        """
        form = AuthenticationForm(data={'username': '******',
                                        'password': '******',
                                        'recaptcha': ''},
                                  use_recaptcha=True)
        form.is_valid()

        assert len(form.errors) == 1
        assert 'recaptcha' in form.errors
Exemple #12
0
 def login(self, request, *args, **kwargs):
     form = AuthenticationForm(request, data=request.data)
     if form.is_valid():
         user = form.get_user()
         if user != request.user:
             logout(request)
         login(request, user)
         request.data.update({'version': self.kwargs['version']})
         request.user.set_device(request.data)
         serializer = self.get_serializer(user)
         data = serializer.data
         return Response(data)
     else:
         errors = json.loads(form.errors.as_json())
         error_data = {e: [code.get('code')] for e, codes in errors.items() for code in codes}
         return Response(error_data, status=HTTP_400_BAD_REQUEST)
Exemple #13
0
    def test_only_active(self):
        # Verify with active user
        u = User.objects.get(username='******')
        assert u.is_active
        form = AuthenticationForm(data={'username': '******',
                                        'password': '******'})
        assert form.is_valid()

        # Verify with inactive user
        u.is_active = False
        u.save()
        u = User.objects.get(username='******')
        assert not u.is_active
        form = AuthenticationForm(data={'username': '******',
                                        'password': '******'})
        assert not form.is_valid()
Exemple #14
0
def activate(request, activation_key, user_id=None):
    """Activate a User account."""
    activation_key = activation_key.lower()

    if user_id:
        user = get_object_or_404(User, id=user_id)
    else:
        user = RegistrationProfile.objects.get_user(activation_key)

    if user and user.is_active:
        messages.add_message(
            request, messages.INFO,
            _(u'Your account is already activated, log in below.'))
        return HttpResponseRedirect(reverse('users.login'))

    account = RegistrationProfile.objects.activate_user(
        activation_key, request)
    my_questions = None
    form = AuthenticationForm()
    if account:
        # Claim anonymous watches belonging to this email
        statsd.incr('user.activate')
        claim_watches.delay(account)

        my_questions = Question.uncached.filter(creator=account)

    return jingo.render(request, 'users/activate.html', {
        'account': account,
        'questions': my_questions,
        'form': form
    })
Exemple #15
0
def login_user(request):
    if request.method == "POST":
        form = AuthenticationForm(request.POST)
        if form.is_valid():
            email = request.POST['email']
            password = request.POST['password']
            user = authenticate(request, email=email, password=password)
            if user is not None:
                login(request, user)
                return redirect('/')
            return HttpResponse(
                'You are not registered or check your email and password again'
            )
    else:
        form = AuthenticationForm()
    context = {'form': form}
    return render(request, 'users/login.html', context)
Exemple #16
0
def password_reset_complete(request):
    """Password reset complete.

    Based on django.contrib.auth.views. Show a success message.

    """
    form = AuthenticationForm()
    return render(request, 'users/pw_reset_complete.html', {'form': form})
Exemple #17
0
    def test_allow_inactive(self):
        # Verify with active user
        user = User.objects.get(username='******')
        assert user.is_active
        form = AuthenticationForm(only_active=False,
                                  data={'username': '******',
                                        'password': '******'})
        assert form.is_valid()

        # Verify with inactive user
        user.is_active = False
        user.save()
        user = User.objects.get(username='******')
        assert not user.is_active
        form = AuthenticationForm(only_active=False,
                                  data={'username': '******',
                                        'password': '******'})
        assert form.is_valid()
Exemple #18
0
def home(request):
    if not request.user.is_authenticated():
        form = AuthenticationForm()
        if request.method == 'POST':
            form = AuthenticationForm(data=request.POST)
            if form.is_valid():
                user = authenticate(username=request.POST['username'],
                                    password=request.POST['password'])
                if user is not None:
                    if user.is_active:
                        django_login(request, user)
                        if user.is_teacher:
                            return redirect('/courses/')
                        else:
                            return redirect('/courses/s')
        return render(request, 'home.html', {'form': form})
    if request.user.is_teacher:
        return redirect('/courses/')
    return redirect('/courses/s')
Exemple #19
0
def home(request):
    if not request.user.is_authenticated():
        form = AuthenticationForm()
        if request.method == 'POST':
            form = AuthenticationForm(data=request.POST)
            if form.is_valid():
                user = authenticate(username=request.POST['username'],
                    password=request.POST['password'])
                if user is not None:
                    if user.is_active:
                        django_login(request, user)
                        if user.is_teacher:
                            return redirect('/courses/')
                        else:
                            return redirect('/courses/s')
        return render(request, 'home.html', {'form': form})
    if request.user.is_teacher:
        return redirect('/courses/')
    return redirect('/courses/s')
Exemple #20
0
def browserid_register(request):
    """Handle user creation when assertion is valid, but no existing user"""
    statsd_waffle_incr('users.browserid_register', 'signin_metrics')
    redirect_to = request.session.get(
        SESSION_REDIRECT_TO,
        getattr(settings, 'LOGIN_REDIRECT_URL', reverse('home')))
    email = request.session.get(SESSION_VERIFIED_EMAIL, None)

    if not email:
        # This is pointless without a verified email.
        return HttpResponseRedirect(redirect_to)

    # Set up the initial forms
    register_form = BrowserIDRegisterForm()
    login_form = AuthenticationForm()

    if request.method == 'POST':
        statsd_waffle_incr('users.browserid_register.POST', 'signin_metrics')

        # If the profile creation form was submitted...
        if 'register' == request.POST.get('action', None):
            register_form = BrowserIDRegisterForm(request.POST)
            if register_form.is_valid():
                # If the registration form is valid, then create a new
                # Django user.
                # TODO: This all belongs in model classes
                username = register_form.cleaned_data['username']

                user = User.objects.create(username=username, email=email)
                user.set_unusable_password()
                user.save()

                profile = UserProfile.objects.create(user=user)
                profile.save()

                user.backend = 'django_browserid.auth.BrowserIDBackend'
                auth.login(request, user)

                # Bounce to the newly created profile page, since the user
                # might want to review & edit.
                statsd_waffle_incr('users.browserid_register.POST.SUCCESS',
                                   'signin_metrics')
                redirect_to = request.session.get(SESSION_REDIRECT_TO,
                                                  profile.get_absolute_url())
                return set_browserid_explained(
                    HttpResponseRedirect(redirect_to))

    # HACK: Pretend the session was modified. Otherwise, the data disappears
    # for the next request.
    request.session.modified = True

    return render(request, 'users/browserid_register.html', {
        'login_form': login_form,
        'register_form': register_form
    })
Exemple #21
0
def login(request):
    """Try to log the user in."""
    next_url = _clean_next_url(request) or settings.LOGIN_REDIRECT_URL
    if request.user.is_authenticated():
        return HttpResponseRedirect(next_url)

    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            auth.login(request, form.get_user())

            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()

            return HttpResponseRedirect(next_url)
    else:
        form = AuthenticationForm(request)

    request.session.set_test_cookie()

    return jingo.render(request, 'users/login.html',
                        {'form': form, 'next_url': next_url})
Exemple #22
0
def handle403(request):
    """A 403 message that looks nicer than the normal Apache forbidden page"""
    no_cookies = False
    referer = request.META.get('HTTP_REFERER')
    if referer:
        no_cookies = (referer.endswith(reverse('users.login'))
                      or referer.endswith(reverse('users.register')))

    return render(request,
                  'handlers/403.html', {
                      'form': AuthenticationForm(),
                      'no_cookies': no_cookies
                  },
                  status=403)
Exemple #23
0
def activate(request, activation_key):
    """Activate a User account."""
    activation_key = activation_key.lower()
    account = RegistrationProfile.objects.activate_user(activation_key)
    my_questions = None
    form = AuthenticationForm()
    if account:
        # Claim anonymous watches belonging to this email
        claim_watches.delay(account)

        # my_questions = Question.uncached.filter(creator=account)
        # TODO: remove this after dropping unconfirmed questions.
        # my_questions.update(status=CONFIRMED)
    return jingo.render(request, 'users/activate.html',
                        {'account': account, 'questions': my_questions,
                         'form': form})
Exemple #24
0
    def test_only_active(self):
        # Verify with active user
        form = AuthenticationForm(data={'username': self.active_user.username,
                                        'password': '******'})
        assert form.is_valid()

        # Verify with inactive user
        form = AuthenticationForm(data={
                'username': self.inactive_user.username,
                'password': '******'})
        assert not form.is_valid()
Exemple #25
0
def user_auth(request, contributor=False, register_form=None, login_form=None):
    """Try to log the user in, or register a user.

    POSTs from these forms do not come back to this view, but instead go to the
    login and register views, which may redirect back to this in case of error.
    """
    next_url = get_next_url(request) or reverse('home')

    if login_form is None:
        login_form = AuthenticationForm()
    if register_form is None:
        register_form = RegisterForm()

    return render(
        request, 'users/auth.html', {
            'login_form': login_form,
            'register_form': register_form,
            'contributor': contributor,
            'next_url': next_url
        })
Exemple #26
0
def login(request):
    """
	Log in view
	"""
    form = AuthenticationForm()
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = authenticate(email=request.POST['email'],
                                password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    django_login(request, user)
                    return redirect('/')
            else:
                form.add_error(None, 'Email or Password did not matched')
    return render(request, 'mainsite/login.jinja', {
        'form': form,
    })
Exemple #27
0
    def test_only_active(self):
        # Verify with active user
        u = User.objects.get(username='******')
        assert u.is_active
        form = AuthenticationForm(data={'username': '******',
                                        'password': '******'})
        assert form.is_valid()

        # Verify with inactive user
        u.is_active = False
        u.save()
        u = User.objects.get(username='******')
        assert not u.is_active
        form = AuthenticationForm(data={'username': '******',
                                        'password': '******'})
        assert not form.is_valid()
Exemple #28
0
    def test_allow_inactive(self):
        # Verify with active user
        user = User.objects.get(username='******')
        assert user.is_active
        form = AuthenticationForm(only_active=False,
                                  data={'username': '******',
                                        'password': '******'})
        assert form.is_valid()

        # Verify with inactive user
        user.is_active = False
        user.save()
        user = User.objects.get(username='******')
        assert not user.is_active
        form = AuthenticationForm(only_active=False,
                                  data={'username': '******',
                                        'password': '******'})
        assert form.is_valid()
Exemple #29
0
 def test_if_valid_on_empty_is_teacher(self):
     form_data = {'username': '******', 'is_teacher': '',
         'password': '******'}
     form = AuthenticationForm(data=form_data)
     self.assertTrue(form.is_valid())
 def test_if_not_valid_on_empty_field_except_is_teacher(self):
     form_data = {'username': '******', 'password': ''}
     form = AuthenticationForm(data=form_data)
     self.assertFalse(form.is_valid())
Exemple #31
0
def handle403(request):
    """A 403 message that looks nicer than the normal Apache forbidden page."""

    return jingo.render(request,
                        'handlers/403.html', {'form': AuthenticationForm()},
                        status=403)
Exemple #32
0
 def test_if_not_valid_on_empty_field_except_is_teacher(self):
     form_data = {'username': '******', 'password': ''}
     form = AuthenticationForm(data=form_data)
     self.assertFalse(form.is_valid())
Exemple #33
0
def browserid_register(request):
    """Handle user creation when assertion is valid, but no existing user"""
    redirect_to = request.session.get(SESSION_REDIRECT_TO,
        getattr(settings, 'LOGIN_REDIRECT_URL', reverse('home')))
    email = request.session.get(SESSION_VERIFIED_EMAIL, None)

    if not email:
        # This is pointless without a verified email.
        return HttpResponseRedirect(redirect_to)

    # Set up the initial forms
    register_form = BrowserIDRegisterForm()
    login_form = AuthenticationForm()

    if request.method == 'POST':

        # If the profile creation form was submitted...
        if 'register' == request.POST.get('action', None):
            register_form = BrowserIDRegisterForm(request.POST)
            if register_form.is_valid():
                try:
                    # If the registration form is valid, then create a new
                    # Django user, a new MindTouch user, and link the two
                    # together.
                    # TODO: This all belongs in model classes
                    username = register_form.cleaned_data['username']

                    user = User.objects.create(username=username, email=email)
                    user.set_unusable_password()
                    user.save()

                    profile = UserProfile.objects.create(user=user)
                    deki_user = DekiUserBackend.post_mindtouch_user(user)
                    profile.deki_user_id = deki_user.id
                    profile.save()

                    user.backend = 'django_browserid.auth.BrowserIDBackend'
                    auth.login(request, user)

                    # Bounce to the newly created profile page, since the user
                    # might want to review & edit.
                    redirect_to = request.session.get(SESSION_REDIRECT_TO,
                                                    profile.get_absolute_url())
                    return set_browserid_explained(
                        _redirect_with_mindtouch_login(redirect_to,
                                                       user.username))
                except MindTouchAPIError:
                    if user:
                        user.delete()
                    return jingo.render(request, '500.html',
                                        {'error_message': "We couldn't "
                                        "register a new account at this time. "
                                        "Please try again later."})

        else:
            # If login was valid, then set to the verified email
            login_form = handle_login(request)
            if login_form.is_valid():
                if request.user.is_authenticated():
                    # Change email to new verified email, for next time
                    user = request.user
                    user.email = email
                    user.save()
                    return _redirect_with_mindtouch_login(redirect_to,
                        login_form.cleaned_data.get('username'),
                        login_form.cleaned_data.get('password'))

    # HACK: Pretend the session was modified. Otherwise, the data disappears
    # for the next request.
    request.session.modified = True

    return jingo.render(request, 'users/browserid_register.html',
                        {'login_form': login_form,
                         'register_form': register_form})
Exemple #34
0
def browserid_register(request):
    """Handle user creation when assertion is valid, but no existing user"""
    statsd_waffle_incr('users.browserid_register', 'signin_metrics')
    redirect_to = request.session.get(SESSION_REDIRECT_TO,
        getattr(settings, 'LOGIN_REDIRECT_URL', reverse('home')))
    email = request.session.get(SESSION_VERIFIED_EMAIL, None)

    if not email:
        # This is pointless without a verified email.
        return HttpResponseRedirect(redirect_to)

    # Set up the initial forms
    register_form = BrowserIDRegisterForm()
    login_form = AuthenticationForm()

    if request.method == 'POST':
        statsd_waffle_incr('users.browserid_register.POST', 'signin_metrics')

        # If the profile creation form was submitted...
        if 'register' == request.POST.get('action', None):
            register_form = BrowserIDRegisterForm(request.POST)
            if register_form.is_valid():
                try:
                    # If the registration form is valid, then create a new
                    # Django user, a new MindTouch user, and link the two
                    # together.
                    # TODO: This all belongs in model classes
                    username = register_form.cleaned_data['username']

                    user = User.objects.create(username=username, email=email)
                    user.set_unusable_password()
                    user.save()

                    profile = UserProfile.objects.create(user=user)
                    if settings.DEKIWIKI_ENDPOINT:
                        deki_user = DekiUserBackend.post_mindtouch_user(user)
                        profile.deki_user_id = deki_user.id
                    profile.save()

                    user.backend = 'django_browserid.auth.BrowserIDBackend'
                    auth.login(request, user)

                    # Bounce to the newly created profile page, since the user
                    # might want to review & edit.
                    statsd_waffle_incr('users.browserid_register.POST.SUCCESS',
                                       'signin_metrics')
                    redirect_to = request.session.get(SESSION_REDIRECT_TO,
                                                    profile.get_absolute_url())
                    return set_browserid_explained(
                        _redirect_with_mindtouch_login(redirect_to,
                                                       user.username))
                except MindTouchAPIError:
                    if user:
                        user.delete()
                    return jingo.render(request, '500.html',
                                        {'error_message': "We couldn't "
                                        "register a new account at this time. "
                                        "Please try again later."})

    # HACK: Pretend the session was modified. Otherwise, the data disappears
    # for the next request.
    request.session.modified = True

    return jingo.render(request, 'users/browserid_register.html',
                        {'login_form': login_form,
                         'register_form': register_form})