class User(db.Model): __tablename__ = 'users' id_ = Column(Integer, primary_key=True, autoincrement=True) create_time = Column(TIMESTAMP, default=func.now()) username = Column(String(64), unique=True) hash_password = Column(Binary(64)) encrypted_symmetric_key = Column(Binary(32), nullable=False) encrypted_private_key = Column(Binary(32), nullable=False) encrypted_public_key = Column(Binary(32), nullable=False) @classmethod def get_by(cls, **kwargs): return cls.query.filter_by(**kwargs).first() @classmethod def create_user(cls, username, hash_password): import secret user = User.get_by(username=username) assert user is None, 'email already registered' # 先随机生成一个用户的对称密钥与公私钥 symmetric_key = secret.new_symmetric_key() private_key, public_key = secret.new_pair() # 再用服务器的公钥加密这些密钥 user = User(username=username, hash_password=hash_password, encrypted_symmetric_key=secret.encrypt(symmetric_key), encrypted_private_key=secret.encrypt(private_key), encrypted_public_key=secret.encrypt(public_key)) db.session.add(user) db.session.commit()
class User(Base, UserMixin): __tablename__ = 'users' id = Column(Integer, primary_key=True) email = Column(String(254), unique=True, nullable=False) password = Column(Binary(60), nullable=False) salt = Column(Binary(40), nullable=False) first_name = Column(String(50)) last_name = Column(String(50)) account = relationship('Account', uselist=False, backref='users')
class FieldUsage(Base): __tablename__ = 'fieldusage' id = Column(Integer(), primary_key=True, autoincrement=True) timestamp = Column(DateTime(), nullable=False, server_default=func.now()) field_id = Column(Binary(16), ForeignKey(Field.id), nullable=False) fieldusage_type = Column(Integer(), ForeignKey(FieldUsageType.id), nullable=False) file_id = Column(Binary(16), ForeignKey(File.id), server_default=None) data = Column(JSONB, server_default="{}", nullable=False)
class RenderedPage(Base): __tablename__ = 'renderedpage' id = Column(Integer(), primary_key=True, autoincrement=True) file_id = Column(Binary(16), ForeignKey(File.id, ondelete="CASCADE"), nullable=False) document_id = Column(Binary(16), ForeignKey(Document.id, ondelete="CASCADE"), nullable=False) page = Column(Integer(), nullable=False)
class AccessURI(Base): __tablename__ = 'accessuri' id = Column(Integer(), primary_key=True, autoincrement=True) uri = Column(String(1024), nullable=False) user_id = Column(Binary(16), ForeignKey(User.id, ondelete="CASCADE"), nullable=False) document_id = Column(Binary(16), ForeignKey(Document.id, ondelete="CASCADE"), nullable=False) revoked = Column(Boolean(), nullable=False, server_default='0')
class URL(Base): __tablename__ = 'url' id = Column(Integer, primary_key=True) hash_domain = Column(Binary(32), nullable=False, index=True) hash_url = Column(Binary(32), nullable=False, unique=True) def __init__(self, hash_domain=None, hash_url=None): self.hash_domain = hash_domain self.hash_url = hash_url def __repr__(self): return '<URL %s %s>' % (self.hash_domain, self.hash_url)
class Document(Base): __tablename__ = 'document' id = Column(Binary(length=16), primary_key=True, nullable=False) title = Column(String(length=256), nullable=False) user_id = Column(Binary(length=16), ForeignKey(User.id, ondelete="CASCADE"), nullable=False) fields = relationship('Field') file_usages = relationship('FileUsage') pages = relationship('RenderedPage') access_uris = relationship('AccessURI')
class User(Base): __tablename__ = 'user' __versioned__ = {} id = Column(Binary(16), primary_key=True, nullable=False) username = Column(String(256), nullable=False) password = Column(Binary(60), nullable=True) business_id = Column(Integer(), ForeignKey(Business.id), nullable=False) deleted = Column(Boolean(), nullable=False, server_default='0') emails = relationship('UserEmail') documents = relationship('Document') fields = relationship('Field')
class ConsumerCredential(Base): __tablename__ = "consumercredential" email = Column(String(256), primary_key=True, unique=True, nullable=False) password = Column(Binary(60)) picture = Column(String()) is_guest = Column(Boolean, default=False) token = Column(Float, default=50.00) tasks =relationship("Tasks",backref="consumercredential", single_parent=True) active_device = Column(String(256), default="") devices = relationship("ConsumerDevice", backref="consumercredential", lazy=True, cascade="all, delete, delete-orphan", single_parent=True) def __repr__(self): return "EMAIL : {}\n" \ "IS_GUEST : {}\n" \ "TOKEN : {}\n" \ "ACTIVE_DEVICE: {}\n" \ "DEVICES : {}\n".format(self.email, self.is_guest, self.token, self.active_device, self.devices)
class XmpCacheEntry(Base): """A keyword cache entry, mapping a file to a set of keywords. Each XmpCacheEntry requires 64 (40 + 8 + 8 + ?) bytes. """ __tablename__ = "files" relpath_md5: str = Column(Binary(16), primary_key=True) relpath: str = Column(String(1024), nullable=False) mtime: int = Column(Integer, nullable=False) keywords_id: int = Column(Integer, ForeignKey("keywords.id"), nullable=False) iso: int = Column(Integer, nullable=False) camera: str = Column(String(1024), nullable=False) lens: str = Column(String(1024), nullable=False) shutter_speed: str = Column(String(128), nullable=False) aperture: str = Column(String(128), nullable=False) focal_length_35mm: str = Column(String(128), nullable=False) flash_fired: bool = Column(Boolean, nullable=False) date_added: datetime.datetime = Column(DateTime, nullable=False, default=datetime.datetime.utcnow) keywords: 'Keywords' = orm.relationship("Keywords")
class User(UserMixin, SurrogatePK, Model): """A user of the app.""" __tablename__ = 'users' id = Column(Integer, primary_key=True) email = Column(String(255), unique=True, nullable=False) full_name = Column(String(255), unique=False, nullable=False) password = Column(Binary(128), nullable=False) last_login_at = Column(DateTime, default=None) is_active = Column(Boolean(), default=False, nullable=False) is_admin = Column(Boolean(), default=False, nullable=False) permissions = relationship('Permission', back_populates='user', foreign_keys='Permission.user_id') modified_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) modified_by_id = reference_col('users', nullable=True) modified_by = relationship('User', remote_side=id, foreign_keys=modified_by_id) created_at = Column(DateTime, default=datetime.utcnow, nullable=False) created_by_id = reference_col('users', nullable=True) created_by = relationship('User', remote_side=id, foreign_keys=created_by_id) def __init__(self, email, full_name, password=None, **kwargs): """Create instance.""" # noinspection PyArgumentList super(User, self).__init__(email=email, full_name=full_name, **kwargs) if password: self.set_password(password) else: self.set_password(hexlify(urandom(16))) @staticmethod def get_by_email(email): """Get by email.""" return session.query(User).filter(User.email.ilike(email)).first() def set_password(self, password): """Set password.""" self.password = Bcrypt().generate_password_hash(password) def save_as(self, current_user, commit=True, preserve_modified=False): """Save instance as 'current_user'.""" if current_user and not self.created_at: self.created_by = current_user if current_user and not preserve_modified: self.modified_by_id = current_user.id # Using ``self.modified_by = current_user`` yields error when user modifies itself: # "sqlalchemy.exc.CircularDependencyError: Circular dependency detected." return self.save(commit=commit, preserve_modified=preserve_modified)
class CachedError(Base): """Cached linter error.""" __tablename__ = "errors" id: int = Column(Integer, primary_key=True) dir: str = Column(Binary(16), ForeignKey("directories.relpath_md5"), nullable=False) relpath: str = Column(String(1024), nullable=False) category: str = Column(String(512), nullable=False) message: str = Column(String(512), nullable=False) fix_it: str = Column(String(512), nullable=False) directory: Directory = orm.relationship("Directory") __table_args__ = (UniqueConstraint('dir', 'relpath', 'category', 'message', 'fix_it', name='unique_error'), ) def __repr__(self): return (f'{self.relpath}: ' f'{shell.ShellEscapeCodes.YELLOW}{self.message}' f'{shell.ShellEscapeCodes.END} [{self.category}]')
class HasThumbMixin(object): thumbCount = Column(Integer(), nullable=False, default=0) firstThumbDominantColor = Column(Binary(3), CheckConstraint('"thumbCount"=0 OR "firstThumbDominantColor" IS NOT NULL', name='check_thumb_has_dominant_color'), nullable=True) def delete_thumb(self, index): delete_public_object("thumbs", self.get_thumb_storage_id(index)) def thumb_date(self, index): return get_public_object_date("thumbs", self.get_thumb_storage_id(index)) def get_thumb_storage_id(self, index): if self.id is None: raise ValueError("Trying to get thumb_storage_id for an unsaved object") return inflect_engine.plural(self.__class__.__name__.lower()) \ + "/" \ + humanize(self.id) \ + (('_' + str(index)) if index > 0 else '') @property def thumbUrl(self): base_url = get_storage_base_url() thumb_url = base_url + "/thumbs" return '{}/{}/{}'.format(thumb_url, get_model_plural_name(self), humanize(self.id))
class PasswordReset(Base): __tablename__ = 'passwordreset' created_at = Column(DateTime(timezone=True), default=func.now(), nullable=False) reset_token = Column(Binary(length=16), primary_key=True) user = relationship('User', backref=backref('password_reset', cascade='all')) user_id = Column(Integer, ForeignKey('user.id'), nullable=False, unique=True) @classmethod def fetch_by(cls, **kwargs): if 'reset_token' in kwargs: kwargs['reset_token'] = uuid.UUID(kwargs['reset_token']).bytes return Session.query(cls).filter_by(**kwargs).first() @classmethod def generate(cls, user): pr = cls.fetch_by(user=user) if pr: retval = None else: retval = cls(reset_token=uuid.uuid4().bytes, user=user) return retval def get_token(self): return str(uuid.UUID(bytes=self.reset_token))
class UserData(SqlDataModel): __tablename__ = "users" name = Column(String, nullable=True) email = Column(String, nullable=False, unique=True, index=True) is_admin = Column(Boolean, nullable=False, default=False) password = Column(Binary(100), nullable=True) def to_model(self): return User( uid=self.uid, created_at=self.created_at, updated_at=self.updated_at, name=self.name, email=self.email, is_admin=self.is_admin, password=self.password, ) def from_model(self, model): self.uid = model.uid self.created_at = model.created_at self.updated_at = model.updated_at self.name = model.name self.email = model.email self.is_admin = model.is_admin self.password = model.password def update_model(self, model): model.uid = self.uid model.created_at = self.created_at model.updated_at = self.updated_at
class User(SitemapMixin, db.Model): __tablename__ = "users" __table_args__ = ( CheckConstraint("length(username) <= 50", name="users_valid_username_length"), CheckConstraint( "username ~* '^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$'", name="users_valid_username", ), ) __repr__ = make_repr("username") username = Column(CIText, nullable=False, unique=True) name = Column(String(length=100), nullable=False) password = Column(String(length=128), nullable=False) password_date = Column(DateTime, nullable=True, server_default=sql.func.now()) is_active = Column(Boolean, nullable=False, server_default=sql.false()) is_superuser = Column(Boolean, nullable=False, server_default=sql.false()) is_moderator = Column(Boolean, nullable=False, server_default=sql.false()) date_joined = Column(DateTime, server_default=sql.func.now()) last_login = Column(DateTime, nullable=False, server_default=sql.func.now()) disabled_for = Column( Enum(DisableReason, values_callable=lambda x: [e.value for e in x]), nullable=True, ) totp_secret = Column(Binary(length=20), nullable=True) emails = orm.relationship( "Email", backref="user", cascade="all, delete-orphan", lazy=False ) @property def primary_email(self): primaries = [x for x in self.emails if x.primary] if primaries: return primaries[0] @hybrid_property def email(self): primary_email = self.primary_email return primary_email.email if primary_email else None @email.expression def email(self): return ( select([Email.email]) .where((Email.user_id == self.id) & (Email.primary.is_(True))) .as_scalar() ) @property def has_two_factor(self): # TODO: This is where user.u2f_provisioned et al. # will also go. return self.totp_secret is not None @property def two_factor_provisioning_allowed(self): return self.primary_email is not None and self.primary_email.verified
class Post(Base): """A Model for defining a post within a subreddit.""" __tablename__ = 'posts' id = Column(String(127), primary_key=True) name = Column(String(255), index=True) url = Column(String(1023), nullable=False, index=True) score = Column(Integer, nullable=False, default=0, index=True) upvote_ratio = Column(Float, nullable=False, index=True) last_updated_on = Column(DateTime, nullable=False, default=datetime.utcnow) deleted = Column(Boolean, nullable=False, default=False, index=True) comments = relationship('Comment', back_populates='post') filepath = Column(String(), nullable=True) filehash = Column(Binary(256), nullable=True) is_downloaded = Column(Boolean, nullable=False, default=True, index=True) subreddit_id = reference_col('subreddits', pk_name='id', index=True) subreddit = relationship('Subreddit', back_populates='posts') def __repr__(self): return f'Post[{self.id}]: {self.url}' def download(self): """Attempt to download the reddit post.""" pass
class Sensor(Base): __tablename__ = "sensor" user_token = Column(VARCHAR(length=8)) device_id = Column(VARCHAR(length=4)) sensor_id = Column(VARCHAR(length=4), primary_key=True) sensor_name = Column(VARCHAR(length=30)) sensor_type = Column(VARCHAR(length=30)) is_alive = Column(Binary(length=1)) def __init__(self, user_token, device_id, sensor_id, sensor_name, sensor_type, is_alive): self.user_token = user_token self.device_id = device_id self.sensor_id = sensor_id self.sensor_name = sensor_name self.sensor_type = sensor_type self.is_alive = is_alive def __repr__(self): result = { "user_token": self.user_token, "device_id": self.device_id, "sensor_id": self.sensor_id, "sensor_name": self.sensor_name, "sensor_type": self.sensor_type, "is_alive": str(self.is_alive.decode())} return json.dumps(result)
class CyRecord(Base): __tablename__ = 'records' # __table_args__ = { # 'mysql_engine': 'InnoDB', # 'mysql_charset': 'utf8mb4', # } record_id = Column('record_id', Integer, primary_key=True, autoincrement=True) name = Column('name', String(24), index=True, nullable=False) box_name = Column('box_name', String(32), nullable=False) last_update = Column('last_update', DateTime, onupdate=datetime.now) record_count = Column('record_count', Integer) record_data = Column('record_data', Binary(200)) def __init__(self, name: str, box_name: str): self.name = name self.box_name = box_name self.last_update = datetime.now() self.record_count = 0 self.record_data = b'' def __repr__(self): repr_args = ', '.join([ "record_id={}".format(self.record_id), "name='{}'".format(self.name), "box_name='{}'".format(self.box_name), "last_update='{}'".format(self.last_update), "record_count={}".format(self.record_count), "record_data=b'{}'".format(self.record_data), ]) return "<CyRecord({})".format(repr_args)
class UserTable(SqlTable): __tablename__ = "users" name = Column(String, nullable=True) email = Column(String, nullable=False, unique=True, index=True) is_admin = Column(Boolean, nullable=False, default=False) password = Column(Binary(100), nullable=True)
class Token(Base): """Simple token object.""" id = Column(Integer, primary_key=True) key = Column(Unicode()) value = Column(Binary()) single_use = Column(Boolean()) validated = Column(Boolean()) expiry = Column(DateTime()) created_at = Column(DateTime()) modified_at = Column(DateTime()) deleted_at = Column(DateTime()) def validate(self, expected_value): """Validate the stored value against an expected. @:param expected_value: str value expected to match. @:return bool """ if not self.value: return False now = datetime.timestamp(datetime.now()) expired = self.expiry < now is_valid = self.objects.get_value(self) == expected_value if expired or is_valid: self.validated = True self.expiry = now self.save() if expired or self.single_use: self.delete() if expired: return False return is_valid
class Meta(DeclarativeBase): __tablename__ = "meta" __table_args__ = {"mysql_engine": "InnoDB", "mysql_charset": "utf8"} id = Column(Integer, primary_key=True) # Secret key secret = Column(Binary(8), nullable=False) # help.mit.edu password pony_rt_pass = Column(Unicode(255)) def __init__(self): self.secret = "".join(chr(random.randint(0, 255)) for x in xrange(8)) @staticmethod def token_for_user(user): return hmac.new(Meta.get().secret, user, hashlib.sha1).hexdigest() @staticmethod def get(): try: return Meta.query.one() except NoResultFound: meta = Meta() DBSession.add(meta) return meta
class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) login = Column(String(128), unique=True, nullable=False) mail = Column(String(256), unique=True, nullable=False) password_hash = Column(Binary(60), nullable=False) role_id = Column(Integer, ForeignKey('role.id'), nullable=False) role = relationship('Role', back_populates='users', lazy=False, innerjoin=True) def __init__(self, login, mail, password, role_id=None): self.login = login self.mail = mail self.generate_password_hash(password) if role_id is not None: self.role_id = role_id def generate_password_hash(self, password): self.password_hash = bcrypt.generate_password_hash(password) def check_password_hash(self, password): return bcrypt.check_password_hash(self.password_hash, password)
class Device(DictionaryBase, Base): __tablename__ = "Device" archiveDepthHour = Column("ArchiveDepthHour", Integer) archiveDepthDay = Column("ArchiveDepthDay", Integer) archiveDepthMonth = Column("ArchiveDepthMonth", Integer) shortName = Column("ShortName", Integer) image = Column("Image", Binary("MAX")) hasDigitalInterface = Column("HasDigitalInterface", Boolean) calibrationInterval = Column("CalibrationInterval", Integer) channelsCount = Column("ChannelsCount", Integer) isIntegralArchiveValue = Column("IsIntegralArchiveValue", Boolean) baudId = Column("BaudId", Integer, ForeignKey("Dictionaries.Baud.Id")) dataBitId = Column("DataBitId", Integer, ForeignKey("Dictionaries.DataBit.Id")) stopBitId = Column("StopBitId", Integer, ForeignKey("Dictionaries.StopBit.Id")) parityId = Column("ParityId", Integer, ForeignKey("Dictionaries.Parity.Id")) baud = relationship("Baud", back_populates="devices") dataBit = relationship("DataBit", back_populates="devices") stopBit = relationship("StopBit", back_populates="devices") parity = relationship("Parity", back_populates="devices") deviceEventParameters = relationship("DeviceEventParameter", back_populates="device") internalDeviceEvents = relationship("InternalDeviceEvent", back_populates="device") deviceParameters = relationship("DeviceParameter", back_populates="device") channelTemplates = relationship("ChannelTemplate", back_populates="device") measurementDevices = relationship("MeasurementDevice", back_populates="device")
class User(Wrapper, Model, HasThumbMixin, NeedsValidationMixin): email = Column(String(120), nullable=False, unique=True) password = Column(Binary(60), nullable=False) publicName = Column(String(30), nullable=False) clearTextPassword = None def checkPassword(self, passwordToCheck): return bcrypt.hashpw(passwordToCheck.encode('utf-8'), self.password) == self.password def errors(self): errors = super(User, self).errors() if self.id is None\ and User.query.filter_by(email=self.email).count()>0: errors.addError('email', 'Un compte lié à cet email existe déjà') if self.publicName: errors.checkMinLength('publicName', self.publicName, 3) if self.email: errors.checkEmail('email', self.email) # if self.firstname: # errors.checkMinLength('firstname', self.firstname, 2) # if self.lastname: # errors.checkMinLength('lastname', self.lastname, 2) if self.clearTextPassword: errors.checkMinLength('password', self.clearTextPassword, 8) return errors def get_id(self): return str(self.id) def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def populateFromDict(self, dct): super(User, self).populateFromDict(dct) if dct.__contains__('password') and dct['password']: self.setPassword(dct['password']) def setPassword(self, newpass): self.clearTextPassword = newpass self.password = bcrypt.hashpw(newpass.encode('utf-8'), bcrypt.gensalt()) def hasRights(self, roleType): return Role.query\ .filter((Role.userId == self.id) & (Role.type == roleType))\ .first() is not None
class Block(Base): __tablename__ = 'block' id = Column(Integer, primary_key=True) hash = Column(Binary(32), unique=True) height = Column(Integer, unique=True) size = Column(Integer) totalfee = Column(Float(asdecimal=True)) timestamp = Column(DateTime, index=True) difficulty = Column(Float(asdecimal=True)) firstseen = Column(DateTime) relayedby = Column(String(48)) miner_id = Column('miner', Integer, ForeignKey('pool.id'), index=True) miner = relationship('Pool') coinbaseinfo = relationship('CoinbaseInfo', back_populates='block', uselist=False) transactionreferences = relationship('BlockTransaction', back_populates='block', cascade='save-update, merge, delete') API_DATA_FIELDS = [ hash, height, size, timestamp, difficulty, firstseen, relayedby, 'Block.totaltransacted', 'Block.totalfees', 'Block.miningreward' ] POSTPROCESS_RESOLVE_FOREIGN_KEYS = [ miner, 'Block.transactions', 'Transaction.mutations', 'Transaction.inputs', 'Transaction.outputs' ] @property def transactions(self): return [ result[1] for result in Session.object_session(self).query( BlockTransaction.id, Transaction).join( BlockTransaction.transaction).filter( BlockTransaction.block_id == self.id).order_by( BlockTransaction.id).all() ] @property def time(self): return self.firstseen if self.firstseen != None else self.timestamp @property def totalfees(self): return self.totalfee @property def miningreward(self): return self.coinbaseinfo.newcoins if self.coinbaseinfo != None else None @property def totaltransacted(self): return sum([ tx.totalvalue for tx in filter(lambda tx: not tx.coinbase, self.transactions) ])
class Account(Base): __tablename__ = 'account' id = Column(Integer, primary_key=True) manager_id = Column('manager', Integer, ForeignKey('manager.id')) user = Column(String(ACCOUNT_NAME_LEN)) iv = Column(Binary(16)) encrypted_key = Column('key', Binary(32)) pubkeyhash = Column(Binary(20)) addresses = relationship('AccountAddress', back_populates='account', cascade='save-update, merge, delete') _consolidationinfo = relationship('AccountAutoConsolidationInfo', back_populates='account', cascade='save-update, merge, delete') manager = relationship('WalletManager', back_populates='accounts') @property def private_key(self): cipher = AES.new(unhexlify(config.ENCRYPTION_KEY), AES.MODE_CBC, self.iv) return cipher.decrypt(self.encrypted_key) @private_key.setter def private_key(self, value): self.iv = os.urandom(AES.block_size) cipher = AES.new(unhexlify(config.ENCRYPTION_KEY), AES.MODE_CBC, self.iv) self.encrypted_key = cipher.encrypt(value) @property def consolidationinfo(self): consolidationinfo = {coin.ticker: None for coin in COINS} for info in self._consolidationinfo: consolidationinfo[info.coin] = info return consolidationinfo def consolidationinfo_for(self, coin): return Session.object_session(self).query( AccountAutoConsolidationInfo).filter( AccountAutoConsolidationInfo.account_id == self.id, AccountAutoConsolidationInfo.coin == coin.ticker).first() API_DATA_FIELDS = [user, 'Account.consolidationinfo'] POSTPROCESS_RESOLVE_FOREIGN_KEYS = [addresses]
class File(Base): __tablename__ = 'file' id = Column(Binary(length=16), nullable=False, primary_key=True) filename = Column(String(100), server_default=None) request_uri = Column(String(512), server_default=None) fileusages = relationship('FileUsage') fieldusages = relationship('FieldUsage')
class Fingerprint(Base): __tablename__ = 'fingerprint' id = Column(Integer, primary_key=True) hash = Column(Binary(length=16), nullable=False) time = Column(Integer, nullable=False) song_id = Column(Integer, ForeignKey('song.id', ondelete='CASCADE'), nullable=False) song = relationship(Song)
class WalletManager(Base): __tablename__ = 'manager' id = Column(Integer, primary_key=True) name = Column(String(64)) tokenhash = Column(Binary(32), unique=True) accounts = relationship('Account', back_populates='manager', cascade='save-update, merge, delete')