Example #1
0
    def restore_object(self, attrs, instance=None):
        user = self.context['request'].user
        classgroup = attrs.get('classgroup')

        attributes = ["text", "source", "reply_to"]

        if (classgroup.class_settings is not None
                and classgroup.class_settings.enable_posting is False
                and not ClassGroupPermissions.is_teacher(classgroup, user)):
            raise serializers.ValidationError(
                "You are not allowed to make a post right now.")

        if instance is None:
            instance = Message(user=user, classgroup=classgroup)
        else:
            if instance.user != user:
                raise serializers.ValidationError(
                    "Attempting to edit a message that is not yours.")

        message_type = attrs.get('message_type')
        if message_type == "A" and not ClassGroupPermissions.is_teacher(
                classgroup, user):
            raise serializers.ValidationError(
                "You cannot make an announcement unless you own a course.")

        instance.message_type = message_type

        instance = set_attributes(attributes, attrs, instance)
        instance.save()
        return instance
Example #2
0
    def restore_object(self, attrs, instance=None):
        user = self.context['request'].user
        classgroup = attrs.get('classgroup')

        attributes = ["text", "source", "reply_to"]

        if (classgroup.class_settings is not None and
            classgroup.class_settings.enable_posting is False and
            not ClassGroupPermissions.is_teacher(classgroup, user)):
            raise serializers.ValidationError("You are not allowed to make a post right now.")


        if instance is None:
            instance = Message(user=user, classgroup=classgroup)
        else:
            if instance.user != user:
                raise serializers.ValidationError("Attempting to edit a message that is not yours.")

        message_type = attrs.get('message_type')
        if message_type == "A" and not ClassGroupPermissions.is_teacher(classgroup, user):
            raise serializers.ValidationError("You cannot make an announcement unless you own a course.")

        instance.message_type = message_type

        instance = set_attributes(attributes, attrs, instance)
        instance.save()
        return instance
Example #3
0
    def __init__(self, classgroup, user):
        self.cg = classgroup
        self.user = user
        if not ClassGroupPermissions.is_teacher(self.cg, self.user):
            raise IsNotTeacher("User must be teacher in order to have a queue.")

        self.key_name = self.cg.name + "_grading_queue"
Example #4
0
    def delete(self, request, pk, format=None):
        classgroup = request.DATA.get('classgroup', None)
        if classgroup is None:
            error_msg = "Need a classgroup in order to delete a user."
            log.error(error_msg)
            return Response(error_msg, status=status.HTTP_400_BAD_REQUEST)
        if classgroup.startswith("#"):
            classgroup = classgroup[1:]

        try:
            classgroup_model = Classgroup.objects.get(name=classgroup)
        except Classgroup.DoesNotExist:
            error_msg = "Cannot find the specified tag."
            log.error(error_msg)
            return Response(error_msg, status=status.HTTP_400_BAD_REQUEST)

        if not ClassGroupPermissions.is_teacher(classgroup_model,
                                                request.user):
            error_msg = "User not authorized to delete others."
            log.error(error_msg)
            return Response(error_msg, status=status.HTTP_400_BAD_REQUEST)

        user = self.get_object(pk)
        user.classgroups.remove(classgroup_model)

        return Response(status=status.HTTP_204_NO_CONTENT)
Example #5
0
    def __init__(self, classgroup, user):
        self.cg = classgroup
        self.user = user
        if not ClassGroupPermissions.is_teacher(self.cg, self.user):
            raise IsNotTeacher(
                "User must be teacher in order to have a queue.")

        self.key_name = self.cg.name + "_grading_queue"
Example #6
0
def get_to_be_graded_count(user, classgroup):
    """
    Get the length of the grading queue for a given classgroup and user.
    Right now only teachers can grade.
    """
    to_be_graded = 0
    if ClassGroupPermissions.is_teacher(classgroup, user):
        grading_queue = GradingQueue(classgroup, user)
        queue = grading_queue.retrieve()
        if queue is not None:
            to_be_graded = len(queue)
    return to_be_graded
Example #7
0
def get_to_be_graded_count(user, classgroup):
    """
    Get the length of the grading queue for a given classgroup and user.
    Right now only teachers can grade.
    """
    to_be_graded = 0
    if ClassGroupPermissions.is_teacher(classgroup, user):
        grading_queue = GradingQueue(classgroup, user)
        queue = grading_queue.retrieve()
        if queue is not None:
            to_be_graded = len(queue)
    return to_be_graded
Example #8
0
    def delete(self, request, pk, format=None):
        message = self.get_object(pk)

        if not ClassGroupPermissions.is_teacher(message.classgroup,
                                                request.user):
            error_msg = "User not authorized to delete this message."
            log.error(error_msg)
            return Response(error_msg, status=status.HTTP_400_BAD_REQUEST)

        message.classgroup = None
        message.save()

        return Response(status=status.HTTP_204_NO_CONTENT)
Example #9
0
    def get(self, request, classgroup):
        self.query_dict = {'classgroup': classgroup}
        self.verify_membership()

        if not ClassGroupPermissions.is_teacher(self.cg, request.user):
            error_msg = "You are not a teacher in this class, and cannot edit class settings."
            return Response(error_msg, status=status.HTTP_400_BAD_REQUEST)

        settings = self.cg.class_settings

        serializer = ClassSettingsSerializer(settings,
                                             context={'request': request})
        return Response(serializer.data)
Example #10
0
    def test_get_classgroup_list(self):
        """
        See if we can get the list of classgroups.
        """
        cg_list_url = reverse('class_list')
        response = self.c0.get(cg_list_url)
        courses = response.data
        # We should have the one class we made in setup.
        self.assertEqual(len(courses), 1)
        self.assertEqual(courses[0]['pk'], self.cg.id)

        # The user should have all permissions in the course, as they are the course owner.
        self.assertTrue(ClassGroupPermissions.is_teacher(self.cg, self.user0))
        self.assertTrue(ClassGroupPermissions.is_administrator(self.cg, self.user0))
        self.assertEqual(ClassGroupPermissions.access_level(self.cg, self.user0), ClassGroupPermissions.administrator)
Example #11
0
    def restore_object(self, attrs, instance=None):
        classgroup = attrs.get('classgroup')
        name = attrs.get('name')

        user = self.context['request'].user

        if instance is None:
            instance = Section(classgroup=classgroup, name=alphanumeric_name(name), display_name=name)
            instance.save()
        else:
            if not ClassGroupPermissions.is_teacher(classgroup, user):
                raise serializers.ValidationError("You do not have permission to modify this section.")
            instance.name = alphanumeric_name(name)
            instance.display_name = name
        return instance
Example #12
0
    def restore_object(self, attrs, instance=None):
        classgroup = attrs.get('classgroup')
        name = attrs.get('name')

        attributes = ['grading_policy']
        user = self.context['request'].user

        if instance is None:
            instance = Skill(classgroup=classgroup,
                             name=alphanumeric_name(name),
                             display_name=name)
            instance.save()
        else:
            if not ClassGroupPermissions.is_teacher(classgroup, user):
                raise serializers.ValidationError(
                    "You do not have permission to modify this skill.")
            instance.name = alphanumeric_name(name)
            instance.display_name = name

        resources = self.context['request'].DATA.get('resources')
        if isinstance(resources, basestring):
            resources = [resources]
        if resources is not None:
            resources = [str(r).strip() for r in resources]
        else:
            resources = []

        skill_resources = []
        for (i, r) in enumerate(resources):
            if len(r) < 1:
                continue
            resource = Resource.objects.get(display_name=r,
                                            classgroup=classgroup)
            skill_resource, created = SkillResource.objects.get_or_create(
                resource=resource, skill=instance)
            skill_resource.priority = i
            skill_resource.save()
            skill_resources.append(skill_resource)

        for s in SkillResource.objects.filter(skill=instance):
            if s not in skill_resources:
                s.delete()

        instance = set_attributes(attributes, attrs, instance)
        return instance
Example #13
0
def create_message_notification(sender, instance, **kwargs):
    if instance.reply_to is not None:
        if instance.user != instance.reply_to.user:
            try:
                MessageNotification.objects.get_or_create(
                    receiving_message=instance.reply_to,
                    receiving_user=instance.reply_to.user,
                    origin_message=instance,
                    notification_type="reply_to_discussion",
                )
            except IntegrityError:
                log.warn(
                    "MessageNotification already exists with receiver message {0} and origin message {1}"
                    .format(instance.reply_to.id, instance.id))
        for m in instance.reply_to.replies.all():
            if m.user != instance.reply_to.user and m.user != instance.user:
                try:
                    MessageNotification.objects.get_or_create(
                        receiving_message=instance.reply_to,
                        receiving_user=m.user,
                        origin_message=instance,
                        notification_type="reply_to_watched_thread",
                    )
                except IntegrityError:
                    log.warn(
                        "MessageNotification already exists with receiver message {0} and origin message {1}"
                        .format(m.id, instance.id))
    elif instance.reply_to is None and instance.classgroup is not None and ClassGroupPermissions.is_teacher(
            instance.classgroup,
            instance.user) and instance.message_type == "A":
        for user in instance.classgroup.users.all():
            if user != instance.user:
                try:
                    MessageNotification.objects.get_or_create(
                        receiving_message=instance,
                        receiving_user=user,
                        origin_message=instance,
                        notification_type="instructor_announcement_made",
                    )
                except IntegrityError:
                    log.warn(
                        "MessageNotification already exists for instructor post with receiver message {0} and origin message {1}"
                        .format(instance.id, instance.id))

    process_saved_message.delay(instance.id)
Example #14
0
    def restore_object(self, attrs, instance=None):
        classgroup = attrs.get('classgroup')
        name = attrs.get('name')

        user = self.context['request'].user

        if instance is None:
            instance = Section(classgroup=classgroup,
                               name=alphanumeric_name(name),
                               display_name=name)
            instance.save()
        else:
            if not ClassGroupPermissions.is_teacher(classgroup, user):
                raise serializers.ValidationError(
                    "You do not have permission to modify this section.")
            instance.name = alphanumeric_name(name)
            instance.display_name = name
        return instance
Example #15
0
    def restore_object(self, attrs, instance=None):
        classgroup = attrs.get('classgroup')
        name = attrs.get('name')

        attributes = ['grading_policy']
        user = self.context['request'].user

        if instance is None:
            instance = Skill(classgroup=classgroup, name=alphanumeric_name(name), display_name=name)
            instance.save()
        else:
            if not ClassGroupPermissions.is_teacher(classgroup, user):
                raise serializers.ValidationError("You do not have permission to modify this skill.")
            instance.name = alphanumeric_name(name)
            instance.display_name = name

        resources = self.context['request'].DATA.get('resources')
        if isinstance(resources, basestring):
            resources = [resources]
        if resources is not None:
            resources = [str(r).strip() for r in resources]
        else:
            resources = []

        skill_resources = []
        for (i, r) in enumerate(resources):
            if len(r) < 1:
                continue
            resource = Resource.objects.get(display_name=r, classgroup=classgroup)
            skill_resource, created = SkillResource.objects.get_or_create(
                resource=resource,
                skill=instance
            )
            skill_resource.priority = i
            skill_resource.save()
            skill_resources.append(skill_resource)

        for s in SkillResource.objects.filter(skill=instance):
            if s not in skill_resources:
                s.delete()

        instance = set_attributes(attributes, attrs, instance)
        return instance
Example #16
0
def create_message_notification(sender, instance, **kwargs):
    if instance.reply_to is not None:
        if instance.user != instance.reply_to.user:
            try:
                MessageNotification.objects.get_or_create(
                    receiving_message=instance.reply_to,
                    receiving_user=instance.reply_to.user,
                    origin_message=instance,
                    notification_type="reply_to_discussion",
                    )
            except IntegrityError:
                log.warn("MessageNotification already exists with receiver message {0} and origin message {1}".format(instance.reply_to.id, instance.id))
        for m in instance.reply_to.replies.all():
            if m.user != instance.reply_to.user and m.user != instance.user:
                try:
                    MessageNotification.objects.get_or_create(
                        receiving_message=instance.reply_to,
                        receiving_user=m.user,
                        origin_message=instance,
                        notification_type="reply_to_watched_thread",
                        )
                except IntegrityError:
                    log.warn("MessageNotification already exists with receiver message {0} and origin message {1}".format(m.id, instance.id))
    elif instance.reply_to is None and instance.classgroup is not None and ClassGroupPermissions.is_teacher(instance.classgroup, instance.user) and instance.message_type == "A":
        for user in instance.classgroup.users.all():
            if user != instance.user:
                try:
                    MessageNotification.objects.get_or_create(
                        receiving_message=instance,
                        receiving_user=user,
                        origin_message=instance,
                        notification_type="instructor_announcement_made",
                        )
                except IntegrityError:
                    log.warn("MessageNotification already exists for instructor post with receiver message {0} and origin message {1}".format(instance.id, instance.id))

    process_saved_message.delay(instance.id)
Example #17
0
    def restore_object(self, attrs, instance=None):
        user = self.context['request'].user
        name = attrs.get('name')
        class_settings_values = attrs.get('class_settings')

        attributes = ["description"]
        settings_attributes = ['moderate_posts', 'is_public', 'allow_signups']

        if instance is None:
            try:
                instance = Classgroup(owner=user, name=alphanumeric_name(name), display_name=name)
                instance.save()
                user.classgroups.add(instance)
                user.save()

                cg_perm = ClassGroupPermissions(instance)
                cg_perm.setup()
                cg_perm.assign_access_level(user, cg_perm.administrator)

                try:
                    class_settings = ClassSettings(classgroup=instance, access_key=make_random_key())
                    class_settings.save()
                except IntegrityError:
                    class_settings = ClassSettings.objects.get(classgroup=instance)

                try:
                    message = Message(
                        user=user,
                        classgroup=instance,
                        source="welcome",
                        text=WELCOME_MESSAGE2_TEMPLATE,
                        message_type="A",
                        )
                    message.save()
                    message = Message(
                        user=user,
                        classgroup=instance,
                        source="welcome",
                        text=WELCOME_MESSAGE_TEMPLATE.format(
                            class_name=instance.display_name,
                            class_link=get_current_site(self.context['request']).domain + instance.link(),
                            access_key=class_settings.access_key
                        ),
                        message_type="A",
                    )
                    message.save()
                except IntegrityError:
                    pass

            except IntegrityError:
                error_msg = "Class name is already taken."
                log.exception(error_msg)
                raise serializers.ValidationError(error_msg)
        else:
            if not ClassGroupPermissions.is_teacher(instance, user):
                raise serializers.ValidationError("Class name is already taken.")
            class_settings = instance.class_settings

        instance = set_attributes(attributes, attrs, instance)
        if class_settings_values is not None:
            class_settings = set_attributes(settings_attributes, class_settings_values, class_settings)
        class_settings.save()
        return instance
Example #18
0
    def restore_object(self, attrs, instance=None):
        user = self.context['request'].user
        name = attrs.get('name')
        class_settings_values = attrs.get('class_settings')

        attributes = ["description"]
        settings_attributes = ['moderate_posts', 'is_public', 'allow_signups']

        if instance is None:
            try:
                instance = Classgroup(owner=user,
                                      name=alphanumeric_name(name),
                                      display_name=name)
                instance.save()
                user.classgroups.add(instance)
                user.save()

                cg_perm = ClassGroupPermissions(instance)
                cg_perm.setup()
                cg_perm.assign_access_level(user, cg_perm.administrator)

                try:
                    class_settings = ClassSettings(
                        classgroup=instance, access_key=make_random_key())
                    class_settings.save()
                except IntegrityError:
                    class_settings = ClassSettings.objects.get(
                        classgroup=instance)

                try:
                    message = Message(
                        user=user,
                        classgroup=instance,
                        source="welcome",
                        text=WELCOME_MESSAGE2_TEMPLATE,
                        message_type="A",
                    )
                    message.save()
                    message = Message(
                        user=user,
                        classgroup=instance,
                        source="welcome",
                        text=WELCOME_MESSAGE_TEMPLATE.format(
                            class_name=instance.display_name,
                            class_link=get_current_site(
                                self.context['request']).domain +
                            instance.link(),
                            access_key=class_settings.access_key),
                        message_type="A",
                    )
                    message.save()
                except IntegrityError:
                    pass

            except IntegrityError:
                error_msg = "Class name is already taken."
                log.exception(error_msg)
                raise serializers.ValidationError(error_msg)
        else:
            if not ClassGroupPermissions.is_teacher(instance, user):
                raise serializers.ValidationError(
                    "Class name is already taken.")
            class_settings = instance.class_settings

        instance = set_attributes(attributes, attrs, instance)
        if class_settings_values is not None:
            class_settings = set_attributes(settings_attributes,
                                            class_settings_values,
                                            class_settings)
        class_settings.save()
        return instance
Example #19
0
 def verify_ownership(self):
     if not ClassGroupPermissions.is_teacher(self.cg, self.request.user):
         error_msg = "User is not a teacher for the given class."
         log.error(error_msg)
         raise PermissionDenied(error_msg)
Example #20
0
 def verify_teacher_or_creator(self, user):
     if not ClassGroupPermissions.is_teacher(
             self.cg, self.request.user) and user != self.request.user:
         error_msg = "User is not a teacher for the given class or did not create the resource."
         log.error(error_msg)
         raise PermissionDenied(error_msg)