You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

274 lines
10 KiB

  1. ###################################################################################
  2. #
  3. # Copyright (C) 2017 MuK IT GmbH
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. #
  18. ###################################################################################
  19. import logging
  20. from odoo import _, SUPERUSER_ID
  21. from odoo import models, api, fields
  22. from odoo.exceptions import AccessError
  23. from odoo.addons.muk_security.tools.security import NoSecurityUid
  24. _logger = logging.getLogger(__name__)
  25. class BaseModelAccessGroups(models.AbstractModel):
  26. _name = 'muk_security.mixins.access_groups'
  27. _description = "Group Access Mixin"
  28. _inherit = 'muk_security.mixins.access'
  29. # Set it to True to enforced security even if no group has been set
  30. _strict_security = False
  31. # If set the group fields are restricted by the access group
  32. _field_groups = None
  33. # If set the suspend fields are restricted by the access group
  34. _suspend_groups = None
  35. #----------------------------------------------------------
  36. # Datebase
  37. #----------------------------------------------------------
  38. @api.model
  39. def _add_magic_fields(self):
  40. super(BaseModelAccessGroups, self)._add_magic_fields()
  41. def add(name, field):
  42. if name not in self._fields:
  43. self._add_field(name, field)
  44. model = self._name.split(".")[-1]
  45. add('suspend_security_read', fields.Boolean(
  46. _module=self._module,
  47. string="Suspend Security for Read",
  48. automatic=True,
  49. default=False,
  50. groups=self._suspend_groups))
  51. add('suspend_security_create', fields.Boolean(
  52. _module=self._module,
  53. string="Suspend Security for Create",
  54. automatic=True,
  55. default=False,
  56. groups=self._suspend_groups))
  57. add('suspend_security_write', fields.Boolean(
  58. _module=self._module,
  59. string="Suspend Security for Write",
  60. automatic=True,
  61. default=False,
  62. groups=self._suspend_groups))
  63. add('suspend_security_unlink', fields.Boolean(
  64. _module=self._module,
  65. string="Suspend Security for Unlink",
  66. automatic=True,
  67. default=False,
  68. groups=self._suspend_groups))
  69. add('groups', fields.Many2many(
  70. _module=self._module,
  71. comodel_name='muk_security.groups',
  72. relation='muk_groups_%s_rel' % model,
  73. column1='aid',
  74. column2='gid',
  75. string="Groups",
  76. automatic=True,
  77. groups=self._field_groups))
  78. add('complete_groups', fields.Many2many(
  79. _module=self._module,
  80. comodel_name='muk_security.groups',
  81. relation='muk_groups_complete_%s_rel' % model,
  82. column1='aid',
  83. column2='gid',
  84. string="Complete Groups",
  85. compute='_compute_groups',
  86. store=True,
  87. automatic=True,
  88. groups=self._field_groups))
  89. #----------------------------------------------------------
  90. # Function
  91. #----------------------------------------------------------
  92. @api.model
  93. def _get_no_access_ids(self):
  94. model = self._name.split(".")[-1]
  95. if not self._strict_security:
  96. sql = '''
  97. SELECT id
  98. FROM %s a
  99. WHERE NOT EXISTS (
  100. SELECT *
  101. FROM muk_groups_complete_%s_rel r
  102. WHERE r.aid = a.id
  103. );
  104. ''' % (self._table, model)
  105. self.env.cr.execute(sql)
  106. fetch = self.env.cr.fetchall()
  107. return len(fetch) > 0 and list(map(lambda x: x[0], fetch)) or []
  108. else:
  109. return []
  110. @api.model
  111. def _get_suspended_access_ids(self, operation):
  112. model = self._name.split(".")[-1]
  113. sql = '''
  114. SELECT id
  115. FROM %s a
  116. WHERE a.suspend_security_%s = true
  117. ''' % (self._table, operation)
  118. self.env.cr.execute(sql)
  119. fetch = self.env.cr.fetchall()
  120. return len(fetch) > 0 and list(map(lambda x: x[0], fetch)) or []
  121. @api.model
  122. def _get_access_ids(self):
  123. model = self._name.split(".")[-1]
  124. sql = '''
  125. SELECT r.aid
  126. FROM muk_groups_complete_%s_rel r
  127. JOIN muk_security_groups g ON r.gid = g.id
  128. JOIN muk_security_groups_users_rel u ON r.gid = u.gid
  129. WHERE u.uid = %s AND g.perm_read = true
  130. ''' % (model, self.env.user.id)
  131. self.env.cr.execute(sql)
  132. fetch = self.env.cr.fetchall()
  133. access_ids = len(fetch) > 0 and list(map(lambda x: x[0], fetch)) or []
  134. return access_ids
  135. @api.model
  136. def _get_ids_without_security(self, operation):
  137. no_access_ids = self._get_no_access_ids()
  138. suspended_access_ids = self._get_suspended_access_ids(operation)
  139. return list(set(no_access_ids).union(suspended_access_ids))
  140. @api.model
  141. def _get_complete_access_ids(self, operation):
  142. access_ids = self._get_access_ids()
  143. no_access_ids = self._get_no_access_ids()
  144. suspended_access_ids = self._get_suspended_access_ids(operation)
  145. return list(set(access_ids).union(no_access_ids, suspended_access_ids))
  146. @api.multi
  147. def _eval_access_skip(self, operation):
  148. if isinstance(self.env.uid, NoSecurityUid):
  149. return True
  150. return False
  151. @api.multi
  152. def check_access_groups(self, operation):
  153. if self.env.user.id == SUPERUSER_ID or self._eval_access_skip(operation):
  154. return None
  155. model = self._name.split(".")[-1]
  156. filter_ids = self._get_ids_without_security(operation)
  157. for record in self.filtered(lambda rec: rec.id not in filter_ids):
  158. sql = '''
  159. SELECT perm_%s
  160. FROM muk_groups_complete_%s_rel r
  161. JOIN muk_security_groups g ON g.id = r.gid
  162. JOIN muk_security_groups_users_rel u ON u.gid = g.id
  163. WHERE r.aid = %s AND u.uid = %s
  164. ''' % (operation, model, record.id, self.env.user.id)
  165. self.env.cr.execute(sql)
  166. fetch = self.env.cr.fetchall()
  167. if not any(list(map(lambda x: x[0], fetch))):
  168. raise AccessError(_("This operation is forbidden!"))
  169. @api.multi
  170. def check_access(self, operation, raise_exception=False):
  171. res = super(BaseModelAccessGroups, self).check_access(operation, raise_exception)
  172. try:
  173. access_groups = self.check_access_groups(operation) == None
  174. access = res and access_groups
  175. if not access and raise_exception:
  176. raise AccessError(_("This operation is forbidden!"))
  177. return access
  178. except AccessError:
  179. if raise_exception:
  180. raise AccessError(_("This operation is forbidden!"))
  181. return False
  182. #----------------------------------------------------------
  183. # Read
  184. #----------------------------------------------------------
  185. @api.multi
  186. def _after_read(self, result, *largs, **kwargs):
  187. result = super(BaseModelAccessGroups, self)._after_read(result)
  188. if self.env.user.id == SUPERUSER_ID or self._eval_access_skip("read"):
  189. return result
  190. access_ids = self._get_complete_access_ids("read")
  191. result = [result] if not isinstance(result, list) else result
  192. if len(access_ids) > 0:
  193. access_result = []
  194. for record in result:
  195. if record['id'] in access_ids:
  196. access_result.append(record)
  197. return access_result
  198. return []
  199. @api.model
  200. def _after_search(self, result, *largs, **kwargs):
  201. result = super(BaseModelAccessGroups, self)._after_search(result)
  202. if self.env.user.id == SUPERUSER_ID or self._eval_access_skip("read"):
  203. return result
  204. access_ids = self._get_complete_access_ids("read")
  205. if len(access_ids) > 0:
  206. access_result = self.env[self._name]
  207. if isinstance(result, int):
  208. if result in access_ids:
  209. return result
  210. else:
  211. for record in result:
  212. if record.id in access_ids:
  213. access_result += record
  214. return access_result
  215. return self.env[self._name]
  216. @api.model
  217. def _after_name_search(self, result, *largs, **kwargs):
  218. result = super(BaseModelAccessGroups, self)._after_name_search(result)
  219. if self.env.user.id == SUPERUSER_ID or self._eval_access_skip("read"):
  220. return result
  221. access_ids = self._get_complete_access_ids("read")
  222. if len(access_ids) > 0:
  223. access_result = []
  224. for tuple in result:
  225. if tuple[0] in access_ids:
  226. access_result.append(tuple)
  227. return access_result
  228. return []
  229. #----------------------------------------------------------
  230. # Read, View
  231. #----------------------------------------------------------
  232. @api.depends('groups')
  233. def _compute_groups(self):
  234. for record in self:
  235. record.complete_groups = record.groups
  236. #----------------------------------------------------------
  237. # Create, Update, Delete
  238. #----------------------------------------------------------
  239. @api.multi
  240. def _before_write(self, vals, *largs, **kwargs):
  241. self.check_access_groups('write')
  242. return super(BaseModelAccessGroups, self)._before_write(vals, *largs, **kwargs)
  243. @api.multi
  244. def _before_unlink(self, *largs, **kwargs):
  245. self.check_access_groups('unlink')
  246. return super(BaseModelAccessGroups, self)._before_unlink(*largs, **kwargs)