Skip to content

Commit

Permalink
@require_slack_verification
Browse files Browse the repository at this point in the history
  • Loading branch information
daveebbelaar committed May 11, 2023
1 parent 8d4f793 commit bd59f35
Showing 1 changed file with 33 additions and 4 deletions.
37 changes: 33 additions & 4 deletions slack/app.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from slack_sdk.signature import SignatureVerifier
from slack_bolt.adapter.flask import SlackRequestHandler
from slack_bolt import App
from dotenv import find_dotenv, load_dotenv
from flask import Flask, request, abort
from functions import draft_email
import logging
from functools import wraps
import time

logging.basicConfig(level=logging.INFO)

Expand All @@ -21,13 +24,41 @@

# Initialize the Slack app
app = App(token=SLACK_BOT_TOKEN)
signature_verifier = SignatureVerifier(SLACK_SIGNING_SECRET)

# Initialize the Flask app
# Flask is a web application framework written in Python
flask_app = Flask(__name__)
handler = SlackRequestHandler(app)


def require_slack_verification(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not verify_slack_request():
abort(403)
return f(*args, **kwargs)

return decorated_function


def verify_slack_request():
# Get the request headers
timestamp = request.headers.get("X-Slack-Request-Timestamp", "")
signature = request.headers.get("X-Slack-Signature", "")

# Check if the timestamp is within five minutes of the current time
current_timestamp = int(time.time())
if abs(current_timestamp - int(timestamp)) > 60 * 5:
return False

# Verify the request signature
return signature_verifier.is_valid(
body=request.get_data().decode("utf-8"),
timestamp=timestamp,
signature=signature,
)


def get_bot_user_id():
"""
Get the bot user ID using the Slack API.
Expand Down Expand Up @@ -80,6 +111,7 @@ def handle_mentions(body, say):


@flask_app.route("/slack/events", methods=["POST"])
@require_slack_verification
def slack_events():
"""
Route for handling Slack events.
Expand All @@ -88,9 +120,6 @@ def slack_events():
Returns:
Response: The result of handling the request.
"""
# # Verify the request signature
# if not app.verify_signature(request):
# abort(401) # Unauthorized request

return handler.handle(request)

Expand Down

0 comments on commit bd59f35

Please sign in to comment.