2024-11-09 01:05:03 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
class UserApiKeyClientsController < ApplicationController
|
|
|
|
layout "no_ember"
|
|
|
|
|
2024-11-20 04:28:04 +08:00
|
|
|
skip_before_action :check_xhr, :preload_json, :verify_authenticity_token
|
2024-11-09 01:05:03 +08:00
|
|
|
|
2024-11-20 04:28:04 +08:00
|
|
|
def show
|
|
|
|
params.require(:client_id)
|
|
|
|
client = UserApiKeyClient.find_by(client_id: params[:client_id])
|
|
|
|
raise Discourse::InvalidParameters unless client && client.auth_redirect.present?
|
|
|
|
head :ok
|
|
|
|
end
|
|
|
|
|
|
|
|
def create
|
|
|
|
rate_limit
|
2024-11-09 01:05:03 +08:00
|
|
|
require_params
|
2024-11-20 04:28:04 +08:00
|
|
|
validate_params
|
|
|
|
ensure_new_client
|
2024-11-09 01:05:03 +08:00
|
|
|
|
2024-11-20 04:28:04 +08:00
|
|
|
client = UserApiKeyClient.new(client_id: params[:client_id])
|
2024-11-09 01:05:03 +08:00
|
|
|
client.application_name = params[:application_name]
|
|
|
|
client.public_key = params[:public_key]
|
|
|
|
client.auth_redirect = params[:auth_redirect]
|
|
|
|
|
2024-11-20 04:28:04 +08:00
|
|
|
ActiveRecord::Base.transaction do
|
|
|
|
client.save!
|
|
|
|
@scopes.each { |scope| client.scopes.create!(name: scope) }
|
|
|
|
end
|
|
|
|
|
|
|
|
if client.persisted?
|
2024-11-09 01:05:03 +08:00
|
|
|
render json: success_json
|
|
|
|
else
|
|
|
|
render json: failed_json
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2024-11-20 04:28:04 +08:00
|
|
|
def rate_limit
|
|
|
|
RateLimiter.new(nil, "user-api-key-clients-#{request.remote_ip}", 1, 24.hours).performed!
|
|
|
|
end
|
|
|
|
|
2024-11-09 01:05:03 +08:00
|
|
|
def require_params
|
2024-11-20 04:28:04 +08:00
|
|
|
%i[client_id application_name public_key auth_redirect scopes].each { |p| params.require(p) }
|
|
|
|
@scopes = params[:scopes].split(",")
|
|
|
|
end
|
|
|
|
|
|
|
|
def validate_params
|
|
|
|
raise Discourse::InvalidAccess unless UserApiKeyClientScope.allowed.superset?(Set.new(@scopes))
|
2024-11-09 01:05:03 +08:00
|
|
|
OpenSSL::PKey::RSA.new(params[:public_key])
|
|
|
|
end
|
2024-11-20 04:28:04 +08:00
|
|
|
|
|
|
|
def ensure_new_client
|
|
|
|
raise Discourse::InvalidAccess if UserApiKeyClient.where(client_id: params[:client_id]).exists?
|
|
|
|
end
|
2024-11-09 01:05:03 +08:00
|
|
|
end
|