feat: Enable reauthorization for Facebook (#1286)
This commit is contained in:
parent
99ca54fd3c
commit
b862817b29
20 changed files with 281 additions and 15 deletions
|
@ -30,7 +30,7 @@ class Api::V1::Accounts::CallbacksController < Api::V1::Accounts::BaseController
|
|||
|
||||
if (page_detail = (page_details || []).detect { |page| fb_page_id == page['id'] })
|
||||
update_fb_page(fb_page_id, page_detail['access_token'])
|
||||
return head :ok
|
||||
render and return
|
||||
end
|
||||
end
|
||||
|
||||
|
@ -44,9 +44,9 @@ class Api::V1::Accounts::CallbacksController < Api::V1::Accounts::BaseController
|
|||
end
|
||||
|
||||
def update_fb_page(fb_page_id, access_token)
|
||||
get_fb_page(fb_page_id)&.update!(
|
||||
user_access_token: @user_access_token, page_access_token: access_token
|
||||
)
|
||||
fb_page = get_fb_page(fb_page_id)
|
||||
fb_page&.update!(user_access_token: @user_access_token, page_access_token: access_token)
|
||||
fb_page&.reauthorized!
|
||||
end
|
||||
|
||||
def get_fb_page(fb_page_id)
|
||||
|
|
|
@ -12,6 +12,13 @@ class FBChannel extends ApiClient {
|
|||
params
|
||||
);
|
||||
}
|
||||
|
||||
reauthorizeFacebookPage({ omniauthToken, inboxId }) {
|
||||
return axios.post(`${this.baseUrl()}/callbacks/reauthorize_page`, {
|
||||
omniauth_token: omniauthToken,
|
||||
inbox_id: inboxId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default new FBChannel();
|
||||
|
|
|
@ -28,3 +28,7 @@ input {
|
|||
font-size: $font-size-small;
|
||||
font-weight: $font-weight-medium;
|
||||
}
|
||||
|
||||
.help-text {
|
||||
font-weight: $font-weight-normal;
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
<template>
|
||||
<div class="row settings--section">
|
||||
<div class="medium-4 small-12">
|
||||
<div class="medium-4 small-12 title--section">
|
||||
<p class="sub-block-title">
|
||||
{{ title }}
|
||||
</p>
|
||||
|
@ -35,7 +35,7 @@ export default {
|
|||
.settings--section {
|
||||
border-bottom: 1px solid $color-border;
|
||||
display: flex;
|
||||
padding: $space-normal 0;
|
||||
padding: $space-normal $space-normal $space-normal 0;
|
||||
|
||||
.sub-block-title {
|
||||
color: $color-woot;
|
||||
|
|
|
@ -233,6 +233,12 @@
|
|||
"INBOX_UPDATE_TITLE": "Inbox Settings",
|
||||
"INBOX_UPDATE_SUB_TEXT": "Update your inbox settings",
|
||||
"AUTO_ASSIGNMENT_SUB_TEXT": "Enable or disable the automatic assignment of new conversations to the agents added to this inbox."
|
||||
},
|
||||
"FACEBOOK_REAUTHORIZE": {
|
||||
"TITLE": "Reauthorize",
|
||||
"SUBTITLE": "Your Facebook connection has expired, please reconnect your Facebook page to continue services",
|
||||
"MESSAGE_SUCCESS": "Reconnection successful",
|
||||
"MESSAGE_ERROR": "There was an error, please try again"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -112,8 +112,6 @@
|
|||
</div>
|
||||
</template>
|
||||
<script>
|
||||
/* global bus */
|
||||
|
||||
import { mapGetters } from 'vuex';
|
||||
import Settings from './Settings';
|
||||
import adminMixin from '../../../../mixins/isAdmin';
|
||||
|
|
|
@ -163,6 +163,10 @@
|
|||
@click="updateInbox"
|
||||
/>
|
||||
</settings-section>
|
||||
<facebook-reauthorize
|
||||
v-if="isAFacebookInbox && inbox.reauthorization_required"
|
||||
:inbox-id="inbox.id"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- update agents in inbox -->
|
||||
|
@ -223,10 +227,12 @@ import configMixin from 'shared/mixins/configMixin';
|
|||
import alertMixin from 'shared/mixins/alertMixin';
|
||||
import SettingsSection from '../../../../components/SettingsSection';
|
||||
import inboxMixin from 'shared/mixins/inboxMixin';
|
||||
import FacebookReauthorize from './facebook/Reauthorize';
|
||||
|
||||
export default {
|
||||
components: {
|
||||
SettingsSection,
|
||||
FacebookReauthorize,
|
||||
},
|
||||
mixins: [alertMixin, configMixin, inboxMixin],
|
||||
data() {
|
||||
|
@ -316,7 +322,6 @@ export default {
|
|||
},
|
||||
methods: {
|
||||
handleFeatureFlag(e) {
|
||||
console.log(e.target.value);
|
||||
this.selectedFeatureFlags = this.toggleInput(
|
||||
this.selectedFeatureFlags,
|
||||
e.target.value
|
||||
|
@ -425,12 +430,10 @@ export default {
|
|||
background: $color-white;
|
||||
|
||||
.settings--content {
|
||||
&:last-child {
|
||||
.settings--section {
|
||||
div:last-child {
|
||||
border-bottom: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.page-top-bar {
|
||||
@include background-light;
|
||||
|
|
|
@ -0,0 +1,115 @@
|
|||
<template>
|
||||
<settings-section
|
||||
:title="$t('INBOX_MGMT.FACEBOOK_REAUTHORIZE.TITLE')"
|
||||
:sub-title="$t('INBOX_MGMT.FACEBOOK_REAUTHORIZE.SUBTITLE')"
|
||||
>
|
||||
<a class="fb--login" href="#" @click="tryFBlogin">
|
||||
<img
|
||||
src="~dashboard/assets/images/channels/facebook_login.png"
|
||||
alt="Facebook-logo"
|
||||
/>
|
||||
</a>
|
||||
</settings-section>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
/* global FB */
|
||||
import SettingsSection from '../../../../../components/SettingsSection';
|
||||
import alertMixin from 'shared/mixins/alertMixin';
|
||||
|
||||
export default {
|
||||
components: {
|
||||
SettingsSection,
|
||||
},
|
||||
mixins: [alertMixin],
|
||||
props: {
|
||||
inboxId: {
|
||||
type: Number,
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
mounted() {
|
||||
this.initFB();
|
||||
this.loadFBsdk();
|
||||
},
|
||||
|
||||
methods: {
|
||||
initFB() {
|
||||
if (window.fbSDKLoaded === undefined) {
|
||||
window.fbAsyncInit = () => {
|
||||
FB.init({
|
||||
appId: window.chatwootConfig.fbAppId,
|
||||
xfbml: true,
|
||||
version: 'v7.0',
|
||||
status: true,
|
||||
});
|
||||
window.fbSDKLoaded = true;
|
||||
FB.AppEvents.logPageView();
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
loadFBsdk() {
|
||||
((d, s, id) => {
|
||||
let js;
|
||||
// eslint-disable-next-line
|
||||
const fjs = (js = d.getElementsByTagName(s)[0]);
|
||||
if (d.getElementById(id)) {
|
||||
return;
|
||||
}
|
||||
js = d.createElement(s);
|
||||
js.id = id;
|
||||
js.src = 'https://connect.facebook.net/en_US/sdk.js';
|
||||
fjs.parentNode.insertBefore(js, fjs);
|
||||
})(document, 'script', 'facebook-jssdk');
|
||||
},
|
||||
|
||||
tryFBlogin() {
|
||||
FB.login(
|
||||
response => {
|
||||
if (response.status === 'connected') {
|
||||
this.reauthorizeFBPage(response.authResponse.accessToken);
|
||||
} else if (response.status === 'not_authorized') {
|
||||
// The person is logged into Facebook, but not your app.
|
||||
this.showAlert(this.$t('INBOX_MGMT.DETAILS.ERROR_FB_AUTH'));
|
||||
} else {
|
||||
// The person is not logged into Facebook, so we're not sure if
|
||||
// they are logged into this app or not.
|
||||
this.showAlert(this.$t('INBOX_MGMT.DETAILS.ERROR_FB_AUTH'));
|
||||
}
|
||||
},
|
||||
{
|
||||
scope: 'pages_manage_metadata,pages_messaging',
|
||||
auth_type: 'reauthorize',
|
||||
}
|
||||
);
|
||||
},
|
||||
async reauthorizeFBPage(omniauthToken) {
|
||||
try {
|
||||
await this.$store.dispatch('inboxes/reauthorizeFacebookPage', {
|
||||
omniauthToken,
|
||||
inboxId: this.inboxId,
|
||||
});
|
||||
this.showAlert(
|
||||
this.$t('INBOX_MGMT.FACEBOOK_REAUTHORIZE.MESSAGE_SUCCESS')
|
||||
);
|
||||
} catch (error) {
|
||||
this.showAlert(
|
||||
this.$t('INBOX_MGMT.FACEBOOK_REAUTHORIZE.MESSAGE_ERROR')
|
||||
);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
@import '~dashboard/assets/scss/variables';
|
||||
|
||||
.fb--login {
|
||||
img {
|
||||
max-width: 240px;
|
||||
padding: $space-normal 0;
|
||||
}
|
||||
}
|
||||
</style>
|
|
@ -139,6 +139,14 @@ export const actions = {
|
|||
throw new Error(error);
|
||||
}
|
||||
},
|
||||
reauthorizeFacebookPage: async ({ commit }, params) => {
|
||||
try {
|
||||
const response = await FBChannel.reauthorizeFacebookPage(params);
|
||||
commit(types.default.EDIT_INBOXES, response.data);
|
||||
} catch (error) {
|
||||
throw new Error(error.message);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export const mutations = {
|
||||
|
|
|
@ -19,6 +19,8 @@
|
|||
class Channel::FacebookPage < ApplicationRecord
|
||||
self.table_name = 'channel_facebook_pages'
|
||||
|
||||
include Reauthorizable
|
||||
|
||||
validates :account_id, presence: true
|
||||
validates :page_id, uniqueness: { scope: :account_id }
|
||||
belongs_to :account
|
||||
|
|
57
app/models/concerns/reauthorizable.rb
Normal file
57
app/models/concerns/reauthorizable.rb
Normal file
|
@ -0,0 +1,57 @@
|
|||
# This concern is primarily targetted for business models dependant on external services
|
||||
# The auth tokens we obtained on their behalf could expire or becomes invalid.
|
||||
# We would be aware of it until we make the API call to the service and it throws error
|
||||
|
||||
# Example:
|
||||
# when a user changes his/her password, the auth token they provided to chatwoot becomes invalid
|
||||
|
||||
# This module helps to capture the errors into a counter and when threshold is passed would mark
|
||||
# the object to be reauthorized. We will also send an email to the owners alerting them of the error.
|
||||
|
||||
# In the UI, we will check for the reauthorization_required? status and prompt the reauthorization flow
|
||||
|
||||
module Reauthorizable
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
AUTHORIZATION_ERROR_THRESHOLD = 2
|
||||
|
||||
# model attribute
|
||||
def reauthorization_required?
|
||||
::Redis::Alfred.get(reauthorization_required_key).present?
|
||||
end
|
||||
|
||||
# model attribute
|
||||
def authorization_error_count
|
||||
::Redis::Alfred.get(authorization_error_count_key).to_i
|
||||
end
|
||||
|
||||
# action to be performed when we recieve authorization errors
|
||||
# Implement in your exception handling logic for authorization errors
|
||||
def authorization_error!
|
||||
::Redis::Alfred.incr(authorization_error_count_key)
|
||||
prompt_reauthorization! if authorization_error_count >= AUTHORIZATION_ERROR_THRESHOLD
|
||||
end
|
||||
|
||||
# Performed automatically if error threshold is breached
|
||||
# could used to manually prompt reauthorization if auth scope changes
|
||||
def prompt_reauthorization!
|
||||
::Redis::Alfred.set(reauthorization_required_key, true)
|
||||
# TODO: send_reauthorize_prompt_email
|
||||
end
|
||||
|
||||
# call this after you successfully Reauthorized the object in UI
|
||||
def reauthorized!
|
||||
::Redis::Alfred.delete(authorization_error_count_key)
|
||||
::Redis::Alfred.delete(reauthorization_required_key)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def authorization_error_count_key
|
||||
format(::Redis::Alfred::AUTHORIZATION_ERROR_COUNT, obj_type: self.class.table_name.singularize, obj_id: id)
|
||||
end
|
||||
|
||||
def reauthorization_required_key
|
||||
format(::Redis::Alfred::REAUTHORIZATION_REQUIRED, obj_type: self.class.table_name.singularize, obj_id: id)
|
||||
end
|
||||
end
|
|
@ -6,7 +6,11 @@ class Facebook::SendOnFacebookService < Base::SendOnChannelService
|
|||
end
|
||||
|
||||
def perform_reply
|
||||
FacebookBot::Bot.deliver(delivery_params, access_token: message.channel_token)
|
||||
result = FacebookBot::Bot.deliver(delivery_params, access_token: message.channel_token)
|
||||
message.update!(source_id: JSON.parse(result)['message_id'])
|
||||
rescue Facebook::Messenger::FacebookError => e
|
||||
Rails.logger.info e
|
||||
channel.authorization_error!
|
||||
end
|
||||
|
||||
def fb_text_message_params
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
json.data do
|
||||
json.partial! 'api/v1/models/inbox.json.jbuilder', resource: @inbox
|
||||
end
|
|
@ -15,3 +15,4 @@ json.web_widget_script resource.channel.try(:web_widget_script)
|
|||
json.forward_to_address resource.channel.try(:forward_to_address)
|
||||
json.phone_number resource.channel.try(:phone_number)
|
||||
json.selected_feature_flags resource.channel.try(:selected_feature_flags)
|
||||
json.reauthorization_required resource.channel.try(:reauthorization_required?) if resource.facebook?
|
||||
|
|
|
@ -1,13 +1,17 @@
|
|||
# refer : https://redis.io/commands
|
||||
|
||||
module Redis::Alfred
|
||||
include Redis::RedisKeys
|
||||
|
||||
class << self
|
||||
# key operations
|
||||
|
||||
# set a value in redis
|
||||
def set(key, value)
|
||||
$alfred.set(key, value)
|
||||
end
|
||||
|
||||
# set a key with expiry period
|
||||
def setex(key, value, expiry = 1.day)
|
||||
$alfred.setex(key, expiry, value)
|
||||
end
|
||||
|
@ -20,6 +24,12 @@ module Redis::Alfred
|
|||
$alfred.del(key)
|
||||
end
|
||||
|
||||
# increment a key by 1. throws error if key value is incompatible
|
||||
# sets key to 0 before operation if key doesn't exist
|
||||
def incr(key)
|
||||
$alfred.incr(key)
|
||||
end
|
||||
|
||||
# list operations
|
||||
|
||||
def llen(key)
|
||||
|
|
|
@ -10,4 +10,8 @@ module Redis::RedisKeys
|
|||
ONLINE_PRESENCE_CONTACTS = 'ONLINE_PRESENCE::%<account_id>d::CONTACTS'.freeze
|
||||
# sorted set storing online presense of account users
|
||||
ONLINE_PRESENCE_USERS = 'ONLINE_PRESENCE::%<account_id>d::USERS'.freeze
|
||||
|
||||
## Authorization Status Keys
|
||||
AUTHORIZATION_ERROR_COUNT = 'AUTHORIZATION_ERROR_COUNT:%<obj_type>s:%<obj_id>d'.freeze
|
||||
REAUTHORIZATION_REQUIRED = 'REAUTHORIZATION_REQUIRED:%<obj_type>s:%<obj_id>d'.freeze
|
||||
end
|
||||
|
|
|
@ -114,6 +114,7 @@ RSpec.describe 'Callbacks API', type: :request do
|
|||
as: :json
|
||||
|
||||
expect(response).to have_http_status(:success)
|
||||
expect(response.body).to include(inbox.id.to_s)
|
||||
end
|
||||
|
||||
it 'returns unprocessable_entity if no page found' do
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
# frozen_string_literal: true
|
||||
|
||||
require 'rails_helper'
|
||||
require Rails.root.join 'spec/models/concerns/reauthorizable_spec.rb'
|
||||
|
||||
RSpec.describe Channel::FacebookPage do
|
||||
let(:channel) { create(:channel_facebook_page) }
|
||||
|
@ -10,6 +11,10 @@ RSpec.describe Channel::FacebookPage do
|
|||
it { is_expected.to belong_to(:account) }
|
||||
it { is_expected.to have_one(:inbox).dependent(:destroy) }
|
||||
|
||||
describe 'concerns' do
|
||||
it_behaves_like 'reauthorizable'
|
||||
end
|
||||
|
||||
it 'has a valid name' do
|
||||
expect(channel.name).to eq('Facebook')
|
||||
end
|
||||
|
|
38
spec/models/concerns/reauthorizable_spec.rb
Normal file
38
spec/models/concerns/reauthorizable_spec.rb
Normal file
|
@ -0,0 +1,38 @@
|
|||
require 'rails_helper'
|
||||
|
||||
shared_examples_for 'reauthorizable' do
|
||||
let(:model) { described_class } # the class that includes the concern
|
||||
|
||||
it 'authorization_error!' do
|
||||
obj = FactoryBot.create(model.to_s.underscore.tr('/', '_').to_sym)
|
||||
expect(obj.authorization_error_count).to eq 0
|
||||
|
||||
obj.authorization_error!
|
||||
|
||||
expect(obj.authorization_error_count).to eq 1
|
||||
end
|
||||
|
||||
it 'prompt_reauthorization!' do
|
||||
obj = FactoryBot.create(model.to_s.underscore.tr('/', '_').to_sym)
|
||||
expect(obj.reauthorization_required?).to eq false
|
||||
|
||||
obj.prompt_reauthorization!
|
||||
|
||||
expect(obj.reauthorization_required?).to eq true
|
||||
end
|
||||
|
||||
it 'reauthorized!' do
|
||||
obj = FactoryBot.create(model.to_s.underscore.tr('/', '_').to_sym)
|
||||
# setting up the object with the errors to validate its cleared on action
|
||||
obj.authorization_error!
|
||||
obj.prompt_reauthorization!
|
||||
expect(obj.reauthorization_required?).to eq true
|
||||
expect(obj.authorization_error_count).not_to eq 0
|
||||
|
||||
obj.reauthorized!
|
||||
|
||||
# authorization errors are reset
|
||||
expect(obj.authorization_error_count).to eq 0
|
||||
expect(obj.reauthorization_required?).to eq false
|
||||
end
|
||||
end
|
|
@ -5,7 +5,7 @@ describe Facebook::SendOnFacebookService do
|
|||
|
||||
before do
|
||||
allow(Facebook::Messenger::Subscriptions).to receive(:subscribe).and_return(true)
|
||||
allow(bot).to receive(:deliver)
|
||||
allow(bot).to receive(:deliver).and_return({ recipient_id: '1008372609250235', message_id: 'mid.1456970487936:c34767dfe57ee6e339' }.to_json)
|
||||
create(:message, message_type: :incoming, inbox: facebook_inbox, account: account, conversation: conversation)
|
||||
end
|
||||
|
||||
|
|
Loading…
Reference in a new issue