This repository has been archived on 2024-05-31. You can view files and clone it, but cannot push or open issues or pull requests.
devicehub-teal/ereuse_devicehub/resources/user/models.py

179 lines
5.7 KiB
Python
Raw Normal View History

2022-11-22 18:12:11 +00:00
import json
2018-04-27 17:16:43 +00:00
from uuid import uuid4
2022-11-22 18:12:11 +00:00
from citext import CIText
from flask import current_app as app
2022-11-24 16:54:25 +00:00
from flask import session
from flask_login import UserMixin
2022-04-06 10:35:08 +00:00
from sqlalchemy import BigInteger, Boolean, Column, Sequence
2018-04-27 17:16:43 +00:00
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy_utils import EmailType, PasswordType
2021-04-13 16:33:15 +00:00
from teal.db import IntEnum
2018-04-27 17:16:43 +00:00
2019-01-21 15:08:55 +00:00
from ereuse_devicehub.db import db
2022-04-06 10:35:08 +00:00
from ereuse_devicehub.resources.enums import SessionType
2019-01-21 15:08:55 +00:00
from ereuse_devicehub.resources.inventory.model import Inventory
from ereuse_devicehub.resources.models import STR_SIZE, Thing
2018-04-27 17:16:43 +00:00
class User(UserMixin, Thing):
2018-04-27 17:16:43 +00:00
__table_args__ = {'schema': 'common'}
id = Column(UUID(as_uuid=True), default=uuid4, primary_key=True)
email = Column(EmailType, nullable=False, unique=True)
2022-04-06 10:35:08 +00:00
password = Column(
PasswordType(
max_length=STR_SIZE,
onload=lambda **kwargs: dict(
schemes=app.config['PASSWORD_SCHEMES'], **kwargs
),
)
)
2019-01-23 15:55:04 +00:00
token = Column(UUID(as_uuid=True), default=uuid4, unique=True, nullable=False)
active = Column(Boolean, default=True, nullable=False)
phantom = Column(Boolean, default=False, nullable=False)
2022-11-22 18:12:11 +00:00
api_keys_dlt = Column(CIText(), nullable=True)
2022-04-06 10:35:08 +00:00
inventories = db.relationship(
Inventory,
backref=db.backref('users', lazy=True, collection_class=set),
secondary=lambda: UserInventory.__table__,
collection_class=set,
)
2019-01-23 15:55:04 +00:00
# todo set restriction that user has, at least, one active db
2022-04-06 10:35:08 +00:00
def __init__(
self, email, password=None, inventories=None, active=True, phantom=False
) -> None:
"""Creates an user.
2019-01-23 15:55:04 +00:00
:param email:
:param password:
:param inventories: A set of Inventory where the user has
access to. If none, the user is granted access to the current
inventory.
:param active: allow active and deactive one account without delete the account
:param phantom: it's util for identify the phantom accounts
create during the trade actions
2019-01-23 15:55:04 +00:00
"""
inventories = inventories or {Inventory.current}
2022-04-06 10:35:08 +00:00
super().__init__(
email=email,
password=password,
inventories=inventories,
active=active,
phantom=phantom,
)
def __repr__(self) -> str:
return '<User {0.email}>'.format(self)
@property
def type(self) -> str:
return self.__class__.__name__
@property
def individual(self):
"""The individual associated for this database, or None."""
return next(iter(self.individuals), None)
2019-01-21 15:08:55 +00:00
2021-07-01 10:08:18 +00:00
@property
def code(self):
"""Code of phantoms accounts"""
if not self.phantom:
return
return self.email.split('@')[0].split('_')[1]
@property
def is_active(self):
"""Alias because flask-login expects `is_active` attribute"""
return self.active
@property
def get_full_name(self):
# TODO(@slamora) create first_name & last_name fields???
# needs to be discussed related to Agent <--> User concepts
return self.email
def check_password(self, password):
# take advantage of SQL Alchemy PasswordType to verify password
return self.password == password
2022-11-22 18:12:11 +00:00
def set_new_dlt_keys(self, password):
if 'trublo' not in app.blueprints.keys():
return
from ereuseapi.methods import register_user
from modules.trublo.utils import encrypt
api_dlt = app.config.get('API_DLT')
data = register_user(api_dlt)
data = json.dumps(data)
self.api_keys_dlt = encrypt(password, data)
2022-11-24 17:00:16 +00:00
return data.get('data', {}).get('api_token')
2022-11-22 18:12:11 +00:00
def get_dlt_keys(self, password):
if 'trublo' not in app.blueprints.keys():
return {}
from modules.trublo.utils import decrypt
2022-11-25 12:27:14 +00:00
if not self.api_keys_dlt:
return {}
2022-11-22 18:12:11 +00:00
data = decrypt(password, self.api_keys_dlt)
return json.loads(data)
def reset_dlt_keys(self, password, data):
if 'trublo' not in app.blueprints.keys():
return
from modules.trublo.utils import encrypt
data = json.dumps(data)
self.api_keys_dlt = encrypt(password, data)
2022-11-24 17:00:16 +00:00
def allow_permitions(self, api_token=None):
2022-11-24 16:54:25 +00:00
if 'trublo' not in app.blueprints.keys():
return
from ereuseapi.methods import API
2022-11-24 17:00:16 +00:00
if not api_token:
api_token = session.get('token_dlt', '.')
target_user = api_token.split(".")[0]
2022-11-24 16:54:25 +00:00
keyUser1 = app.config.get('KEYUSER1')
api_dlt = app.config.get('API_DLT')
if not keyUser1 or api_dlt:
return
apiUser1 = API(api_dlt, keyUser1, "ethereum")
apiUser1.issue_credential("Operator", target_user)
2019-01-21 15:08:55 +00:00
class UserInventory(db.Model):
"""Relationship between users and their inventories."""
2022-04-06 10:35:08 +00:00
2019-01-21 15:08:55 +00:00
__table_args__ = {'schema': 'common'}
user_id = db.Column(db.UUID(as_uuid=True), db.ForeignKey(User.id), primary_key=True)
2022-04-06 10:35:08 +00:00
inventory_id = db.Column(
db.Unicode(), db.ForeignKey(Inventory.id), primary_key=True
)
2021-04-13 16:33:15 +00:00
class Session(Thing):
2021-05-24 11:00:03 +00:00
__table_args__ = {'schema': 'common'}
2021-04-13 16:33:15 +00:00
id = Column(BigInteger, Sequence('device_seq'), primary_key=True)
expired = Column(BigInteger, default=0)
token = Column(UUID(as_uuid=True), default=uuid4, unique=True, nullable=False)
type = Column(IntEnum(SessionType), default=SessionType.Internal, nullable=False)
user_id = db.Column(db.UUID(as_uuid=True), db.ForeignKey(User.id))
2022-04-06 10:35:08 +00:00
user = db.relationship(
User,
backref=db.backref('sessions', lazy=True, collection_class=set),
collection_class=set,
)
2021-04-15 19:18:15 +00:00
def __str__(self) -> str:
return '{0.token}'.format(self)