Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Private courses with sharing link #387

Merged
merged 16 commits into from
May 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions backend/api/locale/en/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,10 @@ msgstr "The teacher is not present in the course."
msgid "courses.error.teachers.last_teacher"
msgstr "The course must have at least one teacher."

#: serializers/course_serializer.py:116
msgid "courses.error.invitation_link"
msgstr "The invitation link is not unique, please try again."

#: serializers/docker_serializer.py:19
msgid "docker.errors.custom"
msgstr "User is not allowed to create public images"
Expand Down
4 changes: 4 additions & 0 deletions backend/api/locale/nl/LC_MESSAGES/django.po
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,10 @@ msgstr "De lesgever bevindt zich niet in de opleiding."
msgid "courses.error.teachers.last_teacher"
msgstr "De opleiding moet minstens één lesgever hebben."

#: serializers/course_serializer.py:116
msgid "courses.error.invitation_link"
msgstr "De uitnodigingslink is niet uniek, probeer het opnieuw."

#: serializers/docker_serializer.py:19
msgid "docker.errors.custom"
msgstr "Gebruiker is niet toegelaten om publieke afbeeldingen te maken"
Expand Down
28 changes: 28 additions & 0 deletions backend/api/migrations/0018_course_invitation_link_and_more.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Generated by Django 5.0.4 on 2024-04-29 20:35

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('api', '0017_merge_20240416_1054'),
]

operations = [
migrations.AddField(
model_name='course',
name='invitation_link',
field=models.CharField(blank=True, max_length=100, null=True),
),
migrations.AddField(
model_name='course',
name='invitation_link_expires',
field=models.DateField(blank=True, null=True),
),
migrations.AddField(
model_name='course',
name='private_course',
field=models.BooleanField(default=False),
),
]
9 changes: 9 additions & 0 deletions backend/api/models/course.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ class Course(models.Model):
null=True,
)

# Field that defines if the course can be joined by anyone, or only using the invite link
private_course = models.BooleanField(default=False)

# Field that contains the invite link for the course
invitation_link = models.CharField(max_length=100, blank=True, null=True)

# Date when the invite link expires
invitation_link_expires = models.DateField(blank=True, null=True)

def __str__(self) -> str:
"""The string representation of the course."""
return str(self.name)
Expand Down
44 changes: 43 additions & 1 deletion backend/api/serializers/course_serializer.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from nh3 import clean
from datetime import timedelta
from django.utils import timezone
from django.utils.translation import gettext
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
Expand Down Expand Up @@ -45,7 +47,20 @@ def validate(self, attrs: dict) -> dict:

class Meta:
model = Course
fields = "__all__"
fields = [
"id",
"name",
"academic_startyear",
"excerpt",
"description",
"faculty",
"parent_course",
"private_course",
"teachers",
"assistants",
"students",
"projects",
]


class CreateCourseSerializer(CourseSerializer):
Expand Down Expand Up @@ -93,6 +108,33 @@ class CourseCloneSerializer(serializers.Serializer):
clone_assistants = serializers.BooleanField()


class SaveInvitationLinkSerializer(serializers.Serializer):
invitation_link = serializers.CharField(required=True)
link_duration = serializers.IntegerField(required=True)

def validate(self, data):
# Check if there is no course with the same invitation link.
if Course.objects.filter(invitation_link=data["invitation_link"]).exists():
raise ValidationError(gettext("courses.error.invitation_link"))

return data

def create(self, validated_data):
# Save the invitation link and the expiration date.
if "course" not in self.context:
raise ValidationError(gettext("courses.error.context"))

course: Course = self.context["course"]

course.invitation_link = validated_data["invitation_link"]

# Save the expiration date as the current date + the invite link expires parameter in days.
course.invitation_link_expires = timezone.now() + timedelta(days=validated_data["link_duration"])
course.save()

return course


class StudentJoinSerializer(StudentIDSerializer):
def validate(self, data):
# The validator needs the course context.
Expand Down
40 changes: 40 additions & 0 deletions backend/api/views/course_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from api.serializers.assistant_serializer import (AssistantIDSerializer,
AssistantSerializer)
from api.serializers.course_serializer import (CourseCloneSerializer,
SaveInvitationLinkSerializer,
CourseSerializer,
StudentJoinSerializer,
StudentLeaveSerializer,
Expand Down Expand Up @@ -67,9 +68,26 @@ def update(self, request: Request, *_, **__):
def search(self, request: Request) -> Response:
# Extract filter params
search = request.query_params.get("search", "")
invitation_link = request.query_params.get("invitationLink", "")
years = request.query_params.getlist("years[]")
faculties = request.query_params.getlist("faculties[]")

# If the invitation link was passed, then only the private course with the invitation link should be returned
if invitation_link != "none":

# Filter based on invitation link, and that the invitation link is not expired
queryset = self.get_queryset().filter(
invitation_link=invitation_link,
invitation_link_expires__gte=timezone.now()
)

# Serialize the resulting queryset
serializer = self.serializer_class(self.paginate_queryset(queryset), many=True, context={
"request": request
})

return self.get_paginated_response(serializer.data)

# Filter the queryset based on the search term
queryset = self.get_queryset().filter(
name__icontains=search
Expand All @@ -83,6 +101,9 @@ def search(self, request: Request) -> Response:
if faculties:
queryset = queryset.filter(faculty__in=faculties)

# No invitation link was passed, so filter out private courses
queryset = queryset.filter(private_course=False)

# Serialize the resulting queryset
serializer = self.serializer_class(self.paginate_queryset(queryset), many=True, context={
"request": request
Expand Down Expand Up @@ -373,3 +394,22 @@ def clone(self, request: Request, **__):
course_serializer = CourseSerializer(course, context={"request": request})

return Response(course_serializer.data)

@action(detail=True, methods=["post"])
@swagger_auto_schema(request_body=SaveInvitationLinkSerializer)
def invitation_link(self, request, **_):
"""Save the invitation link to the course"""
course = self.get_object()

serializer = SaveInvitationLinkSerializer(
data=request.data,
context={"course": course}
)

if serializer.is_valid(raise_exception=True):
serializer.save()

# Return serialized cloned course
course_serializer = CourseSerializer(course, context={"request": request})

return Response(course_serializer.data)
37 changes: 33 additions & 4 deletions frontend/src/assets/lang/app/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
"description": "Description",
"excerpt": "Short description",
"faculty": "Faculty",
"private": "Private course (students can only enroll with an invitation link)",
"year": "Academic year",
"enroll": "Enroll",
"leave": "Leave",
Expand All @@ -127,7 +128,16 @@
"placeholder": "Search a course by name",
"title": "Search a course",
"results": "{0} courses found for set filters"
},
"searchByLink": {
"placeholder": "Find a course using the registration link"
},
"share": {
"title": "Create invitation link",
"duration": "Validity period link (in days):",
"link": "Invitation link:"
}

}
},
"composables": {
Expand All @@ -147,11 +157,14 @@
}
},
"components": {
"submission" : "Submit",
"button": {
"academicYear": "Academic year {0}",
"createProject": "Create a new project",
"searchCourse": "Search a course",
"createCourse": "Create a new course"
"createCourse": "Create a new course",
"public": "Public",
"protected": "Protected"
},
"card": {
"open": "Details",
Expand All @@ -176,8 +189,7 @@
"noIncomingProjects": "No projects with a deadline within 7 days.",
"selectCourse": "Select the course for which you want to create a project:",
"showPastProjects": "Projects with passed deadline"
},
"submission": "Submit"
}
},
"types": {
"roles": {
Expand Down Expand Up @@ -226,7 +238,24 @@
},
"confirmations": {
"cloneCourse": "Are you sure you want to clone this coure? This will create the same course for the next academic year.",
"leaveCourse": "Are you sure you want to leave this course? You will no longer have access to this course."
"leaveCourse": "Are you sure you want to leave this course? You will no longer have access to this course.",
"shareCourse": "By creating an invitation link, you allow students in possession of this link to enroll in this course. Please copy the generated link, only when you click on \"Create invitation link\" will this link become valid."
},
"protectedCourses": {
"screen1": {
"title": "Obtain invitation link",
"content": "Teachers can choose to make their courses private. This means you have to ask the teacher for an invitation link, to be able to join the course."
},
"screen2": {
"title": "Search course",
"content": "Use the invitation link to search a course. If you can't find the course, ask the teacher to share a new link."

},
"screen3": {
"title": "Enroll",
"content": "Enroll in the course. Now you can see all the current projects, deadlines, ..."

}
},
"admin": {
"title": "Admin",
Expand Down
31 changes: 29 additions & 2 deletions frontend/src/assets/lang/app/nl.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
"description": "Beschrijving",
"excerpt": "Korte beschrijving",
"faculty": "Faculteit",
"private": "Gesloten vak (studenten kunnen enkel inschrijven via uitnodigingslink)",
"year": "Academiejaar",
"enroll": "Inschrijven",
"leave": "Uitschrijven",
Expand All @@ -127,6 +128,14 @@
"placeholder": "Zoek een vak op naam",
"title": "Zoek een vak",
"results": "{0} vakken gevonden voor ingestelde filters"
},
"searchByLink": {
"placeholder": "Zoek een vak gebruik makende van een uitnodigingslink"
},
"share": {
"title": "Creëer invitatielink",
"duration": "Geldigheidsduur link (in dagen):",
"link": "Invitatielink:"
}
}
},
Expand All @@ -152,7 +161,9 @@
"academicYear": "Academiejaar {0}",
"createProject": "Creëer nieuw project",
"searchCourse": "Zoek een vak",
"createCourse": "Maak een vak"
"createCourse": "Maak een vak",
"public": "Publiek",
"protected": "Besloten"
},
"card": {
"open": "Details",
Expand Down Expand Up @@ -226,7 +237,23 @@
},
"confirmations": {
"cloneCourse": "Ben je zeker dat je dit vak wil klonen? Dit zal hetzelfde vak aanmaken voor het volgende academiejaar.",
"leaveCourse": "Ben je zeker dat je dit vak wil verlaten? Je zal geen toegang meer hebben tot dit vak."
"leaveCourse": "Ben je zeker dat je dit vak wil verlaten? Je zal geen toegang meer hebben tot dit vak.",
"shareCourse": "Door het creëren van een invitatielink staat u studenten in bezit van deze link toe zich in te schrijven voor dit vak. Gelieve de gegenereerde link te kopiëren, pas wanneer u op \"Creëer invitatielink\" klikt zal deze link geldig worden."
},
"protectedCourses": {
"screen1": {
"title": "Bemachtigen link",
"content": "Professoren kunnen kiezen om hun vakken niet publiek te maken. Vraag de prof om een invitatielink te delen om te kunnen toetreden tot het vak."
},
"screen2": {
"title": "Vak zoeken",
"content": "Gebruik de link om het vak te zoeken. Als je het vak niet kan vinden, kan je de prof vragen om een nieuwe link te delen."

},
"screen3": {
"title": "Inschrijven",
"content": "Schrijf je in voor het vak. Je kan nu een overzicht raadplegen van alle lopende projecten, deadlines, ..."
}
},
"admin": {
"title": "Beheerder",
Expand Down
1 change: 1 addition & 0 deletions frontend/src/components/courses/CourseGeneralList.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<script setup lang="ts">
import CourseGeneralCard from '@/components/courses/CourseGeneralCard.vue';
import Skeleton from 'primevue/skeleton';
import Button from 'primevue/button';
import { storeToRefs } from 'pinia';
import { useAuthStore } from '@/store/authentication.store.ts';
import { watch } from 'vue';
Expand Down
Loading