Skip to content
auth.py 51.1 KiB
Newer Older
from __future__ import annotations
Andreas Klöckner's avatar
Andreas Klöckner committed

__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"

__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.
"""
import re
Andreas Klöckner's avatar
Andreas Klöckner committed
from typing import (  # noqa
    TYPE_CHECKING, Any, Dict, Optional, Text, Tuple, Union, cast,
)

import django.forms as forms
from crispy_forms.helper import FormHelper
Andreas Klöckner's avatar
Andreas Klöckner committed
from crispy_forms.layout import Button, Div, Layout, Submit
from django import http  # noqa
from django.conf import settings
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.contrib import messages
from django.contrib.auth import (
    REDIRECT_FIELD_NAME, get_user_model, login as auth_login, logout as auth_logout,
)
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth.forms import AuthenticationForm as AuthenticationFormBase
Dong Zhuang's avatar
Dong Zhuang committed
from django.contrib.auth.validators import ASCIIUsernameValidator
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.core.exceptions import (
    MultipleObjectsReturned, ObjectDoesNotExist, PermissionDenied,
    SuspiciousOperation,
)
from django.http import HttpResponseRedirect
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.shortcuts import get_object_or_404, redirect, render, resolve_url  # noqa
from django.template.response import TemplateResponse
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.urls import reverse
from django.utils.http import url_has_allowed_host_and_scheme
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
Andreas Klöckner's avatar
Andreas Klöckner committed
from django.views.decorators.debug import sensitive_post_parameters
from django_select2.forms import ModelSelect2Widget
from djangosaml2.backends import Saml2Backend
from accounts.models import User
Andreas Klöckner's avatar
Andreas Klöckner committed
from course.constants import (
    participation_permission as pperm, participation_status, user_status,
)
from course.models import (  # noqa
    AuthenticationToken, Participation, ParticipationRole,
)
from course.utils import course_view, render_course_page
from relate.utils import (
    HTML5DateTimeInput, StyledForm, StyledModelForm, get_site_name, string_concat,
)
Andreas Klöckner's avatar
Andreas Klöckner committed
    import datetime  # noqa

    from django.db.models import query  # noqa
Dong Zhuang's avatar
Dong Zhuang committed

Isuru Fernando's avatar
Isuru Fernando committed

def get_pre_impersonation_user(request):
    is_impersonating = hasattr(
            request, "relate_impersonate_original_user")
    if is_impersonating:
        return request.relate_impersonate_original_user
    return None


def get_impersonable_user_qset(impersonator: User) -> query.QuerySet:
    if impersonator.is_superuser:
        return User.objects.exclude(pk=impersonator.pk)
    my_participations = Participation.objects.filter(
        user=impersonator,
        status=participation_status.active)
    impersonable_user_qset = User.objects.none()
        # Notice: if a TA is not allowed to view participants'
        # profile in one course, then he/she is not able to impersonate
        # any user, even in courses he/she is allow to view profiles
        # of all users.
        if part.has_permission(pperm.view_participant_masked_profile):
            return User.objects.none()
Andreas Klöckner's avatar
Andreas Klöckner committed
        impersonable_roles = [
            argument
            for perm, argument in part.permissions()
            if perm == pperm.impersonate_role]
        q = (Participation.objects
             .filter(course=part.course,
                     status=participation_status.active,
                     roles__identifier__in=impersonable_roles)
             .select_related("user"))
        # There can be duplicate records. Removing duplicate records is needed
        # only when rendering ImpersonateForm
        impersonable_user_qset = (
            impersonable_user_qset
Andreas Klöckner's avatar
Andreas Klöckner committed
            | User.objects.filter(pk__in=q.values_list("user__pk", flat=True))
    return impersonable_user_qset
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if "impersonate_id" in request.session:
            imp_id = request.session["impersonate_id"]
            impersonee = None

            try:
                if imp_id is not None:
                    impersonee = cast(User, get_user_model().objects.get(id=imp_id))
            except ObjectDoesNotExist:
                pass

            may_impersonate = False
            if impersonee is not None:
                if request.user.is_superuser:
                    may_impersonate = True
                    qset = get_impersonable_user_qset(cast(User, request.user))
                    if qset.filter(pk=cast(User, impersonee).pk).count():
                        may_impersonate = True
            if may_impersonate:
                request.relate_impersonate_original_user = request.user
                request.user = impersonee
            else:
                messages.add_message(request, messages.ERROR,
                        _("Error while impersonating."))

        return self.get_response(request)

class UserSearchWidget(ModelSelect2Widget):
    model = User
    search_fields = [
            "username__icontains",
            "email__icontains",
            "first_name__icontains",
            "last_name__icontains",
            ]

    def label_from_instance(self, u):
        if u.first_name and u.last_name:
            return (
                    "%(full_name)s (%(username)s - %(email)s)"
                    % {
                        "full_name": u.get_full_name(),
                        "email": u.email,
                        "username": u.username
        else:
            # for users with "None" fullname
            return (
                    "%(username)s (%(email)s)"
                    % {
                        "email": u.email,
                        "username": u.username
class ImpersonateForm(StyledForm):
    def __init__(self, *args: Any, **kwargs: Any) -> None:
        super().__init__(*args, **kwargs)
        self.fields["user"] = forms.ModelChoiceField(
ifaint's avatar
ifaint committed
                help_text=_("Select user to impersonate."),
                widget=UserSearchWidget(
                    queryset=qset,
                    attrs={"data-minimum-input-length": 0},
                ),
Loading
Loading full blame...