first commit

This commit is contained in:
2026-06-13 21:46:37 +03:00
commit 650b69a97d
131 changed files with 5951 additions and 0 deletions

BIN
server/models/.DS_Store vendored Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

108
server/models/audit.py Normal file
View File

@@ -0,0 +1,108 @@
import sqlite3
from dataclasses import dataclass
import hashlib
from typing import Optional
@dataclass
class AuditModel:
id: Optional[int] = None
user_id: Optional[int] = None
action: Optional[str] = None
endpoint: Optional[str] = None
created_at: Optional[str] = None
status: Optional[str] = None
class Audit:
def __init__(self, db_path="instance/app_database.db"):
self.db_path = db_path
self._create_audit_table()
def _create_audit_table(self):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS audit (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
action TEXT,
endpoint TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
status TEXT
);
"""
)
conn.commit()
def new_entry(self, entry:AuditModel):
"""Create a new entry."""
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO audit (user_id, action, endpoint, status)
VALUES (?, ?, ?, ?)
""",
(entry.user_id, entry.action, entry.endpoint, entry.status),
)
conn.commit()
return cursor.lastrowid
except sqlite3.IntegrityError:
return None
def get_all_entries(self):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM audit")
rows = cursor.fetchall()
return [
AuditModel(
id = row[0],
user_id = row[1],
action = row[2],
endpoint = row[3],
created_at = row[4],
status = row[5]
)
for row in rows
]
def get_entries_by_user_id(self, user_id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM audit WHERE user_id = ?", (user_id, ))
rows = cursor.fetchall()
return [
AuditModel(
id = row[0],
user_id = row[1],
action = row[2],
endpoint = row[3],
created_at = row[4],
status = row[5]
)
for row in rows
]
def delete_entries_older_than(self, date_string):
"""
Deletes logs older than the provided date.
Expected date_string format: 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
"""
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# SQLite allows direct string comparison for ISO 8601 dates
cursor.execute(
"DELETE FROM audit WHERE created_at < ?",
(date_string,)
)
conn.commit()
return cursor.rowcount # Returns the number of deleted rows
except sqlite3.Error as e:
print(f"An error occurred: {e}")
return 0

View File

@@ -0,0 +1,132 @@
import sqlite3
from dataclasses import dataclass
import hashlib
from typing import Optional
@dataclass
class DocumentsCategoryModel:
id: Optional[int] = None
user_id: Optional[int] = None
name: Optional[str] = None
created_at: Optional[str] = None
access: Optional[str] = None
class DocumentsCategory:
def __init__(self, db_path="instance/app_database.db"):
self.db_path = db_path
self._create_audit_table()
def _create_audit_table(self):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS documents_category (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
name TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
access TEXT
);
"""
)
conn.commit()
def new_entry(self, entry:DocumentsCategoryModel):
"""Create a new entry."""
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO documents_category (user_id, name, access)
VALUES (?, ?, ?)
""",
(entry.user_id, entry.name, entry.access)
)
conn.commit()
return cursor.lastrowid
except sqlite3.IntegrityError:
return None
def get_all_entries(self):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM documents_category")
rows = cursor.fetchall()
return [
DocumentsCategoryModel(
id = row[0],
user_id = row[1],
name = row[2],
created_at = row[3],
access = row[4]
)
for row in rows
]
def get_entries_by_user_id(self, user_id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM documents_category WHERE user_id = ?", (user_id, ))
rows = cursor.fetchall()
return [
DocumentsCategoryModel(
id = row[0],
user_id = row[1],
name = row[2],
created_at = row[3],
access = row[4]
)
for row in rows
]
def get_entry_by_id(self, id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM documents_category WHERE id = ?", (id, ))
row = cursor.fetchone()
if row:
return DocumentsCategoryModel(
id = row[0],
user_id = row[1],
name = row[2],
created_at = row[3],
access = row[4]
)
return None
def update_entry(self, id, name, access):
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
UPDATE documents_category
SET name = ?, access = ?
WHERE id = ?
""",
(name, access, id)
)
conn.commit()
return cursor.rowcount
except sqlite3.Error as e:
print(f"An error occurred: {e}")
return 0
def delete_entry(self, id):
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# SQLite allows direct string comparison for ISO 8601 dates
cursor.execute(
"DELETE FROM documents_category WHERE id = ? ",
(id,)
)
conn.commit()
return cursor.rowcount # Returns the number of deleted rows
except sqlite3.Error as e:
print(f"An error occurred: {e}")
return 0

View File

@@ -0,0 +1,303 @@
import sqlite3
from dataclasses import dataclass
import hashlib
from typing import Optional
@dataclass
class DocumentsCustomModel:
id: Optional[int] = None
user_id: Optional[int] = None
name: Optional[str] = None
path: Optional[str] = None
created_at: Optional[str] = None
access: Optional[str] = None
class DocumentsCustom:
def __init__(self, db_path="instance/app_database.db"):
self.db_path = db_path
self._create_audit_table()
def _create_audit_table(self):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS documents_custom (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
name TEXT,
path TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
access TEXT
);
"""
)
conn.commit()
def new_entry(self, entry:DocumentsCustomModel):
"""Create a new entry."""
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO documents_custom (user_id, name, path, access)
VALUES (?, ?, ?, ?)
""",
(entry.user_id, entry.name, entry.path, entry.access),
)
conn.commit()
return cursor.lastrowid
except sqlite3.IntegrityError:
return None
def get_all_entries(self):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM documents_custom")
rows = cursor.fetchall()
return [
DocumentsCustomModel(
id = row[0],
user_id = row[1],
name = row[2],
path = row[3],
created_at = row[4],
access = row[5]
)
for row in rows
]
def get_entries_by_user_id(self, user_id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM documents_custom WHERE user_id = ?", (user_id, ))
rows = cursor.fetchall()
return [
DocumentsCustomModel(
id = row[0],
user_id = row[1],
name = row[2],
path = row[3],
created_at = row[4],
access = row[5]
)
for row in rows
]
def get_entry_by_id(self, id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM documents_custom WHERE id = ?", (id, ))
row = cursor.fetchone()
if row:
return DocumentsCustomModel(
id = row[0],
user_id = row[1],
name = row[2],
path = row[3],
created_at = row[4],
access = row[5]
)
return None
def delete_entry(self, id):
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# SQLite allows direct string comparison for ISO 8601 dates
cursor.execute(
"DELETE FROM documents_custom WHERE id = ? ",
(id,)
)
conn.commit()
return cursor.rowcount # Returns the number of deleted rows
except sqlite3.Error as e:
print(f"An error occurred: {e}")
return 0
@dataclass
class CustomDocumentRequestModel:
id: Optional[int] = None
client_id: Optional[int] = None
request_text: Optional[str] = None
status: Optional[str] = "new"
price: Optional[float] = 0.0
expert_id: Optional[int] = None
document_id: Optional[int] = None
created_at: Optional[str] = None
class CustomDocumentRequests:
def __init__(self, db_path="instance/app_database.db"):
self.db_path = db_path
self._create_table()
def _create_table(self):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS custom_document_requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
client_id INTEGER NOT NULL,
request_text TEXT,
status TEXT DEFAULT 'new',
price REAL DEFAULT 0.0,
expert_id INTEGER,
document_id INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
"""
)
conn.commit()
def new_entry(self, entry: CustomDocumentRequestModel):
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO custom_document_requests (client_id, request_text, status, price, expert_id, document_id)
VALUES (?, ?, ?, ?, ?, ?)
""",
(entry.client_id, entry.request_text, entry.status, entry.price, entry.expert_id, entry.document_id),
)
conn.commit()
return cursor.lastrowid
except sqlite3.Error as e:
print(f"Database error: {e}")
return None
def get_all_entries(self):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM custom_document_requests")
rows = cursor.fetchall()
return [
CustomDocumentRequestModel(
id=row[0],
client_id=row[1],
request_text=row[2],
status=row[3],
price=row[4],
expert_id=row[5],
document_id=row[6],
created_at=row[7]
) for row in rows]
def get_entry_by_id(self, id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM custom_document_requests WHERE id = ?", (id,))
row = cursor.fetchone()
if row:
return CustomDocumentRequestModel(
id=row[0],
client_id=row[1],
request_text=row[2],
status=row[3],
price=row[4],
expert_id=row[5],
document_id=row[6],
created_at=row[7]
)
return None
def get_entries_by_client_id(self, client_id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM custom_document_requests WHERE client_id = ?", (client_id,))
rows = cursor.fetchall()
return [
CustomDocumentRequestModel(
id=row[0],
client_id=row[1],
request_text=row[2],
status=row[3],
price=row[4],
expert_id=row[5],
document_id=row[6],
created_at=row[7]
) for row in rows]
def get_entries_by_expert_id(self, expert_id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM custom_document_requests WHERE expert_id = ? ORDER BY id DESC", (expert_id,))
rows = cursor.fetchall()
return [
CustomDocumentRequestModel(
id=row[0],
client_id=row[1],
request_text=row[2],
status=row[3],
price=row[4],
expert_id=row[5],
document_id=row[6],
created_at=row[7]
) for row in rows]
def update_entry(self, id, status=None, price=None, expert_id=None, document_id=None, request_text=None):
if status is None and price is None and expert_id is None and document_id is None and request_text is None:
return False
# Fetch existing entry to preserve unchanged values if not provided
existing_entry = self.get_entry_by_id(id)
if not existing_entry:
return False
# Use existing values if new ones are not provided
status = status if status is not None else existing_entry.status
price = price if price is not None else existing_entry.price
expert_id = expert_id if expert_id is not None else existing_entry.expert_id
document_id = document_id if document_id is not None else existing_entry.document_id
request_text = request_text if request_text is not None else existing_entry.request_text
fields = []
params = []
if request_text is not None:
fields.append("request_text = ?")
params.append(request_text)
if status is not None:
fields.append("status = ?")
params.append(status)
if price is not None:
fields.append("price = ?")
params.append(price)
if expert_id is not None:
fields.append("expert_id = ?")
params.append(expert_id)
if document_id is not None:
fields.append("document_id = ?")
params.append(document_id)
params.append(id)
query = f"UPDATE custom_document_requests SET {', '.join(fields)} WHERE id = ?"
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(query, tuple(params))
conn.commit()
return cursor.rowcount > 0
except sqlite3.Error as e:
print(f"An error occurred during update: {e}")
return False
def delete_entry(self, id):
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"DELETE FROM custom_document_requests WHERE id = ?",
(id,)
)
conn.commit()
return cursor.rowcount
except sqlite3.Error as e:
print(f"An error occurred during delete: {e}")
return 0

View File

@@ -0,0 +1,143 @@
import sqlite3
from dataclasses import dataclass
import hashlib
from typing import Optional
@dataclass
class DocumentsStandardModel:
id: Optional[int] = None
category_id: Optional[int] = None
user_id: Optional[int] = None
name: Optional[str] = None
path: Optional[str] = None
created_at: Optional[str] = None
access: Optional[str] = None
class DocumentsStandard:
def __init__(self, db_path="instance/app_database.db"):
self.db_path = db_path
self._create_audit_table()
def _create_audit_table(self):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS documents_standard (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category_id INTEGER,
user_id INTEGER NOT NULL,
name TEXT,
path TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
access TEXT
);
"""
)
conn.commit()
def new_entry(self, entry:DocumentsStandardModel):
"""Create a new entry."""
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO documents_standard (category_id, user_id, name, path, access)
VALUES (?, ?, ?, ?, ?)
""",
(entry.category_id, entry.user_id, entry.name, entry.path, entry.access),
)
conn.commit()
return cursor.lastrowid
except sqlite3.IntegrityError:
return None
def get_all_entries(self):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM documents_standard")
rows = cursor.fetchall()
return [
DocumentsStandardModel(
id = row[0],
category_id = row[1],
user_id = row[2],
name = row[3],
path = row[4],
created_at = row[5],
access = row[6]
)
for row in rows
]
def get_entries_by_user_id(self, user_id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM documents_standard WHERE user_id = ?", (user_id, ))
rows = cursor.fetchall()
return [
DocumentsStandardModel(
id = row[0],
category_id = row[1],
user_id = row[2],
name = row[3],
path = row[4],
created_at = row[5],
access = row[6]
)
for row in rows
]
def get_entries_by_category(self, category_id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM documents_standard WHERE category_id = ?", (category_id, ))
rows = cursor.fetchall()
return [
DocumentsStandardModel(
id = row[0],
category_id = row[1],
user_id = row[2],
name = row[3],
path = row[4],
created_at = row[5],
access = row[6]
)
for row in rows
]
def get_entry_by_id(self, id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM documents_standard WHERE id = ?", (id, ))
row = cursor.fetchone()
if row:
return DocumentsStandardModel(
id = row[0],
category_id = row[1],
user_id = row[2],
name = row[3],
path = row[4],
created_at = row[5],
access = row[6]
)
return None
def delete_entry(self, id):
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# SQLite allows direct string comparison for ISO 8601 dates
cursor.execute(
"DELETE FROM documents_standard WHERE id = ? ",
(id,)
)
conn.commit()
return cursor.rowcount # Returns the number of deleted rows
except sqlite3.Error as e:
print(f"An error occurred: {e}")
return 0

View File

@@ -0,0 +1,124 @@
import sqlite3
from dataclasses import dataclass
from typing import Optional
@dataclass
class PaymentsModel:
id: Optional[int] = None
user_id: Optional[int] = None
name: Optional[str] = None
amount: Optional[float] = None
type: Optional[str] = None
created_at: Optional[str] = None
class Payments:
def __init__(self, db_path="instance/app_database.db"):
self.db_path = db_path
self._create_payment_table()
def _create_payment_table(self):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS payments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
name TEXT,
amount REAL,
type TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
"""
)
conn.commit()
def add_payment(self, payment: PaymentsModel):
"""Adds a new payment entry to the database."""
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO subscriptions_and_payments (user_id, name, amount, type)
VALUES (?, ?, ?, ?)
""",
(payment.user_id, payment.name, payment.amount, payment.type),
)
conn.commit()
return cursor.lastrowid
except sqlite3.IntegrityError:
return None
def get_payment(self, payment_id: int) -> PaymentsModel | None:
"""Retrieves a single payment entry by its ID."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM subscriptions_and_payments WHERE id = ?", (payment_id,))
row = cursor.fetchone()
if not row:
return None
return PaymentsModel(
id=row[0],
user_id=row[1],
name=row[2],
amount=row[3],
type=row[4],
created_at=row[5]
)
def get_all_payments(self):
"""Retrieves all payment entries from the database."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM subscriptions_and_payments")
rows = cursor.fetchall()
return [
PaymentsModel(
id=row[0],
user_id=row[1],
name=row[2],
amount=row[3],
type=row[4],
created_at=row[5]
)
for row in rows
]
def update_payment(self, payment_id: int, name: Optional[str] = None, amount: Optional[float] = None, type: Optional[str] = None):
"""Updates an existing payment entry."""
fields = []
params = []
if name is not None:
fields.append("name = ?")
params.append(name)
if amount is not None:
fields.append("amount = ?")
params.append(amount)
if type is not None:
fields.append("type = ?")
params.append(type)
if not fields:
return False # No fields to update
params.append(payment_id)
query = f"UPDATE subscriptions_and_payments SET {', '.join(fields)} WHERE id = ?"
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(query, tuple(params))
conn.commit()
return cursor.rowcount > 0
def delete_payment(self, payment_id: int):
"""Deletes a payment entry by its ID."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM subscriptions_and_payments WHERE id = ?", (payment_id,))
conn.commit()
return cursor.rowcount > 0

View File

@@ -0,0 +1,112 @@
import sqlite3
from dataclasses import dataclass
from typing import Optional
@dataclass
class SubscriptionsModel:
id: Optional[int] = None
user_id: Optional[int] = None
name: Optional[str] = None # Numele abonamentului (ex: "Abonament Lunar", "Abonament Anual")
pay_and_subs_id: Optional[int] = None # ID-ul plății asociate din tabela subscriptions_and_payments
mounts: Optional[int] = None
created_at: Optional[str] = None
class Subscriptions:
def __init__(self, db_path="instance/app_database.db"):
self.db_path = db_path
self._create_subscription_table()
def _create_subscription_table(self):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS subscriptions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
name TEXT,
pay_and_subs_id INTEGER,
mounts INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (pay_and_subs_id) REFERENCES subscriptions_and_payments(id)
);
"""
)
conn.commit()
def add_subscription(self, subscription: SubscriptionsModel):
"""Adds a new subscription entry to the database."""
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO subscriptions (user_id, name, pay_and_subs_id, mounts)
VALUES (?, ?, ?, ?)
""",
(subscription.user_id, subscription.name, subscription.pay_and_subs_id, subscription.mounts),
)
conn.commit()
return cursor.lastrowid
except sqlite3.Error:
return None
def get_subscription(self, subscription_id: int) -> Optional[SubscriptionsModel]:
"""Retrieves a single subscription entry by its ID."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM subscriptions WHERE id = ?", (subscription_id,))
row = cursor.fetchone()
if row:
return SubscriptionsModel(*row)
return None
def get_all_subscriptions(self):
"""Retrieves all subscription entries from the database."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM subscriptions")
rows = cursor.fetchall()
return [SubscriptionsModel(*row) for row in rows]
def get_subscriptions_by_user_id(self, user_id: int):
"""Retrieves all subscriptions for a specific user."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM subscriptions WHERE user_id = ?", (user_id,))
rows = cursor.fetchall()
return [SubscriptionsModel(*row) for row in rows]
def update_subscription(self, subscription_id: int, name: Optional[str] = None, pay_and_subs_id: Optional[int] = None, mounts: Optional[int] = None):
"""Updates an existing subscription entry."""
fields = []
params = []
if name is not None:
fields.append("name = ?")
params.append(name)
if pay_and_subs_id is not None:
fields.append("pay_and_subs_id = ?")
params.append(pay_and_subs_id)
if mounts is not None:
fields.append("mounts = ?")
params.append(mounts)
if not fields:
return False
params.append(subscription_id)
query = f"UPDATE subscriptions SET {', '.join(fields)} WHERE id = ?"
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(query, tuple(params))
conn.commit()
return cursor.rowcount > 0
def delete_subscription(self, subscription_id: int):
"""Deletes a subscription entry by its ID."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM subscriptions WHERE id = ?", (subscription_id,))
conn.commit()
return cursor.rowcount > 0

323
server/models/users.py Normal file
View File

@@ -0,0 +1,323 @@
import sqlite3
from dataclasses import dataclass
import hashlib
from typing import Optional
@dataclass
class UserModel:
id: Optional[int] = None
workspace_id: Optional[int] = None
first_name: Optional[str] = None
last_name: Optional[str] = None
email: Optional[str] = None
password: Optional[str] = None
address: Optional[str] = None
profession: Optional[str] = None
role: Optional[str] = None
status: Optional[str] = None
profile_pic: Optional[str] = None
created_at: Optional[str] = None
otp_code: Optional[str] = None
otp_expiration: Optional[str] = None
active: Optional[int] = None
class Users:
def __init__(self, db_path="instance/app_database.db"):
self.db_path = db_path
self._create_users_table()
def _create_users_table(self):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
workspace_id INTEGER NOT NULL,
first_name TEXT,
last_name TEXT,
email TEXT UNIQUE,
password TEXT,
address TEXT,
profession TEXT,
role TEXT DEFAULT 'user',
status TEXT,
profile_pic TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
otp_code TEXT,
otp_expiration TIMESTAMPTZ,
active INTEGER DEFAULT 1
);
"""
)
conn.commit()
def update_user_otp(self, user_id, otp_code, expiration):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
f"""
UPDATE users
SET otp_code = ?, otp_expiration = ?
WHERE id = ?
""",
(otp_code, expiration.isoformat(), user_id)
)
conn.commit()
def clear_user_otp(self, user_id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
f"""
UPDATE users
SET otp_code = NULL, otp_expiration = NULL
WHERE id = ?
""",
(user_id,)
)
if hasattr(conn, "commit"):
conn.commit()
def update_password(self, email, password):
'''Update user password'''
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
UPDATE users SET password = ?
WHERE email = ?
''', (self.hash_password(password), email))
conn.commit()
def hash_password(self, password: str) -> bytes:
return hashlib.md5(password.encode('utf-8')).hexdigest()
def authenticate(self, email, password):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("""
SELECT * FROM users
WHERE email = ? AND password = ?
""", (email, self.hash_password(password)))
row = cursor.fetchone()
if not row:
return None
return UserModel(
id=row[0],
workspace_id=row[1],
first_name=row[2],
last_name=row[3],
email=row[4],
address=row[6],
profession=row[7],
role=row[8],
status=row[9],
profile_pic=row[10],
created_at=row[11],
otp_code=row[12],
otp_expiration=row[13],
active=row[14]
)
def register_user(self, email, password, workspace_id):
"""Register a new user."""
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("""
INSERT INTO users (workspace_id, email, password)
VALUES (?, ?, ?)
""", (workspace_id, email, self.hash_password(password)))
conn.commit()
return True
except sqlite3.IntegrityError:
return False # Username already exist
def add_user(self, user:UserModel):
"""Create a new post."""
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(
"""
INSERT INTO users (workspace_id, first_name, last_name, email, password, address, profession, role, status, profile_pic)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(user.workspace_id, user.first_name, user.last_name, user.email, user.password, user.address, user.profession, user.role, user.status, user.profile_pic),
)
conn.commit()
return cursor.lastrowid
except sqlite3.IntegrityError:
return None
def get_user(self, user_id: int) -> UserModel | None:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
row = cursor.fetchone()
if not row:
return None
return UserModel(
id=row[0],
workspace_id=row[1],
first_name=row[2],
last_name=row[3],
email=row[4],
address=row[6],
profession=row[7],
role=row[8],
status=row[9],
profile_pic=row[10],
created_at=row[11],
otp_code=row[12],
otp_expiration=row[13],
active=row[14]
)
def get_user_by_email(self, email: str) -> UserModel | None:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE email = ?", (email,))
row = cursor.fetchone()
if not row:
return None
return UserModel(
id=row[0],
workspace_id=row[1],
first_name=row[2],
last_name=row[3],
email=row[4],
password=row[5],
address=row[6],
profession=row[7],
role=row[8],
status=row[9],
profile_pic=row[10],
created_at=row[11],
otp_code=row[12],
otp_expiration=row[13],
active=row[14]
)
def get_users_by_workspace_id(self, workspace_id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE workspace_id = ?", (workspace_id,))
rows = cursor.fetchall()
return [
UserModel(
id=row[0],
workspace_id=row[1],
first_name=row[2],
last_name=row[3],
email=row[4],
address=row[6],
profession=row[7],
role=row[8],
status=row[9],
profile_pic=row[10],
created_at=row[11],
otp_code=row[12],
otp_expiration=row[13],
active=row[14]
)
for row in rows
]
def get_all_users(self):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM users")
rows = cursor.fetchall()
return [
UserModel(
id=row[0],
workspace_id=row[1],
first_name=row[2],
last_name=row[3],
email=row[4],
address=row[6],
profession=row[7],
role=row[8],
status=row[9],
profile_pic=row[10],
created_at=row[11],
otp_code=row[12],
otp_expiration=row[13],
active=row[14]
)
for row in rows
]
def update_user(self, user_id, first_name=None, last_name=None, email=None, password = None, address = None, profession = None, role = None, status = None, profile_pic=None, active=None):
if first_name is None and last_name is None and email is None and password is None and address is None and profession is None and role is None and status is None and profile_pic is None and active is None:
return False
fields = []
params = []
if first_name is not None:
fields.append("first_name = ?")
params.append(first_name)
if last_name is not None:
fields.append("last_name = ?")
params.append(last_name)
if email is not None:
fields.append("email = ?")
params.append(email)
if password is not None:
fields.append("password = ?")
params.append(password)
if address is not None:
fields.append("address = ?")
params.append(address)
if profession is not None:
fields.append("profession = ?")
params.append(profession)
if role is not None:
fields.append("role = ?")
params.append(role)
if status is not None:
fields.append("status = ?")
params.append(status)
if profile_pic is not None:
fields.append("profile_pic = ?")
params.append(profile_pic)
if active is not None:
fields.append("active = ?")
params.append(active)
params.append(user_id)
query = f"UPDATE users SET {', '.join(fields)} WHERE id = ?"
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute(query, tuple(params))
conn.commit()
return cursor.rowcount > 0
#Do not use this method if you do not delete first in cascade, better use inactivate
def delete_user(self, user_id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM users WHERE id = ?", (user_id,))
conn.commit()
return cursor.rowcount > 0
def inactivate_user(self, user_id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("UPDATE users SET status = ? WHERE id = ?", ('inactive',user_id,))
conn.commit()
return cursor.rowcount > 0