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.

308 lines
12 KiB

7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
  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 import helper
  24. _logger = logging.getLogger(__name__)
  25. class BaseModelAccessGroups(models.AbstractModel):
  26. _name = 'muk_security.access_groups'
  27. _description = "MuK Access Groups Model"
  28. _inherit = 'muk_security.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. base, model = self._name.split(".")
  45. add('suspend_security_read', fields.Boolean(
  46. _module=base,
  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=base,
  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=base,
  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=base,
  65. string="Suspend Security for Unlink",
  66. automatic=True,
  67. default=False,
  68. groups=self._suspend_groups))
  69. add('groups', fields.Many2many(
  70. _module=base,
  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=base,
  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.multi
  93. def trigger_computation(self, fields, *largs, **kwargs):
  94. super(BaseModelAccessGroups, self).trigger_computation(fields, *largs, **kwargs)
  95. if "complete_groups" in fields:
  96. self.suspend_security()._compute_groups()
  97. @api.model
  98. def check_group_values(self, values):
  99. if any(field in values for field in ['groups']):
  100. return True
  101. return False
  102. @api.multi
  103. @api.returns('muk_security.groups')
  104. def get_groups(self):
  105. self.ensure_one()
  106. groups = self.env['muk_security.groups']
  107. groups |= self.groups
  108. return groups
  109. @api.model
  110. def _get_no_access_ids(self):
  111. base, model = self._name.split(".")
  112. if not self._strict_security:
  113. sql = '''
  114. SELECT id
  115. FROM %s a
  116. WHERE NOT EXISTS (
  117. SELECT *
  118. FROM muk_groups_complete_%s_rel r
  119. WHERE r.aid = a.id
  120. );
  121. ''' % (self._table, model)
  122. self.env.cr.execute(sql)
  123. fetch = self.env.cr.fetchall()
  124. return len(fetch) > 0 and list(map(lambda x: x[0], fetch)) or []
  125. else:
  126. return []
  127. @api.model
  128. def _get_suspended_access_ids(self, operation):
  129. base, model = self._name.split(".")
  130. sql = '''
  131. SELECT id
  132. FROM %s a
  133. WHERE a.suspend_security_%s = true
  134. ''' % (self._table, operation)
  135. self.env.cr.execute(sql)
  136. fetch = self.env.cr.fetchall()
  137. return len(fetch) > 0 and list(map(lambda x: x[0], fetch)) or []
  138. @api.model
  139. def _get_access_ids(self):
  140. base, model = self._name.split(".")
  141. sql = '''
  142. SELECT r.aid
  143. FROM muk_groups_complete_%s_rel r
  144. JOIN muk_security_groups g ON r.gid = g.id
  145. JOIN muk_security_groups_users_rel u ON r.gid = u.gid
  146. WHERE u.uid = %s AND g.perm_read = true
  147. ''' % (model, self.env.user.id)
  148. self.env.cr.execute(sql)
  149. fetch = self.env.cr.fetchall()
  150. access_ids = len(fetch) > 0 and list(map(lambda x: x[0], fetch)) or []
  151. return access_ids
  152. @api.model
  153. def _get_ids_without_security(self, operation):
  154. no_access_ids = self._get_no_access_ids()
  155. suspended_access_ids = self._get_suspended_access_ids(operation)
  156. return list(set(no_access_ids).union(suspended_access_ids))
  157. @api.model
  158. def _get_complete_access_ids(self, operation):
  159. access_ids = self._get_access_ids()
  160. no_access_ids = self._get_no_access_ids()
  161. suspended_access_ids = self._get_suspended_access_ids(operation)
  162. return list(set(access_ids).union(no_access_ids, suspended_access_ids))
  163. @api.multi
  164. def _eval_access_skip(self, operation):
  165. if isinstance(self.env.uid, helper.NoSecurityUid):
  166. return True
  167. return False
  168. @api.multi
  169. def check_access_groups(self, operation):
  170. if self.env.user.id == SUPERUSER_ID or self._eval_access_skip(operation):
  171. return None
  172. base, model = self._name.split(".")
  173. filter_ids = self._get_ids_without_security(operation)
  174. for record in self.filtered(lambda rec: rec.id not in filter_ids):
  175. sql = '''
  176. SELECT perm_%s
  177. FROM muk_groups_complete_%s_rel r
  178. JOIN muk_security_groups g ON g.id = r.gid
  179. JOIN muk_security_groups_users_rel u ON u.gid = g.id
  180. WHERE r.aid = %s AND u.uid = %s
  181. ''' % (operation, model, record.id, self.env.user.id)
  182. self.env.cr.execute(sql)
  183. fetch = self.env.cr.fetchall()
  184. if not any(list(map(lambda x: x[0], fetch))):
  185. raise AccessError(_("This operation is forbidden!"))
  186. @api.multi
  187. def check_access(self, operation, raise_exception=False):
  188. res = super(BaseModelAccessGroups, self).check_access(operation, raise_exception)
  189. try:
  190. access_groups = self.check_access_groups(operation) == None
  191. access = res and access_groups
  192. if not access and raise_exception:
  193. raise AccessError(_("This operation is forbidden!"))
  194. return access
  195. except AccessError:
  196. if raise_exception:
  197. raise AccessError(_("This operation is forbidden!"))
  198. return False
  199. #----------------------------------------------------------
  200. # Read
  201. #----------------------------------------------------------
  202. @api.multi
  203. def _after_read(self, result, *largs, **kwargs):
  204. result = super(BaseModelAccessGroups, self)._after_read(result)
  205. if self.env.user.id == SUPERUSER_ID or self._eval_access_skip("read"):
  206. return result
  207. access_ids = self._get_complete_access_ids("read")
  208. result = [result] if not isinstance(result, list) else result
  209. if len(access_ids) > 0:
  210. access_result = []
  211. for record in result:
  212. if record['id'] in access_ids:
  213. access_result.append(record)
  214. return access_result
  215. return []
  216. @api.model
  217. def _after_search(self, result, *largs, **kwargs):
  218. result = super(BaseModelAccessGroups, self)._after_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 = self.env[self._name]
  224. if isinstance(result, int):
  225. if result in access_ids:
  226. return result
  227. else:
  228. for record in result:
  229. if record.id in access_ids:
  230. access_result += record
  231. return access_result
  232. return self.env[self._name]
  233. @api.model
  234. def _after_name_search(self, result, *largs, **kwargs):
  235. result = super(BaseModelAccessGroups, self)._after_name_search(result)
  236. if self.env.user.id == SUPERUSER_ID or self._eval_access_skip("read"):
  237. return result
  238. access_ids = self._get_complete_access_ids("read")
  239. if len(access_ids) > 0:
  240. access_result = []
  241. for tuple in result:
  242. if tuple[0] in access_ids:
  243. access_result.append(tuple)
  244. return access_result
  245. return []
  246. #----------------------------------------------------------
  247. # Read, View
  248. #----------------------------------------------------------
  249. @api.multi
  250. def _compute_groups(self, write=True):
  251. if write:
  252. for record in self:
  253. record.complete_groups = record.get_groups()
  254. else:
  255. self.ensure_one()
  256. return {'complete_groups': [(6, 0, self.get_groups().mapped('id'))]}
  257. #----------------------------------------------------------
  258. # Create, Update, Delete
  259. #----------------------------------------------------------
  260. @api.multi
  261. def _before_write(self, vals, *largs, **kwargs):
  262. self.check_access_groups('write')
  263. return super(BaseModelAccessGroups, self)._before_write(vals, *largs, **kwargs)
  264. @api.multi
  265. def _before_unlink(self, *largs, **kwargs):
  266. self.check_access_groups('unlink')
  267. return super(BaseModelAccessGroups, self)._before_unlink(*largs, **kwargs)
  268. @api.multi
  269. def _check_recomputation(self, vals, olds, *largs, **kwargs):
  270. super(BaseModelAccessGroups, self)._check_recomputation(vals, olds, *largs, **kwargs)
  271. fields = []
  272. if self.check_group_values(vals):
  273. fields.extend(['complete_groups'])
  274. if fields:
  275. self.trigger_computation(fields)