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

from django.utils.translation import (
        ugettext_lazy as _,
        pgettext,
        string_concat)
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 import translation
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,
from course.auth import UserSearchWidget

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

from typing import Any, Tuple, Text, Optional  # noqa
from course.utils import CoursePageContext  # noqa

# }}}


# {{{ get_participation_for_request

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

    # "wake up" lazy object
    # http://stackoverflow.com/questions/20534577/int-argument-must-be-a-string-or-a-number-not-simplelazyobject  # noqa
    user = request.user
    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]

# }}}


# {{{ 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]]]

    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)
    participation = get_participation_for_request(request, course)
        messages.add_message(request, messages.ERROR,
                _("Already enrolled. Cannot re-renroll."))
        return redirect("relate-course_page", course_identifier)

    if not course.accepts_enrollment:
        messages.add_message(request, messages.ERROR,
                _("Course is not accepting enrollments."))
        return redirect("relate-course_page", course_identifier)
    if request.method != "POST":
        # This can happen if someone tries to refresh the page, or switches to
        # desktop view on mobile.
        messages.add_message(request, messages.ERROR,
                _("Can only enroll using POST request"))
        return redirect("relate-course_page", course_identifier)

    user = request.user
    if (course.enrollment_required_email_suffix
Andreas Klöckner's avatar
Andreas Klöckner committed
            and user.status != user_status.active):
        messages.add_message(request, messages.ERROR,
ifaint's avatar
ifaint committed
                _("Your email address is not yet confirmed. "
                "Confirm your email to continue."))
        return redirect("relate-course_page", course_identifier)
    preapproval = None
    if request.user.email:
        try:
            preapproval = ParticipationPreapproval.objects.get(
                    course=course, email__iexact=request.user.email)
Loading
Loading full blame...