checks_access.rb 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class User
  3. module ChecksAccess
  4. extend ActiveSupport::Concern
  5. # Checks the given access of a given user for another user.
  6. #
  7. # @param [User] The user that will be checked for given access.
  8. # @param [String] The access that should get checked.
  9. #
  10. # @example
  11. # user.access?(user, 'read')
  12. # #=> true
  13. #
  14. # @return [Boolean]
  15. def access?(requester, access)
  16. # full admins can do whatever they want
  17. return true if requester.permissions?('admin')
  18. send("#{access}able_by?".to_sym, requester)
  19. end
  20. # Checks the given access of a given user for another user and fails with an exception.
  21. #
  22. # @param (see User#access?)
  23. #
  24. # @example
  25. # user.access!(user, 'read')
  26. #
  27. # @raise [NotAuthorized] Gets raised if given user doesn't have the given access.
  28. #
  29. # @return [nil]
  30. def access!(user, access)
  31. return if access?(user, access)
  32. raise Exceptions::NotAuthorized
  33. end
  34. private
  35. def readable_by?(requester)
  36. return true if own_account?(requester)
  37. return true if requester.permissions?('admin.*')
  38. return true if requester.permissions?('ticket.agent')
  39. # check same organization for customers
  40. return false if !requester.permissions?('ticket.customer')
  41. same_organization?(requester)
  42. end
  43. def changeable_by?(requester)
  44. return true if requester.permissions?('admin.user')
  45. # allow agents to change customers
  46. return false if !requester.permissions?('ticket.agent')
  47. permissions?('ticket.customer')
  48. end
  49. def deleteable_by?(requester)
  50. requester.permissions?('admin.user')
  51. end
  52. def own_account?(requester)
  53. id == requester.id
  54. end
  55. def same_organization?(requester)
  56. return false if organization_id.blank?
  57. return false if requester.organization_id.blank?
  58. organization_id == requester.organization_id
  59. end
  60. end
  61. end