Skip to content

Commit

Permalink
Add Slack request verification
Browse files Browse the repository at this point in the history
  • Loading branch information
RadoRado committed Jul 26, 2021
1 parent 30597c7 commit f7d622d
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion solution/main.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import hmac
import hashlib

from pprint import pprint

import requests
Expand All @@ -6,7 +9,7 @@

from dotenv import dotenv_values

from fastapi import Body, FastAPI, Request, Response
from fastapi import Body, FastAPI, Request, Response, status

config = dotenv_values(".env")

Expand All @@ -16,13 +19,37 @@
# This token can be obtained from the `OAuth Tokens for Your Workspace` section
# In `OAuth & Permissions` in the bot settings
BOT_TOKEN = config["BOT_TOKEN"]
SIGNING_SECRET = config["SIGNING_SECRET"]


def slack_validate_request(timestamp, body, slack_signature):
sig_basestring = 'v0:' + timestamp + ':' + body

signature = 'v0=' + hmac.new(
SIGNING_SECRET.encode(),
sig_basestring.encode(),
hashlib.sha256
).hexdigest()

return signature == slack_signature


@app.post("/echo")
async def echo(request: Request, response: Response, data=Body(...)):
raw_body = await request.body()
body = raw_body.decode("utf-8")

# We are following the guide from here:
# https://api.slack.com/authentication/verifying-requests-from-slack
slack_timestamp = request.headers['x-slack-request-timestamp']
slack_signature = request.headers['x-slack-signature']

is_valid = slack_validate_request(slack_timestamp, body, slack_signature)

if not is_valid:
response.status_code = status.HTTP_403_FORBIDDEN
return

# We need to add the `channels:read` scope
# From the `OAuth & Permissions` section in the bot settings
# This will give us `data.event.channel`, which is the channe id,
Expand Down

0 comments on commit f7d622d

Please sign in to comment.