2021-06-01 12:20:20 +00:00
|
|
|
# Copyright (C) 2012-2021 Zammad Foundation, http://zammad-foundation.org/
|
|
|
|
|
2020-09-14 06:34:42 +00:00
|
|
|
# We need a special UserContext when authorizing in controller context
|
|
|
|
# because of Token authentication which has it's own permissions
|
|
|
|
# See: https://github.com/varvet/pundit#additional-context
|
|
|
|
# We use a Delegator here to have transparent / DuckType access
|
|
|
|
# to the underlying User instance in the Policy
|
|
|
|
class UserContext < Delegator
|
|
|
|
|
2021-04-01 15:14:25 +00:00
|
|
|
def initialize(user, token = nil) # rubocop:disable Lint/MissingSuper
|
2020-09-14 06:34:42 +00:00
|
|
|
@user = user
|
|
|
|
@token = token
|
|
|
|
end
|
|
|
|
|
|
|
|
def __getobj__
|
|
|
|
@user
|
|
|
|
end
|
|
|
|
|
|
|
|
def permissions!(permissions)
|
2021-02-04 08:28:41 +00:00
|
|
|
raise Exceptions::Forbidden, 'Authentication required' if !@user
|
|
|
|
raise Exceptions::Forbidden, 'Not authorized (user)!' if !@user.permissions?(permissions)
|
2020-09-14 06:34:42 +00:00
|
|
|
return if !@token
|
|
|
|
return if @token.with_context(user: @user) { permissions?(permissions) }
|
|
|
|
|
2021-02-04 08:28:41 +00:00
|
|
|
raise Exceptions::Forbidden, 'Not authorized (token)!'
|
2020-09-14 06:34:42 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def permissions?(permissions)
|
|
|
|
permissions!(permissions)
|
|
|
|
true
|
2021-02-04 08:28:41 +00:00
|
|
|
rescue Exceptions::Forbidden
|
2020-09-14 06:34:42 +00:00
|
|
|
false
|
|
|
|
end
|
|
|
|
end
|