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

Merging main stuff to side branch #26

Merged
merged 20 commits into from
Mar 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
18 changes: 18 additions & 0 deletions .env_example
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
SECRET_KEY=<django_secret>

DB_NAME=<db_name>
DB_HOST=<db_host>
DB_USER=<db_user>
DB_PORT=<db_port>
DB_PASSWORD=<db_password>

AWS_ACCESS_KEY_ID=<aws_access_id>
AWS_SECRET_ACCESS_KEY=<aws_access_key>
AWS_STORAGE_BUCKET_NAME=<aws_bucket_name>

EMAIL_HOST=<email_host>
EMAIL_PORT=<email_port>
EMAIL_USER=<email_user>
EMAIL_PASSWORD=<email_password>

FRONTEND_URL=<frontend_url> # No / after url
3 changes: 3 additions & 0 deletions api/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@
class ApiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'api'

def ready(self):
import api.signals
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 5.0.2 on 2024-03-17 14:53

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('api', '0005_remove_course_schedule'),
]

operations = [
migrations.AlterField(
model_name='attendenceacknowledgement',
name='attended_student',
field=models.BooleanField(default=None, null=True),
),
migrations.AlterField(
model_name='attendenceacknowledgement',
name='attended_teacher',
field=models.BooleanField(default=None, null=True),
),
]
26 changes: 17 additions & 9 deletions api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def clean(self):
super().clean()
self.email = self.__class__.objects.normalize_email(self.email)

def get_classes(self):
def get_enrolled_courses(self):
return [uc.course for uc in UserCourse.objects.filter(user__id=self.id)]

class LectureTypes(models.TextChoices):
Expand All @@ -68,17 +68,25 @@ def __str__(self):
return str(self.name)

def get_enrolled_students(self):
return [uc.user for uc in UserCourse.objects.filter(user__role=AccountRoles.STUDENT)]
return [uc.user for uc in UserCourse.objects.filter(user__role=AccountRoles.STUDENT, course=self)]

def get_teachers(self):
return [uc.user for uc in UserCourse.objects.filter(user__role=AccountRoles.TEACHER)]
return [uc.user for uc in UserCourse.objects.filter(user__role=AccountRoles.TEACHER, course=self)]

def get_lectures(self):
return [lecture for lecture in CourseLecture.objects.filter(course=self)]
return CourseLecture.objects.filter(course=self)

def get_lectures_week(self, year : int, week : int):
return CourseLecture.objects.filter(course=self, start_time__year=year, start_time__week=week)

def is_user_enrolled(self, user : User):
return bool(UserCourse.objects.filter(user=user, course=self))

def remove_user_from_course(self, user : User):
queryset = UserCourse.objects.filter(user=user, course=self)
if not queryset: return
queryset[0].delete()

def add_user_to_course(self, user: User):
UserCourse.objects.create(user=user, course=self).save()

Expand All @@ -99,13 +107,13 @@ class CourseLecture(models.Model):
default=LectureTypes.LECTURE,
)

def set_attendence_user(self, student : User, teacher=False):
def set_attendence_user(self, student : User, attended : bool, teacher=False):
queryset = AttendenceAcknowledgement.objects.filter(lecture=self, student=student)
if not queryset: ack = AttendenceAcknowledgement.objects.create(lecture=self, student=student)
else: ack = queryset[0]

if teacher: ack.attended_teacher = True
else: ack.attended_student = True
if teacher: ack.attended_teacher = attended
else: ack.attended_student = attended
ack.save()

def get_attendence_user(self, student : User):
Expand All @@ -117,8 +125,8 @@ def get_attendence(self):
return [] if not queryset else queryset[0]

class AttendenceAcknowledgement(models.Model):
attended_student = models.BooleanField(default=False)
attended_teacher = models.BooleanField(default=False)
attended_student = models.BooleanField(default=None, null=True)
attended_teacher = models.BooleanField(default=None, null=True)
student = models.ForeignKey(User, null=False, related_name='user_ack', on_delete=models.CASCADE)
lecture = models.ForeignKey(CourseLecture, null=False, related_name='lecture_ack', on_delete=models.CASCADE)

Expand Down
69 changes: 64 additions & 5 deletions api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework.validators import UniqueValidator

from .models import AccountRoles, Course
from .models import AccountRoles, Course, CourseLecture, LectureTypes

User = get_user_model()

Expand All @@ -24,11 +24,21 @@ class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'


class CourseUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["username", "first_name", "last_name", "role"]

class CourseSerializer(serializers.ModelSerializer):
class Meta:
model = Course
fields = '__all__'

class LectureSerializer(serializers.ModelSerializer):
class Meta:
model = CourseLecture
fields = '__all__'

# Defines the rules for registering a new user. Required fields, validation rules etc.
class CreateUserSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -73,8 +83,6 @@ def create(self, validated_data):
c.save()
return c



class MassEnrollSerializer(serializers.Serializer):
usernames = serializers.ListField(required=True, allow_empty=False, child=serializers.CharField(max_length=150))

Expand All @@ -88,4 +96,55 @@ def validate_enroll(self, username):

def validate(self, attrs):
for username in attrs["usernames"]: self.validate_enroll(username)
return attrs
return attrs

class AddLectureSerializer(serializers.Serializer):
MINIMUM_LECTURE_LENGTH = 10 # Minimum lecture length of 10 minutes

start_time = serializers.DateTimeField(required=True)
end_time = serializers.DateTimeField(required=True)
lecture_type = serializers.CharField(required=True)

def validate(self, attrs):
start_time, end_time = attrs["start_time"], attrs["end_time"]

if start_time > end_time:
raise serializers.ValidationError({"error": f"end_time has to be after start_time"})

lecture_length = (end_time - start_time).seconds / 60
if lecture_length < self.MINIMUM_LECTURE_LENGTH:
raise serializers.ValidationError({"error": f"lecture has to be at least {self.MINIMUM_LECTURE_LENGTH} minutes"})

lecture_type = attrs["lecture_type"]
if lecture_type not in LectureTypes.values:
raise serializers.ValidationError({"error": f"invalid lecture type: '{lecture_type}'"})

course : Course = self.context.get("course")
for lecture in course.get_lectures():
if lecture.start_time <= start_time and start_time < lecture.end_time:
raise serializers.ValidationError({"error": "there is already an active lecture during this time range"})
if lecture.start_time < end_time and end_time <= lecture.end_time:
raise serializers.ValidationError({"error": "there is already an active lecture during this time range"})
return attrs

class SetAttendenceTeacherSerializer(serializers.Serializer):
usernames = serializers.DictField(required=True, allow_empty=False, child=
serializers.CharField(max_length=150)
)

def validate_attendence(self, username, attended):
user_query = User.objects.all().filter(username=username)
if (attended := attended.lower()) not in ["true", "false"]: raise serializers.ValidationError({"error": f"invalid attendence state: '{attended}'"})
if not user_query: raise serializers.ValidationError({"error": f"user '{username}' does not exist"})
if user_query[0].role != AccountRoles.STUDENT: raise serializers.ValidationError({"error": f"cannot set the attendence of a non-student: '{username}' is {user_query[0].role}"})

course : Course = self.context.get("course")
if not course.is_user_enrolled(user_query[0]): raise serializers.ValidationError({"error": f"user '{username}' is not enrolled in '{course.course_name}'"})

def validate(self, attrs):
for username, attended in attrs["usernames"].items(): self.validate_attendence(username, attended)
return attrs

class MailTestSerializer(serializers.Serializer):
email = serializers.CharField(required=True)

31 changes: 28 additions & 3 deletions api/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'DIRS': [os.path.join(BASE_DIR, 'api', 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
Expand Down Expand Up @@ -81,8 +81,9 @@
'django.contrib.staticfiles',
'corsheaders',
'rest_framework',
'drf_spectacular',
'django_rest_passwordreset',
'rest_framework_simplejwt.token_blacklist',
'drf_spectacular',
"api.apps.ApiConfig"
]

Expand All @@ -92,6 +93,15 @@

AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = config('EMAIL_HOST')
EMAIL_PORT = config('EMAIL_PORT')
EMAIL_USE_TLS = True
EMAIL_HOST_USER = config('EMAIL_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_PASSWORD')

FRONTEND_URL = config('FRONTEND_URL')

CORS_ALLOW_HEADERS = [
'x-requested-with',
'content-type',
Expand Down Expand Up @@ -141,4 +151,19 @@
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'AUTH_HEADER_TYPES': ('JWT',),
}
}

DJANGO_REST_PASSWORDRESET_TOKEN_CONFIG = {
"CLASS": "django_rest_passwordreset.tokens.RandomStringTokenGenerator",
"OPTIONS": {
"min_length": 20,
"max_length": 30
}
}
DJANGO_REST_MULTITOKENAUTH_RESET_TOKEN_EXPIRY_TIME = 30 # minutes

DJANGO_REST_PASSWORDRESET_EMAIL_TEMPLATES = {
'subject': 'templates/email/password_reset_subject.txt',
'plain_body': 'templates/email/password_reset_email.html',
'html_body': 'templates/email/password_reset_email.html',
}
46 changes: 46 additions & 0 deletions api/signals.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from django.core.mail import EmailMultiAlternatives
from django.dispatch import receiver
from django.template.loader import render_to_string
from django.urls import reverse
from django.conf import settings


from django_rest_passwordreset.signals import reset_password_token_created


@receiver(reset_password_token_created)
def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs):
"""
Handles password reset tokens
When a token is created, an e-mail needs to be sent to the user
:param sender: View Class that sent the signal
:param instance: View Instance that sent the signal
:param reset_password_token: Token Model Object
:param args:
:param kwargs:
:return:
"""
# send an e-mail to the user
context = {
'current_user': reset_password_token.user,
'username': reset_password_token.user.username,
'email': reset_password_token.user.email,
'reset_password_url': f"{settings.FRONTEND_URL}/reset_password?token={reset_password_token.key}"
}

# render email text
email_html_message = render_to_string('email/password_reset_email.html', context)
email_plaintext_message = render_to_string('email/password_reset_email.txt', context)

msg = EmailMultiAlternatives(
# title:
"Password Reset for Attendunce",
# message:
email_plaintext_message,
# from:
"[email protected]", # Does not matter, it will be overridden
# to:
[reset_password_token.user.email]
)
msg.attach_alternative(email_html_message, "text/html")
msg.send()
9 changes: 9 additions & 0 deletions api/templates/email/password_reset_email.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<p>Hello,</p>

<p>We received a request to reset the password for your account. If you made this request, please click on the link below or copy and paste it into your browser to complete the process:</p>

<p><a href="{{ reset_password_url }}">{{ reset_password_url }}</a></p>

<p>The link will be valid for the next 30 minutes</p>

<p>If you did not request to reset your password, please ignore this email and your password will remain unchanged.</p>
9 changes: 9 additions & 0 deletions api/templates/email/password_reset_email.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Hello,

We received a request to reset the password for your account. If you made this request, please click on the link below or copy and paste it into your browser to complete the process:</p>

{{ reset_password_url }}

The link will be valid for the next 30 minutes

If you did not request to reset your password, please ignore this email and your password will remain unchanged.
Loading
Loading