Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support updating existing channels for Facebook and Instagram, remove… #5692

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions temba/channels/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ class Category(Enum):
beta_only = False

unique_addresses = False
matching_addresses_updates = False
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To allow update the existing channel with matching address


# the courier handling URL, will be wired automatically for use in templates, but wired to a null handler
courier_url = None
Expand Down
135 changes: 53 additions & 82 deletions temba/channels/types/facebookapp/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def setUp(self):
address="12345",
role="SR",
schemes=["facebook"],
config={"auth_token": "09876543"},
config={"auth_token": "09876543", "page_name": "FirstName"},
)

@override_settings(FACEBOOK_APPLICATION_ID="FB_APP_ID", FACEBOOK_APPLICATION_SECRET="FB_APP_SECRET")
Expand Down Expand Up @@ -172,6 +172,11 @@ def test_claim_long_name(self, mock_get, mock_post):
@patch("requests.post")
@patch("requests.get")
def test_claim_already_connected(self, mock_get, mock_post):
channel = Channel.objects.get(address="12345", channel_type="FBA")
self.assertEqual(channel.config[Channel.CONFIG_AUTH_TOKEN], "09876543")
self.assertEqual(channel.config[Channel.CONFIG_PAGE_NAME], "FirstName")
self.assertEqual(channel.name, "Facebook")

token = "x" * 200
name = "Temba"

Expand All @@ -180,7 +185,7 @@ def test_claim_already_connected(self, mock_get, mock_post):
MockResponse(200, json.dumps({"access_token": f"long-life-user-{token}"})),
MockResponse(
200,
json.dumps({"data": [{"name": name, "id": "12345", "access_token": f"page-long-life-{token}"}]}),
json.dumps({"data": [{"name": name, "id": "12345", "access_token": f"page-long-life-update-{token}"}]}),
),
]

Expand All @@ -206,7 +211,10 @@ def test_claim_already_connected(self, mock_get, mock_post):
post_data["page_name"] = name

response = self.client.post(url, post_data, follow=True)
self.assertContains(response, "This channel is already connected in this workspace.")
channel = Channel.objects.get(address="12345", channel_type="FBA")
self.assertEqual(channel.config[Channel.CONFIG_AUTH_TOKEN], f"page-long-life-update-{token}")
self.assertEqual(channel.config[Channel.CONFIG_PAGE_NAME], "Temba")
self.assertEqual(channel.name, "Facebook")

mock_get.side_effect = [
MockResponse(200, json.dumps({"data": {"user_id": "098765", "expired_at": 100}})),
Expand Down Expand Up @@ -246,85 +254,6 @@ def test_release(self, mock_delete):
"https://graph.facebook.com/v18.0/12345/subscribed_apps", params={"access_token": "09876543"}
)

@override_settings(FACEBOOK_APPLICATION_ID="FB_APP_ID", FACEBOOK_APPLICATION_SECRET="FB_APP_SECRET")
@patch("requests.post")
@patch("requests.get")
def test_refresh_token(self, mock_get, mock_post):
token = "x" * 200

url = reverse("channels.types.facebookapp.refresh_token", args=(self.channel.uuid,))

self.login(self.admin)

mock_post.return_value = MockResponse(200, json.dumps({"success": True}))

mock_get.side_effect = [
MockResponse(400, json.dumps({"error": "token invalid"})),
]

response = self.client.get(url)
self.assertContains(response, "Reconnect Facebook Page")
self.assertEqual(response.context["facebook_app_id"], "FB_APP_ID")
self.assertEqual(response.context["refresh_url"], url)
self.assertTrue(response.context["error_connect"])

mock_get.side_effect = [MockResponse(200, json.dumps({"data": {"is_valid": False}}))]
response = self.client.get(url)
self.assertContains(response, "Reconnect Facebook Page")
self.assertEqual(response.context["facebook_app_id"], "FB_APP_ID")
self.assertEqual(response.context["refresh_url"], url)
self.assertTrue(response.context["error_connect"])

mock_get.side_effect = [
MockResponse(200, json.dumps({"data": {"is_valid": True}})),
MockResponse(200, json.dumps({"access_token": f"long-life-user-{token}"})),
MockResponse(
200,
json.dumps({"data": [{"name": "Temba", "id": "12345", "access_token": f"page-long-life-{token}"}]}),
),
]

response = self.client.get(url)
self.assertContains(response, "Reconnect Facebook Page")
self.assertEqual(response.context["facebook_app_id"], "FB_APP_ID")
self.assertEqual(response.context["refresh_url"], url)
self.assertFalse(response.context["error_connect"])

post_data = response.context["form"].initial
post_data["fb_user_id"] = "098765"
post_data["user_access_token"] = token

response = self.client.post(url, post_data, follow=True)

# assert our channel got created
channel = Channel.objects.get(address="12345", channel_type="FBA")
self.assertEqual(channel.config[Channel.CONFIG_AUTH_TOKEN], f"page-long-life-{token}")
self.assertEqual(channel.config[Channel.CONFIG_PAGE_NAME], "Temba")
self.assertEqual(channel.address, "12345")

self.assertEqual(response.request["PATH_INFO"], reverse("channels.channel_read", args=[channel.uuid]))

mock_get.assert_any_call(
"https://graph.facebook.com/oauth/access_token",
params={
"grant_type": "fb_exchange_token",
"client_id": "FB_APP_ID",
"client_secret": "FB_APP_SECRET",
"fb_exchange_token": token,
},
)
mock_get.assert_any_call(
"https://graph.facebook.com/v18.0/098765/accounts", params={"access_token": f"long-life-user-{token}"}
)

mock_post.assert_any_call(
"https://graph.facebook.com/v18.0/12345/subscribed_apps",
data={
"subscribed_fields": "messages,message_deliveries,messaging_optins,messaging_optouts,messaging_postbacks,message_reads,messaging_referrals,messaging_handovers"
},
params={"access_token": f"page-long-life-{token}"},
)

def test_new_conversation_triggers(self):
flow = self.create_flow("Test")

Expand Down Expand Up @@ -394,3 +323,45 @@ def test_get_error_ref_url(self):
"https://developers.facebook.com/docs/messenger-platform/error-codes",
FacebookAppType().get_error_ref_url(None, "190"),
)

@override_settings(FACEBOOK_APPLICATION_ID="FB_APP_ID", FACEBOOK_APPLICATION_SECRET="FB_APP_SECRET")
@patch("requests.get")
def test_check_credentials(self, mock_get):
check_credentials_url = reverse("channels.types.facebookapp.check_credentials", args=(self.channel.uuid,))

self.login(self.admin)

mock_get.return_value = MockResponse(200, json.dumps({"success": True, "data": {}}))
response = self.client.get(check_credentials_url)
self.assertContains(response, "Reconnect Facebook Page")
self.assertContains(
response, "Error with token, you need to reconnect the Facebook page by clicking the button below"
)
self.assertEqual(
response.context["update_token_url"], f"{reverse("channels.types.facebookapp.claim")}?update=1"
)
self.assertFalse(response.context["valid_token"])

mock_get.return_value = MockResponse(200, json.dumps({"success": True, "data": {"is_valid": True}}))

response = self.client.get(check_credentials_url)
self.assertContains(response, "Reconnect Facebook Page")
self.assertContains(response, "Everything looks good. No need to reconnect")
self.assertEqual(
response.context["update_token_url"], f"{reverse("channels.types.facebookapp.claim")}?update=1"
)
self.assertTrue(response.context["valid_token"])

@override_settings(FACEBOOK_APPLICATION_ID="FB_APP_ID", FACEBOOK_APPLICATION_SECRET="FB_APP_SECRET")
@patch("requests.get")
def test_type_check_credentials(self, mock_get):
self.assertFalse(FacebookAppType().check_credentials({}))

mock_get.return_value = MockResponse(200, json.dumps({"success": True, "data": {}}))
self.assertFalse(FacebookAppType().check_credentials({Channel.CONFIG_AUTH_TOKEN: "Token"}))

mock_get.return_value = MockResponse(400, json.dumps({"error": True}))
self.assertFalse(FacebookAppType().check_credentials({Channel.CONFIG_AUTH_TOKEN: "Token"}))

mock_get.return_value = MockResponse(200, json.dumps({"success": True, "data": {"is_valid": True}}))
self.assertTrue(FacebookAppType().check_credentials({Channel.CONFIG_AUTH_TOKEN: "Token"}))
27 changes: 24 additions & 3 deletions temba/channels/types/facebookapp/type.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from temba.triggers.models import Trigger

from ...models import Channel, ChannelType
from .views import ClaimView, RefreshToken
from .views import CheckCredentials, ClaimView


class FacebookAppType(ChannelType):
Expand All @@ -21,6 +21,7 @@ class FacebookAppType(ChannelType):
category = ChannelType.Category.SOCIAL_MEDIA

unique_addresses = True
matching_addresses_updates = True

courier_url = r"^fba/receive"
schemes = [URN.FACEBOOK_SCHEME]
Expand All @@ -32,13 +33,15 @@ class FacebookAppType(ChannelType):
) % {"link": '<a target="_blank" href="http://facebook.com">Facebook</a>'}
claim_view = ClaimView

menu_items = [dict(label=_("Reconnect Facebook Page"), view_name="channels.types.facebookapp.refresh_token")]
menu_items = [dict(label=_("Check Credentials"), view_name="channels.types.facebookapp.check_credentials")]

def get_urls(self):
return [
self.get_claim_url(),
re_path(
r"^(?P<uuid>[a-z0-9\-]+)/refresh_token/$", RefreshToken.as_view(channel_type=self), name="refresh_token"
r"^(?P<uuid>[a-z0-9\-]+)/check_credentials/$",
CheckCredentials.as_view(channel_type=self),
name="check_credentials",
),
]

Expand Down Expand Up @@ -87,3 +90,21 @@ def get_redact_values(self, channel) -> tuple: # pragma: needs cover

def get_error_ref_url(self, channel, code: str) -> str:
return "https://developers.facebook.com/docs/messenger-platform/error-codes"

def check_credentials(self, config: dict) -> bool:
app_id = settings.FACEBOOK_APPLICATION_ID
app_secret = settings.FACEBOOK_APPLICATION_SECRET
url = "https://graph.facebook.com/v18.0/debug_token"

if Channel.CONFIG_AUTH_TOKEN not in config:
return False

params = {
"access_token": f"{app_id}|{app_secret}",
"input_token": config[Channel.CONFIG_AUTH_TOKEN],
}
resp = requests.get(url, params=params)

if resp.status_code == 200:
return resp.json().get("data", dict()).get("is_valid", False)
return False
Loading