Skip to content
enrollment.py 37.9 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.
"""
from sys import intern
Andreas Klöckner's avatar
Andreas Klöckner committed

from django.utils.translation import (
        ugettext_lazy as _,
from django.shortcuts import (  # noqa
        render, get_object_or_404, redirect)
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.core.exceptions import PermissionDenied, SuspiciousOperation
from django.conf import settings
from django.urls import reverse
from django.db import transaction, IntegrityError
from django import forms
from django.utils.safestring import mark_safe

from crispy_forms.layout import Submit

from course.models import (
Andreas Klöckner's avatar
Andreas Klöckner committed
        user_status,
        ParticipationPermission,
        ParticipationTag,
        participation_status)

from course.constants import (
        PARTICIPATION_PERMISSION_CHOICES,
Dong Zhuang's avatar
Dong Zhuang committed
        NAME_VALID_REGEX,
from course.auth import UserSearchWidget

from course.utils import course_view, render_course_page, LanguageOverride
from relate.utils import StyledForm, StyledModelForm, string_concat
Andreas Klöckner's avatar
Andreas Klöckner committed
from pytools.lex import RE as REBase  # noqa
# {{{ for mypy

Dong Zhuang's avatar
Dong Zhuang committed
if False:
    from typing import Any, Tuple, Text, Optional, List, FrozenSet  # noqa
Dong Zhuang's avatar
Dong Zhuang committed
    from course.utils import CoursePageContext  # noqa
Isuru Fernando's avatar
Isuru Fernando committed
    import accounts.models  # noqa
def get_participation_for_user(user, course):
    # type: (accounts.models.User, Course) -> Optional[Participation]

    # "wake up" lazy object
    # http://stackoverflow.com/questions/20534577/int-argument-must-be-a-string-or-a-number-not-simplelazyobject  # noqa
    try:
        possible_user = user._wrapped
    except AttributeError:
        pass
    else:
        if isinstance(possible_user, get_user_model()):
            user = possible_user

    if not user.is_authenticated:
        return None

    participations = list(Participation.objects.filter(
            user=user,
            course=course,
            status=participation_status.active
            ))

    # The uniqueness constraint should have ensured that.
    assert len(participations) <= 1

    if len(participations) == 0:
        return None

    return participations[0]


def get_participation_for_request(request, course):
    # type: (http.HttpRequest, Course) -> Optional[Participation]

    return get_participation_for_user(request.user, course)

# }}}


# {{{ get_participation_role_identifiers

def get_participation_role_identifiers(course, participation):
    # type: (Course, Optional[Participation]) -> List[Text]

    if participation is None:
        return (
                ParticipationRole.objects.filter(
                    course=course,
                    is_default_for_unenrolled=True)
                .values_list("identifier", flat=True))
        return [r.identifier for r in participation.roles.all()]
Andreas Klöckner's avatar
Andreas Klöckner committed
# {{{ get_permissions

def get_participation_permissions(
Andreas Klöckner's avatar
Andreas Klöckner committed
        course,  # type: Course
        participation,  # type: Optional[Participation]
        ):
    # type: (...) -> FrozenSet[Tuple[Text, Optional[Text]]]
Andreas Klöckner's avatar
Andreas Klöckner committed

    if participation is not None:
        return participation.permissions()
    else:
        from course.models import ParticipationRolePermission

        perm_list = list(
                ParticipationRolePermission.objects.filter(
                    role__is_default_for_unenrolled=True)
                .values_list("permission", "argument"))

        perm = frozenset(
                (permission, argument) if argument else (permission, None)
                for permission, argument in perm_list)

        return perm

Andreas Klöckner's avatar
Andreas Klöckner committed

# {{{ enrollment

@login_required
@transaction.atomic
def enroll_view(request, course_identifier):
    # type: (http.HttpRequest, str) -> http.HttpResponse

    course = get_object_or_404(Course, identifier=course_identifier)
    user = request.user
    participations = Participation.objects.filter(course=course, user=user)
    if not participations.count():
        participation = None
    else:
        participation = participations.first()
        if participation.status == participation_status.requested:
            messages.add_message(request, messages.ERROR,
                                 _("You have previously sent the enrollment "
                                   "request. Re-sending the request is not "
                                   "allowed."))
            return redirect("relate-course_page", course_identifier)
        elif participation.status == participation_status.denied:
            messages.add_message(request, messages.ERROR,
                                 _("Your enrollment request had been denied. "
                                   "Enrollment is not allowed."))
            return redirect("relate-course_page", course_identifier)
        elif participation.status == participation_status.dropped:
            messages.add_message(request, messages.ERROR,
                                 _("You had been dropped from the course. "
                                   "Re-enrollment is not allowed."))
            return redirect("relate-course_page", course_identifier)
        else:
            assert participation.status == participation_status.active
Loading
Loading full blame...