|
| 1 | +import hmac |
| 2 | +import hashlib |
| 3 | + |
1 | 4 | from pprint import pprint
|
2 | 5 |
|
3 | 6 | import requests
|
|
6 | 9 |
|
7 | 10 | from dotenv import dotenv_values
|
8 | 11 |
|
9 |
| -from fastapi import Body, FastAPI, Request, Response |
| 12 | +from fastapi import Body, FastAPI, Request, Response, status |
10 | 13 |
|
11 | 14 | config = dotenv_values(".env")
|
12 | 15 |
|
|
16 | 19 | # This token can be obtained from the `OAuth Tokens for Your Workspace` section
|
17 | 20 | # In `OAuth & Permissions` in the bot settings
|
18 | 21 | BOT_TOKEN = config["BOT_TOKEN"]
|
| 22 | +SIGNING_SECRET = config["SIGNING_SECRET"] |
| 23 | + |
| 24 | + |
| 25 | +def slack_validate_request(timestamp, body, slack_signature): |
| 26 | + sig_basestring = 'v0:' + timestamp + ':' + body |
| 27 | + |
| 28 | + signature = 'v0=' + hmac.new( |
| 29 | + SIGNING_SECRET.encode(), |
| 30 | + sig_basestring.encode(), |
| 31 | + hashlib.sha256 |
| 32 | + ).hexdigest() |
| 33 | + |
| 34 | + return signature == slack_signature |
19 | 35 |
|
20 | 36 |
|
21 | 37 | @app.post("/echo")
|
22 | 38 | async def echo(request: Request, response: Response, data=Body(...)):
|
23 | 39 | raw_body = await request.body()
|
24 | 40 | body = raw_body.decode("utf-8")
|
25 | 41 |
|
| 42 | + # We are following the guide from here: |
| 43 | + # https://api.slack.com/authentication/verifying-requests-from-slack |
| 44 | + slack_timestamp = request.headers['x-slack-request-timestamp'] |
| 45 | + slack_signature = request.headers['x-slack-signature'] |
| 46 | + |
| 47 | + is_valid = slack_validate_request(slack_timestamp, body, slack_signature) |
| 48 | + |
| 49 | + if not is_valid: |
| 50 | + response.status_code = status.HTTP_403_FORBIDDEN |
| 51 | + return |
| 52 | + |
26 | 53 | # We need to add the `channels:read` scope
|
27 | 54 | # From the `OAuth & Permissions` section in the bot settings
|
28 | 55 | # This will give us `data.event.channel`, which is the channe id,
|
|
0 commit comments