2020-04-03 07:34:58 +00:00
|
|
|
class Api::V1::Widget::ContactsController < Api::V1::Widget::BaseController
|
2022-06-23 10:18:56 +00:00
|
|
|
include WidgetHelper
|
|
|
|
|
|
|
|
before_action :validate_hmac, only: [:set_user]
|
2021-03-20 12:14:20 +00:00
|
|
|
|
|
|
|
def show; end
|
|
|
|
|
2020-04-03 07:34:58 +00:00
|
|
|
def update
|
2022-06-23 10:18:56 +00:00
|
|
|
identify_contact(@contact)
|
|
|
|
end
|
|
|
|
|
|
|
|
def set_user
|
|
|
|
contact = nil
|
|
|
|
|
|
|
|
if a_different_contact?
|
|
|
|
@contact_inbox, @widget_auth_token = build_contact_inbox_with_token(@web_widget)
|
|
|
|
contact = @contact_inbox.contact
|
|
|
|
else
|
|
|
|
contact = @contact
|
|
|
|
end
|
|
|
|
|
|
|
|
@contact_inbox.update(hmac_verified: true) if should_verify_hmac? && valid_hmac?
|
|
|
|
|
|
|
|
identify_contact(contact)
|
2020-04-03 07:34:58 +00:00
|
|
|
end
|
|
|
|
|
2021-11-15 09:26:35 +00:00
|
|
|
# TODO : clean up this with proper routes delete contacts/custom_attributes
|
|
|
|
def destroy_custom_attributes
|
|
|
|
@contact.custom_attributes = @contact.custom_attributes.excluding(params[:custom_attributes])
|
|
|
|
@contact.save!
|
|
|
|
render json: @contact
|
|
|
|
end
|
|
|
|
|
2020-04-03 07:34:58 +00:00
|
|
|
private
|
|
|
|
|
2022-06-23 10:18:56 +00:00
|
|
|
def identify_contact(contact)
|
|
|
|
contact_identify_action = ContactIdentifyAction.new(
|
|
|
|
contact: contact,
|
|
|
|
params: permitted_params.to_h.deep_symbolize_keys
|
|
|
|
)
|
|
|
|
@contact = contact_identify_action.perform
|
|
|
|
end
|
|
|
|
|
|
|
|
def a_different_contact?
|
|
|
|
@contact.identifier.present? && @contact.identifier != permitted_params[:identifier]
|
|
|
|
end
|
|
|
|
|
|
|
|
def validate_hmac
|
2021-12-09 06:20:28 +00:00
|
|
|
return unless should_verify_hmac?
|
2021-11-11 04:18:38 +00:00
|
|
|
|
|
|
|
render json: { error: 'HMAC failed: Invalid Identifier Hash Provided' }, status: :unauthorized unless valid_hmac?
|
2021-01-17 17:14:03 +00:00
|
|
|
end
|
|
|
|
|
2021-12-09 06:20:28 +00:00
|
|
|
def should_verify_hmac?
|
|
|
|
return false if params[:identifier_hash].blank? && !@web_widget.hmac_mandatory
|
|
|
|
|
|
|
|
# Taking an extra caution that the hmac is triggered whenever identifier is present
|
|
|
|
return false if params[:custom_attributes].present? && params[:identifier].blank?
|
|
|
|
|
|
|
|
true
|
|
|
|
end
|
|
|
|
|
2021-01-17 17:14:03 +00:00
|
|
|
def valid_hmac?
|
|
|
|
params[:identifier_hash] == OpenSSL::HMAC.hexdigest(
|
|
|
|
'sha256',
|
|
|
|
@web_widget.hmac_token,
|
|
|
|
params[:identifier].to_s
|
|
|
|
)
|
|
|
|
end
|
|
|
|
|
2020-04-03 07:34:58 +00:00
|
|
|
def permitted_params
|
2022-02-28 06:40:55 +00:00
|
|
|
params.permit(:website_token, :identifier, :identifier_hash, :email, :name, :avatar_url, :phone_number, custom_attributes: {},
|
|
|
|
additional_attributes: {})
|
2020-04-03 07:34:58 +00:00
|
|
|
end
|
|
|
|
end
|