diff --git a/app/controllers/telegram_bot_updates_controller.rb b/app/controllers/telegram_bot_updates_controller.rb index 6a2d84b..af0e97c 100644 --- a/app/controllers/telegram_bot_updates_controller.rb +++ b/app/controllers/telegram_bot_updates_controller.rb @@ -1,10 +1,31 @@ # frozen_string_literal: true class TelegramBotUpdatesController < ApplicationController + before_action :set_telegram_bot + before_action :verify_telegram_bot_secret + + rescue_from ActiveRecord::RecordNotFound, with: :not_found + # POST /telegram_bot_updates def create logger.info params.inspect render status: :no_content, json: {} end + +private + + def set_telegram_bot + @telegram_bot = TelegramBot.find params[:telegram_bot_id] + end + + def verify_telegram_bot_secret + return if params[:secret] == @telegram_bot.secret + + render status: :unauthorized, json: {} + end + + def not_found + render status: :not_found, json: {} + end end diff --git a/spec/requests/telegram_bot_updates/create_spec.rb b/spec/requests/telegram_bot_updates/create_spec.rb index 95ceb30..430819e 100644 --- a/spec/requests/telegram_bot_updates/create_spec.rb +++ b/spec/requests/telegram_bot_updates/create_spec.rb @@ -3,11 +3,41 @@ require 'rails_helper' RSpec.describe 'POST /telegram_bot_updates' do - before do - post '/telegram_bot_updates' + let(:telegram_bot) { create :telegram_bot } + + context 'with valid params' do + before do + post '/telegram_bot_updates', + params: { telegram_bot_id: telegram_bot.id, + secret: telegram_bot.secret } + end + + specify do + expect(response).to have_http_status :no_content + end end - specify do - expect(response).to have_http_status :no_content + context 'when no telegram bot exist' do + before do + post '/telegram_bot_updates', + params: { telegram_bot_id: rand(10_000..1_000_000), + secret: telegram_bot.secret } + end + + specify do + expect(response).to have_http_status :not_found + end + end + + context 'when secret is not valid' do + before do + post '/telegram_bot_updates', + params: { telegram_bot_id: telegram_bot.id, + secret: SecureRandom.hex } + end + + specify do + expect(response).to have_http_status :unauthorized + end end end