user_context.rb 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. # We need a special UserContext when authorizing in controller context
  3. # because of Token authentication which has it's own permissions
  4. # See: https://github.com/varvet/pundit#additional-context
  5. # We use a Delegator here to have transparent / DuckType access
  6. # to the underlying User instance in the Policy
  7. class UserContext < Delegator
  8. def initialize(user, token = nil) # rubocop:disable Lint/MissingSuper
  9. @user = user
  10. @token = token
  11. end
  12. def __getobj__
  13. @user
  14. end
  15. def permissions!(permissions)
  16. raise Exceptions::Forbidden, __('Authentication required') if !@user
  17. raise Exceptions::Forbidden, __('Not authorized (user)!') if !@user.permissions?(permissions)
  18. return if !@token
  19. return if @token.with_context(user: @user) { permissions?(permissions) }
  20. raise Exceptions::Forbidden, __('Not authorized (token)!')
  21. end
  22. def permissions?(permissions)
  23. permissions!(permissions)
  24. true
  25. rescue Exceptions::Forbidden
  26. false
  27. end
  28. end