2020-09-11 00:00:48 +02:00
|
|
|
from datetime import datetime, timedelta
|
2020-06-05 01:09:55 +02:00
|
|
|
|
|
|
|
from app.schemas import *
|
2020-08-01 19:04:35 +02:00
|
|
|
from database import SessionLocal
|
|
|
|
from database.models import *
|
2020-06-05 01:09:55 +02:00
|
|
|
|
2020-04-15 00:29:59 +02:00
|
|
|
|
2020-08-01 19:04:35 +02:00
|
|
|
def get_db():
|
|
|
|
db = SessionLocal()
|
|
|
|
try:
|
|
|
|
yield db
|
|
|
|
finally:
|
|
|
|
db.close()
|
2020-04-15 00:29:59 +02:00
|
|
|
|
2020-05-28 00:53:23 +02:00
|
|
|
|
2020-09-11 00:00:48 +02:00
|
|
|
def instantiate_model(model, data):
|
|
|
|
table = eval(model)
|
|
|
|
instance = table(**data.dict())
|
2020-05-28 00:53:23 +02:00
|
|
|
return instance
|
|
|
|
|
|
|
|
|
2020-09-11 00:00:48 +02:00
|
|
|
def insert_data(model, data, db):
|
|
|
|
item = instantiate_model(model=model, data=data)
|
2020-08-01 19:04:35 +02:00
|
|
|
db.add(item)
|
|
|
|
db.commit()
|
2020-09-11 00:00:48 +02:00
|
|
|
db.refresh(item)
|
2020-06-05 01:09:55 +02:00
|
|
|
|
|
|
|
|
2020-08-01 19:04:35 +02:00
|
|
|
# FIXME db.id has to be replaced with the table's UID
|
2020-09-11 00:00:48 +02:00
|
|
|
def delete_data(schema, data, db):
|
2020-08-01 19:04:35 +02:00
|
|
|
model = schema.replace('"', "")
|
|
|
|
result = db.query(model).filter(model.email == data.email).delete()
|
|
|
|
return result
|
2020-04-15 00:29:59 +02:00
|
|
|
|
|
|
|
|
2020-09-11 00:00:48 +02:00
|
|
|
def fetch_user(data, db):
|
2020-08-01 19:04:35 +02:00
|
|
|
result = db.query(Users).filter(Users.email == data.email).first()
|
|
|
|
return result
|
2020-04-15 00:29:59 +02:00
|
|
|
|
|
|
|
|
2020-09-11 00:00:48 +02:00
|
|
|
def fetch_otp(data: OTPVerify, db):
|
2020-08-01 19:04:35 +02:00
|
|
|
result = db.query(Users).filter(Users.access_key == data.access_key).first()
|
|
|
|
return result
|
2020-04-15 00:29:59 +02:00
|
|
|
|
|
|
|
|
2020-09-11 00:00:48 +02:00
|
|
|
def save_otp(data: OTPVerify, db):
|
2020-08-01 19:04:35 +02:00
|
|
|
db.query(Users).filter(Users.access_key == data.access_key).update(
|
|
|
|
{Users.otp: data.otp}
|
|
|
|
)
|
|
|
|
db.commit()
|
2020-04-19 21:30:41 +02:00
|
|
|
|
|
|
|
|
2020-09-11 00:00:48 +02:00
|
|
|
def activate_account(data: OTPVerify, db):
|
|
|
|
timestamp = datetime.now() + timedelta(minutes=10)
|
2020-08-01 19:04:35 +02:00
|
|
|
db.query(Users).filter(Users.access_key == data.access_key).update(
|
|
|
|
{Users.otp_valid_time: timestamp, Users.status: 1}
|
2020-04-19 21:30:41 +02:00
|
|
|
)
|
2020-08-01 19:04:35 +02:00
|
|
|
db.commit()
|
2020-04-19 21:30:41 +02:00
|
|
|
|
|
|
|
|
2020-09-11 00:00:48 +02:00
|
|
|
def verify_otp(data: OTPVerify, db):
|
|
|
|
user = fetch_otp(data=data, db=db)
|
|
|
|
same_otp = user.otp == data.otp
|
|
|
|
valid_time = datetime.now() <= user.otp_valid_time
|
|
|
|
valid_otp = same_otp and valid_time
|
|
|
|
if valid_otp:
|
|
|
|
activate_account(data=data, db=db)
|
2020-05-28 00:53:23 +02:00
|
|
|
return True
|
|
|
|
return False
|