hi, i am making auth bot with flask and python, when they click on the authorization link, this error comes to the console and there is no authorization
Error coming to console when someone clicks the link
Error:
[2023-02-03 07:29:44,909] ERROR in app: Exception on /discordauth [GET]
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 2073, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1518, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1516, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1502, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:\Users\Administrator\Desktop\Discord-baker-main\application.py", line 37, in discord
data = exchange_code(code)
File "C:\Users\Administrator\Desktop\Discord-baker-main\application.py", line 187, in exchange_code
r.raise_for_status()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\models.py", line 943, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://discord.com/api/v9/oauth2/token```
When you click on the authorization link, this error appears on the link:
500 Internal Server Error
**Internal Server Error**
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
My code:
import requests
import configparser
import os
from flask import Flask, request, redirect, url_for, render_template
config = configparser.ConfigParser()
config.read('database.ini')
application = Flask(__name__)
API_ENDPOINT = "https://discord.com/api/v9"
#leave this like this
CLIENT_ID = config['apiinfo']['CLIENT_ID']
CLIENT_SECRET = config['apiinfo']['CLIENT_SECRET']
CLIENT_TOKEN = config['botinfo']['bottoken']
DOMAIN = config['apiinfo']['DOMAIN']
exchangepass = config['apiinfo']['exchangepass']
SCOPE = "identify guilds guilds.join"
REDIRECT_URI = f"{DOMAIN}/discordauth"
welcomechannel = str(config['botinfo']['welcome_channel'])
memberrole = str(config['botinfo']['memberrole'])
restorekey = str(config['botinfo']['therestorekey'])
guildid = config['info']['guildid']
def cls():
os.system('cls' if os.name == 'nt' else 'clear')
#application.route('/working', methods=['GET', 'POST'])
def working():
return 'true'
#application.route('/discordauth', methods=['GET', 'POST'])
def discord():
print("In discordauth")
code = request.args.get('code')
data = exchange_code(code)
state = request.args.get('state')
access_token = data.get("access_token")
refresh_token = data.get("refresh_token")
data2 = getid(access_token)
userid = str(data2.get("id"))
username = data2.get("username")
country = data2.get("locale")
if userid in config['useridsincheck']:
config['users'][userid] = 'NA'
config[userid] = {}
config[userid]['refresh_tokens'] = refresh_token
config[userid]['refresh'] = 'true'
config[userid]['country'] = country
with open('database.ini', 'w') as configfile:
config.write(configfile)
if request.method == 'POST':
return 'success'
if request.method == 'GET':
return render_template('Authcomplete.html')
elif userid in config['users']:
if request.method == 'POST':
return 'success'
if request.method == 'GET':
return render_template('Authcomplete.html')
else:
return 'fail'
#application.route('/restore', methods=['GET', 'POST'])
def restore():
password = request.json['code']
if password == exchangepass:
restoreserver()
return 'succsess'
else:
print("Invalid password" + password)
return 'wrong password'
#application.route('/', methods=['GET', 'POST'])
def testbuild():
return render_template('home.html')
def getid(info):
url = "https://discord.com/api/v9/users/#me"
payload={}
accsestokentoget = info
headers = {
'Authorization': 'Bearer ' + accsestokentoget,
}
response = requests.request("GET", url, headers=headers, data=payload)
response.raise_for_status()
return response.json()
#error to fix in here
#application.route('/requestid', methods=['GET', 'POST'])
def requestid():
print("Part requestid")
key = request.json['key']
id = str(request.json['id'])
print(id)
print(key)
if key == exchangepass:
if id in config['users']:
return 'succsess'
else:
print("key was correct")
#check if the category is in the config
config['useridsincheck'] = {}
config['useridsincheck'][id] = 'waiting'
with open('database.ini', 'w') as configfile:
config.write(configfile)
return 'succsess'
else:
print("key was wrong")
return 'wrong key'
#application.route('/data', methods=['GET', 'POST'])
def data():
key = request.json['key']
dataset = request.json['dataset']
print("part data")
if key == config['apiinfo']['tempkey']:
if dataset == 'CLIENT_ID':
return CLIENT_ID
if dataset == 'guildid':
return guildid
if dataset == 'CLIENT_SECRET':
return CLIENT_SECRET
if dataset == 'bottoken':
return CLIENT_TOKEN
if dataset == 'exchangepass':
return exchangepass
if dataset == 'welcomechannel':
return welcomechannel
if dataset == 'verifiedrole':
return memberrole
if dataset == 'restorekey':
return restorekey
if config['apiinfo']['botsetupcomplete'] == 'no':
if dataset == 'pass':
return config['apiinfo']['tempkey']
config['apiinfo']['botsetupcomplete'] = 'yes'
with open('database.ini', 'w') as configfile:
config.write(configfile)
return 'error dataset wrong'
#application.route('/checkifverifydone', methods=['GET', 'POST'])
def checkifverifydone():
print("Part checkifverifydone")
key = request.json['key']
id = str(request.json['id'])
print(id)
print(key)
if key == exchangepass:
print("key was correct")
if id in config['users']:
config['useridsincheck'][id] = 'verified'
with open('database.ini', 'w') as configfile:
config.write(configfile)
print("corect")
return 'true'
else:
print("id was not found")
return 'false'
else:
return 'false'
def exchange_code(code):
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
data = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
'scope': SCOPE
}
r = requests.post(
f"{API_ENDPOINT}/oauth2/token",
data=data,
headers=headers
)
r.raise_for_status()
return r.json()
def get_new_token(old_token): # gets new refresh_token
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
data = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'refresh_token',
'refresh_token': old_token
}
r = requests.post(
f"{API_ENDPOINT}/oauth2/token",
data=data,
headers=headers
)
r.raise_for_status()
return r.json()
def add_to_guild(access_token, user_id, guild_id):
headers = {
"Authorization" : f"Bot {CLIENT_TOKEN}",
'Content-Type': 'application/json'
}
data = {
"access_token" : access_token
}
response = requests.put(
url=f"{API_ENDPOINT}/guilds/{guild_id}/members/{user_id}",
headers=headers,
json=data
)
def restoreserver():
userids = config['users']
guildid = config['info']['guildid']
for idsinlist in userids:
print(idsinlist)
code = config[idsinlist]['refresh_tokens']
if config[idsinlist]['refresh'] == "false":
try:
data = exchange_code(code)
access_token = data.get("access_token")
add_to_guild(access_token, idsinlist, guildid)
config[idsinlist]['refresh_tokens'] = data.get("refresh_token")
config[idsinlist]['refresh'] = 'true'
with open('database.ini', 'w') as configfile:
config.write(configfile)
except:
print("error")
if config[idsinlist]['refresh'] == "true":
try:
data = get_new_token(code)
access_token = data.get("access_token")
add_to_guild(access_token, idsinlist, guildid)
config[idsinlist]['refresh_tokens'] = data.get("refresh_token")
with open('database.ini', 'w') as configfile:
config.write(configfile)
except:
print("error")
else:
print("Refresh status is invalid")
print(code)
if __name__ == '__main__':
cls()
application.run(host='0.0.0.0', port=80) #change to your port default port is 80
Related
https://prom.ua/cloud-cgi/static/uaprom-static/docs/swagger/index.html#/Products/post_products_import_file - link documentation
import json
import http.client
import pprint
import base64
API Settigs
AUTH_TOKEN = '56bggtygugttttttttttttttyt7u7u' # Your authorization token
HOST = 'my.prom.ua' # e.g.: my.prom.ua, my.tiu.ru, my.satu.kz, my.deal.by, my.prom.md
class HTTPError(Exception):
pass
class EvoClientExample(object):
def __init__(self, token):
self.token = token
def make_request(self, method, url, body=None):
connection = http.client.HTTPSConnection(HOST)
headers = {'Authorization': 'Bearer {}'.format(self.token),
'Content-type': 'application/json'}
if body:
body = json.dumps(body)
connection.request(method, url, body=body, headers=headers)
response = connection.getresponse()
if response.status != 200:
raise HTTPError('{}: {}'.format(response.status, response.reason))
response_data = response.read()
return json.loads(response_data.decode())
def get_order_list(self):
url = '/api/v1/orders/list'
method = 'GET'
return self.make_request(method, url)
def get_order(self, order_id):
url = '/api/v1/orders/{id}'
method = 'GET'
return self.make_request(method, url.format(id=order_id))
def set_order_status(self, status, ids, cancellation_reason=None, cancellation_text=None):
url = '/api/v1/orders/set_status'
method = 'POST'
body = {
'status': status,
'ids': ids
}
if cancellation_reason:
body['cancellation_reason'] = cancellation_reason
if cancellation_text:
body['cancellation_text'] = cancellation_text
return self.make_request(method, url, body)
def set_import_file(self, string_binary):
url = '/api/v1/products/import_file'
method = 'POST'
file = open("final.xml", "rb")
string_binary = file.read()
file.close()
body = {
"file": f'{string_binary}',
"data": {
"force_update": True,
"only_available": True,
"mark_missing_product_as": "none",
"updated_fields": [
"price",
"presence"
]
}
}
return self.make_request(method, url, body)
def main():
# Initialize Client
if not AUTH_TOKEN:
raise Exception('Sorry, there's no any AUTH_TOKEN!')
api_example = EvoClientExample(AUTH_TOKEN)
# file = open("final.xml", "rb")
# encoded_string = file.read()
# print(encoded_string)
# encoded_string = base64.b64encode(file.read())
import_file_response = api_example.set_import_file("")
# file.close()
print(import_file_response)
# if not order_list['orders']:
# raise Exception('Sorry, there\'s no any order!')
#
# pprint.pprint(api_example.get_order_list())
#
# # Order example data. Requred to be setup to get example work
# order_id = order_list['orders'][0]['id']
# order_ids = [order_id]
# status = 'received'
#
# # Setting order status
# pprint.pprint(api_example.set_order_status(status=status, ids=order_ids))
#
# # # Getting order by id
# pprint.pprint(api_example.get_order(order_id))
if name == 'main':
main()
error:
Traceback (most recent call last):
File "/home/dev/Documents/Workspace/prom/unload_prom/prom_api.py", line 118, in
main()
File "/home/dev/Documents/Workspace/prom/unload_prom/prom_api.py", line 97, in main
import_file_response = api_example.set_import_file("")
File "/home/dev/Documents/Workspace/prom/unload_prom/prom_api.py", line 84, in set_import_file
return self.make_request(method, url, body)
File "/home/dev/Documents/Workspace/prom/unload_prom/prom_api.py", line 31, in make_request
raise HTTPError('{}: {}'.format(response.status, response.reason))
main.HTTPError: 400: Bad Request
When I was using Flask, every API call is authenticated before processed:
app = connexion.App(__name__, specification_dir='./swagger/', swagger_json=True, swagger_ui=True, server='tornado')
app.app.json_encoder = encoder.JSONEncoder
app.add_api('swagger.yaml', arguments={'title': 'ABCD API'})
# add CORS support
CORS(app.app)
#app.app.before_request
def before_request_func():
app_id = request.headers.get("X-AppId")
token = request.headers.get("X-Token")
user, success = security.Security().authorize(token)
if not success:
status_code = 401
response = {
'code': status_code,
'message': 'Unauthorized user'
}
return jsonify(response), status_code
g.user = user
When I changed it to AioHttp, my authentication is not properly setup:
options = {'swagger_path': 'swagger/', "swagger_ui": True}
app = connexion.AioHttpApp(__name__, specification_dir='swagger/', options=options)
app.add_api('swagger.yaml', arguments={'title': ' ABCD API'})
app = web.Application(middlewares=[auth_through_token])
async def auth_through_token(app: web.Application, handler: Any) -> Callable:
#web.middleware
async def middleware_handler(request: web.Request) -> web.Response:
headers = request.headers
x_auth_token = headers.get("X-Token")
app_id = headers.get("X-AppId")
user, success = security.Security().authorize(x_auth_token)
if not success:
return web.json_response(status=401, data={
"error": {
"message": ("Not authorized. Reason: {}"
)
}
})
response = await handler(request)
return response
return middleware_handler
My request is not getting redirected to the API method.
Could anyone please help me to set up, my before_request authentication for every API?
Thanks.
Firstly, you have to move middleware_handler out from auth_through_token.
Then,
Quote your code:
options = {'swagger_path': 'swagger/', "swagger_ui": True}
app = connexion.AioHttpApp(__name__, specification_dir='swagger/', options=options)
app.add_api('swagger.yaml', arguments={'title': ' ABCD API'})
app = web.Application(middlewares=[auth_through_token])
You have to remove the last line and change the first line to:
options = {'swagger_path': 'swagger/', "swagger_ui": True, 'middlewares': [middleware_handler]}
So finally the code should look like:
options = {'swagger_path': 'swagger/', "swagger_ui": True, 'middlewares': [middleware_handler]}
app = connexion.AioHttpApp(__name__, specification_dir='swagger/', options=options)
app.add_api('swagger.yaml', arguments={'title': ' ABCD API'})
#web.middleware
async def middleware_handler(request: web.Request, handler: Any) -> web.Response:
headers = request.headers
x_auth_token = headers.get("X-Token")
app_id = headers.get("X-AppId")
user, success = security.Security().authorize(x_auth_token)
if not success:
return web.json_response(status=401, data={
"error": {
"message": ("Not authorized. Reason: {}"
)
}
})
response = await handler(request)
return response
I suspect it has something got to do with refresh token. Could not understand how to use it by the docs. Can I know the exact code how to use it?
The access token is created during login:
#app.route('/login', methods=['POST','GET'])
def login():
username = request.form["email"]
password = request.form["password"]
my_token_expiry_time = datetime.timedelta(seconds=60)
segments = 0
access_token = None
if request.method == 'POST':
result_set = authenticate_user(username, password)
if result_set:
ss1 = select([nsettings]).\
where(nsettings.c.mattribute == 'my_jwt_expiry_time_min')
rss1 = g.conn.execute(ss1)
if rss1.rowcount > 0:
for r in rss1:
my_token_expiry_time = datetime.timedelta(seconds=
(int(r[nsettings.c.mvalue])* 60))
else:
my_token_expiry_time = datetime.timedelta(
seconds=(2 * 60 *60)) # 2 hours
#print result_set, 'result_set result_set'
session['email'] = result_set['email']
access_token = create_access_token(
identity=username, expires_delta=my_token_expiry_time)
user_dict = result_set
if user_dict:
session['email'] = user_dict['email']
session['id'] = result_set['id']
# users and related views
session['access_token'] = access_token
print access_token, 'aaaaaaaaaaa'
return jsonify({
'email': session['email'],
'user_id': result_set['id'],
'access_token': access_token,
'id': session['id'],
}), 200
else:
return jsonify({'message': "Invalid credentials, retry"}), 401
return "True"
The flask api call to upload:
#app.route('/rt/api/v1.0/issues/<int:issue_id>/documents', methods=['POST'])
#jwt_required
def rt_doc_upload(issue_id):
'''
Upload documents for a rt ticket.
'''
# Iterate through the list of files, we don't care about the
# attribute name. We consider only the first file and ignore the
# rest.
if 'id' in session:
uploader = "3"
minternal_only = True
bool_internal_update = False
msg_str = None
for attr, document in request.files.iteritems():
trans = g.conn.begin()
try:
orig_filename = document.filename
filename, upload_folder = check_or_insert_document(
orig_filename, uploader)
new_doc = add_doc(orig_filename, filename)
print orig_filename, 'origooooo'
ins = archival_docs.insert().values(new_doc)
rs = g.conn.execute(ins)
doc_id = rs.inserted_primary_key[0]
filename = (str(doc_id) + '_' + orig_filename)
stmt = archival_docs.update().values(stored_name=filename).\
where(archival_docs.c.id == doc_id)
g.conn.execute(stmt)
document.save(os.path.join(upload_folder, filename))
mattach_doc_id = genUrl(doc_id)
trans.commit()
return jsonify(
{'issue_doc_id': rs.inserted_primary_key[0]}), 201
except Exception, e:
print e
trans.rollback()
return jsonify({'message': "Did not find any file"}), 400
return jsonify({'message': "UNAUTHORIZED"}), 401
When used with runserver and on commenting the jwt_required decorator I am able to upload and download files
Using sqlalchemy core, python and flask. The api call to upload worked for more than a month, but suddenly stopped working now
When I request something to python by AJAX, everything runs OK in python, but, when the route return my informations for AJAX, simply he create another blank page with the text that I returned, and not did what I want in the page who needs to be.
Here the response image
image2
Here is the code:
#app.route('/', methods=['POST', 'GET'])
def bot():
texto = request.form['text']
print(texto)
conversation = ConversationV1(
username='a33eb2c9-d218-4e05-a8ff-a46b59c5c3b1',
password='VATP3XEHsrPL',
version='2017-05-26'
)
context = {}
workspace_id = '96cbce3b-2fd3-49b0-ad57-da62c33547ee'
user = texto
response = conversation.message(
workspace_id=workspace_id,
message_input={'text': user},
context=context
)
context = response['context']
#se há intenções e dialogo
if response['intents'] or response['entities']:
if response['intents']:
intent = (json.dumps(response['intents'][0]['intent'],indent = 2))
intent = intent[1:-1]
dialog = (json.dumps(response['output']['nodes_visited'][0],indent = 2))
dialog = dialog[1:-1]
#se há resesposta à intenção
if response['output']['text']:
resposta = json.dumps(response['output']['text'][0],sort_keys=True, indent=4)
resposta = resposta[1:-1]
resposta = resposta.encode('utf-8')
resp = (resposta.decode('unicode-escape'))
#se entrou no nó x,y,z
if dialog == "perfil_e_id":
ID = (json.dumps(response['entities'][0]['value'],indent = 2))
ID = ID[1:-1]
print (ID)
resp = perfill(ID)
elif dialog == "perfil":
return resp
ID = texto
print ("Ikrl : " + ID)
resp = perfil()
elif dialog == "heroi":
ID = (json.dumps(response['entities'][0]['value']))
ID = ID[1:-1]
resp = herostats(int(ID))
return resp
elif dialog == "counterheroi":
ID = (json.dumps(response['entities'][0]['value']))
ID = ID[1:-1]
resp = herostats(int(ID))
return resp
else:
resposta = json.dumps(response['output']['text'][0],sort_keys=True, indent=4)
resposta = resposta[1:-1]
resposta = resposta.encode('utf-8')
resp = (resposta.decode('unicode-escape'))
print (resp)
return resp
And my ajax code:
$(function(){
$(".mytext").on("keyup", function(e){
if (e.which == 13){
var text = $(this).val();
if (text !== ""){
insertChat("me", text);
document.getElementById("nome").innerHTML = text;
$(this).val('');
}
$.ajax({
url: '/',
data: $(text),
type: 'POST',
success: function(response){
console.log(response);
insertChat("you", response)
},
error: function(error){
console.log(error)
}
})
}
});
});
if you need test in your pc, I upload a .rar file
https://drive.google.com/open?id=0B9TVHd_5neJ1amdqZWVrbm9mX2c
You haven't cancelled the default submit action.
if (e.which == 13){
e.preventDefault();
...
I have the following class:
class Connection(object):
defaults = {
'application_key':None,
}
def __init__(self, application_key="None"):
self.application_key = application_key or Connection.defaults.get('application_key')
def make_request(self, params=None, method=None):
url = URL_FORMAT % {
'params': params,
}
headers = {
'Authorization': 'Token token='+ self.application_key,
'content-type': 'application/json',
}
if method == "get":
request = requests.get(url, headers=headers)
if request.status_code == requests.codes.ok:
return request.json()
else:
raise APIError("%s status received (not 200)" % request.status_code)
elif method == "post":
request = requests.post(url, headers=headers)
request.status_code == requests.codes.ok
if request.status_code == requests.codes.ok:
return request.json()
else:
raise APIError("%s status received (not 200)" % request.status_code)
def get_geofence(self):
try:
data = self.make_request('geofences', 'get')
return data
except APIError:
raise GeofenceNotFound("Geofence not found")
def get_geofence_id(self, geofence_id=None):
try:
data = self.make_request('geofences/'+self.geofence_id+'/', 'get')
return data
except APIError:
raise GeofenceNotFound("Geofence not found with id #%s" % self.geofence_id)
The problem line seems to be data = self.make_request('geofences/'+self.geofence_id+'/', 'get') returning AttributeError: 'Connection' object has no attribute 'geofence_id'
I'm pretty stumped here.
geofence_id is not a class attribute, it is a function parameter. Thus, you should just refer to is as geofence_id and not self.geofence_id.