2021-02-09 17:45:12 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module PermissionCheckableModel
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
2021-10-22 17:43:20 +08:00
|
|
|
included do
|
|
|
|
include PermissionExtends
|
|
|
|
|
|
|
|
scope :with_granted_permissions, lambda { |user, permissions|
|
|
|
|
left_outer_joins(user_assignments: :user_role)
|
|
|
|
.where(user_assignments: { user: user })
|
|
|
|
.where('user_roles.permissions @> ARRAY[?]::varchar[]', permissions)
|
|
|
|
}
|
|
|
|
end
|
|
|
|
|
2021-02-09 17:45:12 +08:00
|
|
|
def permission_granted?(user, permission)
|
|
|
|
user_role_permissions = load_user_role_permissions(user)
|
|
|
|
return false if user_role_permissions.blank?
|
|
|
|
|
|
|
|
user_role_permissions.include?(permission)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def load_user_role_permissions(user)
|
2021-10-22 17:43:20 +08:00
|
|
|
if user_assignments.loaded?
|
2022-07-01 17:55:27 +08:00
|
|
|
user_assignments.detect do |user_assignment|
|
2022-10-04 19:53:45 +08:00
|
|
|
user_assignment.user == user && (is_a?(Team) || user_assignment.team == user.current_team)
|
2022-07-01 17:55:27 +08:00
|
|
|
end&.user_role&.permissions
|
2021-10-22 17:43:20 +08:00
|
|
|
else
|
2022-10-04 19:53:45 +08:00
|
|
|
load_criteria = is_a?(Team) ? { user: user } : { user: user, team: user.current_team }
|
|
|
|
user_assignments.find_by(load_criteria)&.user_role&.permissions
|
2021-10-22 17:43:20 +08:00
|
|
|
end
|
2021-02-09 17:45:12 +08:00
|
|
|
end
|
|
|
|
end
|