covot/database/crud.py

59 lines
1.4 KiB
Python

from sqlalchemy import or_
from sqlalchemy.orm import Query
from database import SessionLocal, engine, models
from database.models import Users
db = SessionLocal()
def search_database(id) -> Query:
"""
Returns the user associated with the id argument
"""
return db.query(Users).filter(
or_(Users.correo_institucional == id, Users.numero_de_documento == id)
)
def insert_data(data) -> None:
"""
Inserts a new user into the database
"""
item = Users(**data)
db.add(item)
db.commit()
db.refresh(item)
def create_database(data) -> None:
"""
Creates the SQL database from scratch and populates it
"""
models.Base.metadata.create_all(bind=engine)
existing_row = search_database(data["correo_institucional"])
if existing_row:
return
insert_data(data)
def save_attribute(attribute, data) -> None:
"""
Updates the attribute value with the content of data
"""
key = eval("Users." + attribute)
db.query(Users).filter(
or_(Users.correo_institucional == id, Users.numero_de_documento == id)
).update({key: data})
def verify_code(id, code) -> bool:
"""
Verifies that two-factor authentification code matches the database record
"""
db_record = search_database(id=id)
valid_code = code == db_record
if valid_code:
return True
return False