Skip to content

Commit 370c018

Browse files
committed
Link new users to their backend profile
1 parent f806a2a commit 370c018

3 files changed

Lines changed: 77 additions & 11 deletions

File tree

pybot/endpoints/slack/events.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66

77
from pybot.endpoints.slack.utils.event_utils import (
88
build_messages,
9+
get_backend_auth_headers,
10+
link_backend_user,
911
send_community_notification,
1012
send_user_greetings,
1113
)
@@ -25,8 +27,9 @@ async def team_join(event: Event, app: SirBot) -> None:
2527
notifies the community channel of the new member.
2628
"""
2729
slack_api = app.plugins["slack"].api
30+
user_id = event["user"]["id"]
2831

29-
*user_messages, community_message = build_messages(event["user"]["id"])
32+
*user_messages, community_message = build_messages(user_id)
3033
futures = [
3134
send_user_greetings(user_messages, slack_api),
3235
send_community_notification(community_message, slack_api),
@@ -35,3 +38,7 @@ async def team_join(event: Event, app: SirBot) -> None:
3538
logger.info(f"New team join event: {event}")
3639
await asyncio.sleep(30)
3740
await asyncio.wait(futures)
41+
42+
headers = await get_backend_auth_headers(app.http_session)
43+
if headers:
44+
await link_backend_user(user_id, headers, slack_api, app.http_session)

pybot/endpoints/slack/utils/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@
1212
PORT = os.environ.get("SIRBOT_PORT", 5000)
1313
HOST = os.environ.get("SIRBOT_ADDR", "0.0.0.0")
1414
PYBOT_ENV = os.environ.get("PYBOT_ENV", "dev")
15+
BACKEND_URL = os.environ.get("BACKEND_URL", "https://api.operationcode.org")
16+
BACKEND_USERNAME = os.environ.get("BACKEND_USERNAME", "Pybot@test.test")
17+
BACKEND_PASS = os.environ.get("BACKEND_PASS", "fakePassword")
18+
1519
BOT_URL = "https://github.com/OperationCode/operationcode-pybot"
1620

1721
slack_configs = {

pybot/endpoints/slack/utils/event_utils.py

Lines changed: 65 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
1-
from typing import List
1+
import logging
2+
from typing import Dict, List, Tuple
23

4+
from aiohttp import ClientSession
35
from slack import methods
46
from slack.events import Message
57
from slack.io.abc import SlackAPI
68

7-
from pybot.endpoints.slack.utils import COMMUNITY_CHANNEL
9+
from pybot.endpoints.slack.utils import (
10+
BACKEND_PASS,
11+
BACKEND_URL,
12+
BACKEND_USERNAME,
13+
COMMUNITY_CHANNEL,
14+
)
815
from pybot.endpoints.slack.utils.action_messages import not_greeted_attachment
916
from pybot.endpoints.slack.utils.event_messages import (
1017
base_resources,
@@ -13,8 +20,17 @@
1320
team_join_initial_message,
1421
)
1522

23+
logger = logging.getLogger(__name__)
24+
1625

17-
def build_messages(user_id):
26+
def base_user_message(user_id: str) -> Message:
27+
message = Message()
28+
message["channel"] = user_id
29+
message["as_user"] = True
30+
return message
31+
32+
33+
def build_messages(user_id) -> Tuple[Message, Message, Message, Message]:
1834
initial_message = base_user_message(user_id)
1935
initial_message["text"] = team_join_initial_message(user_id)
2036

@@ -34,17 +50,56 @@ def build_messages(user_id):
3450
return initial_message, second_message, action_menu, community_message
3551

3652

37-
async def send_user_greetings(user_messages: List[Message], slack_api: SlackAPI):
53+
async def send_user_greetings(
54+
user_messages: List[Message], slack_api: SlackAPI
55+
) -> None:
3856
for message in user_messages:
3957
await slack_api.query(url=methods.CHAT_POST_MESSAGE, data=message)
4058

4159

42-
async def send_community_notification(community_message: Message, slack_api: SlackAPI):
60+
async def send_community_notification(
61+
community_message: Message, slack_api: SlackAPI
62+
) -> dict:
4363
return await slack_api.query(url=methods.CHAT_POST_MESSAGE, data=community_message)
4464

4565

46-
def base_user_message(user_id):
47-
message = Message()
48-
message["channel"] = user_id
49-
message["as_user"] = True
50-
return message
66+
async def link_backend_user(
67+
slack_id: str,
68+
auth_header: Dict[str, str],
69+
slack_api: SlackAPI,
70+
session: ClientSession,
71+
) -> None:
72+
"""
73+
Updates the slack user with their profile in the backend
74+
"""
75+
76+
user_info = await slack_api.query(methods.USERS_INFO, {"user": slack_id})
77+
email = user_info["user"]["profile"]["email"]
78+
79+
async with session.patch(
80+
f"{BACKEND_URL}/auth/profile/admin/",
81+
headers=auth_header,
82+
params={"email": email},
83+
json={"slackId": slack_id},
84+
) as response:
85+
data = await response.json()
86+
logger.info(f"Backend response from user linking: {data}")
87+
88+
89+
async def get_backend_auth_headers(session: ClientSession) -> Dict[str, str]:
90+
"""
91+
Authenticates with the OC Backend server
92+
93+
:return: Authorization header containing the returned JWT
94+
"""
95+
async with session.post(
96+
f"{BACKEND_URL}/auth/login/",
97+
json={"email": BACKEND_USERNAME, "password": BACKEND_PASS},
98+
) as response:
99+
if 400 <= response.status:
100+
logger.exception("Failed to authenticate with backend")
101+
return {}
102+
response.raise_for_status()
103+
data = await response.json()
104+
headers = {"Authorization": f"Bearer {data['token']}"}
105+
return headers

0 commit comments

Comments
 (0)