Coverage for /home/runner/work/viur-core/viur-core/viur/src/viur/core/bones/user.py: 18%
22 statements
« prev ^ index » next coverage.py v7.6.3, created at 2024-10-16 22:16 +0000
« prev ^ index » next coverage.py v7.6.3, created at 2024-10-16 22:16 +0000
1import typing as t
2from viur.core import current
3from viur.core.bones.relational import RelationalBone
6class UserBone(RelationalBone):
7 """
8 A specialized relational bone for handling user references. Extends the functionality of
9 :class:`viur.core.bones.relational.RelationalBone` to include support for creation and update magic,
10 and comes with a predefined descr, format, kind and refKeys setting.
11 """
13 def __init__(
14 self,
15 *,
16 creationMagic: bool = False,
17 descr: str = "User",
18 format: str = "$(dest.lastname), $(dest.firstname) ($(dest.name))",
19 kind: str = "user",
20 readOnly: bool = False,
21 refKeys: t.Iterable[str] = ("key", "name", "firstname", "lastname"),
22 updateMagic: bool = False,
23 visible: t.Optional[bool] = None,
24 **kwargs
25 ):
26 """
27 Initializes a new UserBone.
29 :param creationMagic: If True, the bone will automatically store the creating user when a new entry is added.
30 :param updateMagic: If True, the bone will automatically store the last user who updated the entry.
32 :raises ValueError: If the bone is multiple=True and creation/update magic is set.
33 """
34 if creationMagic or updateMagic:
35 readOnly = False
36 if visible is None:
37 visible = False # defaults
38 elif visible is None:
39 visible = True
41 super().__init__(
42 kind=kind,
43 descr=descr,
44 format=format,
45 refKeys=refKeys,
46 visible=visible,
47 readOnly=readOnly,
48 **kwargs
49 )
51 self.creationMagic = creationMagic
52 self.updateMagic = updateMagic
54 if self.multiple and (creationMagic or updateMagic):
55 raise ValueError("Cannot be multiple and have a creation/update-magic set!")
57 def performMagic(self, skel, key, isAdd, *args, **kwargs):
58 """
59 Perform the magic operation on the bone value.
61 If updateMagic is enabled or creationMagic is enabled and the operation is an addition,
62 the bone will store the current user's key.
64 :param SkeletonInstance skel: The skeleton instance to operate on.
65 :param str key: The key of the bone in the skeleton.
66 :param bool isAdd: If True, the operation is an addition. Otherwise, it is an update.
67 :param args: Additional positional arguments.
68 :param kwargs: Additional keyword arguments.
69 :return: True if the magic operation was successful, False otherwise.
70 :rtype: bool
71 """
72 if self.updateMagic or (self.creationMagic and isAdd):
73 if user := current.user.get():
74 return self.setBoneValue(skel, key, user["key"], False)
76 skel[key] = None
77 return True