Skip to content
test_auth.py 103 KiB
Newer Older
__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.
"""

Josh Asplund's avatar
Josh Asplund committed
import pytest
from urllib.parse import ParseResult, quote, urlparse
ifaint's avatar
ifaint committed
import unittest
from datetime import timedelta
import re

from django.utils.timezone import now
from djangosaml2.urls import urlpatterns as djsaml2_urlpatterns
Dong Zhuang's avatar
Dong Zhuang committed
from django.test import TestCase, override_settings, RequestFactory
from django.conf import settings
from django.core import mail
from django.contrib.auth import (
    REDIRECT_FIELD_NAME, SESSION_KEY,
)
ifaint's avatar
ifaint committed
from django.contrib.auth.hashers import check_password

from django.http import QueryDict, HttpResponse, JsonResponse
from django.urls import NoReverseMatch, reverse
ifaint's avatar
ifaint committed
from django.conf.urls import url
from django.core.exceptions import PermissionDenied

from relate.urls import urlpatterns as base_urlpatterns, COURSE_ID_REGEX

Dong Zhuang's avatar
Dong Zhuang committed
from course.auth import (
    get_impersonable_user_qset, get_user_model,
ifaint's avatar
ifaint committed
    EmailedTokenBackend, with_course_api_auth, APIError, APIBearerTokenBackend,
    APIContext
ifaint's avatar
ifaint committed
from course.models import FlowPageVisit, ParticipationPermission, AuthenticationToken
Dong Zhuang's avatar
Dong Zhuang committed
from course import constants
Dong Zhuang's avatar
Dong Zhuang committed
from tests.base_test_mixins import (
ifaint's avatar
ifaint committed
    CoursesTestMixinBase, SingleCoursePageTestMixin, MockAddMessageMixing,
    APITestMixin
)
Dong Zhuang's avatar
Dong Zhuang committed
from tests.utils import (
Josh Asplund's avatar
Josh Asplund committed
    LocmemBackendTestsMixin, load_url_pattern_names, reload_urlconf, mock)
Dong Zhuang's avatar
Dong Zhuang committed
from tests import factories
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.c.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.c.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.c.session["impersonate_id"],
                             self.student_participation.user.pk)

            # stop_impersonating
            self.post_stop_impersonate()
            self.assertIsNone(self.c.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, 'form', 'user',
                                 IMPERSONATE_FORM_ERROR_NOT_VALID_USER_MSG)
            self.assertIsNone(self.c.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, 'form', 'user',
                                 IMPERSONATE_FORM_ERROR_NOT_VALID_USER_MSG)
            self.assertIsNone(self.c.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.c.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)
        self.assertEqual(impersonatable.count(), 2)

        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)

            # first impersonate ta who has pperm
Loading
Loading full blame...