FIX: Missing allowed urls when displaying granualar API key scopes.

Follow-up to 3791fbd919
This commit is contained in:
Alan Guo Xiang Tan 2021-12-06 10:51:47 +08:00
parent 44588255fc
commit 4e67297a7c
2 changed files with 18 additions and 9 deletions

View File

@ -88,32 +88,29 @@ class ApiKeyScope < ActiveRecord::Base
end end
def find_urls(actions:, methods:) def find_urls(actions:, methods:)
action_urls = [] urls = []
method_urls = []
if actions.present? if actions.present?
Rails.application.routes.routes.reduce([]) do |memo, route| Rails.application.routes.routes.each do |route|
defaults = route.defaults defaults = route.defaults
action = "#{defaults[:controller].to_s}##{defaults[:action]}" action = "#{defaults[:controller].to_s}##{defaults[:action]}"
path = route.path.spec.to_s.gsub(/\(\.:format\)/, '') path = route.path.spec.to_s.gsub(/\(\.:format\)/, '')
api_supported_path = path.end_with?('.rss') || route.path.requirements[:format]&.match?('json') api_supported_path = path.end_with?('.rss') || route.path.requirements[:format]&.match?('json')
excluded_paths = %w[/new-topic /new-message /exception] excluded_paths = %w[/new-topic /new-message /exception]
memo.tap do |m| if actions.include?(action) && api_supported_path && !excluded_paths.include?(path)
if actions.include?(action) && api_supported_path && !excluded_paths.include?(path) urls << "#{path} (#{route.verb})"
m << "#{path} (#{route.verb})"
end
end end
end end
end end
if methods.present? if methods.present?
methods.each do |method| methods.each do |method|
method_urls << "* (#{method})" urls << "* (#{method})"
end end
end end
action_urls + method_urls urls
end end
end end

View File

@ -0,0 +1,12 @@
# frozen_string_literal: true
require 'rails_helper'
describe ApiKeyScope do
describe '.find_urls' do
it 'should return the right urls' do
expect(ApiKeyScope.find_urls(actions: ["posts#create"], methods: []))
.to contain_exactly("/posts (POST)")
end
end
end