2020-11-17 14:16:44 +01:00
|
|
|
from sqlalchemy import or_
|
|
|
|
|
|
|
|
from database import SessionLocal, engine, models
|
2020-11-25 18:21:22 +01:00
|
|
|
from database.models import User
|
2020-11-17 14:16:44 +01:00
|
|
|
|
|
|
|
db = SessionLocal()
|
|
|
|
|
|
|
|
|
2020-11-26 01:58:43 +01:00
|
|
|
def search_database(id) -> User:
|
2020-11-25 13:44:07 +01:00
|
|
|
"""
|
|
|
|
Returns the user associated with the id argument
|
|
|
|
"""
|
2020-11-26 01:58:43 +01:00
|
|
|
return (
|
|
|
|
db.query(User)
|
|
|
|
.filter(or_(User.correo_institucional == id, User.numero_de_documento == id))
|
|
|
|
.first()
|
2020-11-17 14:16:44 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2020-11-25 13:44:07 +01:00
|
|
|
def insert_data(data) -> None:
|
|
|
|
"""
|
|
|
|
Inserts a new user into the database
|
|
|
|
"""
|
2020-11-25 18:21:22 +01:00
|
|
|
item = User(**data)
|
2020-11-17 14:16:44 +01:00
|
|
|
db.add(item)
|
|
|
|
db.commit()
|
|
|
|
db.refresh(item)
|
|
|
|
|
|
|
|
|
2020-11-25 13:44:07 +01:00
|
|
|
def create_database(data) -> None:
|
|
|
|
"""
|
|
|
|
Creates the SQL database from scratch and populates it
|
|
|
|
"""
|
2020-11-17 14:16:44 +01:00
|
|
|
models.Base.metadata.create_all(bind=engine)
|
|
|
|
existing_row = search_database(data["correo_institucional"])
|
2021-01-08 04:12:23 +01:00
|
|
|
if not existing_row:
|
|
|
|
insert_data(data)
|
2020-11-25 11:06:38 +01:00
|
|
|
|
|
|
|
|
2020-11-26 01:58:43 +01:00
|
|
|
def save_attribute(id, attribute, data) -> None:
|
2020-11-25 13:44:07 +01:00
|
|
|
"""
|
|
|
|
Updates the attribute value with the content of data
|
|
|
|
"""
|
2020-11-25 18:21:22 +01:00
|
|
|
key = eval("User." + attribute)
|
|
|
|
db.query(User).filter(
|
|
|
|
or_(User.correo_institucional == id, User.numero_de_documento == id)
|
2020-11-25 11:06:38 +01:00
|
|
|
).update({key: data})
|
2020-11-26 01:58:43 +01:00
|
|
|
db.commit()
|
2020-11-25 11:06:38 +01:00
|
|
|
|
|
|
|
|
2020-11-25 13:44:07 +01:00
|
|
|
def verify_code(id, code) -> bool:
|
|
|
|
"""
|
|
|
|
Verifies that two-factor authentification code matches the database record
|
|
|
|
"""
|
2020-11-25 11:06:38 +01:00
|
|
|
db_record = search_database(id=id)
|
2020-11-26 01:58:43 +01:00
|
|
|
valid_code = code == db_record.codigo
|
2020-11-25 11:06:38 +01:00
|
|
|
if valid_code:
|
|
|
|
return True
|
|
|
|
return False
|
2020-11-25 18:21:54 +01:00
|
|
|
|
|
|
|
|
|
|
|
def parse_boolean_string(value) -> bool:
|
|
|
|
"""
|
|
|
|
Converts string response to a boolean
|
|
|
|
"""
|
2020-11-26 01:59:50 +01:00
|
|
|
mapping = {"si": True, "sí": True, "no": False}
|
2020-11-25 18:21:54 +01:00
|
|
|
return mapping[value]
|
|
|
|
|
|
|
|
|
|
|
|
def boolean_to_string(value) -> str:
|
|
|
|
"""
|
|
|
|
Converts boolean to string
|
|
|
|
"""
|
|
|
|
if value:
|
|
|
|
return "Sí"
|
|
|
|
return "No"
|