class Household(Model): id = fields.IntField(pk=True) week = fields.BinaryField(null=True) @classmethod async def get_user(cls, name, **kwargs): return cls.get(name=name)
class SampleModelChild(Model): id = fields.UUIDField(pk=True) name = fields.TextField(max_length=400) number = fields.IntField() created = fields.DatetimeField(auto_now_add=True) data = fields.BinaryField() sample_model = fields.ForeignKeyField('tests.SampleModel', related_name='childs')
class File(Model): id = fields.UUIDField(pk=True) name = fields.CharField(max_length=255) data = fields.BinaryField() status = fields.IntEnumField(FileStatus) def __str__(self): return f'id: {self.id} url:{self.name}'
class KeywordReply(BaseModel): """ 关键词回复 """ keyword = fields.TextField(max_length=200) reply_type = fields.TextField(null=False, max_length=10) reply = fields.BinaryField(null=False) reply_md5 = fields.TextField(max_length=32) class Meta: name = "keyword_reply" unique_together = ("keyword", "reply_md5")
class PubSubMsgRecord(Model): sizeRaw = fields.IntField(default=0) sizeTr = fields.IntField(default=0) seqNo = fields.BinaryField(null=True) senderPeerId = fields.CharField(max_length=128) dateRcv = fields.DatetimeField(auto_now_add=True) channel = fields.ForeignKeyField('models.PubSubChannel', related_name='channel', through='messagerecord_channel', description='PS Channel')
class Image(models.Model): """ The image model """ id = fields.IntField(pk=True) description = fields.TextField() user = fields.ForeignKeyField('models.Users', on_delete=fields.CASCADE) image = fields.BinaryField() count_faces = fields.IntField() faces: fields.ReverseRelation["Faces"] class PydanticMeta: exclude = ['image']
class User(BaseModelTortoise): """User""" email = fields.CharField(unique=True, max_length=256) password_hash = fields.BinaryField(null=True) first_name = fields.CharField(max_length=64, null=True) last_name = fields.CharField(max_length=64, null=True) picture = fields.CharField(max_length=1024, null=True) role: fields.ForeignKeyRelation[Role] = fields.ForeignKeyField( "models.Role", related_name="assigned_users") # type: ignore @staticmethod def get_search_fields() -> List[str]: return ["email", "first_name", "last_name"]
class User(Model): id = fields.IntField(pk=True) email = fields.CharField(max_length=255) _password = fields.BinaryField(null=True) salt = fields.BinaryField(null=True) city = fields.CharField(max_length=255, null=True) timestamp = fields.DatetimeField(auto_now_add=True) is_active = fields.BooleanField(default=False) is_login = fields.BooleanField(default=False) @property def password(self): return self._password @password.setter def password(self, password): self.salt = bcrypt.gensalt() self._password = bcrypt.hashpw(password.encode(), self.salt) def __str__(self): return ''.join(f'{key}:{val}, ' for key, val in self.__dict__.items())
class Account(BaseModel): username = fields.CharField(max_length=45) email = fields.CharField(unique=True, max_length=45) phone = fields.CharField(unique=True, max_length=20, null=True) password = fields.BinaryField() disabled = fields.BooleanField(default=False) verified = fields.BooleanField(default=False) class ErrorFactory(BaseErrorFactory): def get(self, model): error = None if not model: error = Account.NotFoundError('This account does not exist.') elif model.deleted: error = Account.DeletedError( 'This account has been permanently deleted.') elif model.disabled: error = Account.DisabledError() elif not model.verified: error = Account.UnverifiedError() return error class AccountError(RoseError): def __init__(self, message, code): super().__init__(message, code) class AccountExistsError(AccountError): def __init__(self): super().__init__( 'Account with this email or phone number already exists.', 409) class DisabledError(AccountError): def __init__(self): super().__init__( "This account has been disabled. This could be due to an infraction.", 401) class IncorrectPasswordError(AccountError): def __init__(self): super().__init__('The password provided is incorrect.', 401) class UnverifiedError(AccountError): def __init__(self): super().__init__('Account requires verification.', 401)
class User(Model): crypter = None authId = fields.CharField(128, null=True, unique=True, description='OAuth identity') name = fields.CharField(64, description='UNIX user name') passwordEncrypted = fields.BinaryField(description='UNIX user password') def __repr__(self): return f'<User {self.name}>' def __str__(self): return repr(self) @classmethod def setup(cls, key): # Obviously this is security through obscurity. But we want to make sure # that someone with access to the database cannot gain SSH access unless he # also has access to this application, which would be game over anyway. It # would be nice if we could encrypt it with the user’s password, but – you # know – OAuth. cls.crypter = Fernet(key) @property def password(self): return self.crypter.decrypt(self.passwordEncrypted).decode('utf-8') @password.setter def password(self, password): self.passwordEncrypted = self.crypter.encrypt(password.encode('utf-8')) async def getChannel(self, kind, *args, **kwargs): return await connmgr.getChannel(self, kind, *args, **kwargs) async def getConnection(self, acceptTos=False): return await connmgr._getConnection(self, acceptTos) async def getSftp(self): return await connmgr.getSftp(self)
class BinaryFields(Model): id = fields.IntField(pk=True) binary = fields.BinaryField() binary_null = fields.BinaryField(null=True)
class User(Model): id = fields.IntField(pk=True) login = fields.CharField(max_length=255, unique=True) first_name = fields.CharField(max_length=255) last_name = fields.CharField(max_length=255) hashed_password = fields.BinaryField() created_at = fields.DatetimeField(auto_now_add=True) updated_at = fields.DatetimeField(auto_now=True) is_deleted = fields.BooleanField(default=False) photo = fields.IntField( null=True, default=None) # Альтернатива - ForeignKey для модели Upload totp_active = fields.BooleanField(default=False) totp_key = fields.CharField(max_length=26, null=True, default=None) @staticmethod async def find(user_id: int = None, user_login: str = None, is_deleted: bool = False, **kwargs): try: if user_id is not None: user = await User.get(id=user_id, is_deleted=is_deleted, **kwargs) else: user = await User.get(login=user_login, is_deleted=is_deleted, **kwargs) return user except DoesNotExist: raise InvalidUsage('This user does not exist') @staticmethod async def register(first_name: str, last_name: str, login: str, password: str): if await User.exists(login=login): raise InvalidUsage('This login is already taken') user = await User.create(first_name=first_name, last_name=last_name, login=login, hashed_password=hash_pass(password)) return user async def update(self, **kwargs): try: await self.update_from_dict(kwargs) await self.save() except ValueError: raise InvalidUsage('Invalid data') async def add_totp(self): self.totp_key = pyotp.random_base32() await self.save() async def check_totp(self, code: str): if self.totp_key is None: raise InvalidUsage('Two-factor authentication not activated') if pyotp.TOTP(self.totp_key).verify(code): return True else: raise InvalidUsage('Code is invalid') class DoesNotExist(DoesNotExist): pass async def dump(self): user = (await UserSchema.from_tortoise_orm(self)).dict() user.pop('hashed_password') user.pop('totp_key') user.pop('totp_active') user['created_at'] = str(user['created_at']) user['updated_at'] = str(user['updated_at']) return user def __str__(self): return self.login
class BinaryFields(Model): id = fields.IntegerField(primary_key=True) binary = fields.BinaryField() binary_null = fields.BinaryField(null=True)