Skip to content

Commit

Permalink
Reformat
Browse files Browse the repository at this point in the history
  • Loading branch information
mureytasroc committed Nov 5, 2023
1 parent 726f4fe commit 216dde8
Show file tree
Hide file tree
Showing 20 changed files with 342 additions and 112 deletions.
6 changes: 3 additions & 3 deletions backend/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ WORKDIR /app/

# Install dependencies
RUN apt-get update \
&& apt-get install --no-install-recommends -y python3.10-dev python3-distutils libpq-dev gcc \
&& wget -qO get-pip.py "https://raw.githubusercontent.com/pypa/get-pip/4cfa4081d27285bda1220a62a5ebf5b4bd749cdb/public/get-pip.py" \
&& python3.10 get-pip.py \
&& apt-get install --no-install-recommends -y python3.7-dev python3-distutils libpq-dev gcc \
&& wget -qO get-pip.py "https://github.com/pypa/get-pip/raw/0c72a3b4ece313faccb446a96c84770ccedc5ec5/get-pip.py" \
&& python3.7 get-pip.py \
--disable-pip-version-check \
--no-cache-dir \
&& pip3 install pipenv \
Expand Down
12 changes: 9 additions & 3 deletions backend/Platform/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("SECRET_KEY", "o7ql0!vuk0%rgrh9p2bihq#pege$qqlm@zo#8&t==%&za33m*2")
SECRET_KEY = os.environ.get(
"SECRET_KEY", "o7ql0!vuk0%rgrh9p2bihq#pege$qqlm@zo#8&t==%&za33m*2"
)

IDENTITY_RSA_PRIVATE_KEY = os.environ.get(
"IDENTITY_RSA_PRIVATE_KEY",
Expand Down Expand Up @@ -112,7 +114,9 @@
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
"default": dj_database_url.config(default="sqlite:///" + os.path.join(BASE_DIR, "db.sqlite3"))
"default": dj_database_url.config(
default="sqlite:///" + os.path.join(BASE_DIR, "db.sqlite3")
)
}

# Set default PK type
Expand All @@ -122,7 +126,9 @@
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"},
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
},
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
{"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
Expand Down
4 changes: 3 additions & 1 deletion backend/accounts/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,9 @@ class LabsAdminSite(admin.AdminSite):

def login(self, request, extra_context=None):
if not request.user.is_authenticated:
return redirect(reverse("accounts:login") + "?next=" + request.GET.get("next"))
return redirect(
reverse("accounts:login") + "?next=" + request.GET.get("next")
)
return super().login(request, extra_context)


Expand Down
4 changes: 3 additions & 1 deletion backend/accounts/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ def authenticate(self, request, remote_user, shibboleth_attributes):
# Update groups with every log in
user.groups.clear()
for affiliation_name in shibboleth_attributes["affiliation"]:
if affiliation_name: # Some users don't have any affiliation somehow ¯\_(ツ)_/¯
if (
affiliation_name
): # Some users don't have any affiliation somehow ¯\_(ツ)_/¯
group, _ = Group.objects.get_or_create(name=affiliation_name)
user.groups.add(group)

Expand Down
24 changes: 18 additions & 6 deletions backend/accounts/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ class Migration(migrations.Migration):
("password", models.CharField(max_length=128, verbose_name="password")),
(
"last_login",
models.DateTimeField(blank=True, null=True, verbose_name="last login"),
models.DateTimeField(
blank=True, null=True, verbose_name="last login"
),
),
(
"is_superuser",
Expand All @@ -35,25 +37,35 @@ class Migration(migrations.Migration):
(
"username",
models.CharField(
error_messages={"unique": "A user with that username already exists."},
error_messages={
"unique": "A user with that username already exists."
},
help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.",
max_length=150,
unique=True,
validators=[django.contrib.auth.validators.UnicodeUsernameValidator()],
validators=[
django.contrib.auth.validators.UnicodeUsernameValidator()
],
verbose_name="username",
),
),
(
"first_name",
models.CharField(blank=True, max_length=30, verbose_name="first name"),
models.CharField(
blank=True, max_length=30, verbose_name="first name"
),
),
(
"last_name",
models.CharField(blank=True, max_length=150, verbose_name="last name"),
models.CharField(
blank=True, max_length=150, verbose_name="last name"
),
),
(
"email",
models.EmailField(blank=True, max_length=254, verbose_name="email address"),
models.EmailField(
blank=True, max_length=254, verbose_name="email address"
),
),
(
"is_staff",
Expand Down
4 changes: 3 additions & 1 deletion backend/accounts/migrations/0002_auto_20200213_1711.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ def copy_permissions(apps, schema_editor):
ContentType = apps.get_model("contenttypes", "ContentType")
for user in User.objects.all():
for product_permission in user.product_permission.all():
content_type = ContentType.objects.get(app_label="accounts", model="user")
content_type = ContentType.objects.get(
app_label="accounts", model="user"
)
perm, _ = Permission.objects.get_or_create(
codename=product_permission.id,
name=product_permission.name,
Expand Down
4 changes: 3 additions & 1 deletion backend/accounts/migrations/0003_auto_20210918_2041.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,9 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name="user",
name="first_name",
field=models.CharField(blank=True, max_length=150, verbose_name="first name"),
field=models.CharField(
blank=True, max_length=150, verbose_name="first name"
),
),
migrations.CreateModel(
name="PhoneNumber",
Expand Down
22 changes: 18 additions & 4 deletions backend/accounts/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,22 @@ def _lookup_item(self, model, field_name, item, mode=None):
return model.objects.get(**item)
except ObjectDoesNotExist:
raise serializers.ValidationError(
{field_name: ["The object with these values does not exist: {}".format(item)]},
{
field_name: [
"The object with these values does not exist: {}".format(
item
)
]
},
code="invalid",
)
except MultipleObjectsReturned:
raise serializers.ValidationError(
{field_name: ["Multiple objects exist with these values: {}".format(item)]}
{
field_name: [
"Multiple objects exist with these values: {}".format(item)
]
}
)

def save(self):
Expand Down Expand Up @@ -65,15 +75,19 @@ def save(self):

for item in items:
# adds item to list
m2m_lists[field_name].append(self._lookup_item(model, field_name, item, mode))
m2m_lists[field_name].append(
self._lookup_item(model, field_name, item, mode)
)
else:
m2m["many"] = False
# handles if it's a 1:1 field
if hasattr(field, "Meta"):
model = field.Meta.model
item = self.validated_data.pop(field_name, None)
# creates/gets objects associaated with list and creates list of objects
m2m_lists[field_name] = self._lookup_item(model, field_name, item, mode)
m2m_lists[field_name] = self._lookup_item(
model, field_name, item, mode
)
else:
# handles if it's accidentally added (e.g. Integer field, character field, etc.)
ignore_fields.add(field_name)
Expand Down
23 changes: 17 additions & 6 deletions backend/accounts/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ class User(AbstractUser):
pennid = models.IntegerField(primary_key=True)
uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False)
preferred_name = models.CharField(max_length=225, blank=True)
profile_pic = models.ImageField(upload_to=get_user_image_filepath, blank=True, null=True)
profile_pic = models.ImageField(
upload_to=get_user_image_filepath, blank=True, null=True
)

VERIFICATION_EXPIRATION_MINUTES = 10

Expand All @@ -88,7 +90,9 @@ class Student(models.Model):
)
major = models.ManyToManyField(Major, blank=True)
school = models.ManyToManyField(School, blank=True)
graduation_year = models.PositiveIntegerField(validators=[MinValueValidator(1740)], null=True)
graduation_year = models.PositiveIntegerField(
validators=[MinValueValidator(1740)], null=True
)

def __str__(self):
return self.user.username
Expand All @@ -104,7 +108,9 @@ def ensure_student_object(sender, instance, created, **kwargs):


class Email(models.Model):
user = models.ForeignKey(get_user_model(), related_name="emails", on_delete=models.CASCADE)
user = models.ForeignKey(
get_user_model(), related_name="emails", on_delete=models.CASCADE
)
value = models.EmailField(unique=True)
primary = models.BooleanField(default=False)
verification_code = models.CharField(max_length=6, blank=True, null=True)
Expand Down Expand Up @@ -146,7 +152,9 @@ def add_privacy_resource(sender, instance, created, **kwargs):
to true.
"""
users = User.objects.all()
settings = [PrivacySetting(user=user, resource=instance, enabled=True) for user in users]
settings = [
PrivacySetting(user=user, resource=instance, enabled=True) for user in users
]
# Bulk creating for all User objects
PrivacySetting.objects.bulk_create(settings, ignore_conflicts=True)

Expand All @@ -155,7 +163,9 @@ class PrivacySetting(models.Model):
user = models.ForeignKey(
get_user_model(), related_name="privacy_setting", on_delete=models.CASCADE
)
resource = models.ForeignKey(PrivacyResource, related_name="resource", on_delete=models.CASCADE)
resource = models.ForeignKey(
PrivacyResource, related_name="resource", on_delete=models.CASCADE
)
enabled = models.BooleanField(default=True)


Expand All @@ -171,6 +181,7 @@ def load_privacy_settings(sender, instance, created, **kwargs):
if not instance.privacy_setting.exists():
resources = PrivacyResource.objects.all()
settings = [
PrivacySetting(user=instance, resource=resource, enabled=True) for resource in resources
PrivacySetting(user=instance, resource=resource, enabled=True)
for resource in resources
]
PrivacySetting.objects.bulk_create(settings, ignore_conflicts=True)
52 changes: 40 additions & 12 deletions backend/accounts/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ def create(self, validated_data):
instance = super().create(validated_data)
instance.verified = False
instance.primary = False
instance.verification_code = get_random_string(length=6, allowed_chars="1234567890")
instance.verification_code = get_random_string(
length=6, allowed_chars="1234567890"
)
# timestamp is set by django
instance.save()
sendSMSVerification(instance.value, instance.verification_code)
Expand All @@ -73,24 +75,37 @@ def update(self, instance, validated_data):
elapsed_time = timezone.now() - instance.verification_timestamp
if (
validated_data["verification_code"] == instance.verification_code
and elapsed_time.total_seconds() < User.VERIFICATION_EXPIRATION_MINUTES * 60
and elapsed_time.total_seconds()
< User.VERIFICATION_EXPIRATION_MINUTES * 60
):
if self.context["request"].user.phone_numbers.filter(verified=True).count() == 0:
if (
self.context["request"]
.user.phone_numbers.filter(verified=True)
.count()
== 0
):
instance.primary = True
instance.verified = True
elif elapsed_time.total_seconds() >= User.VERIFICATION_EXPIRATION_MINUTES * 60:
elif (
elapsed_time.total_seconds()
>= User.VERIFICATION_EXPIRATION_MINUTES * 60
):
raise serializers.ValidationError(
detail={"detail": "Verification code has expired"}
)
else:
raise serializers.ValidationError(detail={"detail": "Incorrect verification code"})
raise serializers.ValidationError(
detail={"detail": "Incorrect verification code"}
)
if "primary" in validated_data and validated_data["primary"]:
if instance.verified:
self.context["request"].user.phone_numbers.all().update(primary=False)
instance.primary = True
else:
raise serializers.ValidationError(
detail={"detail": "Must verify point of contact before marking as primary"}
detail={
"detail": "Must verify point of contact before marking as primary"
}
)
instance.save()
return instance
Expand All @@ -107,7 +122,9 @@ def create(self, validated_data):
instance = super().create(validated_data)
instance.verified = False
instance.primary = False
instance.verification_code = get_random_string(length=6, allowed_chars="1234567890")
instance.verification_code = get_random_string(
length=6, allowed_chars="1234567890"
)
# timestamp is set by django
instance.save()
sendEmailVerification(instance.value, instance.verification_code)
Expand All @@ -118,24 +135,35 @@ def update(self, instance, validated_data):
elapsed_time = timezone.now() - instance.verification_timestamp
if (
validated_data["verification_code"] == instance.verification_code
and elapsed_time.total_seconds() < User.VERIFICATION_EXPIRATION_MINUTES * 60
and elapsed_time.total_seconds()
< User.VERIFICATION_EXPIRATION_MINUTES * 60
):
if self.context["request"].user.emails.filter(verified=True).count() == 0:
if (
self.context["request"].user.emails.filter(verified=True).count()
== 0
):
instance.primary = True
instance.verified = True
elif elapsed_time.total_seconds() >= User.VERIFICATION_EXPIRATION_MINUTES * 60:
elif (
elapsed_time.total_seconds()
>= User.VERIFICATION_EXPIRATION_MINUTES * 60
):
raise serializers.ValidationError(
detail={"detail": "Verification code has expired"}
)
else:
raise serializers.ValidationError(detail={"detail": "Incorrect verification code"})
raise serializers.ValidationError(
detail={"detail": "Incorrect verification code"}
)
if "primary" in validated_data and validated_data["primary"]:
if instance.verified:
self.context["request"].user.emails.all().update(primary=False)
instance.primary = True
else:
raise serializers.ValidationError(
detail={"detail": "Must verify point of contact before marking as primary"}
detail={
"detail": "Must verify point of contact before marking as primary"
}
)
instance.save()
return instance
Expand Down
8 changes: 6 additions & 2 deletions backend/accounts/update_majors.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ def update_all_majors():

listed_majors = set()
# iterate through all list tags with "item" in the class (all programs)
for program in soup.find_all("li", class_=lambda value: value and value.startswith("item ")):
for program in soup.find_all(
"li", class_=lambda value: value and value.startswith("item ")
):
curr_filter_list = program.attrs["class"]
# check if entry meets relevant desired and excluded filter criteria
if not contains_filters(
Expand All @@ -58,7 +60,9 @@ def update_all_majors():
curr_degree_type = Major.DEGREE_PROFESSIONAL

# create new major entry if it does not already exist
Major.objects.update_or_create(name=major_name, defaults={"degree_type": curr_degree_type})
Major.objects.update_or_create(
name=major_name, defaults={"degree_type": curr_degree_type}
)

# keep track of found majors
listed_majors.add(major_name)
Expand Down
Loading

0 comments on commit 216dde8

Please sign in to comment.