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.

309 lines
12 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 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, operation):
  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. JOIN muk_security_groups g ON r.gid = g.id
  120. WHERE r.aid = a.id AND g.perm_%s = true
  121. );
  122. ''' % (self._table, model, operation)
  123. self.env.cr.execute(sql)
  124. fetch = self.env.cr.fetchall()
  125. return len(fetch) > 0 and list(map(lambda x: x[0], fetch)) or []
  126. else:
  127. return []
  128. @api.model
  129. def _get_suspended_access_ids(self, operation):
  130. base, model = self._name.split(".")
  131. sql = '''
  132. SELECT id
  133. FROM %s a
  134. WHERE a.suspend_security_%s = true
  135. ''' % (self._table, operation)
  136. self.env.cr.execute(sql)
  137. fetch = self.env.cr.fetchall()
  138. return len(fetch) > 0 and list(map(lambda x: x[0], fetch)) or []
  139. @api.model
  140. def _get_access_ids(self):
  141. base, model = self._name.split(".")
  142. sql = '''
  143. SELECT r.aid
  144. FROM muk_groups_complete_%s_rel r
  145. JOIN muk_security_groups g ON r.gid = g.id
  146. JOIN muk_security_groups_users_rel u ON r.gid = u.gid
  147. WHERE u.uid = %s AND g.perm_read = true
  148. ''' % (model, self.env.user.id)
  149. self.env.cr.execute(sql)
  150. fetch = self.env.cr.fetchall()
  151. access_ids = len(fetch) > 0 and list(map(lambda x: x[0], fetch)) or []
  152. return access_ids
  153. @api.model
  154. def _get_ids_without_security(self, operation):
  155. no_access_ids = self._get_no_access_ids(operation)
  156. suspended_access_ids = self._get_suspended_access_ids(operation)
  157. return list(set(no_access_ids).union(suspended_access_ids))
  158. @api.model
  159. def _get_complete_access_ids(self, operation):
  160. access_ids = self._get_access_ids()
  161. no_access_ids = self._get_no_access_ids(operation)
  162. suspended_access_ids = self._get_suspended_access_ids(operation)
  163. return list(set(access_ids).union(no_access_ids, suspended_access_ids))
  164. @api.multi
  165. def _eval_access_skip(self, operation):
  166. if isinstance(self.env.uid, helper.NoSecurityUid):
  167. return True
  168. return False
  169. @api.multi
  170. def check_access_groups(self, operation):
  171. if self.env.user.id == SUPERUSER_ID or self._eval_access_skip(operation):
  172. return None
  173. base, model = self._name.split(".")
  174. filter_ids = self._get_ids_without_security(operation)
  175. for record in self.filtered(lambda rec: rec.id not in filter_ids):
  176. sql = '''
  177. SELECT perm_%s
  178. FROM muk_groups_complete_%s_rel r
  179. JOIN muk_security_groups g ON g.id = r.gid
  180. JOIN muk_security_groups_users_rel u ON u.gid = g.id
  181. WHERE r.aid = %s AND u.uid = %s
  182. ''' % (operation, model, record.id, self.env.user.id)
  183. self.env.cr.execute(sql)
  184. fetch = self.env.cr.fetchall()
  185. if not any(list(map(lambda x: x[0], fetch))):
  186. raise AccessError(_("This operation is forbidden!"))
  187. @api.multi
  188. def check_access(self, operation, raise_exception=False):
  189. res = super(BaseModelAccessGroups, self).check_access(operation, raise_exception)
  190. try:
  191. access_groups = self.check_access_groups(operation) == None
  192. access = res and access_groups
  193. if not access and raise_exception:
  194. raise AccessError(_("This operation is forbidden!"))
  195. return access
  196. except AccessError:
  197. if raise_exception:
  198. raise AccessError(_("This operation is forbidden!"))
  199. return False
  200. #----------------------------------------------------------
  201. # Read
  202. #----------------------------------------------------------
  203. @api.multi
  204. def _after_read(self, result, *largs, **kwargs):
  205. result = super(BaseModelAccessGroups, self)._after_read(result)
  206. if self.env.user.id == SUPERUSER_ID or self._eval_access_skip("read"):
  207. return result
  208. access_ids = self._get_complete_access_ids("read")
  209. result = [result] if not isinstance(result, list) else result
  210. if len(access_ids) > 0:
  211. access_result = []
  212. for record in result:
  213. if record['id'] in access_ids:
  214. access_result.append(record)
  215. return access_result
  216. return []
  217. @api.model
  218. def _after_search(self, result, *largs, **kwargs):
  219. result = super(BaseModelAccessGroups, self)._after_search(result)
  220. if self.env.user.id == SUPERUSER_ID or self._eval_access_skip("read"):
  221. return result
  222. access_ids = self._get_complete_access_ids("read")
  223. if len(access_ids) > 0:
  224. access_result = self.env[self._name]
  225. if isinstance(result, int):
  226. if result in access_ids:
  227. return result
  228. else:
  229. for record in result:
  230. if record.id in access_ids:
  231. access_result += record
  232. return access_result
  233. return self.env[self._name]
  234. @api.model
  235. def _after_name_search(self, result, *largs, **kwargs):
  236. result = super(BaseModelAccessGroups, self)._after_name_search(result)
  237. if self.env.user.id == SUPERUSER_ID or self._eval_access_skip("read"):
  238. return result
  239. access_ids = self._get_complete_access_ids("read")
  240. if len(access_ids) > 0:
  241. access_result = []
  242. for tuple in result:
  243. if tuple[0] in access_ids:
  244. access_result.append(tuple)
  245. return access_result
  246. return []
  247. #----------------------------------------------------------
  248. # Read, View
  249. #----------------------------------------------------------
  250. @api.multi
  251. def _compute_groups(self, write=True):
  252. if write:
  253. for record in self:
  254. record.complete_groups = record.get_groups()
  255. else:
  256. self.ensure_one()
  257. return {'complete_groups': [(6, 0, self.get_groups().mapped('id'))]}
  258. #----------------------------------------------------------
  259. # Create, Update, Delete
  260. #----------------------------------------------------------
  261. @api.multi
  262. def _before_write(self, vals, *largs, **kwargs):
  263. self.check_access_groups('write')
  264. return super(BaseModelAccessGroups, self)._before_write(vals, *largs, **kwargs)
  265. @api.multi
  266. def _before_unlink(self, *largs, **kwargs):
  267. self.check_access_groups('unlink')
  268. return super(BaseModelAccessGroups, self)._before_unlink(*largs, **kwargs)
  269. @api.multi
  270. def _check_recomputation(self, vals, olds, *largs, **kwargs):
  271. super(BaseModelAccessGroups, self)._check_recomputation(vals, olds, *largs, **kwargs)
  272. fields = []
  273. if self.check_group_values(vals):
  274. fields.extend(['complete_groups'])
  275. if fields:
  276. self.trigger_computation(fields)