class Label(db.Model): __tablename__ = 'labels' label_id = db.Column(db.String(32), primary_key=True) user_id = db.Column(db.String(32), db.ForeignKey('users.user_id')) songs = db.relationship('Song', backref='label') label_name = db.Column(db.String(50), nullable=False)
class Status(db.Model): """Status table in the database.""" __tablename__ = 'statuses' id = db.Column(db.Integer, primary_key=True) status = db.Column(db.Text)
class Role(db.Model): """Role table in the database""" __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) role = db.Column(db.Text, nullable=False)
class Attachment(db.Model): """Attachment table in the database.""" __tablename__ = 'attachments' id = db.Column(db.Integer, primary_key=True) issue_id = db.Column(db.ForeignKey(u'issues.id'), index=True) image_url = db.Column(db.Text) issue = db.relationship(u'Issue') def get_thumbnail_url(self): head, tail = os.path.split(self.image_url) thumb_name = "thumb-{}".format(tail) return "{}/{}".format(head, thumb_name) def delete(self): db.session.delete(self) db.session.commit() delete_file(self.image_url) delete_file(self.get_thumbnail_url()) directory_path = os.path.abspath( os.path.join(current_app.config['MEDIA_FOLDER'], self.image_url, os.pardir)) if os.path.exists(directory_path) and not os.listdir(directory_path): os.rmdir(directory_path) def get_full_thumbnail_url(self): url = self.get_thumbnail_url() if current_app.config.get('MEDIA_URL'): return current_app.config['MEDIA_URL'] + url return '/media/' + url
class Category(db.Model): """Category table in the database.""" __tablename__ = 'category' id = db.Column(db.Integer, primary_key=True) category = db.Column(db.Text) favicon = db.Column(db.Text)
class User(UserMixin, db.Model): __tablename__ = 'user' # attributes id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(50), nullable=False) phoneNumber = db.Column(db.String(10), nullable=False, unique=True) # Relationships tkt = db.relationship('Ticket', backref=db.backref('tickets', lazy=True))
class Booking(db.Model): """Booking database model.""" __tablename__ = "booking" id = db.Column(Integer, primary_key=True, autoincrement=True) username = db.Column(String(250), nullable=False) email = db.Column(String(250), nullable=False) property_id = db.Column(Integer, ForeignKey(Property.id), nullable=False)
class SqlQuery(db.Model): id = db.Column(db.Integer, primary_key=True) label = db.Column(db.String(64), index=True, unique=True) raw_sql = db.Column(db.Text) creator_user_id = db.Column(db.Integer, db.ForeignKey('user.id'), index=True, nullable=False) charts = db.relationship('Chart', backref='sql_query', lazy='dynamic') usergroups = db.relationship("Usergroup", secondary=query_perms, backref="queries") @validates('label') def validate_label(self, key, label): if not label: raise AssertionError('No label provided') if Usergroup.query.filter( func.lower(Usergroup.label) == func.lower(label)).first(): raise AssertionError('Provided label is already in use') return label @validates('raw_sql') def validate_raw_sql(self, key, raw_sql): if not raw_sql: raise AssertionError('No raw_sql provided') if not isinstance(raw_sql, str): raise AssertionError('raw_sql must be a string') return raw_sql @validates('usergroups') def validate_usergroups(self, key, usergroups): if not isinstance(usergroups, Usergroup): raise AssertionError('Provided usergroup is not recognized') return usergroups def get_dict(self): dict_format = { 'query_id': self.id, 'label': self.label, 'raw_sql': self.raw_sql, 'creator': self.creator.get_dict(), } return dict_format def get_usergroups(self): usergroups = helpers.get_dicts_from_usergroups(self.usergroups) return usergroups def get_authorized_users(self): users = dict(users=helpers.get_users_from_usergroups(self.usergroups)) return users def __repr__(self): return '<SqlQuery {}:{}'.format(self.id, self.label)
class Ticket(db.Model): __tablename__ = 'ticket' # attributes tid = db.Column(db.Integer, primary_key=True, autoincrement=True) cust_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) time_of_movie = db.Column(db.DateTime, db.ForeignKey('movieShow.timing'), nullable=False) hasexpired = db.Column(db.Boolean, default=0)
class MovieShow(db.Model): __tablename__ = 'movieShow' # attributes timing = db.Column(db.DateTime, primary_key=True, unique=True, nullable=False) number_of_tickets = db.Column(db.Integer, default=20) # Relationships time = db.relationship('Ticket', cascade="save-update", backref=db.backref('time', lazy=True))
class Property(db.Model): """Property database model.""" __tablename__ = "property" id = db.Column(Integer, primary_key=True, autoincrement=True) property_name = db.Column(String(250), nullable=False) property_latitude = db.Column(Float, nullable=False) property_longitude = db.Column(Float, nullable=False) __table_args__ = (UniqueConstraint("property_latitude", "property_longitude", "property_name"), )
class Catalogue (BaseModel, db.Model): """Model for Catalogue table""" __tablename__ = "catalogue" id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(128), nullable=False) content = db.Column(db.UnicodeText(), nullable=False) def __init__(self, name, content): super().__init__() self.name = name self.content = content
class User(db.Model): __tablename__ = 'users' user_id = db.Column(db.String(32), primary_key=True) email = db.Column(db.String(80), unique=True, nullable=False) name = db.Column(db.String(50), nullable=False) password = db.Column(db.String(80), nullable=False) created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) labels = db.relationship('Label', backref='owner')
class IssueHistory(db.Model): """IssueHistory table in the database.""" __tablename__ = 'issue_History' id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.ForeignKey(u'users.id')) issue_id = db.Column(db.ForeignKey(u'issues.id'), index=True) status_id = db.Column(db.ForeignKey(u'statuses.id'), index=True) transaction_date = db.Column(db.TIMESTAMP(timezone=True)) issue = db.relationship(u'Issue') status = db.relationship(u'Status') user = db.relationship(u'User')
class UserTasks(db.Model): __tablename__ = 'user_tasks' id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.String(200), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey(User.id, ondelete='CASCADE'), nullable=False) def __init__(self, uuid: str, user_id: int): self.uuid = uuid self.user_id = user_id def __repr__(self): return f'<id: {self.id}><{self.uuid}><user_id: {self.user_id}>'
class BibboxApp(BaseModel, db.Model): """Model for App table""" __tablename__ = "apps" id = db.Column(db.Integer, primary_key=True, autoincrement=True) appid = db.Column(db.String(128), nullable=False) version = db.Column(db.String(128), nullable=False) appinfo = db.Column(db.UnicodeText(), nullable=False) environment_parameters = db.Column(db.UnicodeText(), nullable=False) def __init__(self, appid, version, appinfo, environment_parameters): super().__init__() self.appid = appid self.version = version self.appinfo = appinfo self.environment_parameters = environment_parameters
class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(255), unique=True, nullable=False) email = db.Column(db.String(255), unique=True, nullable=False) password = db.Column(PasswordType(schemes=[ 'sha256_crypt', ])) created_at = db.Column(db.DateTime, default=datetime.utcnow) updated_at = db.Column(db.DateTime, default=datetime.utcnow) password_changed_at = db.Column(db.DateTime) identities = db.relationship('Identity', backref='user', lazy='dynamic') sessions = db.relationship('Session', backref='user', lazy='dynamic') @classmethod def find_by_email_or_username(cls, username): return (User.query.filter((User.email == username) | (User.username == username)).first()) def change_password(self, password): self.password = password self.password_changed_at = datetime.utcnow()
class Session(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) token = db.Column(db.String(255), default=generate_token) user_agent = db.Column(db.String(255)) ip_address = db.Column(db.String(255)) platform = db.Column(db.String(255)) browser = db.Column(db.String(255)) created_at = db.Column(db.DateTime, default=datetime.utcnow) last_active_at = db.Column(db.DateTime, default=datetime.utcnow)
class Activity(BaseModel, db.Model): """Model for Activity table""" __tablename__ = "Activities" id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(128), nullable=False) type_ = db.Column(db.String(128), nullable=False) start_time = db.Column(db.DateTime, nullable=False) finished_time = db.Column(db.DateTime, nullable=True) state = db.Column(db.String, nullable=False) result = db.Column(db.String, nullable=True) logs = db.relationship('Log', back_populates='activity', lazy=True, cascade="all, delete", passive_deletes=False) def __init__(self, name, type_, start_time, finished_time, state, result): super().__init__() self.name = name self.type_ = type_ self.start_time = start_time self.finished_time = finished_time self.state = state self.result = result
class Log(BaseModel, db.Model): """Model for Log table""" __tablename__ = "Logs" id = db.Column(db.Integer, primary_key=True, autoincrement=True) timestamp = db.Column(db.String, nullable="False") log_message = db.Column(db.String, nullable="False") type_ = db.Column(db.String(20), nullable="False") activity_id = db.Column(db.Integer, db.ForeignKey('Activities.id', ondelete="CASCADE"), nullable=False) activity = db.relationship("Activity", back_populates="logs") def __init__(self, timestamp, log_message, type_, activity_id): super().__init__() self.timestamp = timestamp self.log_message = log_message self.type_ = type_ self.activity_id = activity_id
class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(50), nullable=False, unique=True) password_hash = db.Column(db.String(200)) created_on = db.Column(db.DateTime, default=datetime.datetime.utcnow()) updated_on = db.Column(db.DateTime, default=datetime.datetime.utcnow(), onupdate=datetime.datetime.utcnow()) def __init__(self, username: str): self.username = username def __repr__(self): return f'<{self.id}:{self.username}>' def set_password(self, password: str): self.password_hash = generate_password_hash(password) def check_password(self, password: str): return check_password_hash(self.password_hash, password)
class Identity(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) provider = db.Column(db.String(255), nullable=False) provider_user_id = db.Column(db.String(255), nullable=False) created_at = db.Column(db.DateTime, default=datetime.utcnow) last_used_at = db.Column(db.DateTime) __table_args__ = (db.UniqueConstraint('provider', 'provider_user_id', name='uniq_provider_user_id'), )
class Comments(db.Model): """ Issues table in the database. """ __tablename__ = 'comments' id = db.Column(db.Integer, primary_key=True) comment = db.Column(db.Text) date_public = db.Column(db.TIMESTAMP(timezone=True)) user_id = db.Column(db.ForeignKey(u'users.id')) issue_id = db.Column(db.ForeignKey(u'issues.id'), index=True) status = db.Column(db.Text) pre_deletion_status = db.Column(db.Text) issue = db.relationship(u'Issue') user = db.relationship(u'User') class Meta: """...""" app_label = 'city_issues' managed = False db_table = 'comments'
class User(BaseModel, db.Model): """Model for users table""" __tablename__ = "users" id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(128), nullable=False) email = db.Column(db.String(128), nullable=False) password_hash = db.Column(db.String(128), nullable=False) active = db.Column(db.Boolean(), default=True, nullable=False) # using func.now(), so time is calculated by the DB server and not by server backend. # https://stackoverflow.com/questions/13370317/sqlalchemy-default-datetime?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa created_date = db.Column(db.DateTime, nullable=False, default=func.now()) def __init__(self, username, email="", password_hash=""): super().__init__() self.username = username self.email = email self.password_hash = password_hash def hash_password(self, password): self.password_hash = pwd_context.encrypt(password) def verify_password(self, password): return pwd_context.verify(password, self.password_hash) def generate_auth_token(self, expiration=600): s = Serializer(app.config['SECRET_KEY'], expires_in=expiration) return s.dumps({'id': self.id}) @staticmethod def verify_auth_token(token): s = Serializer(app.config['SECRET_KEY']) try: data = s.loads(token) except SignatureExpired: return None # valid token, but expired except BadSignature: return None # invalid token user = User.query.get(data['id']) return user
class Contact(db.Model): id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(64)) last_name = db.Column(db.String(64)) email = db.Column(db.String(128)) public = db.Column(db.Boolean) creator_user_id = db.Column(db.Integer, db.ForeignKey('user.id'), index=True) publication_ids = db.relationship("Publication", secondary=publication_recipients, backref="recipients") @validates('first_name') def validate_first_name(self, key, first_name): if not first_name: return None if not isinstance(first_name, str): raise AssertionError('First name must be string') if len(first_name) > 50: raise AssertionError('First names must be less than 50 characters') return first_name @validates('last_name') def validate_last_name(self, key, last_name): if not last_name: return None if not isinstance(last_name, str): raise AssertionError('Last name must be string') if len(last_name) > 50: raise AssertionError('Last names must be less than 50 characters') return last_name @validates('email') def validate_email(self, key, email): if not email: raise AssertionError('No email provided') if not isinstance(email, str): raise AssertionError('Email must be string') if not re.match("[^@]+@[^@]+\.[^@]+", email): raise AssertionError('Provided email is not an email address') return email.lower() @validates('public') def validates_public(self, key, public): if not public: return None if isinstance(public, bool): return public if isinstance(public, str): if public.lower() == 'true': return True if public.lower() == 'false': return False else: raise AssertionError('Public flag must be boolean value') @validates('publications') def validate_publications(self, key, publication): if not publication: raise AssertionError('No publication provided') if not isinstance(publication, Publication): raise AssertionError('Publication not recognized') return publication def get_dict(self): dict_format = { 'contact_id': self.id, 'first_name': self.first_name, 'last_name': self.last_name, 'email': self.email, 'public': self.public, 'creator': self.creator.get_dict(), } return dict_format def __repr__(self): return '<Recipient {}, {}>'.format(self.last_name, self.first_name)
class Report(db.Model): id = db.Column(db.Integer, primary_key=True) label = db.Column(db.String(64), index=True, unique=True) creator_user_id = db.Column(db.Integer, db.ForeignKey('user.id'), index=True) created_on = db.Column(db.DateTime, default=datetime.utcnow) last_published = db.Column(db.DateTime) parameters = db.Column(db.Text) publications = db.relationship('Publication', backref='publication_report', lazy='dynamic') usergroups = db.relationship("Usergroup", secondary=report_perms, backref="reports") @validates('label') def validate_label(self, key, label): if not label: raise AssertionError('No label provided') if Usergroup.query.filter( func.lower(Usergroup.label) == func.lower(label)).first(): raise AssertionError('Provided label is already in use') return label @validates('parameters') def validate_parameters(self, key, parameters): if not parameters: raise AssertionError('No parameters provided') if not isinstance(parameters, str): raise AssertionError('Provided parameters is wrong data type') return parameters @validates('usergroups') def validate_usergroups(self, key, usergroups): if not isinstance(usergroups, Usergroup): raise AssertionError('Provided usergroup is not recognized') return usergroups def get_dict(self): dict_format = { 'report_id': self.id, 'label': self.label, 'creator': self.creator.get_dict(), 'created_on': self.created_on, 'last_published': self.last_published, 'parameters': self.parameters, 'publications': self.get_publications(), } return dict_format def get_usergroups(self): usergroups = helpers.get_dicts_from_usergroups(self.usergroups) return usergroups def get_authorized_users(self): users = dict(users=helpers.get_users_from_usergroups(self.usergroups)) return users def get_publications(self): return list(map(lambda obj: obj.get_dict(), self.publications)) def __repr__(self): return '<Report {}>'.format(self.label)
class Publication(db.Model): id = db.Column(db.Integer, primary_key=True) type = db.Column(db.Enum('email_attachment', 'email_embedded', 'dashboard', name='pub_type'), default='dashboard') creator_user_id = db.Column(db.Integer, db.ForeignKey('user.id'), index=True) frequency = db.Column(db.Enum('manual', 'days_of_week', 'day_of_month', 'daily', 'hourly', 'every_ten_min', name='pub_frequency'), default='manual') monday = db.Column(db.Boolean(), default=False) tuesday = db.Column(db.Boolean(), default=False) wednesday = db.Column(db.Boolean(), default=False) thursday = db.Column(db.Boolean(), default=False) friday = db.Column(db.Boolean(), default=False) saturday = db.Column(db.Boolean(), default=False) sunday = db.Column(db.Boolean(), default=False) day_of_month = db.Column(db.Integer) pub_time = db.Column(db.Time, default=time()) report_id = db.Column(db.Integer, db.ForeignKey('report.id'), index=True) # contact_ids = db.relationship("Contact", secondary=publication_recipients, backref="publications") @validates('recipients') def validate_recipients(self, key, contact): if not contact: raise AssertionError('No contact id provided') if not isinstance(contact, Contact): raise AssertionError('Contact ID not recognized') return contact @validates('type') def validate_type(self, key, type): if not type: raise AssertionError('Publication type not provided') if type not in ['email_attachment', 'email_embedded', 'dashboard']: raise AssertionError('Publication type not recognized') return type @validates('frequency') def validate_type(self, key, frequency): if not frequency: raise AssertionError('Publication frequency not provided') if frequency not in [ 'manual', 'days_of_week', 'day_of_month', 'daily', 'hourly', 'every_ten_min' ]: raise AssertionError('Publication frequency not recognized') return frequency @validates('publication_report') def validate_contact_ids(self, key, report): if not report: raise AssertionError('No report provided') if not isinstance(report, Report): raise AssertionError('Report ID not recognized') return report def get_dict(self): dict_format = { 'publication_id': self.id, 'type': self.type, 'creator': self.creator.get_dict(), 'frequency': self.frequency, 'monday': self.monday, 'tuesday': self.tuesday, 'wednesday': self.wednesday, 'thursday': self.thursday, 'friday': self.friday, 'saturday': self.saturday, 'sunday': self.sunday, 'day_of_month': self.day_of_month, 'publication_time': self.pub_time.strftime('%l:%M%p'), 'report_id': self.report_id, 'recipients': self.get_recipients() } return dict_format def get_recipients(self): return list(map(lambda obj: obj.get_dict(), self.recipients)) def __repr__(self): return '<Publication {} for report {}'.format(self.type, self.report_id)
class TokenBlacklist(db.Model): id = db.Column(db.Integer, primary_key=True) jti = db.Column(db.String(36), nullable=False) def __repr__(self): return '<Blacklist jti: {}'.format(self.jti)
class User(db.Model): """User table in the database""" ROLE_ADMIN = 1 ROLE_MODERATOR = 2 ROLE_USER = 3 __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text) alias = db.Column(db.Text) email = db.Column(db.Text) hashed_password = db.Column(db.Text) role_id = db.Column(db.ForeignKey(u'roles.id'), index=True) avatar = db.Column(db.Text) delete_date = db.Column(db.TIMESTAMP) last_login = db.Column(db.TIMESTAMP) role = db.relationship(u'Role') @hybrid_property def password(self): """Getting the password.""" return self.hashed_password @password.setter def password(self, raw_password): """Hashing password before being stored.""" self.hashed_password = django_bcrypt.hash(raw_password) def check_password(self, raw_password): """Checking the password form database.""" return django_bcrypt.verify(raw_password, self.hashed_password) # pylint: disable=no-self-use # This needs to be checked because no self is used in function def is_last_admin(self): """Looking for the last admin""" count = User.query.filter_by(role_id=User.ROLE_ADMIN, delete_date=None).count() if count > 1: return False return True def delete(self): """Setting deleting date for user""" if self.role_id == User.ROLE_ADMIN: if not self.is_last_admin(): self.delete_date = func.current_timestamp() return True else: self.delete_date = func.current_timestamp() return True return False def restore(self): """Restoring user from deletion""" if self.delete_date: self.delete_date = None return True return False
class Chart(db.Model): id = db.Column(db.Integer, primary_key=True) label = db.Column(db.String(64), index=True, unique=True) type = db.Column(db.String(128)) parameters = db.Column(db.Text) creator_user_id = db.Column(db.Integer, db.ForeignKey('user.id'), index=True) sql_query_id = db.Column(db.Integer, db.ForeignKey('sql_query.id')) connection_id = db.Column(db.Integer, db.ForeignKey('connection.id')) usergroups = db.relationship("Usergroup", secondary=chart_perms, backref="charts") @validates('label') def validate_label(self, key, label): if not label: raise AssertionError('No label provided') if Usergroup.query.filter( func.lower(Usergroup.label) == func.lower(label)).first(): raise AssertionError('Provided label is already in use') return label @validates('type') def validate_type(self, key, type): if not type: raise AssertionError('No chart type provided') if not isinstance(type, str): raise AssertionError('chart type must be a string') return type @validates('parameters') def validate_parameters(self, key, parameters): if not parameters: raise AssertionError('No parameters provided') if not isinstance(parameters, str): raise AssertionError('Provided parameters is wrong data type') return parameters @validates('sql_query_id') def validate_sql_query_id(self, key, sql_query_id): if not sql_query_id: raise AssertionError('sql_query_id not provided') if not helpers.get_record_from_id(SqlQuery, sql_query_id): raise AssertionError('sql_query_id not recognized') return sql_query_id @validates('connection_id') def validate_connection_id(self, key, connection_id): if not connection_id: raise AssertionError('connection_id not provided') if not helpers.get_record_from_id(Connection, connection_id): raise AssertionError('connection_id not recognized') return connection_id @validates('usergroups') def validate_usergroups(self, key, usergroups): if not isinstance(usergroups, Usergroup): raise AssertionError('Provided usergroup is not recognized') return usergroups def get_dict(self): dict_format = { 'chart_id': self.id, 'label': self.label, 'creator': self.creator.get_dict(), 'type': self.type, 'parameters': self.parameters, 'sql_query': self.sql_query.get_dict(), 'connection': self.chart_connection.get_dict(), } return dict_format def get_usergroups(self): usergroups = helpers.get_dicts_from_usergroups(self.usergroups) return usergroups def get_authorized_users(self): users = dict(users=helpers.get_users_from_usergroups(self.usergroups)) return users def __repr__(self): return '<Chart label: {}>'.format(self.label)