Ejemplo n.º 1
0
def is_logged_in_as_student(request):
    is_student = hasattr(request.user, "userprofile") and hasattr(
        request.user.userprofile, "student"
    )
    return (
        request.user.is_verified() or not using_two_factor(request.user) and is_student
    )
Ejemplo n.º 2
0
def two_form_authentication_warnings(request, teacher):
    # For teachers using 2FA, warn if they don't have any backup tokens set, and warn solo-admins to set up another admin
    if using_two_factor(request.user):
        # check backup tokens
        try:
            backup_tokens = request.user.staticdevice_set.all()[0].token_set.count()
        except Exception:
            backup_tokens = 0
        if not backup_tokens > 0:
            link = reverse('two_factor:profile')
            messages.warning(request,
                             'You do not have any backup tokens set up for two factor authentication, so could lose '
                             'access to your account if you have problems with your smartphone or tablet. '
                             '<a href="{link}">Set up backup tokens now</a>.'.format(link = link), extra_tags='safe')
        # check admin
        if teacher.is_admin:
            admins = Teacher.objects.filter(school=teacher.school, is_admin=True)
            manageSchoolLink = reverse('organisation_manage')
            if len(admins) == 1:
                messages.warning(request,
                                'You are the only administrator in your school and are using Two Factor Authentication '
                                '(2FA). We recommend you <a href="{manageSchoolLink}">set up another '
                                'administrator</a> who will be able to disable your 2FA should you have problems with '
                                'your smartphone or tablet.'.format(manageSchoolLink = manageSchoolLink),
                                 extra_tags='safe')
Ejemplo n.º 3
0
def is_logged_in_as_teacher(request):
    logged_in_as_teacher = (
        hasattr(request.user, "userprofile")
        and hasattr(request.user.userprofile, "teacher")
        and (request.user.is_verified() or not using_two_factor(request.user))
    )
    return logged_in_as_teacher
Ejemplo n.º 4
0
def process_login_form(request, login_form):
    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["teacher_password"],
            },
        )

    next_url = request.GET.get("next", None)
    if next_url and is_safe_url(next_url):
        return HttpResponseRedirect(next_url)

    teacher = request.user.userprofile.teacher

    return redirect_user_to_correct_page(request, teacher)
Ejemplo n.º 5
0
    def wrapped(request, *args, **kwargs):
        u = request.user
        if (not hasattr(u, 'userprofile') or not hasattr(u.userprofile, 'teacher') or
                (not u.is_verified() and using_two_factor(u))):
            return HttpResponseRedirect(reverse_lazy('teach'))

        return view_func(request, *args, **kwargs)
Ejemplo n.º 6
0
def teacher_edit_account(request):
    teacher = request.user.userprofile.teacher

    backup_tokens = 0
    # For teachers using 2FA, find out how many backup tokens they have
    if using_two_factor(request.user):
        try:
            backup_tokens = request.user.staticdevice_set.all()[0].token_set.count()
        except Exception:
            backup_tokens = 0

    if request.method == 'POST':
        form = TeacherEditAccountForm(request.user, request.POST)
        if form.is_valid():
            data = form.cleaned_data
            changing_email = False

            # check not default value for CharField
            if (data['password'] != ''):
                teacher.user.user.set_password(data['password'])
                teacher.user.user.save()
                update_session_auth_hash(request, form.user)

            teacher.title = data['title']
            teacher.user.user.first_name = data['first_name']
            teacher.user.user.last_name = data['last_name']
            new_email = data['email']
            if new_email != '' and new_email != teacher.user.user.email:
                    # new email to set and verify
                    changing_email = True
                    send_verification_email(request, teacher.user.user, new_email)

            teacher.save()
            teacher.user.user.save()

            if changing_email:
                logout(request)
                messages.success(request, 'Your account details have been successfully changed. Your email will be changed once you have verified it, until then you can still log in with your old email.')
                return render(request, 'portal/email_verification_needed.html',
                              {'userprofile': teacher.user,
                               'email': new_email})

            messages.success(request, 'Your account details have been successfully changed.')

            return HttpResponseRedirect(reverse_lazy('teacher_home'))
    else:
        form = TeacherEditAccountForm(request.user, initial={
            'title': teacher.title,
            'first_name': teacher.user.user.first_name,
            'last_name': teacher.user.user.last_name,
            'school': teacher.school,
        })

    return render(request, 'portal/teach/teacher_edit_account.html',
                  {'form': form,
                   'backup_tokens': backup_tokens})
def check_backup_tokens(request):
    backup_tokens = 0
    # For teachers using 2FA, find out how many backup tokens they have
    if using_two_factor(request.user):
        try:
            backup_tokens = request.user.staticdevice_set.all()[0].token_set.count()
        except Exception:
            backup_tokens = 0

    return backup_tokens
Ejemplo n.º 8
0
def is_logged_in(u):
    return (
        u
        and u.is_authenticated()
        and (not using_two_factor(u) or (hasattr(u, "is_verified") and u.is_verified()))
    )
Ejemplo n.º 9
0
def has_2FA(u):
    return using_two_factor(u)
Ejemplo n.º 10
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 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.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 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
Ejemplo n.º 11
0
def logged_in_as_teacher(u):
    if not hasattr(u, 'userprofile') or not hasattr(u.userprofile, 'teacher'):
        return False

    return u.is_verified() or not using_two_factor(u)
Ejemplo n.º 12
0
def has_2FA(u):
    return using_two_factor(u)
Ejemplo n.º 13
0
def teacher_edit_account(request):
    teacher = request.user.new_teacher

    backup_tokens = 0
    # For teachers using 2FA, find out how many backup tokens they have
    if using_two_factor(request.user):
        try:
            backup_tokens = request.user.staticdevice_set.all(
            )[0].token_set.count()
        except Exception:
            backup_tokens = 0

    if request.method == 'POST':
        form = TeacherEditAccountForm(request.user, request.POST)
        if form.is_valid():
            data = form.cleaned_data
            changing_email = False

            # check not default value for CharField
            if (data['password'] != ''):
                teacher.new_user.set_password(data['password'])
                teacher.new_user.save()
                update_session_auth_hash(request, form.user)

            teacher.title = data['title']
            teacher.new_user.first_name = data['first_name']
            teacher.new_user.last_name = data['last_name']
            new_email = data['email']
            if new_email != '' and new_email != teacher.new_user.email:
                # new email to set and verify
                changing_email = True
                send_verification_email(request, teacher.new_user, new_email)

            teacher.save()
            teacher.new_user.save()

            if changing_email:
                logout(request)
                messages.success(
                    request,
                    'Your account details have been successfully changed. Your email will be changed once you have verified it, until then you can still log in with your old email.'
                )
                return render(request, 'portal/email_verification_needed.html',
                              {
                                  'userprofile': teacher.user,
                                  'email': new_email
                              })

            messages.success(
                request,
                'Your account details have been successfully changed.')

            return HttpResponseRedirect(reverse_lazy('teacher_home'))
    else:
        form = TeacherEditAccountForm(request.user,
                                      initial={
                                          'title': teacher.title,
                                          'first_name':
                                          teacher.new_user.first_name,
                                          'last_name':
                                          teacher.new_user.last_name,
                                          'school': teacher.school,
                                      })

    return render(request, 'portal/teach/teacher_edit_account.html', {
        'form': form,
        'backup_tokens': backup_tokens
    })
Ejemplo n.º 14
0
def has_completed_auth_setup(u):
    return (not using_two_factor(u)) or (u.is_verified() and using_two_factor(u))
Ejemplo n.º 15
0
def is_logged_in_as_teacher(request):
    logged_in_as_teacher = hasattr(request.user, 'userprofile') and \
        hasattr(request.user.userprofile, 'teacher') and \
        (request.user.is_verified() or not using_two_factor(request.user))
    return logged_in_as_teacher
Ejemplo n.º 16
0
def logged_in_as_teacher(u):
    if not hasattr(u, 'userprofile') or not hasattr(u.userprofile, 'teacher'):
        return False

    return u.is_verified() or not using_two_factor(u)
Ejemplo n.º 17
0
def is_logged_in(u):
    return (u and u.is_authenticated()
            and (not using_two_factor(u) or
                 (hasattr(u, "is_verified") and u.is_verified())))
Ejemplo n.º 18
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