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.
76 lines
2.5 KiB
76 lines
2.5 KiB
from django.shortcuts import render, reverse, get_object_or_404 |
|
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 |
|
from . import services |
|
|
|
|
|
def leave_comment(request, post_id): |
|
parent: Union[Comment, None] |
|
post: Post |
|
author: Union[CommentAuthor, None] |
|
|
|
post = get_object_or_404(Post, pk=post_id) |
|
|
|
# сделать проверку более вменяемой |
|
parent_id = request.POST["reply_to"].strip() |
|
|
|
if not parent_id: |
|
parent = None |
|
else: |
|
try: |
|
parent = Comment.objects.get(id=parent_id, post=post_id) |
|
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"].strip() |
|
|
|
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, |
|
) |
|
response = HttpResponseRedirect(reverse("posts:detail", args=(post.id,))) |
|
response.set_cookie("nickname", services.encode_nickname(nickname), max_age=300) |
|
|
|
return response |
|
|
|
|
|
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.strip(), author_secret_hash=hash |
|
) |
|
except IntegrityError: |
|
# если имя/хеш не совпадают, то игнорируем такого автора и отображаем ником |
|
author = None |
|
|
|
return author
|
|
|