import time
import hmac
import hashlib


def verify_request(event, slack_secret, timeout=True):
    """Verify that Lambda event came from Slack"""
    version = 'v0'
    request_headers = event.get('headers')
    timestamp = request_headers.get('X-Slack-Request-Timestamp')
    if timeout and abs(time.time() - float(timestamp)) > 60 * 5:
        # The request timestamp is more than five minutes from local time
        # It could be a replay attack, so let's ignore it
        return False, 'Request timeout'

    request_body = event.get('body')
    sig_basestring = '{0}:{1}:{2}'.format(version, timestamp, request_body)
    sig = hmac.new(
        slack_secret.encode('utf-8'),
        msg=sig_basestring.encode('utf-8'),
        digestmod=hashlib.sha256).hexdigest()

    my_signature = '{0}={1}'.format(version, sig).encode('utf-8')
    slack_signature = request_headers.get('X-Slack-Signature')
    slack_signature_encoded = slack_signature.encode('utf-8')

    if hmac.compare_digest(my_signature, slack_signature_encoded):
        # Validate body, check for missing fields
        # token, team_id, team_domain, channel_id, etc
        return True, 'Valid signature'
    return False, 'Invalid signature'