Compare commits

..
26 Commits
Author SHA1 Message Date
Kita Trofimov 0440c25395 style(database): Fixed the issue with long function declarations 2025-10-26 21:20:44 +03:00
Kita Trofimov d4a561b79b style(database): Changed logging 2025-10-26 21:16:23 +03:00
Kita Trofimov 7786680f43 fix(database): Fixed the database connection 2025-10-26 21:16:23 +03:00
Kita Trofimov 33c3b81f6e style(database): Refactor repository name 2025-10-26 21:16:23 +03:00
Kita Trofimov 6006e074d8 fix(model/user.py): Removed unnecesary methods 2025-10-26 21:16:23 +03:00
Kita Trofimov 771f7e0549 feat(database/repositories/user_repository.py): A new login verification method has been added 2025-10-26 21:16:23 +03:00
Kita Trofimov fd1b7df93a feat(database/repositories/ai_prediction_repository.py): Added new repository AIPredictionsRepository 2025-10-26 21:16:23 +03:00
Kita Trofimov 88c4460da9 feat(model/ai_prediction.py): Added new model AIPrediction 2025-10-26 21:16:23 +03:00
Kita Trofimov 51bf856434 feat(database/repositories/inventory_repository.py): Added inventory repository 2025-10-26 21:16:23 +03:00
Kita Trofimov 0ded143c55 feat(database/repositories/product_repository.py): Added product repository 2025-10-26 21:16:23 +03:00
Kita Trofimov 056d800c4f feat(database/repositories/robot_repository.py): Added robot_repository 2025-10-26 21:16:23 +03:00
Kita Trofimov 3be4556844 feat(database/repositories/user_repository.py): Added user repository 2025-10-26 21:16:23 +03:00
Kita Trofimov 928677fea8 feat(database): Implemented database connection 2025-10-26 21:16:23 +03:00
Kita Trofimov e80c5645f1 feat(model): Added correct data models 2025-10-26 21:16:23 +03:00
Sweetbread 70041fa58e feat(jwt): add iat field 2025-10-26 21:16:23 +03:00
Sweetbread 6f478d717a feat(log): use loguru 2025-10-26 21:16:23 +03:00
Sweetbread be5732bc32 refactor(auth): remove /api/auth/* handlers to api/auth.py 2025-10-26 21:16:23 +03:00
Sweetbread 4ad7869e27 refactor(user): rename to toJson back 2025-10-26 21:16:23 +03:00
Sweetbread 67c06a0203 feat(auth): add data validation 2025-10-26 21:16:23 +03:00
Sweetbread df5317432d refactor(user): change class name to uppercase 2025-10-26 21:16:23 +03:00
Sweetbread 96a310a80d fix(env): ensure the .env is loaded 2025-10-26 21:16:22 +03:00
Kirill ec985a808d fix(api/auth/loginapi.py, app.py, utils/PostgressConnect.py, utils/createLogger.py, utils/loadDotEnv.py): Review fix
https://g.codrs.ru/Hackaton/Backend/pulls/2#issuecomment-23
https://g.codrs.ru/Hackaton/Backend/pulls/2#issuecomment-31
2025-10-26 21:16:17 +03:00
Kirill f93b94531c fix(utils/token.py): Code review fix
https://g.codrs.ru/Hackaton/Backend/pulls/2#issuecomment-24
2025-10-25 21:01:45 +03:00
Kirill 22da586aec fix(app.py): Code review fix
https://g.codrs.ru/Hackaton/Backend/pulls/2#issuecomment-30
2025-10-25 20:59:41 +03:00
Kirill 5058df8b7d fix(model/user.py): Code review fix
https://g.codrs.ru/Hackaton/Backend/pulls/2#issuecomment-20
https://g.codrs.ru/Hackaton/Backend/pulls/2#issuecomment-25
https://g.codrs.ru/Hackaton/Backend/pulls/2#issuecomment-21
2025-10-25 20:57:23 +03:00
Kirill 3a118c51b5 fix(api/auth/loginapi.py): Pull request review
https://g.codrs.ru/Hackaton/Backend/pulls/2#issuecomment-26
https://g.codrs.ru/Hackaton/Backend/pulls/2#issuecomment-20
https://g.codrs.ru/Hackaton/Backend/pulls/2#issuecomment-35
2025-10-25 20:53:48 +03:00
14 changed files with 148 additions and 100 deletions
+2
View File
@@ -0,0 +1,2 @@
KEY= # Key for JWT token
POSTGRES_URL=postgresql://
+28
View File
@@ -0,0 +1,28 @@
from flask import Blueprint, request, jsonify
from model.user import User
auth = Blueprint("auth", __name__)
@auth.route('/login', methods = ['POST'])
def login():
if request.is_json:
req = request.json
email = req.get('email')
password = req.get('password')
if not email or not password:
return "Request must have email and password", 400
if len(email.strip()) < 4 or '@' not in email or '.' not in email:
return "Email is incorrect", 400
if len(password.strip()) < 8:
return "Password is too short", 400
user = User(email, password)
return jsonify(user.toJson())
else:
return "Request is not a json", 400
-12
View File
@@ -1,12 +0,0 @@
from flask import Blueprint, request
from model.user import user
loginBP = Blueprint("loginapi", __name__)
@loginBP.route('/api/login', methods = ['POST'])
def login():
email = request.form['email']
password = request.form['password']
#if(isvalid(email, password)):
us = user.initialize(email, password)
return us.toJSON()
+7 -2
View File
@@ -1,6 +1,11 @@
from sys import exit
from flask import Flask
from api.loginapi import loginBP
from api.auth import auth
from utils.loadDotEnv import initializeENV
if not initializeENV():
exit(-1)
app = Flask(__name__)
app.register_blueprint(loginBP)
app.register_blueprint(auth, url_prefix='/api/auth')
+3 -3
View File
@@ -24,7 +24,7 @@ def get_connection() -> Generator[psycopg2.extensions.connection, None, None]:
conn = None
try:
conn = PSQLConnect()
logger.debug("Подключение к БД установлено")
logger.info("Подключение к БД установлено")
yield conn
except psycopg2.OperationalError as e:
logger.error(f"Ошибка подключения к БД: {e}")
@@ -39,7 +39,7 @@ def get_connection() -> Generator[psycopg2.extensions.connection, None, None]:
if conn:
try:
conn.close()
logger.debug("Соединение с БД закрыто")
logger.info("Соединение с БД закрыто")
except Exception as e:
logger.warning(f"Ошибка при закрытии соединения: {e}")
@@ -50,7 +50,7 @@ def test_connection() -> bool:
try:
cur.execute("SELECT version();")
version = cur.fetchone()
logger.debug(f"Версия PostgreSQL: {version[0]}")
logger.info(f"Версия PostgreSQL: {version[0]}")
return True
finally:
cur.close()
+14 -12
View File
@@ -23,7 +23,7 @@ class AIPredictionsRepository:
created_at=row[6]
) for row in cur.fetchall()
]
logger.debug(f"Получено {len(predictions)} прогнозов")
logger.info(f"Получено {len(predictions)} прогнозов")
return predictions
except Exception as e:
logger.error(f"Ошибка получения прогнозов: {e}")
@@ -36,7 +36,7 @@ class AIPredictionsRepository:
cur.execute("SELECT * FROM ai_predictions WHERE id = %s", (prediction_id,))
row = cur.fetchone()
if row:
logger.debug(f"Прогноз {prediction_id} найден")
logger.info(f"Прогноз {prediction_id} найден")
return AIPrediction(*row)
logger.warning(f"Прогноз {prediction_id} не найден")
return None
@@ -55,7 +55,7 @@ class AIPredictionsRepository:
LIMIT %s
""", (product_id, limit))
predictions = [AIPrediction(*row) for row in cur.fetchall()]
logger.debug(f"Получено {len(predictions)} прогнозов для товара {product_id}")
logger.info(f"Получено {len(predictions)} прогнозов для товара {product_id}")
return predictions
except Exception as e:
logger.error(f"Ошибка получения прогноза по товару {product_id}: {e}")
@@ -71,18 +71,20 @@ class AIPredictionsRepository:
ORDER BY product_id, prediction_date DESC
""")
predictions = [AIPrediction(*row) for row in cur.fetchall()]
logger.debug(f"Получено {len(predictions)} последних прогнозов по товарам")
logger.info(f"Получено {len(predictions)} последних прогнозов по товарам")
return predictions
except Exception as e:
logger.error(f"Ошибка получения последних прогнозов по товарам: {e}")
return []
def create_prediction(self,
product_id: str,
prediction_date: date,
days_until_stockout: int,
recommended_order: int,
confidence_score: float) -> Optional[int]:
def create_prediction(
self,
product_id: str,
prediction_date: date,
days_until_stockout: int,
recommended_order: int,
confidence_score: float
) -> Optional[int]:
try:
with get_connection() as conn:
with conn.cursor() as cur:
@@ -95,7 +97,7 @@ class AIPredictionsRepository:
prediction_id = cur.fetchone()[0]
conn.commit()
logger.debug(f"Создан новый прогноз ID: {prediction_id} для товара {product_id}")
logger.info(f"Создан новый прогноз ID: {prediction_id} для товара {product_id}")
return prediction_id
except Exception as e:
logger.error(f"Ошибка создания прогноза: {e}")
@@ -111,7 +113,7 @@ class AIPredictionsRepository:
""", (older_than_days,))
deleted_count = cur.rowcount
conn.commit()
logger.debug(f"Удалено {deleted_count} старых прогнозов старше {older_than_days} дней")
logger.info(f"Удалено {deleted_count} старых прогнозов старше {older_than_days} дней")
return deleted_count
except Exception as e:
logger.error(f"Ошибка удаления старых прогнозов: {e}")
+19 -17
View File
@@ -27,7 +27,7 @@ class InventoryRepository:
created_at=row[9]
) for row in cur.fetchall()
]
logger.debug(f"Получено {len(records)} записей инвентаризации")
logger.info(f"Получено {len(records)} записей инвентаризации")
return records
except Exception as e:
logger.error(f"Ошибка получения истории инвентаризации: {e}")
@@ -40,7 +40,7 @@ class InventoryRepository:
cur.execute("SELECT * FROM inventory_history WHERE id = %s", (record_id,))
row = cur.fetchone()
if row:
logger.debug(f"Запись инвентаризации {record_id} найдена")
logger.info(f"Запись инвентаризации {record_id} найдена")
return InventoryRecord(*row)
logger.warning(f"Запись инвентаризации {record_id} не найдена")
return None
@@ -48,15 +48,17 @@ class InventoryRepository:
logger.error(f"Ошибка получения записи инвентаризации {record_id}: {e}")
return None
def create_record(self,
robot_id: str,
product_id: str,
quantity: int,
zone: str,
row_number: int,
shelf_number: int,
status: str,
scanned_at: datetime) -> Optional[int]:
def create_record(
self,
robot_id: str,
product_id: str,
quantity: int,
zone: str,
row_number: int,
shelf_number: int,
status: str,
scanned_at: datetime
) -> Optional[int]:
try:
with get_connection() as conn:
with conn.cursor() as cur:
@@ -69,7 +71,7 @@ class InventoryRepository:
record_id = cur.fetchone()[0]
conn.commit()
logger.debug(f"Создана новая запись инвентаризации ID: {record_id}")
logger.info(f"Создана новая запись инвентаризации ID: {record_id}")
return record_id
except Exception as e:
logger.error(f"Ошибка создания записи инвентаризации: {e}")
@@ -85,7 +87,7 @@ class InventoryRepository:
ORDER BY product_id, scanned_at DESC
""")
records = [InventoryRecord(*row) for row in cur.fetchall()]
logger.debug(f"Получено {len(records)} последних записей инвентаризации по товарам")
logger.info(f"Получено {len(records)} последних записей инвентаризации по товарам")
return records
except Exception as e:
logger.error(f"Ошибка получения последней записи инвентаризации по каждому товару: {e}")
@@ -102,7 +104,7 @@ class InventoryRepository:
LIMIT %s
""", (product_id, limit))
records = [InventoryRecord(*row) for row in cur.fetchall()]
logger.debug(f"Получено {len(records)} записей инвентаризации для товара {product_id}")
logger.info(f"Получено {len(records)} записей инвентаризации для товара {product_id}")
return records
except Exception as e:
logger.error(f"Ошибка получения записи инвентаризации по продукту {product_id}: {e}")
@@ -119,7 +121,7 @@ class InventoryRepository:
LIMIT %s
""", (robot_id, limit))
records = [InventoryRecord(*row) for row in cur.fetchall()]
logger.debug(f"Получено {len(records)} записей инвентаризации для робота {robot_id}")
logger.info(f"Получено {len(records)} записей инвентаризации для робота {robot_id}")
return records
except Exception as e:
logger.error(f"Ошибка получения записи инвентаризации по роботу {robot_id}: {e}")
@@ -136,7 +138,7 @@ class InventoryRepository:
LIMIT %s
""", (zone, limit))
records = [InventoryRecord(*row) for row in cur.fetchall()]
logger.debug(f"Получено {len(records)} записей инвентаризации для зоны {zone}")
logger.info(f"Получено {len(records)} записей инвентаризации для зоны {zone}")
return records
except Exception as e:
logger.error(f"Ошибка получения записи инвентаризации по зоне {zone}: {e}")
@@ -153,7 +155,7 @@ class InventoryRepository:
ORDER BY scanned_at DESC
""", (hours,))
records = [InventoryRecord(*row) for row in cur.fetchall()]
logger.debug(f"Получено {len(records)} критических товаров за последние {hours} часов")
logger.info(f"Получено {len(records)} критических товаров за последние {hours} часов")
return records
except Exception as e:
logger.error(f"Ошибка получения товаров с критическим статусом: {e}")
+8 -8
View File
@@ -20,7 +20,7 @@ class ProductRepository:
optimal_stock=row[4]
) for row in cur.fetchall()
]
logger.debug(f"Получено {len(products)} товаров")
logger.info(f"Получено {len(products)} товаров")
return products
except Exception as e:
logger.error(f"Ошибка получения продуктов: {e}")
@@ -33,7 +33,7 @@ class ProductRepository:
cur.execute("SELECT * FROM products WHERE id = %s", (product_id,))
row = cur.fetchone()
if row:
logger.debug(f"Товар {product_id} найден")
logger.info(f"Товар {product_id} найден")
return Product(*row)
logger.warning(f"Товар {product_id} не найден")
return None
@@ -47,7 +47,7 @@ class ProductRepository:
with conn.cursor() as cur:
cur.execute("SELECT * FROM products WHERE category = %s ORDER BY name", (category,))
products = [Product(*row) for row in cur.fetchall()]
logger.debug(f"Получено {len(products)} товаров категории {category}")
logger.info(f"Получено {len(products)} товаров категории {category}")
return products
except Exception as e:
logger.error(f"Ошибка получения товаров по категории {category}: {e}")
@@ -65,7 +65,7 @@ class ProductRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.debug(f"Создан новый товар {product_id}: {name}")
logger.info(f"Создан новый товар {product_id}: {name}")
else:
logger.warning(f"Не удалось создать товар {product_id}")
return success
@@ -108,7 +108,7 @@ class ProductRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.debug(f"Товар {product_id} успешно обновлен")
logger.info(f"Товар {product_id} успешно обновлен")
else:
logger.warning(f"Товар {product_id} не найден для обновления")
return success
@@ -124,7 +124,7 @@ class ProductRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.debug(f"Товар {product_id} удален")
logger.info(f"Товар {product_id} удален")
else:
logger.warning(f"Товар {product_id} не найден для удаления")
return success
@@ -142,7 +142,7 @@ class ProductRepository:
ORDER BY name
""", (f'%{search_term}%', f'%{search_term}%'))
products = [Product(*row) for row in cur.fetchall()]
logger.debug(f"Найдено {len(products)} товаров по запросу '{search_term}'")
logger.info(f"Найдено {len(products)} товаров по запросу '{search_term}'")
return products
except Exception as e:
logger.error(f"Ошибка поиска товаров по названию '{search_term}': {e}")
@@ -161,7 +161,7 @@ class ProductRepository:
ORDER BY p.name
""")
products = [Product(*row) for row in cur.fetchall()]
logger.debug(f"Получено {len(products)} товаров с низким запасом")
logger.info(f"Получено {len(products)} товаров с низким запасом")
return products
except Exception as e:
logger.error(f"Ошибка получения товаров с низким запасом: {e}")
+23 -19
View File
@@ -22,7 +22,7 @@ class RobotRepository:
current_shelf=row[6]
) for row in cur.fetchall()
]
logger.debug(f"Получено {len(robots)} роботов")
logger.info(f"Получено {len(robots)} роботов")
return robots
except Exception as e:
logger.error(f"Ошибка получения всех роботов: {e}")
@@ -35,7 +35,7 @@ class RobotRepository:
cur.execute("SELECT * FROM robots WHERE id = %s", (robot_id,))
row = cur.fetchone()
if row:
logger.debug(f"Робот {robot_id} найден")
logger.info(f"Робот {robot_id} найден")
return Robot(*row)
logger.warning(f"Робот {robot_id} не найден")
return None
@@ -43,13 +43,15 @@ class RobotRepository:
logger.error(f"Ошибка получения робота {robot_id}: {e}")
return None
def update_robot(self,
robot_id: str,
status: str = None,
battery_level: int = None,
current_zone: str = None,
current_row: int = None,
current_shelf: int = None) -> bool:
def update_robot(
self,
robot_id: str,
status: str = None,
battery_level: int = None,
current_zone: str = None,
current_row: int = None,
current_shelf: int = None
) -> bool:
try:
with get_connection() as conn:
with conn.cursor() as cur:
@@ -83,7 +85,7 @@ class RobotRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.debug(f"Робот {robot_id} успешно обновлен")
logger.info(f"Робот {robot_id} успешно обновлен")
else:
logger.warning(f"Робот {robot_id} не найден для обновления")
return success
@@ -97,7 +99,7 @@ class RobotRepository:
with conn.cursor() as cur:
cur.execute("SELECT * FROM robots WHERE status = %s ORDER BY id", (status,))
robots = [Robot(*row) for row in cur.fetchall()]
logger.debug(f"Получено {len(robots)} роботов со статусом {status}")
logger.info(f"Получено {len(robots)} роботов со статусом {status}")
return robots
except Exception as e:
logger.error(f"Ошибка получения роботов по статусу {status}: {e}")
@@ -113,7 +115,7 @@ class RobotRepository:
ORDER BY battery_level ASC
""", (threshold,))
robots = [Robot(*row) for row in cur.fetchall()]
logger.debug(f"Получено {len(robots)} роботов с низким зарядом (<{threshold}%)")
logger.info(f"Получено {len(robots)} роботов с низким зарядом (<{threshold}%)")
return robots
except Exception as e:
logger.error(f"Ошибка получения роботов с низким зарядом: {e}")
@@ -125,16 +127,18 @@ class RobotRepository:
with conn.cursor() as cur:
cur.execute("SELECT * FROM robots WHERE current_zone = %s ORDER BY id", (zone,))
robots = [Robot(*row) for row in cur.fetchall()]
logger.debug(f"Получено {len(robots)} роботов в зоне {zone}")
logger.info(f"Получено {len(robots)} роботов в зоне {zone}")
return robots
except Exception as e:
logger.error(f"Ошибка получения роботов в зоне {zone}: {e}")
return []
def create_robot(self,
robot_id: str,
status: str = 'active',
battery_level: int = 100) -> bool:
def create_robot(
self,
robot_id: str,
status: str = 'active',
battery_level: int = 100
) -> bool:
try:
with get_connection() as conn:
with conn.cursor() as cur:
@@ -145,7 +149,7 @@ class RobotRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.debug(f"Создан новый робот {robot_id}")
logger.info(f"Создан новый робот {robot_id}")
else:
logger.warning(f"Не удалось создать робота {robot_id}")
return success
@@ -161,7 +165,7 @@ class RobotRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.debug(f"Робот {robot_id} удален")
logger.info(f"Робот {robot_id} удален")
else:
logger.warning(f"Робот {robot_id} не найден для удаления")
return success
+19 -17
View File
@@ -21,7 +21,7 @@ class UserRepository:
created_at=row[5]
) for row in cur.fetchall()
]
logger.debug(f"Получено {len(users)} пользователей")
logger.info(f"Получено {len(users)} пользователей")
return users
except Exception as e:
logger.error(f"Ошибка получения пользователей: {e}")
@@ -34,7 +34,7 @@ class UserRepository:
cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
row = cur.fetchone()
if row:
logger.debug(f"Пользователь {user_id} найден")
logger.info(f"Пользователь {user_id} найден")
return User(*row)
logger.warning(f"Пользователь {user_id} не найден")
return None
@@ -49,7 +49,7 @@ class UserRepository:
cur.execute("SELECT * FROM users WHERE email = %s", (email,))
row = cur.fetchone()
if row:
logger.debug(f"Пользователь с email {email} найден")
logger.info(f"Пользователь с email {email} найден")
return User(*row)
logger.warning(f"Пользователь с email {email} не найден")
return None
@@ -57,11 +57,13 @@ class UserRepository:
logger.error(f"Ошибка получения пользователя по email {email}: {e}")
return None
def create_user(self,
email: str,
password_hash: str,
name: str,
role: str) -> Optional[User]:
def create_user(
self,
email: str,
password_hash: str,
name: str,
role: str
) -> Optional[User]:
try:
with get_connection() as conn:
with conn.cursor() as cur:
@@ -75,7 +77,7 @@ class UserRepository:
conn.commit()
if row:
logger.debug(f"Создан новый пользователь {email} с ID {row[0]}")
logger.info(f"Создан новый пользователь {email} с ID {row[0]}")
return User(*row)
logger.warning(f"Не удалось создать пользователя {email}")
return None
@@ -109,7 +111,7 @@ class UserRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.debug(f"Пользователь {user_id} успешно обновлен")
logger.info(f"Пользователь {user_id} успешно обновлен")
else:
logger.warning(f"Пользователь {user_id} не найден для обновления")
return success
@@ -125,7 +127,7 @@ class UserRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.debug(f"Пользователь {user_id} удален")
logger.info(f"Пользователь {user_id} удален")
else:
logger.warning(f"Пользователь {user_id} не найден для удаления")
return success
@@ -139,7 +141,7 @@ class UserRepository:
with conn.cursor() as cur:
cur.execute("SELECT * FROM users WHERE role = %s ORDER BY name", (role,))
users = [User(*row) for row in cur.fetchall()]
logger.debug(f"Получено {len(users)} пользователей с ролью {role}")
logger.info(f"Получено {len(users)} пользователей с ролью {role}")
return users
except Exception as e:
logger.error(f"Ошибка получения пользователей по роли {role}: {e}")
@@ -157,7 +159,7 @@ class UserRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.debug(f"Пароль пользователя {user_id} изменен")
logger.info(f"Пароль пользователя {user_id} изменен")
else:
logger.warning(f"Пользователь {user_id} не найден для смены пароля")
return success
@@ -175,7 +177,7 @@ class UserRepository:
""", (email, password_hash))
row = cur.fetchone()
if row:
logger.debug(f"Успешная аутентификация пользователя {email}")
logger.info(f"Успешная аутентификация пользователя {email}")
return User(*row)
logger.warning(f"Неудачная аутентификация пользователя {email}")
return None
@@ -193,7 +195,7 @@ class UserRepository:
""", (email, password_hash))
is_valid = cur.fetchone() is not None
if is_valid:
logger.debug(f"Валидные учетные данные для пользователя {email}")
logger.info(f"Валидные учетные данные для пользователя {email}")
else:
logger.warning(f"Невалидные учетные данные для пользователя {email}")
return is_valid
@@ -208,9 +210,9 @@ class UserRepository:
cur.execute("SELECT 1 FROM users WHERE email = %s", (email,))
exists = cur.fetchone() is not None
if exists:
logger.debug(f"Пользователь с email {email} существует")
logger.info(f"Пользователь с email {email} существует")
else:
logger.debug(f"Пользователь с email {email} не существует")
logger.info(f"Пользователь с email {email} не существует")
return exists
except Exception as e:
logger.error(f"Ошибка проверки существования пользователя {email}: {e}")
+2 -1
View File
@@ -1,4 +1,5 @@
flask==3.1.2
python-dotenv
psycopg-binary
psycopg2-binary
pyjwt
loguru
+11
View File
@@ -1,5 +1,6 @@
from dataclasses import dataclass
from datetime import datetime
from utils.token import generateKey
@dataclass
@@ -10,3 +11,13 @@ class User:
name: str
role: str
created_at: datetime
def __init__(self, email: str, passwd: str):
#us = getUsModel() #возвращает словарь
self.id = 1#us['id']
self.name = 'Bob'#us['name']
self.role = 'Backend'#us['role']
self.token = generateKey(email, passwd)
def toJson(self):
return {"user": {"id": self.id, "name": self.name, "role": self.role}, "token": self.token}
+10 -8
View File
@@ -1,12 +1,14 @@
import os
from dotenv import load_dotenv
from loguru import logger as log
def initializeENV():
dotenv_path = '../.env'
if os.path.exists(dotenv_path):
load_dotenv(dotenv_path)
print('.env is loaded')
return 1
DOTENV_PATH = '.env'
def initializeENV() -> bool:
if os.path.exists(DOTENV_PATH):
load_dotenv(DOTENV_PATH)
log.info('.env is loaded')
return True
else:
print('.env isn`t loaded')
return 0
log.error('.env isn`t loaded')
return False
+2 -1
View File
@@ -1,7 +1,8 @@
import jwt
import os
from time import time
def generateKey(email, passwd):
key = os.getenv('KEY')
encoded = jwt.encode({f"{email}": f"{passwd}"}, key, algorithm="HS256")
encoded = jwt.encode({email: passwd, 'iat': time()}, key, algorithm="HS256")
return encoded