Skip to content
auth.py 37.6 KiB
Newer Older
# -*- coding: utf-8 -*-

from __future__ import division

__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.
"""
Dong Zhuang's avatar
Dong Zhuang committed
from typing import cast
from django.utils.translation import ugettext_lazy as _, string_concat
from django.shortcuts import (  # noqa
        render, get_object_or_404, redirect, resolve_url)
from django.contrib import messages
import django.forms as forms
from django.core.exceptions import (PermissionDenied, SuspiciousOperation,
        ObjectDoesNotExist)
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Div
from django.conf import settings
from django.contrib.auth import (get_user_model, REDIRECT_FIELD_NAME,
        login as auth_login, logout as auth_logout)
from django.contrib.auth.forms import \
        AuthenticationForm as AuthenticationFormBase
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
Dong Zhuang's avatar
Dong Zhuang committed
from django.contrib.auth.validators import ASCIIUsernameValidator
from django.utils.http import is_safe_url
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse
from django.views.decorators.debug import sensitive_post_parameters
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from djangosaml2.backends import Saml2Backend as Saml2BackendBase

Andreas Klöckner's avatar
Andreas Klöckner committed
        user_status,
        participation_status,
        participation_permission as pperm,
from course.models import Participation, Course  # noqa
from accounts.models import User

Andreas Klöckner's avatar
Andreas Klöckner committed
from relate.utils import StyledForm, StyledModelForm
from django_select2.forms import ModelSelect2Widget
Dong Zhuang's avatar
Dong Zhuang committed
if False:
    from typing import Any, Optional, Text  # noqa

# {{{ impersonation

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 may_impersonate(impersonator, impersonee):
    # type: (User, User) -> bool
    if impersonator.is_superuser:
    my_participations = Participation.objects.filter(
            user=impersonator,
        # FIXME: 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 False
Andreas Klöckner's avatar
Andreas Klöckner committed
        impersonable_roles = [
                argument
                for perm, argument in part.permissions()
Andreas Klöckner's avatar
Andreas Klöckner committed
                if perm == pperm.impersonate_role]
Andreas Klöckner's avatar
Andreas Klöckner committed
        if Participation.objects.filter(
Andreas Klöckner's avatar
Andreas Klöckner committed
                course=part.course,
                status=participation_status.active,
Andreas Klöckner's avatar
Andreas Klöckner committed
                roles__identifier__in=impersonable_roles,
Andreas Klöckner's avatar
Andreas Klöckner committed
                user=impersonee).count():
class ImpersonateMiddleware(object):
    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

            if impersonee is not None:
                if may_impersonate(cast(User, request.user), impersonee):
                    request.relate_impersonate_original_user = request.user
                    request.user = impersonee
                    messages.add_message(request, messages.ERROR,
                            _("Error while impersonating."))
            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):
        return (
            (
                # Translators: information displayed when selecting
                # userfor impersonating. Customize how the name is
                # shown, but leave email first to retain usability
                # of form sorted by last name.
                "%(full_name)s (%(username)s - %(email)s)"
                % {
                    "full_name": u.get_full_name(),
                    "email": u.email,
                    "username": u.username
                    }))


class ImpersonateForm(StyledForm):
    def __init__(self, *args, **kwargs):
        # type:(*Any, **Any) -> None

        super(ImpersonateForm, self).__init__(*args, **kwargs)

        self.fields["user"] = forms.ModelChoiceField(
                queryset=User.objects.order_by("last_name"),
ifaint's avatar
ifaint committed
                help_text=_("Select user to impersonate."),
                widget=UserSearchWidget(),
                label=_("User"))
        self.fields["add_impersonation_header"] = forms.BooleanField(
                required=False,
                initial=True,
                label=_("Add impersonation header"),
                help_text=_("Add impersonation header to every page rendered "
                    "while impersonating, as a reminder that impersonation "
                    "is in progress."))

        self.helper.add_input(Submit("submit", _("Impersonate")))


def impersonate(request):
    # type: (http.HttpRequest) -> http.HttpResponse
    if hasattr(request, "relate_impersonate_original_user"):
        messages.add_message(request, messages.ERROR,
                _("Already impersonating someone."))
        return redirect("relate-stop_impersonating")
    if request.method == 'POST':
        form = ImpersonateForm(request.POST)
        if form.is_valid():
Loading
Loading full blame...