user_context.rb 943 B

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