From de99127541a29806e8bf9d5f4a0727ddc5b8704f Mon Sep 17 00:00:00 2001 From: Stepan Pilipenko Date: Tue, 21 Oct 2025 21:14:23 +0300 Subject: [PATCH] registration + login --- backend/api.py | 68 +++++++++++++++++++++++++++++++++++++++- backend/main.py | 16 +++++++--- backend/requirements.txt | 3 +- 3 files changed, 81 insertions(+), 6 deletions(-) diff --git a/backend/api.py b/backend/api.py index de51c13..9389204 100644 --- a/backend/api.py +++ b/backend/api.py @@ -1,4 +1,71 @@ from utils import * +import bcrypt +import uuid +from datetime import date +from psycopg2 import IntegrityError + +def hash_password(plain_password: str): + hashed_bytes = bcrypt.hashpw(plain_password.encode('utf-8'), bcrypt.gensalt()) + hashed_str = hashed_bytes.decode('utf-8') + return hashed_str + +class AuthError(Exception): + pass + +def login(email: str, password: str) : + connection = psycopg2.connect(**DB_CONFIG) + cursor = connection.cursor() + try: + cursor.execute("SELECT password,token FROM users WHERE mail = %s", (email,)) + result = cursor.fetchone() + + if result is None: + raise AuthError("Неверный email или пароль") + + print(result) + stored_hash, token = result + if not bcrypt.checkpw(password.encode('utf-8'), stored_hash.encode('utf-8')): + raise AuthError("Неверный email или пароль") + + if token is None: + # Опционально: можно сгенерировать новый токен здесь + raise AuthError("У пользователя отсутствует токен") + + return token + finally: + cursor.close() + + +def registration(nickname: str, password: str, email: str) -> str: + # Хэшируем пароль + hashed = hash_password(password) + token = str(uuid.uuid4()) + token_expiry_date = date.today().strftime("%Y.%m.%d") + + money = "100" + histories_id = "{}" + + connection = psycopg2.connect(**DB_CONFIG) + cursor = connection.cursor() + try: + cursor.execute( + "INSERT INTO users (nickname, mail, password, token, token_expiry_date, money, histories_id) " + "VALUES (%s, %s, %s, %s, %s, %s, %s)", + (nickname, email, hashed, token, token_expiry_date, money, histories_id) + ) + connection.commit() + print("Пользователь успешно создан") + return token + except IntegrityError as e: + connection.rollback() + if "email_uniq" in str(e) or "users_email_key" in str(e): + print("Ошибка: пользователь с таким email уже существует") + raise AuthError("Пользователь с таким email уже существует") from e + else: + print("Другая ошибка базы данных:", e) + raise + finally: + cursor.close() def get_products() -> list[dict]: connection = None @@ -19,7 +86,6 @@ def get_products() -> list[dict]: return res - def get_product(product_id: int): connection = None cursor = None diff --git a/backend/main.py b/backend/main.py index efa7574..bd232f3 100644 --- a/backend/main.py +++ b/backend/main.py @@ -1,8 +1,16 @@ from api import * if __name__ == "__main__": - products_json = get_products() - print(json.dumps(products_json, ensure_ascii=False, indent=2)) + # products_json = get_products() + # print(json.dumps(products_json, ensure_ascii=False, indent=2)) + # + # product1_json = get_product(1) + # print(json.dumps(product1_json, ensure_ascii=False, indent=2)) + + try: + # registration("Vasya1", "Vasya2005", "vasili_pupkin@gmail.com") + print(login("vasili_pupkin@gmail.com", "Vasy2005")) + + except Exception as e: + print(e) - product1_json = get_product(1) - print(json.dumps(product1_json, ensure_ascii=False, indent=2)) diff --git a/backend/requirements.txt b/backend/requirements.txt index 810ba6c..5550361 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -1 +1,2 @@ -psycopg2-binary \ No newline at end of file +psycopg2-binary +bcrypt \ No newline at end of file