Test coverage report: permission.models

# permission.models: 96 total statements, 88.4% covered

Generated: Thu 2012-03-01 14:22 CST

Source file: /home/alisue/Dropbox/Codes/django-permission/permission/models.py

Stats: 76 executed, 10 missed, 10 excluded, 108 ignored

1. `# vim: set fileencoding=utf-8 :`
2. `"""`
3. `Permission handler base`
4. ``
5. ``
6. `AUTHOR:`
7. `lambdalisue[Ali su ae] (lambdalisue@hashnote.net)`
8. ``
9. `License:`
10. `The MIT License (MIT)`
11. ``
12. `Copyright (c) 2012 Alisue allright reserved.`
13. ``
14. `Permission is hereby granted, free of charge, to any person obtaining a copy`
15. `of this software and associated documentation files (the "Software"), to`
16. `deal in the Software without restriction, including without limitation the`
17. `rights to use, copy, modify, merge, publish, distribute, sublicense, and/or`
18. `sell copies of the Software, and to permit persons to whom the Software is`
19. `furnished to do so, subject to the following conditions:`
20. ``
21. `The above copyright notice and this permission notice shall be included in`
22. `all copies or substantial portions of the Software.`
23. ``
24. `THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR`
25. `IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,`
26. `FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE`
27. `AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER`
28. `LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING`
29. `FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS`
30. `IN THE SOFTWARE.`
31. ``
32. `"""`
33. `from __future__ import with_statement`
34. `from django.db import models`
35. `from django.contrib.auth.models import User`
36. `from django.contrib.auth.models import Permission`
37. `from django.utils.translation import ugettext_lazy as _`
38. ``
39. `from mptt.models import MPTTModel`
40. `from mptt.models import TreeForeignKey`
41. `from mptt.models import TreeManager`
42. ``
43. `class RoleManager(TreeManager):`
44. `def get_by_natural_key(self, codename):`
45. `return self.get(codename=codename)`
46. ``
47. `def filter_by_user(self, user_obj):`
48. `"""return queryset of roles which ``user_obj`` have"""`
49. `# do not defer anything otherwise the returning queryset`
50. `# contains defered instance.`
51. `roles_qs = self.none()`
52. `for role in self.filter(_users=user_obj).iterator():`
53. `roles_qs |= role.get_descendants(include_self=True)`
54. `return roles_qs`
55. ``
56. `def get_all_permissions_of_user(self, user_obj):`
57. `"""get a set of all permissions of ``user_obj``"""`
58. `# name, parent, _users, _permissions are required.`
59. `roles = self.defer('codename', 'description').filter(_users=user_obj)`
60. `permissions = Permission.objects.none()`
61. `for role in roles.iterator():`
62. `permissions |= role.permissions`
63. `return permissions.distinct()`
64. ``
65. ``
66. `class Role(MPTTModel):`
67. `"""A role model for enhanced permission system."""`
68. `name = models.CharField(_('name'), max_length=50)`
69. `codename = models.CharField(_('codename'), max_length=100, unique=True)`
70. `description = models.TextField(_('description'), blank=True,`
71. `help_text=_('A description of this permission role'))`
72. ``
73. `parent = TreeForeignKey('self', verbose_name=_('parent role'),`
74. `related_name='children', blank=True, null=True)`
75. ``
76. `_users = models.ManyToManyField(User, verbose_name=_('user'),`
77. `related_name='_roles', db_column='users', blank=True)`
78. ``
79. `_permissions = models.ManyToManyField(Permission, verbose_name=_('permissions'),`
80. `related_name='roles', db_column='permissions', blank=True)`
81. ``
82. `objects = RoleManager()`
83. ``
84. `class Meta:`
85. `verbose_name = _('role')`
86. `verbose_name_plural = _('roles')`
87. ``
88. `class MPTTMeta:`
89. `order_insertion_by = ['name']`
90. ``
91. `def __unicode__(self):`
92. `return self.name`
93. ``
94. `def natural_key(self):`
95. `return (self.codename,)`
96. ``
97. `@property`
98. `def users(self):`
99. `"""get all users who belongs to this role or superroles"""`
100. `role_pks = self.get_descendants(include_self=True).values_list('id', flat=True)`
101. `qs = User.objects.only('id', '_roles').filter(_roles__pk__in=role_pks).distinct()`
102. `return qs.defer(None)`
103. ``
104. `@property`
105. `def permissions(self):`
106. `"""get all permissions which this role or subroles have"""`
107. `role_pks = self.get_descendants(include_self=True).values_list('id', flat=True)`
108. `qs = Permission.objects.only('id', 'roles').filter(roles__pk__in=role_pks).distinct()`
109. `return qs.defer(None)`
110. ``
111. `def is_belong(self, user_obj):`
112. `"""whether the ``user_obj`` belongs to this role or superroles"""`
113. `return self.users.filter(pk=user_obj.pk).exists()`
114. ``
115. `def add_users(self, *user_or_iterable):`
116. `"""add users if the users have not belong to this role or subroles`
117. ``
118. `.. Note::`
119. `Adding user doesn't add the user who belongs to this role or`
120. `all subroles of this role. Adding users directly to ``_users```
121. `is not recommended.`
122. ``
123. `"""`
124. `if isinstance(user_or_iterable, User):`
125. `user_or_iterable = [user_or_iterable]`
126. `users_add = []`
127. `existing_users = self.users`
128. `for user in user_or_iterable:`
129. `if not existing_users.filter(pk=user.pk).exists():`
130. `users_add.append(user)`
131. `if len(users_add) > 0:`
132. `self._users.add(*users_add)`
133. ``
134. `def remove_users(self, *user_or_iterable):`
135. `"""remove users if the users have belong to this role`
136. ``
137. `.. Note::`
138. `Removing user doesn't remove the user who have not belong to this`
139. `role. All users who belongs to the subroles of this roles are`
140. `protected from removing by ``remove_users``.`
141. ``
142. `"""`
143. `if isinstance(user_or_iterable, User):`
144. `user_or_iterable = [user_or_iterable]`
145. `users_remove = []`
146. `existing_users = self._users`
147. `for user in user_or_iterable:`
148. `if existing_users.filter(pk=user.pk).exists():`
149. `users_remove.append(user)`
150. `if len(users_remove) > 0:`
151. `self._users.remove(*users_remove)`
152. ``
153. `def add_permissions(self, *perm_or_iterable):`
154. `"""add permissions if the permissions have not belong to this role or subroles`
155. ``
156. `.. Note::`
157. `Adding permissions doesn't add the permission which belongs to this role or`
158. `all subroles of this role. Adding permissions directly to ``_permissions```
159. `is not recommended.`
160. ``
161. `"""`
162. `if isinstance(perm_or_iterable, (basestring, Permission)):`
163. `perm_or_iterable = [perm_or_iterable]`
164. `existing_perms = self.permissions`
165. `for perm in perm_or_iterable:`
166. `if isinstance(perm, basestring):`
167. `app_label, codename = perm.split('.', 1)`
168. `instance = Permission.objects.get(`
169. `content_type__app_label=app_label,`
170. `codename=codename`
171. `)`
172. `else:`
173. `instance = perm`
174. `app_label = perm.content_type.app_label`
175. `codename = perm.codename`
176. `if not existing_perms.filter(content_type__app_label=app_label, codename=codename).exists():`
177. `self._permissions.add(instance)`
178. ``
179. `def remove_permissions(self, *perm_or_iterable):`
180. `"""remove permissions if the permissions have belong to this role`
181. ``
182. `.. Note::`
183. `Removing permission doesn't remove the permission who have not belong to this`
184. `role. All permissions who belongs to the subroles of this roles are`
185. `protected from removing by ``remove_permissions``.`
186. ``
187. `"""`
188. `if isinstance(perm_or_iterable, (basestring, Permission)):`
189. `perm_or_iterable = [perm_or_iterable]`
190. `existing_perms = self.permissions`
191. `for perm in perm_or_iterable:`
192. `if isinstance(perm, basestring):`
193. `app_label, codename = perm.split('.', 1)`
194. `instance = Permission.objects.get(`
195. `content_type__app_label=app_label,`
196. `codename=codename`
197. `)`
198. `else:`
199. `instance = perm`
200. `app_label = perm.content_type.app_label`
201. `codename = perm.codename`
202. `if existing_perms.filter(content_type__app_label=app_label, codename=codename).exists():`
203. `self._permissions.remove(instance)`
204. ``