class AbstractManagerModel(Model): all_objects = Manager() status = fields.IntField(default=0) class Meta: manager = StatusManager() abstract = True
class Permission(SharedMixin, models.Model): name = fields.CharField(max_length=191, unique=True) code = fields.CharField(max_length=30, index=True, unique=True) deleted_at = fields.DatetimeField(null=True) created_at = fields.DatetimeField(auto_now_add=True) # groups: fields.ReverseRelation[Group] # permission_users: fields.ReverseRelation['UserMod'] full = Manager() class Meta: table = 'auth_permission' manager = ActiveManager() def __str__(self): return modstr(self, 'name') @classmethod async def add(cls, code: str, name: Optional[str] = ''): if not code: raise ValueError if not name: words = code.split('.') words = [i.capitalize() for i in words] name = ' '.join(words) return await cls.create(code=code, name=name) @classmethod async def get_groups(cls, *code) -> list: """ Get the groups which contain a permission. :param code: Permission code :return: list """ if not code: return [] groups = await Group.filter(permissions__code__in=[*code] ).values_list('name', flat=True) return list(set(groups)) @classmethod async def update_permission(cls, perm: UpdatePermissionVM): if perminst := await Permission.get_or_none(pk=perm.id).only( 'id', 'code', 'name'): ll = [] if perm.code is not None: ll.append('code') perminst.code = perm.code if perm.name is not None: ll.append('name') perminst.name = perm.name if ll: await perminst.save(update_fields=ll)
class SharedMixin(object): full = Manager() def to_dict(self, exclude: Optional[List[str]] = None): d = {} exclude = ['created_at', 'deleted_at', 'updated_at' ] if exclude is None else exclude for field in self._meta.db_fields: # noqa if hasattr(self, field) and field not in exclude: d[field] = getattr(self, field) return d async def soft_delete(self): self.deleted_at = datetime.now(tz=pytz.UTC) # noqa await self.save(update_fields=['deleted_at']) # noqa
class TokenMod(models.Model): token = fields.CharField(max_length=128, unique=True) expires = fields.DatetimeField(index=True) is_blacklisted = fields.BooleanField(default=False) author = fields.ForeignKeyField('models.UserMod', on_delete=fields.CASCADE, related_name='author_tokens') full = Manager() class Meta: table = 'auth_token' manager = ActiveManager() def __str__(self): return modstr(self, 'token')
class Option(SharedMixin, models.Model): name = fields.CharField(max_length=20) value = fields.CharField(max_length=191) user = fields.ForeignKeyField('models.UserMod', related_name='options', null=True) is_active = fields.BooleanField(default=True) admin_only = fields.BooleanField(default=False) deleted_at = fields.DatetimeField(null=True) updated_at = fields.DatetimeField(auto_now=True) full = Manager() class Meta: table = 'core_option' manager = ActiveManager() def __str__(self): return modstr(self, 'name')
class Group(SharedMixin, models.Model): name = fields.CharField(max_length=191, index=True, unique=True) summary = fields.TextField(default='') deleted_at = fields.DatetimeField(null=True) created_at = fields.DatetimeField(auto_now_add=True) permissions: models.ManyToManyRelation['Permission'] = \ fields.ManyToManyField('models.Permission', related_name='groups', through='auth_group_permissions', backward_key='group_id') full = Manager() class Meta: table = 'auth_group' manager = ActiveManager() def __str__(self): return modstr(self, 'name') @classmethod async def get_and_cache(cls, group: str) -> list: """ Get a group's permissions and cache it for future use. Replaces data if exists. Only one group must be given so each can be cached separately. :param group: Group name :return: list """ perms = await Permission.filter(groups__name=group ).values_list('code', flat=True) perms = perms or [] if perms: # Save back to cache partialkey = s.CACHE_GROUPNAME.format(group) red.set(partialkey, perms, ttl=-1, clear=True) grouplist = red.exists('groups') and red.get('groups') or [] if group not in grouplist: grouplist.append(group) red.set('groups', grouplist, clear=True) return perms @classmethod async def get_permissions(cls, *groups, debug=False) -> Union[list, tuple]: """ Get a consolidated list of permissions for groups. Uses cache else query. :param groups: Names of groups :param debug: Return debug data for tests :return: List of permissions for that group """ debug = debug if s.DEBUG else False allperms, sources = set(), [] for group in groups: partialkey = s.CACHE_GROUPNAME.format(group) if perms := red.get(partialkey): sources.append('CACHE') else: sources.append('QUERY') perms = await cls.get_and_cache(group) # ic(group, perms) if perms: allperms.update(perms) if debug: return list(allperms), sources return list(allperms)
class UserMod(DTMixin, TortoiseBaseUserModel): username = fields.CharField(max_length=50, null=True) first_name = fields.CharField(max_length=191, default='') middle_name = fields.CharField(max_length=191, default='') last_name = fields.CharField(max_length=191, default='') civil = fields.CharField(max_length=20, default='') bday = fields.DateField(null=True) mobile = fields.CharField(max_length=50, default='') telephone = fields.CharField(max_length=50, default='') avatar = fields.CharField(max_length=191, default='') status = fields.CharField(max_length=20, default='') bio = fields.CharField(max_length=191, default='') address1 = fields.CharField(max_length=191, default='') address2 = fields.CharField(max_length=191, default='') country = fields.CharField(max_length=2, default='') zipcode = fields.CharField(max_length=20, default='') timezone = fields.CharField(max_length=10, default='+00:00') website = fields.CharField(max_length=20, default='') last_login = fields.DatetimeField(null=True) groups = fields.ManyToManyField('models.Group', related_name='group_users', through='auth_user_groups', backward_key='user_id') permissions = fields.ManyToManyField('models.Permission', related_name='permission_users', through='auth_user_permissions', backward_key='user_id') full = Manager() class Meta: table = 'auth_user' manager = ActiveManager() def __str__(self): return modstr(self, 'id') @property def fullname(self): return f'{self.first_name} {self.last_name}'.strip() @property async def display_name(self): if self.username: return self.username elif self.fullname: return self.fullname.split()[0] else: emailname = self.email.split('@')[0] return ' '.join(emailname.split('.')) # @classmethod # def has_perm(cls, id: str, *perms): # partialkey = s.CACHE_USERNAME.format('id') # if red.exists(partialkey): # groups = red.get(partialkey).get('groups') async def to_dict(self, exclude: Optional[List[str]] = None, prefetch=False) -> dict: """ Converts a UserMod instance into UserModComplete. Included fields are based on UserDB + groups, options, and permissions. :param exclude: Fields not to explicitly include :param prefetch: Query used prefetch_related to save on db hits :return: UserDBComplete """ d = {} exclude = ['created_at', 'deleted_at', 'updated_at' ] if exclude is None else exclude for field in self._meta.db_fields: if hasattr(self, field) and field not in exclude: d[field] = getattr(self, field) if field == 'id': d[field] = str(d[field]) if hasattr(self, 'groups'): if prefetch: d['groups'] = [i.name for i in self.groups] else: d['groups'] = await self.groups.all().values_list('name', flat=True) if hasattr(self, 'options'): if prefetch: d['options'] = {i.name: i.value for i in self.options} else: d['options'] = { i.name: i.value for i in await self.options.all().only( 'id', 'name', 'value', 'is_active') if i.is_active } if hasattr(self, 'permissions'): if prefetch: d['permissions'] = [i.code for i in self.permissions] else: d['permissions'] = await self.permissions.all().values_list( 'code', flat=True) # ic(d) return d @classmethod async def get_and_cache(cls, id, model=False): """ Get a user's cachable data and cache it for future use. Replaces data if exists. Similar to the dependency current_user. :param id: User id as str :param model: Also return the UserMod instance :return: DOESN'T NEED cache.restoreuser() since data is from the db not redis. The id key in the hash is already formatted to a str from UUID. Can be None if user doesn't exist. """ from app.auth import userdb query = UserMod.get_or_none(pk=id) \ .prefetch_related( Prefetch('groups', queryset=Group.all().only('id', 'name')), Prefetch('options', queryset=Option.all().only('user_id', 'name', 'value')), Prefetch('permissions', queryset=Permission.filter(deleted_at=None).only('id', 'code')) ) if userdb.oauth_account_model is not None: query = query.prefetch_related("oauth_accounts") usermod = await query.only(*userdb.select_fields) if usermod: user_dict = await usermod.to_dict(prefetch=True) partialkey = s.CACHE_USERNAME.format(id) red.set(partialkey, cache.prepareuser_dict(user_dict), clear=True) if model: return userdb.usercomplete(**user_dict), usermod return userdb.usercomplete(**user_dict) @classmethod async def get_data(cls, id, force_query=False, debug=False): """ Get the UserDBComplete data whether it be via cache or query. Checks cache first else query. :param force_query: Force use query instead of checking the cache :param id: User id :param debug: Debug data for tests :return: UserDBComplete/tuple or None """ from app.auth import userdb debug = debug if s.DEBUG else False partialkey = s.CACHE_USERNAME.format(id) if not force_query and red.exists(partialkey): source = 'CACHE' user_data = cache.restoreuser_dict(red.get(partialkey)) user = userdb.usercomplete(**user_data) else: source = 'QUERY' user = await UserMod.get_and_cache(id) if debug: return user, source return user async def get_permissions(self, perm_type: Optional[str] = None) -> list: """ Collate all the permissions a user has from groups + user :param perm_type: user or group :return: List of permission codes to match data with """ group_perms, user_perms = [], [] groups = await self.get_groups() if perm_type is None or perm_type == 'group': for group in groups: partialkey = s.CACHE_GROUPNAME.format(group) if perms := red.get(partialkey): group_perms += perms else: perms = Group.get_and_cache(group) group_perms += perms red.set(partialkey, perms) if perm_type is None or perm_type == 'user': partialkey = s.CACHE_USERNAME.format(self.id) if user_dict := red.get(partialkey): user_dict = cache.restoreuser_dict(user_dict) user_perms = user_dict.get('permissions') else: user = await UserMod.get_and_cache(self.id) user_perms = user.permissions