diff --git a/app/controllers/api/v1/widget/contacts_controller.rb b/app/controllers/api/v1/widget/contacts_controller.rb index 8bc5cfd0b..983f12965 100644 --- a/app/controllers/api/v1/widget/contacts_controller.rb +++ b/app/controllers/api/v1/widget/contacts_controller.rb @@ -14,8 +14,9 @@ class Api::V1::Widget::ContactsController < Api::V1::Widget::BaseController private def process_hmac - return if params[:identifier_hash].blank? - raise StandardError, 'HMAC failed: Invalid Identifier Hash Provided' unless valid_hmac? + return if params[:identifier_hash].blank? && !@web_widget.hmac_mandatory + + render json: { error: 'HMAC failed: Invalid Identifier Hash Provided' }, status: :unauthorized unless valid_hmac? @contact_inbox.update(hmac_verified: true) end diff --git a/spec/controllers/api/v1/widget/contacts_controller_spec.rb b/spec/controllers/api/v1/widget/contacts_controller_spec.rb index 62676da6d..c8da290e5 100644 --- a/spec/controllers/api/v1/widget/contacts_controller_spec.rb +++ b/spec/controllers/api/v1/widget/contacts_controller_spec.rb @@ -38,5 +38,53 @@ RSpec.describe '/api/v1/widget/contacts', type: :request do expect(identify_action).to have_received(:perform) end end + + context 'with mandatory hmac' do + let(:identify_action) { double } + let(:web_widget) { create(:channel_widget, account: account, hmac_mandatory: true) } + let(:correct_identifier_hash) { OpenSSL::HMAC.hexdigest('sha256', web_widget.hmac_token, params[:identifier].to_s) } + let(:incorrect_identifier_hash) { 'test' } + + before do + allow(ContactIdentifyAction).to receive(:new).and_return(identify_action) + allow(identify_action).to receive(:perform) + end + + it 'returns success when correct identifier hash is provided' do + patch '/api/v1/widget/contact', + params: params.merge(identifier_hash: correct_identifier_hash), + headers: { 'X-Auth-Token' => token }, + as: :json + + expect(response).to have_http_status(:success) + end + + it 'returns error when incorrect identifier hash is provided' do + patch '/api/v1/widget/contact', + params: params.merge(identifier_hash: incorrect_identifier_hash), + headers: { 'X-Auth-Token' => token }, + as: :json + + expect(response).to have_http_status(:unauthorized) + end + + it 'returns error when identifier hash is blank' do + patch '/api/v1/widget/contact', + params: params.merge(identifier_hash: ''), + headers: { 'X-Auth-Token' => token }, + as: :json + + expect(response).to have_http_status(:unauthorized) + end + + it 'returns error when identifier hash is not provided' do + patch '/api/v1/widget/contact', + params: params, + headers: { 'X-Auth-Token' => token }, + as: :json + + expect(response).to have_http_status(:unauthorized) + end + end end end