2022-03-03 13:49:26 +01:00
|
|
|
# CRUD (Create, Read, Update, Delete) from db
|
|
|
|
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
|
2022-04-13 04:24:06 +02:00
|
|
|
from . import models, schemas, crypto, auth_helper
|
2022-03-03 13:49:26 +01:00
|
|
|
|
|
|
|
|
|
|
|
def get_user(db: Session, user_id: int):
|
|
|
|
return db.query(models.User).filter(models.User.id == user_id).first()
|
|
|
|
|
2022-04-13 07:34:12 +02:00
|
|
|
def get_iot_entity(db: Session, id: int):
|
|
|
|
return db.query(models.IotEntity).filter(models.IotEntity.id == id).first()
|
2022-03-03 13:49:26 +01:00
|
|
|
|
2022-04-14 00:37:30 +02:00
|
|
|
def get_iot_entity_by_description(db: Session, description: str):
|
|
|
|
return db.query(models.IotEntity).filter(models.IotEntity.description == description).first()
|
|
|
|
|
2022-03-03 13:49:26 +01:00
|
|
|
def get_user_by_email(db: Session, email: str):
|
|
|
|
return db.query(models.User).filter(models.User.email == email).first()
|
|
|
|
|
2022-04-04 01:02:29 +02:00
|
|
|
def get_user_by_username(db: Session, username: str):
|
|
|
|
return db.query(models.User).filter(models.User.username == username).first()
|
|
|
|
|
2022-03-03 13:49:26 +01:00
|
|
|
def get_users(db: Session, skip: int = 0, limit: int = 100):
|
|
|
|
return db.query(models.User).offset(skip).limit(limit).all()
|
|
|
|
|
|
|
|
def create_user(db: Session, user: schemas.UserCreate):
|
2022-03-16 20:46:50 +01:00
|
|
|
key = crypto.gen_new_key(user.password)
|
|
|
|
salt = key[1]
|
|
|
|
hashed_pass = key[0]
|
2022-04-04 01:02:29 +02:00
|
|
|
db_user = models.User(email=user.email, username=user.username,hashed_password=hashed_pass, passwd_salt=salt)
|
2022-03-03 13:49:26 +01:00
|
|
|
db.add(db_user)
|
|
|
|
db.commit()
|
|
|
|
db.refresh(db_user)
|
|
|
|
return db_user
|
|
|
|
|
|
|
|
|
|
|
|
def get_iot_entities(db: Session, skip: int = 0, limit: int = 100):
|
|
|
|
return db.query(models.IotEntity).offset(skip).limit(limit).all()
|
|
|
|
|
|
|
|
|
2022-04-13 07:34:12 +02:00
|
|
|
def create_iot_entity(db: Session, iot_entity: schemas.IotEntityCreate):
|
2022-04-13 08:39:25 +02:00
|
|
|
db_item = models.IotEntity(bluetooth_mac=iot_entity.bluetooth_mac,
|
|
|
|
description=iot_entity.description)
|
2022-03-03 13:49:26 +01:00
|
|
|
db.add(db_item)
|
|
|
|
db.commit()
|
|
|
|
db.refresh(db_item)
|
|
|
|
return db_item
|
2022-04-13 07:34:12 +02:00
|
|
|
|
|
|
|
def create_user_link_to_iot(db: Session, user_id: int, iot_dev_id: int):
|
|
|
|
# Ensure link is not already present and it does not allow duplicates
|
|
|
|
new_link = models.UserAuthToIoTDev(user_id=user_id, iot_entity_id=iot_dev_id)
|
|
|
|
db.add(new_link)
|
|
|
|
db.commit()
|
|
|
|
db.refresh(new_link)
|
|
|
|
return True
|