app: Now disallows duplicate posts

This makes the proof-of-work system actually useful :3
This commit is contained in:
Yuki Joou 2023-06-04 22:57:24 +02:00
parent 10b7960dd9
commit f671d3f443

26
app.py
View file

@ -39,14 +39,25 @@ def get_all_quotes() -> list[Quote]:
return quotes return quotes
def add_quote(new_quote: Quote): def add_quote(new_quote: Quote) -> bool:
db_connexion = get_database_connection() db_connection = get_database_connection()
db_connexion.execute(
matching_quote = db_connection.execute(
"SELECT author, content, timestamp FROM quotes WHERE author = ? AND content = ?",
(new_quote.author, new_quote.content)
).fetchall()
if matching_quote:
# There is already an author and a quote with the same content, let's not do duplicates...
return False
db_connection.execute(
"INSERT INTO quotes (author, content) VALUES (?, ?)", "INSERT INTO quotes (author, content) VALUES (?, ?)",
(new_quote.author, new_quote.content) (new_quote.author, new_quote.content)
) )
db_connexion.commit() db_connection.commit()
db_connexion.close() db_connection.close()
return True
@app.route('/', methods=["POST", "GET"]) @app.route('/', methods=["POST", "GET"])
@ -62,8 +73,11 @@ def index():
else: else:
quote = Quote(form["username"], form["message"]) quote = Quote(form["username"], form["message"])
if quote.proof_of_work_is_valid(form["proof-of-work"]): if quote.proof_of_work_is_valid(form["proof-of-work"]):
add_quote(Quote(form["username"], form["message"])) if add_quote(Quote(form["username"], form["message"])):
message = "Your quote was added successfully" message = "Your quote was added successfully"
else:
message = "Couldn't add your quote. Is it a duplicate?"
response_code = 400
else: else:
message = "You didn't do the work, silly!" message = "You didn't do the work, silly!"
response_code = 400 response_code = 400