Skip to content

Commit

Permalink
Merge pull request #402 from Pet-projects-CodePET/refactor/requests_a…
Browse files Browse the repository at this point in the history
…nd_serializers

refactor: Поправил ошибки с отоббражение избранного профиля, так же п…
  • Loading branch information
Denis-Shtanskiy authored Jan 6, 2025
2 parents 17206fd + 1f34895 commit b170b7c
Show file tree
Hide file tree
Showing 7 changed files with 140 additions and 31 deletions.
6 changes: 2 additions & 4 deletions src/backend/api/v1/profile/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,5 @@
"span",
# разрешенные теги котоыре не нужно очищать
]
ALLOWED_ATTRIBUTES_BY_FRONT = {
"span": ["class", "style", "contenteditable"],
# разрещенные атрибуты.
}
ALLOWED_ATTRIBUTES_BY_FRONT = ["class", "style", "contenteditable"]
# разрещенные атрибуты.
23 changes: 15 additions & 8 deletions src/backend/api/v1/profile/serializers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import html
from typing import ClassVar, Optional

import bleach
from bleach.css_sanitizer import CSSSanitizer
from bleach.sanitizer import Cleaner
from django.core.validators import RegexValidator
from django.db.models import Q
from rest_framework import serializers
Expand All @@ -14,11 +15,10 @@
ProfessionSerializer,
SkillSerializer,
)

# from api.v1.profile.constants import (
# ALLOWED_ATTRIBUTES_BY_FRONT,
# ALLOWED_TAGS_BY_FRONT,
# )
from api.v1.profile.constants import (
ALLOWED_ATTRIBUTES_BY_FRONT,
ALLOWED_TAGS_BY_FRONT,
)
from apps.general.constants import MAX_SKILLS, MAX_SKILLS_MESSAGE
from apps.general.models import Profession
from apps.profile.constants import MAX_SPECIALISTS, MAX_SPECIALISTS_MESSAGE
Expand All @@ -31,6 +31,12 @@
USERNAME_REGEX,
)

cleaner = Cleaner(
tags=ALLOWED_TAGS_BY_FRONT,
attributes=ALLOWED_ATTRIBUTES_BY_FRONT,
css_sanitizer=CSSSanitizer(),
)


class CurrentProfile(serializers.CurrentUserDefault):
"""Получение профиля текущего пользователя."""
Expand Down Expand Up @@ -270,6 +276,7 @@ def validate_about(self, value):
Метод валидации и защиты от потенциально вредоносных
HTML-тегов и атрибутов.
"""

safe_about = bleach.clean(value)
safe_about = cleaner.clean(
value,
) # защита потенциально вредоносных HTML-тегов и атрибутов
return safe_about
33 changes: 15 additions & 18 deletions src/backend/api/v1/projects/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
from itertools import chain
from typing import Any, ClassVar, Dict, Optional, OrderedDict, Tuple

import bleach
from bleach.css_sanitizer import CSSSanitizer
from bleach.sanitizer import Cleaner
from django.db import transaction
from rest_framework import serializers

Expand Down Expand Up @@ -36,6 +37,12 @@
ProjectSpecialist,
)

cleaner = Cleaner(
tags=ALLOWED_TAGS_BY_FRONT,
attributes=ALLOWED_ATTRIBUTES_BY_FRONT,
css_sanitizer=CSSSanitizer(),
)


class DirectionSerializer(CustomModelSerializer):
"""Сериализатор направления разработки."""
Expand Down Expand Up @@ -229,10 +236,8 @@ def validate_description(self, value):
HTML-тегов и атрибутов.
"""

safe_description = bleach.clean(
safe_description = cleaner.clean(
value,
tags=ALLOWED_TAGS_BY_FRONT,
attributes=ALLOWED_ATTRIBUTES_BY_FRONT,
)
return safe_description

Expand Down Expand Up @@ -407,10 +412,8 @@ class Meta:
fields: ClassVar[Tuple[str, ...]] = ("cover_letter",)

def validate_cover_letter(self, value):
escaped_html = bleach.clean(
escaped_html = cleaner.clean(
value,
tags=ALLOWED_TAGS_BY_FRONT,
attributes=ALLOWED_ATTRIBUTES_BY_FRONT,
) # защита потенциально вредоносных HTML-тегов и атрибутов
return escaped_html

Expand Down Expand Up @@ -544,10 +547,8 @@ def validate(self, attrs) -> Dict[str, Any]:
return attrs

def validate_cover_letter(self, value):
escaped_html = bleach.clean(
escaped_html = cleaner.clean(
value,
tags=ALLOWED_TAGS_BY_FRONT,
attributes=ALLOWED_ATTRIBUTES_BY_FRONT,
) # защита потенциально вредоносных HTML-тегов и атрибутов
return escaped_html

Expand Down Expand Up @@ -590,14 +591,12 @@ def to_representation(self, instance):

def get_is_favorite_profile(self, obj) -> bool:
"""
Метод возвращает True если Владелец добавил участника в избранное.
В противном случе возвращает False.
Метод возвращает True если владелец добавил участника в избранное.
Иначе False.
"""
user = self.context.get("request").user
if user.is_authenticated:
return obj.request_participants.favorited_by.filter(
id=user.pk
).exists()
return obj.user.profile.favorited_by.filter(id=user.pk).exists()
return False

def get_request_status(self, obj) -> str:
Expand Down Expand Up @@ -755,10 +754,8 @@ def validate(self, attrs) -> OrderedDict:
return attrs

def validate_cover_letter(self, value):
escaped_html = bleach.clean(
escaped_html = cleaner.clean(
value,
tags=ALLOWED_TAGS_BY_FRONT,
attributes=ALLOWED_ATTRIBUTES_BY_FRONT,
) # защита потенциально вредоносных HTML-тегов и атрибутов
return escaped_html

Expand Down
2 changes: 1 addition & 1 deletion src/backend/apps/profile/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
REGEX_PROFILE_NAME = r"^[a-zA-Zа-яА-ЯёЁ-]+$"
REGEX_PROFILE_NAME_MESSAGE = "Введите кириллицу или латиницу"
REGEX_PROFILE_ABOUT = (
r"^[\wа-яА-ЯёЁ0-9\s<>,.?!'\"/\-+:;@#\$%\^&\*\(\)\[\]\{\}]*$"
r"^[\wа-яА-ЯёЁ0-9\s<>,.?!'\"/\-+:;@#\$%\^&\*\(\)\[\]\{\}]*$|^<.*>$"
)
REGEX_PROFILE_ABOUT_MESSAGE = "Введите кириллицу или латиницу"
MAX_SPECIALISTS = 2
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Generated by Django 5.0.1 on 2025-01-06 11:38

import django.core.validators
from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("profile", "0010_add_trigramextension"),
]

operations = [
migrations.AlterField(
model_name="profile",
name="about",
field=models.TextField(
blank=True,
max_length=1500,
validators=[
django.core.validators.RegexValidator(
message="Введите кириллицу или латиницу",
regex="^[\\wа-яА-ЯёЁ0-9\\s<>,.?!'\\\"/\\-+:;@#\\$%\\^&\\*\\(\\)\\[\\]\\{\\}]*$|^<.*>$",
),
django.core.validators.MinLengthValidator(limit_value=20),
],
verbose_name="О себе",
),
),
migrations.AlterField(
model_name="profile",
name="name",
field=models.CharField(
max_length=30,
validators=[
django.core.validators.RegexValidator(
message="Введите кириллицу или латиницу",
regex="^[a-zA-Zа-яА-ЯёЁ-]+$",
),
django.core.validators.MinLengthValidator(
limit_value=2, message="Должно быть минимум символов"
),
],
verbose_name="Имя",
),
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Generated by Django 5.0.1 on 2025-01-06 11:38

import apps.general.fields
import django.core.validators
import re
from django.db import migrations


class Migration(migrations.Migration):
dependencies = [
(
"projects",
"0020_remove_invitationtoproject_projects_invitationtoproject_unique_request_per_project_and_more",
),
]

operations = [
migrations.AlterField(
model_name="invitationtoproject",
name="answer",
field=apps.general.fields.BaseTextField(
blank=True,
max_length=750,
null=True,
validators=[
django.core.validators.RegexValidator(
flags=re.RegexFlag["IGNORECASE"],
message="Поле может содержать: кириллические и латинские символы, цифры и спецсимовлы -!#$%%&'*+/=?^_;():@,.<>`{}~«»",
regex="(^[-%!#$&*'+/=?^_;():@,.<>`{|}~\\\"\\\\\\-«»0-9A-ZА-ЯЁ\\s]+)\\Z",
),
django.core.validators.MinLengthValidator(
limit_value=5,
message="Длина поля от 5 до 750 символов.",
),
],
verbose_name="Ответ",
),
),
migrations.AlterField(
model_name="participationrequest",
name="answer",
field=apps.general.fields.BaseTextField(
blank=True,
max_length=750,
null=True,
validators=[
django.core.validators.RegexValidator(
flags=re.RegexFlag["IGNORECASE"],
message="Поле может содержать: кириллические и латинские символы, цифры и спецсимовлы -!#$%%&'*+/=?^_;():@,.<>`{}~«»",
regex="(^[-%!#$&*'+/=?^_;():@,.<>`{|}~\\\"\\\\\\-«»0-9A-ZА-ЯЁ\\s]+)\\Z",
),
django.core.validators.MinLengthValidator(
limit_value=5,
message="Длина поля от 5 до 750 символов.",
),
],
verbose_name="Ответ",
),
),
]
1 change: 1 addition & 0 deletions src/backend/apps/projects/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ class ParticipationRequestAndInvitationBasemodel(CreatedModifiedFields):
answer = BaseTextField(
verbose_name="Ответ",
null=True,
blank=True,
)

class Meta:
Expand Down

0 comments on commit b170b7c

Please sign in to comment.