You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
79 lines
2.7 KiB
79 lines
2.7 KiB
from django.shortcuts import render, reverse |
|
from posts.models import Post |
|
from django.http import Http404, HttpResponseRedirect |
|
from .models import Comment, CommentAuthor |
|
from datetime import datetime |
|
from django.core.exceptions import ObjectDoesNotExist |
|
from django.db import IntegrityError |
|
import hashlib |
|
|
|
from typing import Union |
|
|
|
|
|
def leave_comment(request, post_id): |
|
parent: Union[Comment, None] |
|
|
|
try: |
|
post = Post.objects.get(id=post_id) |
|
except ObjectDoesNotExist: |
|
raise Http404("Пост не найден") |
|
|
|
# сделать проверку более вменяемой |
|
parent_id = request.POST["reply_to"] |
|
|
|
if parent_id == "": |
|
parent = None |
|
else: |
|
try: |
|
parent = Comment.objects.get(id=parent_id) |
|
# если комментарий, на который отвечает пользователь не к |
|
# этой статье, то игнорируем поле ответа |
|
if not parent in post.comment_set.all(): |
|
parent = None |
|
|
|
except ObjectDoesNotExist: |
|
parent = None |
|
|
|
# обработка секрета Перед записью в базу, нужно извлечь записи по |
|
# нику. Где поле author_secret_hash не null, нужно вычислить и |
|
# сравнить хэши; если хеши валидные то пишем в базу (еще раз уник не запишется); |
|
|
|
# если не передан секрет, то пользователь Anonym |
|
# если секрет не совпал, то польозхватель Anonym |
|
|
|
author = get_or_create_author(request.POST["name"], request.POST["secret"]) |
|
nickname = request.POST["name"] |
|
|
|
if not author: |
|
post.comment_set.create( |
|
nickname=nickname, |
|
comment_text=request.POST["text"], |
|
reply=parent, |
|
) |
|
else: |
|
post.comment_set.create( |
|
author=author, |
|
nickname=nickname, |
|
comment_text=request.POST["text"], |
|
reply=parent, |
|
) |
|
|
|
return HttpResponseRedirect(reverse("posts:detail", args=(post.id,))) |
|
|
|
|
|
def get_or_create_author(name: str, secret: str) -> Union[CommentAuthor, None]: |
|
|
|
if secret == "": |
|
return None |
|
|
|
hash = hashlib.md5(secret.encode("utf-8")).hexdigest() |
|
|
|
try: |
|
author, result = CommentAuthor.objects.get_or_create( |
|
author_name=name, author_secret_hash=hash |
|
) |
|
except IntegrityError: |
|
# если имя/хеш не совпадают, то игнорируем такого автора и отображаем ником |
|
author = None |
|
|
|
return author
|
|
|