Slack challenge parameter issue with ngrok - slack

I've been trying to learn how to build a slack bot. I'm following this tutorial:
https://www.youtube.com/watch?v=6gHvqXrfjuo
I ran ngrok on http 5000, and I have my python file running on the same port.
I'm trying to add event subscriptions, but the link doesn't respond with a challenge parameter. I get a 403 forbidden response from the post request. I currently live in a student accommodation, so I don't have my own private Internet connection from a router, but I use something called ASK4 which is the same sort of specialist ISP that hotels use I'm assuming. I thought it was my firewall at first, but after turning that off, I'm starting to think it's the nature of my connection itself. Any Ideas?
import slack
import os
from pathlib import Path
from dotenv import load_dotenv
from flask import Flask
from slackeventsapi import SlackEventAdapter
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
app = Flask(__name__)
slack_event_adapter = SlackEventAdapter(os.environ['SIGNING_SECRET'], '/slack/events', app)
client = slack.WebClient(token=os.environ['SLACK_TOKEN'])
client.chat_postMessage(channel='#acme-explosives', text="Hello World")
if __name__ == "__main__":
app.run(debug=True)

Just change Ngrok port and application port, it will help

Related

Stripe webhook returns 301 error but works in localhost

I have implemented a Stripe webhook to handle payment events in my Django rest framewrok application. When I test the webhook locally, it works as expected and I am able to receive and process the payment events. However, when I deploy the application and try to use the webhook, I receive a 301 error from Stripe. There is no response from the webhook call as shown in Stripe dashboard. The webhook URL is reachable and I am able to access it without any issues. I have also checked the logs and there are no errors on the server side, which mean that the content of post function is not executed.
I am not sure what is causing this issue and would appreciate any help in troubleshooting and fixing it. Thank you.
The webhook url
urlpatterns = [
path('stripe-webhook', stripe_webhook.as_view()),]
The webhook function is as shown:
class stripe_webhook(APIView):
def post(self, request):
#verify webhook request
print(request.body)
payload = request.body
sig_header = request.headers['STRIPE_SIGNATURE']
event = None
try:
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
except ValueError as e:
# Invalid payload
raise e
except stripe.error.SignatureVerificationError as e:
# Invalid signature
raise e
# Handle the event
if event['type'] == 'payment_intent.succeeded':
payment_intent = event['data']['object']
print(payment_intent)
else:
print('Unhandled event type {}'.format(event['type']))
return HttpResponse(status=200)
You might happen to have a middleware or a load balancer for the server hosting your webhook endpoint which might explain 301 status code. Just a guess though. You would likely want to talk to your hosting provider to see if they can shed any lights on why the requests are being redirected once they come in.

Google auth2.0 won't work when send request from Google Composer

I am running sample code from google document, everything works fine in local. I put http://localhost under the Authorized redirect URIs so I am able to authenticate from the browser and get results (calendar event) back. I have converted the code into an airflow dag:
from airflow import DAG, macros
from airflow.operators.python import PythonOperator
from utils.aircal_utils import sync_tp_gcalendar, test_from_local
with DAG(
"update_calendar",
default_args={"start_date": macros.datetime(2022, 10, 9, 22, 0, tzinfo=TZ)},
) as dag:
task = PythonOperator(task_id="update_calender",
python_callable=main) # main function from example
task
And test the dag from the composer. I got same authentication request inlog. After authenticate from browser, I get error:
This site can’t be reachedlocalhost refused to connect.
Try:
Checking the connection
Checking the proxy and the firewall
ERR_CONNECTION_REFUSED
I have tried to add composer domain in to Authorized redirect URI but it seems that google doesn't allow google service provided domain. Error as: Invalid Redirect: uses a forbidden domain. Similar error found in google bug tracker but it seems to be an intended behavior. Does anyone know how can I successfully run the code in google composer?

Watson ASR python WebSocket

I use python Websockets implemented using the websocket-client library in order to perform live speech recognition using Watson ASR. This solution was working until very recently but about a month ago it stopped working. There is not even a handshake. Weirdly enough I haven't changed the code (below). Another colleague using a different account has the same problem, so we don't believe that there is anything wrong with our accounts. I've contact IBM regarding this, but since there is no handshake there is no way they can track if something is wrong on their side. The code for websocket is shown below.
import websocket
(...)
ws = websocket.WebSocketApp(
self.api_url,
header=headers,
on_message=self.on_message,
on_error=self.on_error,
on_close=self.on_close,
on_open=self.on_open
)
Where the url is 'wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize', headers are the authorization tokens, and the other functions and methods to handle callbacks. What happens at the moment is that this method runs and waits until there is a time out for the connection. I was wondering if this problem is happening to anyone else running live ASR with Watson in Python running this websocket-client library.
#zedavid Over a month ago we switch to use IAM so username and password was replaced with an IAM apikey. You should migrate your Cloud Foundry Speech to Text instance to IAM. There is a Migration page that will help you understand more about this. You can also create a new Speech to Text instance which will be a resource controlled instance by default.
Once you have the new instance you will need to get an access_token which is similar to the token in Cloud Foundry. The access_token will be used to authorize your request.
Finally, We recently released support for Speech to Text and Text to Speech in the Python SDK. I encourage you to use that rather than writing the code for the token exchange and WebSocket connection management.
service = SpeechToTextV1(
iam_apikey='YOUR APIKEY',
url='https://stream.watsonplatform.net/speech-to-text/api')
# Example using websockets
class MyRecognizeCallback(RecognizeCallback):
def __init__(self):
RecognizeCallback.__init__(self)
def on_transcription(self, transcript):
print(transcript)
def on_connected(self):
print('Connection was successful')
def on_error(self, error):
print('Error received: {}'.format(error))
def on_inactivity_timeout(self, error):
print('Inactivity timeout: {}'.format(error))
def on_listening(self):
print('Service is listening')
def on_hypothesis(self, hypothesis):
print(hypothesis)
def on_data(self, data):
print(data)
# Example using threads in a non-blocking way
mycallback = MyRecognizeCallback()
audio_file = open(join(dirname(__file__), '../resources/speech.wav'), 'rb')
audio_source = AudioSource(audio_file)
recognize_thread = threading.Thread(
target=service.recognize_using_websocket,
args=(audio_source, "audio/l16; rate=44100", mycallback))
recognize_thread.start()
Thanks for the headers information. Here's how it worked for me.
I am using WebSocket-client 0.54.0, which is currently the latest version. I generated a token using
curl -u <USERNAME>:<PASSWORD> "https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api"
Using the returned token in the below code, I was able to make the handshake
import websocket
try:
import thread
except ImportError:
import _thread as thread
import time
import json
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("### closed ###")
def on_open(ws):
def run(*args):
for i in range(3):
time.sleep(1)
ws.send("Hello %d" % i)
time.sleep(1)
ws.close()
print("thread terminating...")
thread.start_new_thread(run, ())
if __name__ == "__main__":
# headers["Authorization"] = "Basic " + base64.b64encode(auth.encode()).decode('utf-8')
websocket.enableTrace(True)
ws = websocket.WebSocketApp("wss://stream.watsonplatform.net/speech-to-text/api/v1/recognize",
on_message=on_message,
on_error=on_error,
on_close=on_close,
header={
"X-Watson-Authorization-Token": <TOKEN>"})
ws.on_open = on_open
ws.run_forever()
Response:
--- request header ---
GET /speech-to-text/api/v1/recognize HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: stream.watsonplatform.net
Origin: http://stream.watsonplatform.net
Sec-WebSocket-Key: Yuack3TM04/MPePJzvH8bA==
Sec-WebSocket-Version: 13
X-Watson-Authorization-Token: <TOKEN>
-----------------------
--- response header ---
HTTP/1.1 101 Switching Protocols
Date: Tue, 04 Dec 2018 12:13:57 GMT
Content-Type: application/octet-stream
Connection: upgrade
Upgrade: websocket
Sec-Websocket-Accept: 4te/E4t9+T8pBtxabmxrvPZfPfI=
x-global-transaction-id: a83c91fd1d100ff0cb2a6f50a7690694
X-DP-Watson-Tran-ID: a83c91fd1d100ff0cb2a6f50a7690694
-----------------------
send: b'\x81\x87\x9fd\xd9\xae\xd7\x01\xb5\xc2\xf0D\xe9'
Connection is already closed.
### closed ###
Process finished with exit code 0
According to RFC 6455, the server should respond with 101 Switching protocol,
The handshake from the server looks as follows:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat
Additionally, when I am using ws:// instead of wss://, I am facing the operation timeout issue.
Update: Example with Live Speech Recognition - https://github.com/watson-developer-cloud/python-sdk/blob/master/examples/microphone-speech-to-text.py

Angular + Django: Sending POST request with cookies (CORS)

I'm developing an app using Angular for client side and Django for server side. During development I'm running Django in port 8000 for managing all API requests, and serving my client app using Angular CLI running at port 4200.
Sending GET requests to Django work w/o problems but when I try to send a POST request that includes some cookies with session information, it fails as the cookies are not included in the header.
I know that the source of this "problem" is the CORS issue [read more here] and that it won't be a problem in production as both client and server apps will be running in the same server and port, however I wonder how can I fix this situation at least for development.
I've tried using the django-cors-headers module with the options CORS_ALLOW_CREDENTIALSand CORS_ORIGIN_ALLOW_ALL set to True but it didn't work.
Any ideas?
Finally I managed to make all work.
I thought it was a problem of Django so I installed django-cors-headers module, however the "problem" is in the browser (actually is not a problem, it is a security issue, see [here][1]).
Anyway, I solved the problem using a proxy rule for my Angular CLI, as follows:
First, instead of sending my requests to http://localhost:8000/api/..., I send them to /api/ (i.e. to my Angular server running at port 4200).
Then I added a file in my Angular project called "proxy.conf.json" with the following content:
{
"/api": {
"target": "http://localhost:8000",
"secure": false
}
}
Finally, I added the flag "--proxy-config" to the Angular CLI server:
ng serve --watch **--proxy-config proxy.conf.json**
Now, all API requests are sent to the port 4200 and Angular internally redirects them to Django, avoiding the CORS problem.
Note: With this solution I didn't need anymore the django-cors-headers module.

Django Ajax 403 only when Posting from custom localhost url

I followed all the instructions to get Ajax working properly with Django (ajaxSetup to add the X-CSRFToken header on every request, etc) and that part now works fine.
I'm using django-rest-framework, django-allauth and rest-auth
I'm now trying to test Facebook login with DRF, since Facebook doesn't allow for localhost to be a registered app I edited ~/etc/host and added local.test.com as an alias for 127.0.0.1. Now whenever I try to post to Django I get 403 forbidden again. I think it may have something to do with the Request URL and the Remote Address being different, but I don't really know what to do with it.
Since I'm not sure where the problem is I think it makes more sense to just share the link to the project on github: https://github.com/Sebastiansc/Sauti
What can I do to allow POST Ajax requests coming from local.test.com to work?
try with #csrf_exempt
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def your_view(request):
print "fff"
print "do your things..."

Resources