Esempio n. 1
0
def render_login_form(request):
    invalid_form = False

    limits = getattr(request, 'limits', {'ip': [0], 'email': [0]})
    captcha_limit = 5

    LoginFormWithCaptcha = partial(create_form_subclass_with_recaptcha(TeacherLoginForm, recaptcha_client), request)
    InputLoginForm = compute_input_login_form(LoginFormWithCaptcha, limits, captcha_limit)
    OutputLoginForm = compute_output_login_form(LoginFormWithCaptcha, limits, captcha_limit)

    login_form = OutputLoginForm(prefix='login')

    if request.method == 'POST':
        login_form = InputLoginForm(request.POST, prefix='login')
        if login_form.is_valid():
            return process_login_form(request, login_form)

        else:
            login_form = OutputLoginForm(request.POST, prefix='login')
            invalid_form = True

    res = render(request, 'redesign/login.html', {
        'login_form': login_form,
        'logged_in_as_teacher': is_logged_in_as_teacher(request),
    })

    res.count = invalid_form
    return res
Esempio n. 2
0
def admin_login(request):
    show_captcha = getattr(request, 'limits', {'def': [0]})['def'][0] >= block_limit

    authentication_form = create_form_subclass_with_recaptcha(AdminLoginForm, recaptcha_client) if show_captcha \
        else AdminLoginForm

    return auth_views.login(request, authentication_form=authentication_form)
def organisation_create(request):
    increment_count = False
    limits = getattr(request, 'limits', {'ip': [0]})
    captcha_limit = 5

    using_captcha = (limits['ip'][0] > captcha_limit)
    should_use_captcha = (limits['ip'][0] >= captcha_limit)

    OrganisationJoinFormWithCaptcha = partial(create_form_subclass_with_recaptcha(OrganisationJoinForm, recaptcha_client), request)
    InputOrganisationJoinForm = compute_input_join_form(OrganisationJoinFormWithCaptcha, OrganisationJoinForm, using_captcha)
    OutputOrganisationJoinForm = compute_output_join_form(OrganisationJoinFormWithCaptcha, OrganisationJoinForm, should_use_captcha)

    teacher = request.user.new_teacher

    create_form = OrganisationForm(user=request.user)
    join_form = OutputOrganisationJoinForm()

    if request.method == 'POST':
        if 'create_organisation' in request.POST:
            create_form = OrganisationForm(request.POST, user=request.user)
            if create_form.is_valid():
                data = create_form.cleaned_data
                name = data.get('name', '')
                postcode = data.get('postcode', '').upper()
                country = data.get('country', '')

                error, town, lat, lng = '', '0', '0', '0'  # lookup_coord(postcode, country)

                school = School.objects.create(
                    name=name,
                    postcode=postcode,
                    town=town,
                    latitude=lat,
                    longitude=lng,
                    country=country
                )

                teacher.school = school
                teacher.is_admin = True
                teacher.save()

                messages.success(request, "The school or club '" + teacher.school.name + "' has been successfully added.")

                return HttpResponseRedirect(reverse_lazy('onboarding-classes'))

        elif 'join_organisation' in request.POST:
            increment_count = True
            process_join_form(request, teacher, InputOrganisationJoinForm, OutputOrganisationJoinForm)

        else:
            return process_revoke_request(request, teacher)

    res = render(request, 'portal/teach/onboarding_school.html', {
        'create_form': create_form,
        'join_form': join_form,
        'teacher': teacher,
    })

    res.count = increment_count
    return res
Esempio n. 4
0
def do_signup(request):
    args = {'label': 'Are you human?'}
    CaptchaNewUserForm = create_form_subclass_with_recaptcha(NewUserForm, 
        recaptcha_client, args)
    if request.method == 'POST': 
        uform = CaptchaNewUserForm(request, request.POST)
        if uform.is_valid():
            user = uform.save()
            np2 = uform.cleaned_data['new_password2']
            user.set_password(np2)
            user.save()
            user = authenticate(username=uform.cleaned_data['username'], password=np2)
            login(request, user)
            reset_last_modified(user)
            
            messages.success(request, 'Account created! Next, update the rest of your profile information below.')
            log.info("Created account for %s (%s)", user, user.email)
            return HttpResponseRedirect(reverse('run.views.userprofile_update', args=[user.username]))
    else: 
        uform = CaptchaNewUserForm(request)

    context = {'uform': uform}
    return render_to_response('run/signup.html', 
        context,
        context_instance=RequestContext(request))
Esempio n. 5
0
def admin_login(request):
    show_captcha = getattr(request, "limits", {"def": [0]})["def"][0] >= block_limit

    authentication_form = (
        create_form_subclass_with_recaptcha(AdminLoginForm, recaptcha_client) if show_captcha else AdminLoginForm
    )

    return auth_views.login(request, authentication_form=authentication_form)
def admin_login(request):
    show_captcha = getattr(request, 'limits',
                           {'def': [0]})['def'][0] >= block_limit

    authentication_form = create_form_subclass_with_recaptcha(AdminLoginForm, recaptcha_client) if show_captcha \
        else AdminLoginForm

    return auth_views.login(request, authentication_form=authentication_form)
def decorate_with_captcha(base_class, request, recaptcha_client):
    form_with_captcha_class = create_form_subclass_with_recaptcha(base_class, recaptcha_client)

    class FormWithCaptcha(form_with_captcha_class):

        def __init__(self, *args, **kwargs):
            super(FormWithCaptcha, self).__init__(request, *args, **kwargs)

    return FormWithCaptcha
Esempio n. 8
0
def decorate_with_captcha(base_class, request, recaptcha_client):
    form_with_captcha_class = create_form_subclass_with_recaptcha(
        base_class, recaptcha_client)

    class FormWithCaptcha(form_with_captcha_class):
        def __init__(self, *args, **kwargs):
            super(FormWithCaptcha, self).__init__(request, *args, **kwargs)

    return FormWithCaptcha
Esempio n. 9
0
def contact(request):
    increment_count = False
    limits = getattr(request, 'limits', {'ip': [0]})
    captcha_limit = 5

    using_captcha = (limits['ip'][0] > captcha_limit)
    should_use_captcha = (limits['ip'][0] >= captcha_limit)

    ContactFormWithCaptcha = partial(
        create_form_subclass_with_recaptcha(ContactForm, recaptcha_client),
        request)
    InputContactForm = ContactFormWithCaptcha if using_captcha else ContactForm
    OutputContactForm = ContactFormWithCaptcha if should_use_captcha else ContactForm

    anchor = ''

    if request.method == 'POST':
        contact_form = InputContactForm(request.POST)
        increment_count = True

        if contact_form.is_valid():
            email_message = emailMessages.contactEmail(
                request, contact_form.cleaned_data['name'],
                contact_form.cleaned_data['telephone'],
                contact_form.cleaned_data['email'],
                contact_form.cleaned_data['message'],
                contact_form.cleaned_data['browser'])
            send_email(CONTACT_EMAIL, CONTACT_FORM_EMAILS,
                       email_message['subject'], email_message['message'])

            confirmed_email_message = emailMessages.confirmationContactEmailMessage(
                request, contact_form.cleaned_data['name'],
                contact_form.cleaned_data['telephone'],
                contact_form.cleaned_data['email'],
                contact_form.cleaned_data['message'])
            send_email(CONTACT_EMAIL, [contact_form.cleaned_data['email']],
                       confirmed_email_message['subject'],
                       confirmed_email_message['message'])

            messages.success(request, 'Your message was sent successfully.')
            return HttpResponseRedirect('.')
        else:
            contact_form = OutputContactForm(request.POST)
            anchor = "contact"

    else:
        contact_form = OutputContactForm()

    response = render(request, 'portal/help-and-support.html', {
        'form': contact_form,
        'anchor': anchor
    })

    response.count = increment_count
    return response
 def test_additional_field_arguments(self):
     field_label = 'Are you human?'
     form_class = create_form_subclass_with_recaptcha(
         _MockRegistrationForm,
         FAKE_RECAPTCHA_CLIENT,
         additional_field_kwargs={'label': field_label},
         )
     form = form_class(_MockHttpRequest())
     
     recaptcha_field = form.fields['recaptcha']
     eq_(field_label, recaptcha_field.label)
Esempio n. 11
0
    def test_additional_field_arguments(self):
        field_label = 'Are you human?'
        form_class = create_form_subclass_with_recaptcha(
            _MockRegistrationForm,
            FAKE_RECAPTCHA_CLIENT,
            additional_field_kwargs={'label': field_label},
        )
        form = form_class(_MockHttpRequest())

        recaptcha_field = form.fields['recaptcha']
        eq_(field_label, recaptcha_field.label)
Esempio n. 12
0
def student_join_organisation(request):
    increment_count = False
    limits = getattr(request, 'limits', { 'ip': [0] })
    captcha_limit = 5

    using_captcha = (limits['ip'][0] > captcha_limit)
    should_use_captcha = (limits['ip'][0] >= captcha_limit)

    StudentJoinOrganisationFormWithCaptcha = partial(create_form_subclass_with_recaptcha(StudentJoinOrganisationForm, recaptcha_client), request)
    InputStudentJoinOrganisationForm = StudentJoinOrganisationFormWithCaptcha if using_captcha else StudentJoinOrganisationForm
    OutputStudentJoinOrganisationForm = StudentJoinOrganisationFormWithCaptcha if should_use_captcha else StudentJoinOrganisationForm

    student = request.user.userprofile.student
    request_form = OutputStudentJoinOrganisationForm()

    # check student not managed by a school
    if student.class_field:
        raise Http404

    if request.method == 'POST':
        if 'class_join_request' in request.POST:
            increment_count = True
            request_form = InputStudentJoinOrganisationForm(request.POST)
            if request_form.is_valid():
                student.pending_class_request = request_form.klass
                student.save()

                emailMessage = emailMessages.studentJoinRequestSentEmail(request, request_form.klass.teacher.school.name, request_form.klass.access_code)
                send_email(NOTIFICATION_EMAIL, [student.user.user.email], emailMessage['subject'], emailMessage['message'])

                emailMessage = emailMessages.studentJoinRequestNotifyEmail(request, student.user.user.username, student.user.user.email, student.pending_class_request.access_code)
                send_email(NOTIFICATION_EMAIL, [student.pending_class_request.teacher.user.user.email], emailMessage['subject'], emailMessage['message'])

                messages.success(request, 'Your request to join a school has been received successfully.')

            else:
                request_form = OutputStudentJoinOrganisationForm(request.POST)

        elif 'revoke_join_request' in request.POST:
            student.pending_class_request = None
            student.save()
            # Check teacher hasn't since accepted rejection before posting success message
            if not student.class_field:
                messages.success(request, 'Your request to join a school has been cancelled successfully.')
            return HttpResponseRedirect(reverse_lazy('student_edit_account'))

    res = render(request, 'portal/play/student_join_organisation.html', {
        'request_form': request_form,
        'student': student }
    )

    res.count = increment_count
    return res
Esempio n. 13
0
def contact(request):
    increment_count = False
    limits = getattr(request, 'limits', {'ip': [0]})
    captcha_limit = 5

    using_captcha = (limits['ip'][0] > captcha_limit)
    should_use_captcha = (limits['ip'][0] >= captcha_limit)

    ContactFormWithCaptcha = partial(
        create_form_subclass_with_recaptcha(ContactForm, recaptcha_client), request)
    InputContactForm = ContactFormWithCaptcha if using_captcha else ContactForm
    OutputContactForm = ContactFormWithCaptcha if should_use_captcha else ContactForm

    if request.method == 'POST':
        contact_form = InputContactForm(request.POST)
        increment_count = True

        if contact_form.is_valid():
            emailMessage = emailMessages.contactEmail(
                request, contact_form.cleaned_data['name'], contact_form.cleaned_data['telephone'],
                contact_form.cleaned_data['email'], contact_form.cleaned_data['message'],
                contact_form.cleaned_data['browser'])
            send_email(CONTACT_EMAIL, CONTACT_FORM_EMAILS, emailMessage['subject'],
                       emailMessage['message'])

            confirmedEmailMessage = emailMessages.confirmationContactEmailMessage(
                request, contact_form.cleaned_data['name'], contact_form.cleaned_data['telephone'],
                contact_form.cleaned_data['email'], contact_form.cleaned_data['message'])
            send_email(CONTACT_EMAIL, [contact_form.cleaned_data['email']],
                       confirmedEmailMessage['subject'], confirmedEmailMessage['message'])

            messages.success(request, 'Your message was sent successfully.')
            return HttpResponseRedirect('.')

        else:
            contact_form = OutputContactForm(request.POST)

    else:
        contact_form = OutputContactForm()

    response = render(request, 'portal/contact.html', {'form': contact_form})

    response.count = increment_count
    return response
Esempio n. 14
0
def render_login_form(request):
    invalid_form = False

    teacher_limits = getattr(request, 'limits', {'ip': [0], 'email': [0]})
    teacher_captcha_limit = 5

    LoginFormWithCaptcha = partial(
        create_form_subclass_with_recaptcha(TeacherLoginForm,
                                            recaptcha_client), request)
    InputLoginForm = compute_teacher_input_login_form(LoginFormWithCaptcha,
                                                      teacher_limits,
                                                      teacher_captcha_limit)
    OutputLoginForm = compute_teacher_output_login_form(
        LoginFormWithCaptcha, teacher_limits, teacher_captcha_limit)

    login_form = OutputLoginForm(prefix='login')

    student_limits = getattr(request, 'limits', {'ip': [0], 'name': [0]})
    student_captcha_limit = 30
    student_name_captcha_limit = 5

    StudentLoginFormWithCaptcha = partial(
        create_form_subclass_with_recaptcha(StudentLoginForm,
                                            recaptcha_client), request)
    InputStudentLoginForm = compute_student_input_login_form(
        StudentLoginFormWithCaptcha, student_limits, student_captcha_limit,
        student_name_captcha_limit)
    OutputStudentLoginForm = compute_student_output_login_form(
        StudentLoginFormWithCaptcha, student_limits, student_captcha_limit,
        student_name_captcha_limit)

    school_login_form = OutputStudentLoginForm(prefix='login')

    IndependentStudentLoginFormWithCaptcha = partial(
        create_form_subclass_with_recaptcha(IndependentStudentLoginForm,
                                            recaptcha_client), request)
    InputIndependentStudentLoginForm = compute_indep_student_input_login_form(
        IndependentStudentLoginFormWithCaptcha, student_limits,
        student_captcha_limit, student_name_captcha_limit)
    OutputIndependentStudentLoginForm = compute_indep_student_output_login_form(
        IndependentStudentLoginFormWithCaptcha, student_limits,
        student_captcha_limit, student_name_captcha_limit)

    independent_student_login_form = IndependentStudentLoginForm(
        prefix='independent_student')
    independent_student_view = False

    render_dict = {
        'login_form': login_form,
        'school_login_form': school_login_form,
        'independent_student_login_form': independent_student_login_form,
        'independent_student_view': independent_student_view,
        'logged_in_as_teacher': is_logged_in_as_teacher(request),
    }

    if request.method == 'POST':
        if 'school_login' in request.POST:
            form = InputStudentLoginForm(request.POST, prefix="login")
            process_form = process_student_login_form
            render_dict['school_login_form'] = OutputStudentLoginForm(
                request.POST, prefix='login')

        elif 'independent_student_login' in request.POST:
            form = InputIndependentStudentLoginForm(
                request.POST, prefix='independent_student')
            process_form = process_indep_student_login_form
            render_dict[
                'independent_student_login_form'] = OutputIndependentStudentLoginForm(
                    request.POST, prefix='independent_student')
            render_dict['independent_student_view'] = True

        else:
            form = InputLoginForm(request.POST, prefix='login')
            process_form = process_login_form
            render_dict['login_form'] = OutputLoginForm(request.POST,
                                                        prefix='login')

        if form.is_valid():
            return process_form(request, form)
        else:
            invalid_form = True

    res = render(request, 'redesign/login.html', render_dict)

    res.count = invalid_form
    return res
Esempio n. 15
0
    value = AntiSpamBase.VALUE
    timestamp = AntiSpamBase.TIMESTAMP
    token = AntiSpamBase.TOKEN
    security_hash = AntiSpamBase.SECURITY_HASH

    def __init__(self, *args, **kwargs):
        kwargs['initial'] = self.init_security(kwargs.get('initial', {}))
        super(AntiSpamBaseForm, self).__init__(*args, **kwargs)


class AntiSpamModelBaseForm(forms.ModelForm, AntiSpamBase):
    value = AntiSpamBase.VALUE
    timestamp = AntiSpamBase.TIMESTAMP
    token = AntiSpamBase.TOKEN
    security_hash = AntiSpamBase.SECURITY_HASH

    def __init__(self, *args, **kwargs):
        kwargs['initial'] = self.init_security(kwargs.get('initial', {}))
        super(AntiSpamModelBaseForm, self).__init__(*args, **kwargs)


# dynamically make BaseForms to CAPTCHA forms if settings.RECAPTCHA_CLIENT
if settings.RECAPTCHA_CLIENT is not None:
    AntiSpamModelForm = create_form_subclass_with_recaptcha(
        AntiSpamModelBaseForm, settings.RECAPTCHA_CLIENT)
    AntiSpamForm = create_form_subclass_with_recaptcha(
        AntiSpamBaseForm, settings.RECAPTCHA_CLIENT)
else:
    AntiSpamModelForm = AntiSpamModelBaseForm
    AntiSpamForm = AntiSpamBaseForm
#{ Stubs


class _MockHttpRequest(HttpRequest):
    
    def __init__(self, is_ssl_used=False, remote_addr=None):
        super(_MockHttpRequest, self).__init__()
        
        self.is_ssl_used = is_ssl_used
        self.META['REMOTE_ADDR'] = remote_addr
    
    def is_secure(self):
        return self.is_ssl_used


class _MockRegistrationForm(Form):

    full_name = CharField(max_length=255)
    
    email_address = EmailField(max_length=255)


_MockRecaptchaProtectedRegistrationForm = create_form_subclass_with_recaptcha(
    _MockRegistrationForm,
    FAKE_RECAPTCHA_CLIENT,
    )


#}
Esempio n. 17
0
def teach(request):
    invalid_form = False
    limits = getattr(request, 'limits', {'ip': [0], 'email': [0]})
    captcha_limit = 5

    using_captcha = (limits['ip'][0] > captcha_limit or limits['email'][0] > captcha_limit)
    should_use_captcha = (limits['ip'][0] >= captcha_limit or limits['email'][0] >= captcha_limit)

    LoginFormWithCaptcha = partial(
        create_form_subclass_with_recaptcha(TeacherLoginForm, recaptcha_client), request)
    InputLoginForm = LoginFormWithCaptcha if using_captcha else TeacherLoginForm
    OutputLoginForm = LoginFormWithCaptcha if should_use_captcha else TeacherLoginForm

    login_form = OutputLoginForm(prefix='login')
    signup_form = TeacherSignupForm(prefix='signup')

    if request.method == 'POST':
        if 'login' in request.POST:
            login_form = InputLoginForm(request.POST, prefix='login')
            if login_form.is_valid():
                user = login_form.user
                if not is_verified(user):
                    send_verification_email(request, user)
                    return render(request, 'portal/email_verification_needed.html',
                                  {'user': user})

                login(request, login_form.user)

                if using_two_factor(request.user):
                    return render(request, 'portal/2FA_redirect.html', {
                        'form': AuthenticationForm(),
                        'username': request.user.username,
                        'password': login_form.cleaned_data['password'],
                    })
                else:
                    link = reverse('two_factor:profile')
                    messages.info(
                        request, ("You are not currently set up with two-factor authentication. "
                                  + "Use your phone or tablet to enhance your account's security. "
                                  + "Click <a href='" + link + "'>here</a> to find out more and "
                                  + "set it up or go to your account page at any time."),
                        extra_tags='safe')

                next_url = request.GET.get('next', None)
                if next_url:
                    return HttpResponseRedirect(next_url)

                return HttpResponseRedirect(reverse_lazy('teacher_home'))

            else:
                login_form = OutputLoginForm(request.POST, prefix='login')
                invalid_form = True

        if 'signup' in request.POST:
            signup_form = TeacherSignupForm(request.POST, prefix='signup')
            if signup_form.is_valid():
                data = signup_form.cleaned_data

                teacher = Teacher.objects.factory(
                    title=data['title'],
                    first_name=data['first_name'],
                    last_name=data['last_name'],
                    email=data['email'],
                    password=data['password'])

                send_verification_email(request, teacher.new_user)

                return render(request, 'portal/email_verification_needed.html',
                              {'user': teacher.new_user})

    logged_in_as_teacher = hasattr(request.user, 'userprofile') and \
        hasattr(request.user, 'teacher') and \
        (request.user.is_verified() or not using_two_factor(request.user))

    res = render(request, 'portal/teach.html', {
        'login_form': login_form,
        'signup_form': signup_form,
        'logged_in_as_teacher': logged_in_as_teacher,
    })

    res.count = invalid_form
    return res
Esempio n. 18
0
def play(request):
    invalid_form = False
    limits = getattr(request, 'limits', {'ip': [0], 'name': [0]})
    ip_captcha_limit = 30
    name_captcha_limit = 5

    using_captcha = (limits['ip'][0] > ip_captcha_limit or limits['name'][0] >= name_captcha_limit)
    should_use_captcha = (limits['ip'][0] >= ip_captcha_limit or limits['name'][0] >= name_captcha_limit)

    StudentLoginFormWithCaptcha = partial(
        create_form_subclass_with_recaptcha(StudentLoginForm, recaptcha_client), request)
    InputStudentLoginForm = StudentLoginFormWithCaptcha if using_captcha else StudentLoginForm
    OutputStudentLoginForm = StudentLoginFormWithCaptcha if should_use_captcha else StudentLoginForm

    IndependentStudentLoginFormWithCaptcha = partial(
        create_form_subclass_with_recaptcha(IndependentStudentLoginForm, recaptcha_client), request)
    InputIndependentStudentLoginForm = IndependentStudentLoginFormWithCaptcha if using_captcha else IndependentStudentLoginForm
    OutputIndependentStudentLoginForm = IndependentStudentLoginFormWithCaptcha if should_use_captcha else IndependentStudentLoginForm

    school_login_form = OutputStudentLoginForm(prefix='login')
    independent_student_login_form = IndependentStudentLoginForm(prefix='independent_student')
    signup_form = StudentSignupForm(prefix='signup')

    independent_student_view = False
    signup_view = False
    if request.method == 'POST':
        if 'school_login' in request.POST:
            school_login_form = InputStudentLoginForm(request.POST, prefix='login')
            if school_login_form.is_valid():
                login(request, school_login_form.user)

                next_url = request.GET.get('next', None)
                if next_url:
                    return HttpResponseRedirect(next_url)

                return HttpResponseRedirect(reverse_lazy('student_details'))

            else:
                school_login_form = OutputStudentLoginForm(request.POST, prefix='login')
                invalid_form = True

        elif 'independent_student_login' in request.POST:
            independent_student_login_form = InputIndependentStudentLoginForm(request.POST, prefix='independent_student')
            if independent_student_login_form.is_valid():
                user = independent_student_login_form.user
                if not is_verified(user):
                    send_verification_email(request, user)
                    return render(request, 'portal/email_verification_needed.html',
                                  {'user': user})

                login(request, independent_student_login_form.user)

                next_url = request.GET.get('next', None)
                if next_url:
                    return HttpResponseRedirect(next_url)

                return HttpResponseRedirect(reverse_lazy('student_details'))
            else:
                independent_student_view = True
                independent_student_login_form = OutputIndependentStudentLoginForm(request.POST, prefix='independent_student')
                school_login_form = StudentLoginForm(prefix='login')
                invalid_form = True

        elif 'signup' in request.POST:
            signup_form = StudentSignupForm(request.POST, prefix='signup')
            if signup_form.is_valid():
                data = signup_form.cleaned_data

                student = Student.objects.independentStudentFactory(
                    username=data['username'],
                    name=data['name'],
                    email=data['email'],
                    password=data['password'])

                email_supplied = (data['email'] != '')
                if (email_supplied):
                    send_verification_email(request, student.new_user)
                    return render(request, 'portal/email_verification_needed.html',
                                  {'user': student.new_user})
                else:  # dead code - frontend ensures email supplied.
                    auth_user = authenticate(username=data['username'], password=data['password'])
                    login(request, auth_user)

                return render(request, 'portal/play/student_details.html')
            else:
                signup_view = True

    res = render(request, 'portal/play.html', {
        'school_login_form': school_login_form,
        'independent_student_login_form': independent_student_login_form,
        'signup_form': signup_form,
        'independent_student_view': independent_student_view,
        'signup_view': signup_view,
    })

    res.count = invalid_form
    return res
Esempio n. 19
0
def organisation_create(request):
    increment_count = False
    limits = getattr(request, 'limits', {'ip': [0]})
    captcha_limit = 5

    using_captcha = (limits['ip'][0] > captcha_limit)
    should_use_captcha = (limits['ip'][0] >= captcha_limit)

    OrganisationJoinFormWithCaptcha = partial(
        create_form_subclass_with_recaptcha(OrganisationJoinForm,
                                            recaptcha_client), request)
    InputOrganisationJoinForm = OrganisationJoinFormWithCaptcha if using_captcha else OrganisationJoinForm
    OutputOrganisationJoinForm = OrganisationJoinFormWithCaptcha if should_use_captcha else OrganisationJoinForm

    teacher = request.user.userprofile.teacher

    create_form = OrganisationForm(user=request.user)
    join_form = OutputOrganisationJoinForm()

    if request.method == 'POST':
        if 'create_organisation' in request.POST:
            create_form = OrganisationForm(request.POST, user=request.user)
            if create_form.is_valid():
                data = create_form.cleaned_data
                name = data.get('name', '')
                postcode = data.get('postcode', '')
                country = data.get('country', '')

                error, town, lat, lng = '', '0', '0', '0'  #lookup_coord(postcode, country)

                school = School.objects.create(name=name,
                                               postcode=postcode,
                                               town=town,
                                               latitude=lat,
                                               longitude=lng,
                                               country=country)

                teacher.school = school
                teacher.is_admin = True
                teacher.save()

                messages.success(
                    request, "The school or club '" + teacher.school.name +
                    "' has been successfully added.")

                return HttpResponseRedirect(reverse_lazy('teacher_home'))

        elif 'join_organisation' in request.POST:
            increment_count = True
            join_form = InputOrganisationJoinForm(request.POST)
            if join_form.is_valid():
                school = get_object_or_404(
                    School, id=join_form.cleaned_data['chosen_org'])

                teacher.pending_join_request = school
                teacher.save()

                emailMessage = emailMessages.joinRequestPendingEmail(
                    request, teacher.user.user.email)

                for admin in Teacher.objects.filter(school=school,
                                                    is_admin=True):
                    send_email(NOTIFICATION_EMAIL, [admin.user.user.email],
                               emailMessage['subject'],
                               emailMessage['message'])

                emailMessage = emailMessages.joinRequestSentEmail(
                    request, school.name)
                send_email(NOTIFICATION_EMAIL, [teacher.user.user.email],
                           emailMessage['subject'], emailMessage['message'])

                messages.success(
                    request,
                    'Your request to join the school or club has been sent successfully.'
                )

            else:
                join_form = OutputOrganisationJoinForm(request.POST)

        elif 'revoke_join_request' in request.POST:
            teacher.pending_join_request = None
            teacher.save()

            messages.success(
                request,
                'Your request to join the school or club has been revoked successfully.'
            )

    res = render(request, 'portal/teach/organisation_create.html', {
        'create_form': create_form,
        'join_form': join_form,
        'teacher': teacher,
    })

    res.count = increment_count
    return res
Esempio n. 20
0
def student_join_organisation(request):
    increment_count = False
    limits = getattr(request, 'limits', {'ip': [0]})
    captcha_limit = 5

    using_captcha = (limits['ip'][0] > captcha_limit)
    should_use_captcha = (limits['ip'][0] >= captcha_limit)

    StudentJoinOrganisationFormWithCaptcha = partial(
        create_form_subclass_with_recaptcha(StudentJoinOrganisationForm,
                                            recaptcha_client), request)
    InputStudentJoinOrganisationForm = StudentJoinOrganisationFormWithCaptcha if using_captcha else StudentJoinOrganisationForm
    OutputStudentJoinOrganisationForm = StudentJoinOrganisationFormWithCaptcha if should_use_captcha else StudentJoinOrganisationForm

    student = request.user.new_student
    request_form = OutputStudentJoinOrganisationForm()

    # check student not managed by a school
    if student.class_field:
        raise Http404

    if request.method == 'POST':
        if 'class_join_request' in request.POST:
            increment_count = True
            request_form = InputStudentJoinOrganisationForm(request.POST)
            if request_form.is_valid():
                student.pending_class_request = request_form.klass
                student.save()

                emailMessage = emailMessages.studentJoinRequestSentEmail(
                    request, request_form.klass.teacher.school.name,
                    request_form.klass.access_code)
                send_email(NOTIFICATION_EMAIL, [student.new_user.email],
                           emailMessage['subject'], emailMessage['message'])

                emailMessage = emailMessages.studentJoinRequestNotifyEmail(
                    request, student.new_user.username, student.new_user.email,
                    student.pending_class_request.access_code)
                send_email(
                    NOTIFICATION_EMAIL,
                    [student.pending_class_request.teacher.new_user.email],
                    emailMessage['subject'], emailMessage['message'])

                messages.success(
                    request,
                    'Your request to join a school has been received successfully.'
                )

            else:
                request_form = OutputStudentJoinOrganisationForm(request.POST)

        elif 'revoke_join_request' in request.POST:
            student.pending_class_request = None
            student.save()
            # Check teacher hasn't since accepted rejection before posting success message
            if not student.class_field:
                messages.success(
                    request,
                    'Your request to join a school has been cancelled successfully.'
                )
            return HttpResponseRedirect(reverse_lazy('student_edit_account'))

    res = render(request, 'portal/play/student_join_organisation.html', {
        'request_form': request_form,
        'student': student
    })

    res.count = increment_count
    return res
def organisation_create(request):
    increment_count = False
    limits = getattr(request, 'limits', { 'ip': [0] })
    captcha_limit = 5

    using_captcha = (limits['ip'][0] > captcha_limit)
    should_use_captcha = (limits['ip'][0] >= captcha_limit)

    OrganisationJoinFormWithCaptcha = partial(create_form_subclass_with_recaptcha(OrganisationJoinForm, recaptcha_client), request)
    InputOrganisationJoinForm = OrganisationJoinFormWithCaptcha if using_captcha else OrganisationJoinForm
    OutputOrganisationJoinForm = OrganisationJoinFormWithCaptcha if should_use_captcha else OrganisationJoinForm

    teacher = request.user.userprofile.teacher

    create_form = OrganisationForm(user=request.user)
    join_form = OutputOrganisationJoinForm()

    if request.method == 'POST':
        if 'create_organisation' in request.POST:
            create_form = OrganisationForm(request.POST, user=request.user)
            if create_form.is_valid():
                data = create_form.cleaned_data
                name = data.get('name', '')
                postcode = data.get('postcode', '')
                country = data.get('country', '')

                error, town, lat, lng = '', '0', '0', '0' #lookup_coord(postcode, country)

                school = School.objects.create(
                    name=name,
                    postcode=postcode,
                    town = town,
                    latitude = lat,
                    longitude = lng,
                    country=country)

                teacher.school = school
                teacher.is_admin = True
                teacher.save()

                messages.success(request, "The school or club '" + teacher.school.name + "' has been successfully added.")

                return HttpResponseRedirect(reverse_lazy('teacher_home'))

        elif 'join_organisation' in request.POST:
            increment_count = True
            join_form = InputOrganisationJoinForm(request.POST)
            if join_form.is_valid():
                school = get_object_or_404(School, id=join_form.cleaned_data['chosen_org'])

                teacher.pending_join_request = school
                teacher.save()

                emailMessage = emailMessages.joinRequestPendingEmail(request, teacher.user.user.email)

                for admin in Teacher.objects.filter(school=school, is_admin=True):
                    send_email(NOTIFICATION_EMAIL, [admin.user.user.email], emailMessage['subject'], emailMessage['message'])

                emailMessage = emailMessages.joinRequestSentEmail(request, school.name)
                send_email(NOTIFICATION_EMAIL, [teacher.user.user.email], emailMessage['subject'], emailMessage['message'])

                messages.success(request, 'Your request to join the school or club has been sent successfully.')

            else:
                join_form = OutputOrganisationJoinForm(request.POST)

        elif 'revoke_join_request' in request.POST:
            teacher.pending_join_request = None
            teacher.save()

            messages.success(request, 'Your request to join the school or club has been revoked successfully.')

    res = render(request, 'portal/teach/organisation_create.html', {
        'create_form': create_form,
        'join_form': join_form,
        'teacher': teacher,
    })

    res.count = increment_count
    return res
Esempio n. 22
0
def teach(request):
    invalid_form = False
    limits = getattr(request, 'limits', {'ip': [0], 'email': [0]})
    captcha_limit = 5

    using_captcha = (limits['ip'][0] > captcha_limit or limits['email'][0] > captcha_limit)
    should_use_captcha = (limits['ip'][0] >= captcha_limit or limits['email'][0] >= captcha_limit)

    LoginFormWithCaptcha = partial(
        create_form_subclass_with_recaptcha(TeacherLoginForm, recaptcha_client), request)
    InputLoginForm = LoginFormWithCaptcha if using_captcha else TeacherLoginForm
    OutputLoginForm = LoginFormWithCaptcha if should_use_captcha else TeacherLoginForm

    login_form = OutputLoginForm(prefix='login')
    signup_form = TeacherSignupForm(prefix='signup')

    if request.method == 'POST':
        if 'login' in request.POST:
            login_form = InputLoginForm(request.POST, prefix='login')
            if login_form.is_valid():
                userProfile = login_form.user.userprofile
                if userProfile.awaiting_email_verification:
                    send_verification_email(request, userProfile)
                    return render(request, 'portal/email_verification_needed.html',
                                  {'userprofile': userProfile})

                login(request, login_form.user)

                if default_device(request.user):
                    return render(request, 'portal/2FA_redirect.html', {
                        'form': AuthenticationForm(),
                        'username': request.user.username,
                        'password': login_form.cleaned_data['password'],
                    })
                else:
                    link = reverse('two_factor:profile')
                    messages.info(
                        request, ("You are not currently set up with two-factor authentication. "
                                  + "Use your phone or tablet to enhance your account's security. "
                                  + "Click <a href='" + link + "'>here</a> to find out more and "
                                  + "set it up or go to your account page at any time."),
                        extra_tags='safe')

                next_url = request.GET.get('next', None)
                if next_url:
                    return HttpResponseRedirect(next_url)

                return HttpResponseRedirect(reverse_lazy('teacher_home'))

            else:
                login_form = OutputLoginForm(request.POST, prefix='login')
                invalid_form = True

        if 'signup' in request.POST:
            signup_form = TeacherSignupForm(request.POST, prefix='signup')
            if signup_form.is_valid():
                data = signup_form.cleaned_data

                teacher = Teacher.objects.factory(
                    title=data['title'],
                    first_name=data['first_name'],
                    last_name=data['last_name'],
                    email=data['email'],
                    password=data['password'])

                send_verification_email(request, teacher.user)

                return render(request, 'portal/email_verification_needed.html',
                              {'userprofile': teacher.user})

    logged_in_as_teacher = hasattr(request.user, 'userprofile') and \
        hasattr(request.user.userprofile, 'teacher') and \
        (request.user.is_verified() or not default_device(request.user))

    res = render(request, 'portal/teach.html', {
        'login_form': login_form,
        'signup_form': signup_form,
        'logged_in_as_teacher': logged_in_as_teacher,
    })

    res.count = invalid_form
    return res
Esempio n. 23
0
def play(request):
    invalid_form = False
    limits = getattr(request, 'limits', {'ip': [0], 'name': [0]})
    ip_captcha_limit = 30
    name_captcha_limit = 5

    using_captcha = (limits['ip'][0] > ip_captcha_limit or limits['name'][0] >= name_captcha_limit)
    should_use_captcha = (limits['ip'][0] >= ip_captcha_limit or limits['name'][0] >= name_captcha_limit)

    StudentLoginFormWithCaptcha = partial(
        create_form_subclass_with_recaptcha(StudentLoginForm, recaptcha_client), request)
    InputStudentLoginForm = StudentLoginFormWithCaptcha if using_captcha else StudentLoginForm
    OutputStudentLoginForm = StudentLoginFormWithCaptcha if should_use_captcha else StudentLoginForm

    IndependentStudentLoginFormWithCaptcha = partial(
        create_form_subclass_with_recaptcha(IndependentStudentLoginForm, recaptcha_client), request)
    InputIndependentStudentLoginForm = IndependentStudentLoginFormWithCaptcha if using_captcha else IndependentStudentLoginForm
    OutputIndependentStudentLoginForm = IndependentStudentLoginFormWithCaptcha if should_use_captcha else IndependentStudentLoginForm

    school_login_form = OutputStudentLoginForm(prefix='login')
    independent_student_login_form = IndependentStudentLoginForm(prefix='independent_student')
    signup_form = StudentSignupForm(prefix='signup')

    independent_student_view = False
    signup_view = False
    if request.method == 'POST':
        if 'school_login' in request.POST:
            school_login_form = InputStudentLoginForm(request.POST, prefix='login')
            if school_login_form.is_valid():
                login(request, school_login_form.user)

                next_url = request.GET.get('next', None)
                if next_url:
                    return HttpResponseRedirect(next_url)

                return HttpResponseRedirect(reverse_lazy('student_details'))

            else:
                school_login_form = OutputStudentLoginForm(request.POST, prefix='login')
                invalid_form = True

        elif 'independent_student_login' in request.POST:
            independent_student_login_form = InputIndependentStudentLoginForm(request.POST, prefix='independent_student')
            if independent_student_login_form.is_valid():
                userProfile = independent_student_login_form.user.userprofile
                if userProfile.awaiting_email_verification:
                    send_verification_email(request, userProfile)
                    return render(request, 'portal/email_verification_needed.html',
                                  {'userprofile': userProfile})

                login(request, independent_student_login_form.user)

                next_url = request.GET.get('next', None)
                if next_url:
                    return HttpResponseRedirect(next_url)

                return HttpResponseRedirect(reverse_lazy('student_details'))
            else:
                independent_student_view = True
                independent_student_login_form = OutputIndependentStudentLoginForm(request.POST, prefix='independent_student')
                school_login_form = StudentLoginForm(prefix='login')
                invalid_form = True

        elif 'signup' in request.POST:
            signup_form = StudentSignupForm(request.POST, prefix='signup')
            if signup_form.is_valid():
                data = signup_form.cleaned_data

                student = Student.objects.independentStudentFactory(
                    username=data['username'],
                    name=data['name'],
                    email=data['email'],
                    password=data['password'])

                email_supplied = (data['email'] != '')
                if (email_supplied):
                    send_verification_email(request, student.user)
                    return render(request, 'portal/email_verification_needed.html',
                                  {'userprofile': student.user})
                else:
                    auth_user = authenticate(username=data['username'], password=data['password'])
                    login(request, auth_user)

                return render(request, 'portal/play/student_details.html')
            else:
                signup_view = True

    res = render(request, 'portal/play.html', {
        'school_login_form': school_login_form,
        'independent_student_login_form': independent_student_login_form,
        'signup_form': signup_form,
        'independent_student_view': independent_student_view,
        'signup_view': signup_view,
    })

    res.count = invalid_form
    return res
Esempio n. 24
0
        self.helper = FormHelper()
        self.helper.form_id = 'id-grouppageform'
        self.helper.form_class = "form-horizontal"
        self.helper.layout = Layout(
            HTML('{{ wizard.management_form }}'),
            'acceptance',
            FormActions(
                HTML("""{% if wizard.steps.prev %}<button name="wizard_goto_step" type="submit" class="btn" value="{{ wizard.steps.prev }}">Edit</button>{% endif %}"""),
                Submit('submit', 'Submit', css_class='btn')
            )
        )

recaptcha_client = RecaptchaClient(RECAPTCHA_PRIVATE_KEY, RECAPTCHA_PUBLIC_KEY)

GroupPageConfirmRecaptcha = create_form_subclass_with_recaptcha(
    GroupPageConfirmation,
    recaptcha_client
)


FORMS = [('entry', GroupPageForm), ('confirm', GroupPageConfirmation), ]
TEMPLATES = {
    'entry': 'grouppages/group_page_create.html',
    'confirm': 'grouppages/group_page_preview.html',
}


class GroupPageWizard(SessionWizardView):
    file_storage = TempFileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'grouppages/temp'))

    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
Esempio n. 25
0
        eq_(field_label, recaptcha_field.label)


#{ Stubs


class _MockHttpRequest(HttpRequest):
    def __init__(self, is_ssl_used=False, remote_addr=None):
        super(_MockHttpRequest, self).__init__()

        self.is_ssl_used = is_ssl_used
        self.META['REMOTE_ADDR'] = remote_addr

    def is_secure(self):
        return self.is_ssl_used


class _MockRegistrationForm(Form):

    full_name = CharField(max_length=255)

    email_address = EmailField(max_length=255)


_MockRecaptchaProtectedRegistrationForm = create_form_subclass_with_recaptcha(
    _MockRegistrationForm,
    FAKE_RECAPTCHA_CLIENT,
)

#}