Skip to content
test_auth.py 103 KiB
Newer Older
from __future__ import annotations


__copyright__ = "Copyright (C) 2018 Dong Zhuang"

__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

Andreas Klöckner's avatar
Andreas Klöckner committed
import re
ifaint's avatar
ifaint committed
import unittest
from datetime import timedelta
Andreas Klöckner's avatar
Andreas Klöckner committed
from urllib.parse import ParseResult, quote, urlparse
ifaint's avatar
ifaint committed

Andreas Klöckner's avatar
Andreas Klöckner committed
import pytest
from django.conf import settings
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.contrib.auth import REDIRECT_FIELD_NAME, SESSION_KEY
ifaint's avatar
ifaint committed
from django.contrib.auth.hashers import check_password
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.core import mail
ifaint's avatar
ifaint committed
from django.core.exceptions import PermissionDenied
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.http import HttpResponse, JsonResponse, QueryDict
from django.test import Client, RequestFactory, TestCase, override_settings
from django.urls import NoReverseMatch, re_path, reverse
from django.utils.timezone import now
from djangosaml2.urls import urlpatterns as djsaml2_urlpatterns
ifaint's avatar
ifaint committed

Andreas Klöckner's avatar
Andreas Klöckner committed
from course import constants
Dong Zhuang's avatar
Dong Zhuang committed
from course.auth import (
    APIBearerTokenBackend,
    APIContext,
    APIError,
    EmailedTokenBackend,
    get_impersonable_user_qset,
    get_user_model,
    with_course_api_auth,
Andreas Klöckner's avatar
Andreas Klöckner committed
from course.models import AuthenticationToken, FlowPageVisit, ParticipationPermission
from relate.urls import COURSE_ID_REGEX, urlpatterns as base_urlpatterns
from tests import factories
Dong Zhuang's avatar
Dong Zhuang committed
from tests.base_test_mixins import (
    APITestMixin,
    CoursesTestMixinBase,
    MockAddMessageMixing,
Andreas Klöckner's avatar
Andreas Klöckner committed
    SingleCoursePageTestMixin,
ifaint's avatar
ifaint committed
)
Dong Zhuang's avatar
Dong Zhuang committed
from tests.utils import (
    LocmemBackendTestsMixin,
    load_url_pattern_names,
    mock,
    reload_urlconf,
Andreas Klöckner's avatar
Andreas Klöckner committed
)

Dong Zhuang's avatar
Dong Zhuang committed
# settings names
EDITABLE_INST_ID_BEFORE_VERI = "RELATE_EDITABLE_INST_ID_BEFORE_VERIFICATION"
SHOW_INST_ID_FORM = "RELATE_SHOW_INST_ID_FORM"
SHOW_EDITOR_FORM = "RELATE_SHOW_EDITOR_FORM"

NOT_IMPERSONATING_MESSAGE = "Not currently impersonating anyone."
NO_LONGER_IMPERSONATING_MESSAGE = "No longer impersonating anyone."
ALREADY_IMPERSONATING_SOMEONE_MESSAGE = "Already impersonating someone."
ERROR_WHILE_IMPERSONATING_MESSAGE = "Error while impersonating."
IMPERSONATE_FORM_ERROR_NOT_VALID_USER_MSG = (
    "Select a valid choice. That choice is "
    "not one of the available choices.")


ifaint's avatar
ifaint committed
_TOKEN_AUTH_DATA_RE = re.compile(
    r"[^0-9]+(?P<token_id>[0-9]+)_(?P<token_hash>[a-z0-9]+).+")


Dong Zhuang's avatar
Dong Zhuang committed
class ImpersonateTest(SingleCoursePageTestMixin, MockAddMessageMixing, TestCase):
    def test_impersonate_by_not_authenticated(self):
        with self.temporarily_switch_to_user(None):
Dong Zhuang's avatar
Dong Zhuang committed
            resp = self.get_impersonate_view()
            self.assertEqual(resp.status_code, 403)

Dong Zhuang's avatar
Dong Zhuang committed
            resp = self.post_impersonate_view(
                impersonatee=self.student_participation.user)
            self.assertEqual(resp.status_code, 403)

            resp = self.get_stop_impersonate()
            self.assertEqual(resp.status_code, 403)

            resp = self.post_stop_impersonate()
            self.assertEqual(resp.status_code, 403)

    def test_impersonate_by_student(self):
        user = self.student_participation.user
        impersonatable = get_impersonable_user_qset(user)
        self.assertEqual(impersonatable.count(), 0)

        with self.temporarily_switch_to_user(user):
Dong Zhuang's avatar
Dong Zhuang committed
            resp = self.get_impersonate_view()
            self.assertEqual(resp.status_code, 403)

Dong Zhuang's avatar
Dong Zhuang committed
            resp = self.post_impersonate_view(
                impersonatee=self.student_participation.user)
            self.assertEqual(resp.status_code, 403)
            resp = self.get_stop_impersonate()
            self.assertEqual(resp.status_code, 403)
            self.assertIsNone(self.client.session.get("impersonate_id"))

            resp = self.post_stop_impersonate()
            self.assertEqual(resp.status_code, 403)

    def test_impersonate_by_ta(self):
        user = self.ta_participation.user
        impersonatable = get_impersonable_user_qset(user)
        self.assertEqual(impersonatable.count(), 1)
Dong Zhuang's avatar
Dong Zhuang committed

        # create 2 participations, on is not active,
        # impersonatable count should be 2, not 3
Dong Zhuang's avatar
Dong Zhuang committed
        factories.ParticipationFactory.create(
Dong Zhuang's avatar
Dong Zhuang committed
            course=self.course,
            status=constants.participation_status.active)
Dong Zhuang's avatar
Dong Zhuang committed
        factories.ParticipationFactory.create(
Dong Zhuang's avatar
Dong Zhuang committed
            course=self.course,
            status=constants.participation_status.requested)
        impersonatable = get_impersonable_user_qset(user)
        self.assertEqual(impersonatable.count(), 2)
        self.assertNotIn(self.instructor_participation.user, impersonatable)

        with self.temporarily_switch_to_user(user):
Dong Zhuang's avatar
Dong Zhuang committed
            resp = self.get_impersonate_view()
            self.assertEqual(resp.status_code, 200)

Dong Zhuang's avatar
Dong Zhuang committed
            resp = self.post_impersonate_view(
                impersonatee=self.student_participation.user)
            self.assertEqual(resp.status_code, 200)
            self.assertEqual(self.client.session["impersonate_id"],
                             self.student_participation.user.pk)

            # re-impersonate without stop_impersonating
Dong Zhuang's avatar
Dong Zhuang committed
            resp = self.post_impersonate_view(
                impersonatee=self.student_participation.user)
            # because the request.user is the impernatee (student)
            # who has no pperm
            self.assertEqual(resp.status_code, 403)
            self.assertEqual(self.client.session["impersonate_id"],
                             self.student_participation.user.pk)

            # stop_impersonating
            self.post_stop_impersonate()
            self.assertIsNone(self.client.session.get("impersonate_id"))
Dong Zhuang's avatar
Dong Zhuang committed
            self.assertAddMessageCalledWith(NO_LONGER_IMPERSONATING_MESSAGE)

            # fail re-stop_impersonating
            resp = self.post_stop_impersonate()
            self.assertEqual(resp.status_code, 200)
Dong Zhuang's avatar
Dong Zhuang committed
            self.assertAddMessageCalledWith(NOT_IMPERSONATING_MESSAGE)

            # not allowed to impersonate instructor
Dong Zhuang's avatar
Dong Zhuang committed
            resp = self.post_impersonate_view(
                impersonatee=self.instructor_participation.user)

            self.assertEqual(resp.status_code, 200)
            self.assertFormError(resp.context["form"], "user",
                                 IMPERSONATE_FORM_ERROR_NOT_VALID_USER_MSG)
            self.assertIsNone(self.client.session.get("impersonate_id"))

            # not allowed to impersonate self
Dong Zhuang's avatar
Dong Zhuang committed
            resp = self.post_impersonate_view(
                impersonatee=user)
            self.assertEqual(resp.status_code, 200)
            self.assertFormError(resp.context["form"], "user",
                                 IMPERSONATE_FORM_ERROR_NOT_VALID_USER_MSG)
            self.assertIsNone(self.client.session.get("impersonate_id"))

    def test_impersonate_by_superuser(self):
        user = self.superuser
        impersonatable = get_impersonable_user_qset(user)
        self.assertEqual(impersonatable.count(), 3)

        with self.temporarily_switch_to_user(user):
Dong Zhuang's avatar
Dong Zhuang committed
            resp = self.post_impersonate_view(
                impersonatee=self.instructor_participation.user)
            self.assertEqual(resp.status_code, 200)
            self.assertEqual(self.client.session["impersonate_id"],
                             self.instructor_participation.user.pk)

    def test_impersonate_by_instructor(self):
        user = self.instructor_participation.user
        impersonatable = get_impersonable_user_qset(user)
Loading
Loading full blame...