0
0
Fork 1
Spiegel von https://github.com/paviliondev/discourse-custom-wizard.git synchronisiert 2024-11-14 05:52:52 +01:00
discourse-custom-wizard/controllers/api.rb

117 Zeilen
2,7 KiB
Ruby

2019-05-31 09:54:11 +02:00
class CustomWizard::ApiController < ::ApplicationController
before_action :ensure_logged_in
before_action :ensure_admin
skip_before_action :check_xhr, only: [:redirect]
def index
end
def list
serializer = ActiveModel::ArraySerializer.new(
CustomWizard::Api.list,
each_serializer: CustomWizard::BasicApiSerializer
)
render json: MultiJson.dump(serializer)
end
def find
render_serialized(CustomWizard::Api.get(api_params[:name]), CustomWizard::ApiSerializer, root: false)
2019-05-31 09:54:11 +02:00
end
def save
current = CustomWizard::Api.get(api_params[:name])
2019-05-31 09:54:11 +02:00
if api_params[:new] && current
raise Discourse::InvalidParameters, "An API with that name already exists: '#{current.title || current.name}'"
2019-06-01 01:06:30 +02:00
end
2019-05-31 09:54:11 +02:00
PluginStoreRow.transaction do
CustomWizard::Api.set(api_params[:name], title: api_params[:title])
if auth_data.present?
CustomWizard::Api::Authorization.set(api_params[:name], auth_data)
end
if api_params[:endpoints].is_a? String
begin
endpoints = JSON.parse(api_params[:endpoints])
endpoints.each do |endpoint|
CustomWizard::Api::Endpoint.set(api_params[:name], endpoint)
end
rescue => e
puts e
end
2019-06-01 01:06:30 +02:00
end
2019-05-31 09:54:11 +02:00
end
render json: success_json.merge(
api: CustomWizard::ApiSerializer.new(
CustomWizard::Api.get(api_params[:name]),
root: false
)
2019-05-31 09:54:11 +02:00
)
end
def remove
PluginStoreRow.transaction do
CustomWizard::Api.remove(api_params[:name])
CustomWizard::Api::Authorization.remove(api_params[:name])
CustomWizard::Api::Endpoint.remove(api_params[:name])
end
2019-05-31 09:54:11 +02:00
render json: success_json
end
def redirect
params.require(:name)
params.require(:code)
2019-05-31 09:54:11 +02:00
CustomWizard::Api::Authorization.set(params[:name], code: params[:code])
CustomWizard::Api::Authorization.get_token(params[:name])
2019-05-31 09:54:11 +02:00
return redirect_to path('/admin/wizards/apis/' + params[:name])
2019-05-31 09:54:11 +02:00
end
private
def api_params
params.require(:name)
data = params.permit(
:name,
:title,
2019-05-31 09:54:11 +02:00
:auth_type,
:auth_url,
:token_url,
:client_id,
:client_secret,
:username,
:password,
:auth_params,
:endpoints,
:new
2019-05-31 09:54:11 +02:00
).to_h
data[:name] = data[:name].underscore
@api_params ||= data
2019-05-31 09:54:11 +02:00
end
def auth_data
auth_data = api_params.slice(
:auth_type,
:auth_url,
:token_url,
:client_id,
:client_secret,
:username,
:password,
2019-06-03 09:09:24 +02:00
:auth_params
)
2019-06-03 09:09:24 +02:00
auth_data[:auth_params] = JSON.parse(auth_data[:auth_params]) if auth_data[:auth_params].present?
@auth_data ||= auth_data
2019-05-31 09:54:11 +02:00
end
end