Esempio n. 1
0
def login(request, facility):
    facility_id = facility and facility.id or None
    facilities = list(Facility.objects.all())

    # Fix for #1211: refresh cached facility info when it's free and relevant
    refresh_session_facility_info(request, facility_count=len(facilities))

    if request.method == 'POST':
        # log out any Django user or facility user
        logout(request)

        username = request.POST.get("username", "")
        password = request.POST.get("password", "")

        # first try logging in as a Django user
        user = authenticate(username=username, password=password)
        if user:
            auth_login(request, user)
            return HttpResponseRedirect(request.next or reverse("easy_admin"))

        # try logging in as a facility user
        form = LoginForm(data=request.POST, request=request, initial={"facility": facility_id})
        if form.is_valid():
            user = form.get_user()

            try:
                UserLog.begin_user_activity(user, activity_type="login", language=request.language)  # Success! Log the event (ignoring validation failures)
            except ValidationError as e:
                logging.error("Failed to begin_user_activity upon login: %s" % e)

            request.session["facility_user"] = user
            messages.success(request, _("You've been logged in! We hope you enjoy your time with KA Lite ") +
                                        _("-- be sure to log out when you finish."))

            # Send them back from whence they came
            landing_page = form.cleaned_data["callback_url"]
            if not landing_page:
                # Just going back to the homepage?  We can do better than that.
                landing_page = reverse("coach_reports") if form.get_user().is_teacher else None
                landing_page = landing_page or (reverse("account_management") if not settings.package_selected("RPi") else reverse("homepage"))

            return HttpResponseRedirect(form.non_field_errors() or request.next or landing_page)

        else:
            messages.error(
                request,
                _("There was an error logging you in. Please correct any errors listed below, and try again."),
            )

    else:  # render the unbound login form
        referer = urlparse.urlparse(request.META["HTTP_REFERER"]).path if request.META.get("HTTP_REFERER") else None
        # never use the homepage as the referer
        if referer in [reverse("homepage"), reverse("add_facility_student")]:
            referer = None
        form = LoginForm(initial={"facility": facility_id, "callback_url": referer})

    return {
        "form": form,
        "facilities": facilities,
    }
def custom(request):
    return {
        "central_server_host": settings.CENTRAL_SERVER_HOST,
        "securesync_protocol": settings.SECURESYNC_PROTOCOL,
        "base_template": "base.html",
        "is_central": False,
        "settings": settings,
        "restricted": settings.package_selected("UserRestricted"),
        "VERSION": version.VERSION,
        "BUILD_ID": BUILD_ID,
    }
def custom(request):
    return {
        "central_server_host": settings.CENTRAL_SERVER_HOST,
        "securesync_protocol": settings.SECURESYNC_PROTOCOL,
        "base_template": "base.html",
        "is_central": False,
        "settings": settings,
        "restricted": settings.package_selected("UserRestricted"),
        "VERSION": version.VERSION,
        "BUILD_ID": BUILD_ID,
    }
def custom(request):
    return {
        "central_server_host": settings.CENTRAL_SERVER_HOST,
        "securesync_protocol": settings.SECURESYNC_PROTOCOL,
        "base_template": "base.html",
        "CONTENT_ROOT": settings.CONTENT_ROOT,
        "CONTENT_URL": settings.CONTENT_URL,
        "DATA_PATH": settings.DATA_PATH,
        "settings": settings,
        "is_central": False,
        "restricted": settings.package_selected("UserRestricted")
    }
Esempio n. 5
0
def custom(request):
    return {
        "central_server_host": settings.CENTRAL_SERVER_HOST,
        "securesync_protocol": settings.SECURESYNC_PROTOCOL,
        "base_template": "base.html",
        "CONTENT_ROOT": settings.CONTENT_ROOT,
        "CONTENT_URL": settings.CONTENT_URL,
        "DATA_PATH": settings.DATA_PATH,
        "settings": settings,
        "is_central": False,
        "restricted": settings.package_selected("UserRestricted")
    }
Esempio n. 6
0
def edit_facility_user(request, facility, is_teacher=None, id=None):
    """Different codepaths for the following:
    * Django admin/teacher creates user, teacher
    * Student creates self

    Each has its own message and redirect.
    """

    title = ""
    user = get_object_or_404(FacilityUser, id=id) if id != "new" else None

    # Check permissions
    if user and not request.is_admin and user != request.session.get("facility_user"):
        # Editing a user, user being edited is not self, and logged in user is not admin
        raise PermissionDenied()
    elif settings.package_selected("UserRestricted") and not request.is_admin:
        # Users cannot create/edit their own data when UserRestricted
        raise PermissionDenied(_("Please contact a teacher or administrator to receive login information to this installation."))

    # Data submitted to create the user.
    if request.method == "POST":  # now, teachers and students can belong to a group, so all use the same form.

        form = FacilityUserForm(facility, data=request.POST, instance=user)
        if form.is_valid():
            if form.cleaned_data["password_first"]:
                form.instance.set_password(form.cleaned_data["password_first"])
            form.save()

            if getattr(request.session.get("facility_user"), "id", None) == form.instance.id:
                # Edited: own account; refresh the facility_user setting
                request.session["facility_user"] = form.instance
                messages.success(request, _("You successfully updated your user settings."))
                return HttpResponseRedirect(request.next or reverse("account_management"))

            elif id != "new":
                # Edited: by admin; someone else's ID
                messages.success(request, _("User changes saved for user '%s'") % form.instance.get_name())
                if request.next:
                    return HttpResponseRedirect(request.next)

            elif request.is_admin:
                # Created: by admin
                messages.success(request, _("You successfully created user '%s'") % form.instance.get_name())
                return HttpResponseRedirect(request.META.get("PATH_INFO", request.next or reverse("homepage")))  # allow them to add more of the same thing.

            else:
                # Created: by self
                messages.success(request, _("You successfully registered."))
                return HttpResponseRedirect(request.next or "%s?facility=%s" % (reverse("login"), form.data["facility"]))

    # For GET requests
    elif user:
        form = FacilityUserForm(facility=facility, instance=user)
        title = _("Edit user") + " " + user.username

    else:
        assert is_teacher is not None, "Must call this function with is_teacher set."
        form = FacilityUserForm(facility, initial={
            "group": request.GET.get("group", None),
            "is_teacher": is_teacher,
        })

    if not title:
        if not request.is_admin:
            title = _("Sign up for an account")
        elif is_teacher:
            title = _("Add a new teacher")
        else:
            title = _("Add a new student")

    return {
        "title": title,
        "user_id": id,
        "form": form,
        "facility": facility,
        "singlefacility": request.session["facility_count"] == 1,
        "num_groups": form.fields["group"].choices.queryset.count(),
        "teacher": is_teacher,
        "cur_url": request.path,
    }
Esempio n. 7
0
def edit_facility_user(request, facility, is_teacher=None, id=None):
    """Different codepaths for the following:
    * Django admin/teacher creates user, teacher
    * Student creates self

    Each has its own message and redirect.
    """

    title = ""
    user = get_object_or_404(FacilityUser, id=id) if id != "new" else None

    # Check permissions
    if user and not request.is_admin and user != request.session.get(
            "facility_user"):
        # Editing a user, user being edited is not self, and logged in user is not admin
        raise PermissionDenied()
    elif settings.package_selected("UserRestricted") and not request.is_admin:
        # Users cannot create/edit their own data when UserRestricted
        raise PermissionDenied(
            _("Please contact a teacher or administrator to receive login information to this installation."
              ))

    # Data submitted to create the user.
    if request.method == "POST":  # now, teachers and students can belong to a group, so all use the same form.

        form = FacilityUserForm(facility, data=request.POST, instance=user)
        if form.is_valid():
            if form.cleaned_data["password_first"]:
                form.instance.set_password(form.cleaned_data["password_first"])
            form.save()

            if getattr(request.session.get("facility_user"), "id",
                       None) == form.instance.id:
                # Edited: own account; refresh the facility_user setting
                request.session["facility_user"] = form.instance
                messages.success(
                    request, _("You successfully updated your user settings."))
                return HttpResponseRedirect(request.next
                                            or reverse("account_management"))

            elif id != "new":
                # Edited: by admin; someone else's ID
                messages.success(
                    request,
                    _("User changes saved for user '%s'") %
                    form.instance.get_name())
                if request.next:
                    return HttpResponseRedirect(request.next)

            elif request.is_admin:
                # Created: by admin
                messages.success(
                    request,
                    _("You successfully created user '%s'") %
                    form.instance.get_name())
                return HttpResponseRedirect(
                    request.META.get("PATH_INFO", request.next
                                     or reverse("homepage"))
                )  # allow them to add more of the same thing.

            else:
                # Created: by self
                messages.success(request, _("You successfully registered."))
                return HttpResponseRedirect(
                    request.next or "%s?facility=%s" %
                    (reverse("login"), form.data["facility"]))

    # For GET requests
    elif user:
        form = FacilityUserForm(facility=facility, instance=user)
        title = _("Edit user") + " " + user.username

    else:
        assert is_teacher is not None, "Must call this function with is_teacher set."
        form = FacilityUserForm(facility,
                                initial={
                                    "group": request.GET.get("group", None),
                                    "is_teacher": is_teacher,
                                })

    if not title:
        if not request.is_admin:
            title = _("Sign up for an account")
        elif is_teacher:
            title = _("Add a new teacher")
        else:
            title = _("Add a new student")

    return {
        "title": title,
        "user_id": id,
        "form": form,
        "facility": facility,
        "singlefacility": request.session["facility_count"] == 1,
        "num_groups": form.fields["group"].choices.queryset.count(),
        "teacher": is_teacher,
        "cur_url": request.path,
    }
Esempio n. 8
0
def login(request, facility):
    facility_id = facility and facility.id or None
    facilities = list(Facility.objects.all())

    # Fix for #1211: refresh cached facility info when it's free and relevant
    refresh_session_facility_info(request, facility_count=len(facilities))

    if request.method == 'POST':
        # log out any Django user or facility user
        logout(request)

        username = request.POST.get("username", "")
        password = request.POST.get("password", "")

        # first try logging in as a Django user
        user = authenticate(username=username, password=password)
        if user:
            auth_login(request, user)
            return HttpResponseRedirect(request.next or reverse("easy_admin"))

        # try logging in as a facility user
        form = LoginForm(data=request.POST,
                         request=request,
                         initial={"facility": facility_id})
        if form.is_valid():
            user = form.get_user()

            try:
                UserLog.begin_user_activity(
                    user, activity_type="login", language=request.language
                )  # Success! Log the event (ignoring validation failures)
            except ValidationError as e:
                logging.error("Failed to begin_user_activity upon login: %s" %
                              e)

            request.session["facility_user"] = user
            messages.success(
                request,
                _("You've been logged in! We hope you enjoy your time with KA Lite "
                  ) + _("-- be sure to log out when you finish."))

            # Send them back from whence they came
            landing_page = form.cleaned_data["callback_url"]
            if not landing_page:
                # Just going back to the homepage?  We can do better than that.
                landing_page = reverse(
                    "coach_reports") if form.get_user().is_teacher else None
                landing_page = landing_page or (
                    reverse("account_management")
                    if not settings.package_selected("RPi") else
                    reverse("homepage"))

            return HttpResponseRedirect(form.non_field_errors() or request.next
                                        or landing_page)

        else:
            messages.error(
                request,
                _("There was an error logging you in. Please correct any errors listed below, and try again."
                  ),
            )

    else:  # render the unbound login form
        referer = urlparse.urlparse(
            request.META["HTTP_REFERER"]).path if request.META.get(
                "HTTP_REFERER") else None
        # never use the homepage as the referer
        if referer in [reverse("homepage"), reverse("add_facility_student")]:
            referer = None
        form = LoginForm(initial={
            "facility": facility_id,
            "callback_url": referer
        })

    return {
        "form": form,
        "facilities": facilities,
        "sign_up_url": reverse("add_facility_student"),
    }
        Tests that a device is initially unregistered, and that it can
        be registered through automatic means.
        """
        home_url = self.reverse("homepage")

        # First, get the homepage without any automated information.
        self.browser.get(home_url) # Load page
        self.browser_check_django_message(message_type="warning", contains="complete the setup.")
        self.assertFalse(self.browser_is_logged_in(), "Not (yet) logged in")

        # Now, log in as admin
        self.browser_login_admin()


@distributed_server_test
@unittest.skipIf(settings.package_selected("UserRestricted"), "Registration not allowed when UserRestricted set.")
class UserRegistrationCaseTest(KALiteDistributedWithFacilityBrowserTestCase):
    username   = "******"
    password   = "******"

    def test_register_login_exact(self):
        """Tests that a user can login with the exact same email address as registered"""

        # Register user in one case
        self.browser_register_user(username=self.username.lower(), password=self.password)

        # Login in the same case
        self.browser_login_student(username=self.username.lower(), password=self.password)
        self.browser_logout_user()

Esempio n. 10
0
        be registered through automatic means.
        """
        home_url = self.reverse("homepage")

        # First, get the homepage without any automated information.
        self.browser.get(home_url)  # Load page
        self.browser_check_django_message(message_type="warning",
                                          contains="complete the setup.")
        self.assertFalse(self.browser_is_logged_in(), "Not (yet) logged in")

        # Now, log in as admin
        self.browser_login_admin()


@distributed_server_test
@unittest.skipIf(settings.package_selected("UserRestricted"),
                 "Registration not allowed when UserRestricted set.")
class UserRegistrationCaseTest(KALiteDistributedWithFacilityBrowserTestCase):
    username = "******"
    password = "******"

    def test_register_login_exact(self):
        """Tests that a user can login with the exact same email address as registered"""

        # Register user in one case
        self.browser_register_user(username=self.username.lower(),
                                   password=self.password)

        # Login in the same case
        self.browser_login_student(username=self.username.lower(),
                                   password=self.password)