Tornado authentication help - python

I just started using tornado and got it set up with nginx proxing tornado and php and everything is working corretly
What im trying to achieve is a notification system.
When a user does something such as send an email or update a field in the database if the other user is browsing the web he will get notified.
So using jquery ajax I will send the message and the name of the user to tornado.
I got that part working. ex:
$.ajax({url: "/send/notification", data: "data//Serialise from form , dataType: "text", type: "POST",
success: function(response) {
alert("Message From Tornado : "+response);
}, error: function(response) {
console.log("ERROR:", response)
alert("Failed");
}});
Then on Tornado get the name of the recipient
recipient = self.get_argument("recipient", None)
Now Using jquery ajax function to long poll tornado for a response.
But im completly lost on how to make tornado check if that notification is for him and if so send him data.
something like
if self.current_user == recipient:
self.write(some data);
Any help would be greatly appreciated

It's not quite that simple. You need to keep a list of waiting messages, and the users they are for. The example chat application is probably the best place to start, although it just delivers each message to everyone.
However, it shouldn't be too hard to modify. You could, for example, add a dict mapping users to waiting messages, and when the poll for new messages occurs, check if there are any messages for that user. Or you could just do a quick and dirty iteratation through all messages on every poll.

Related

What's the URL to implement a login functionality for Sleeper (fantasy football) INSIDE Reactjs app? after user is registered/logged into Reactjs app

I'm working on a multi-league fantasy football assistant, where a the user has there choice between a few platforms they can login to and import selected leagues from a list of all their avb leagues from that platform. Reactjs + Node.js frontend & Python + Django Rest backend (MySQL db)--working on just Sleeper functionality at the moment though.
I have tried a number of different ways, including trying to make a POST request to https://api.sleeper.app/v1/auth/login and I am having no luck! I keep getting a 404 status. I even tried a GET request to see what the URL returned and still nothing. If there is no exact URL, how should I go about getting user's logged in to Sleeper and get their initial info (mainly username) in order to go about my other requests?
Tried making POST requests in Postman with the https://api.sleeper.app/v1/auth/login URL using the below as my 'body' and was getting 404 status codes back.
{
"username": "my_usernam_here",
"password": "my_password_here"
}

Using requests to automate "logging" into a server

I am trying to create a bot that joins the server by putting in a name and pressing a button that connects the request into the server., but in requests. The system hasn't been working as supposed to. It is supposed to POST the information in the correct places with the json.
payload = {
'idOftheInputBar': 'Username'
}
After that, I tried posting, getting, and patching but the response ended up with 404 or 200 but didn't send. How can make a request join the public server after putting in a username?

Flask-wtf: csrf_token is removed from session before I can POST my form

I'm using Flask with Flask-Security (specifically Flask-WTF regarding my csrf issue) to "ease" the process of register/loggin users (not easy so far). I'm using BackboneJS on the front-end, therefore I kind of hacked the original way to use Flask-WTF. Indeed, I make an AJAX GET request on /register to get the register page (generated by Flask-Security) and I put the resulting HTML in a modal.
render: function () {
var self = this;
$.ajax({
type: 'GET',
url: Config.constants.serverGateway + "/register"
}).done(function(result){
console.log("get register done", result);
var html = self.template({ config: Config, form: result });
self.$el.html(html);
}).fail(function(error){
console.log("Could not get register token", error);
var html = this.errorTemplate({ config: Config });
self.$el.html(html);
});
return this;
}
This way I have the generated csrf, and when I POST the registration data, I send the right csrf along the user data (email and password).
submit: function () {
console.log("submit");
var self = this;
var formData = this.$el.find('form').serialize();
$.ajax({
type: 'POST',
url: Config.constants.serverGateway + "/register",
data: formData,
dataType: 'json'
}).done(function(result){
self.trigger('close');
}).fail(function(error){
console.log("Could not submit register data", error);
});
}
On the server-side, I can debug my python code to see that the csrf_token which has been generated when I requested the register page has disappeared from the session object, therefore leading to the generation of a new one, which of course didn't match the one I send with my form. The session is still the same though, as the _id is the same during the GET and the POST.
You can see the code in flask_wtf/csrf.py::generate_csrf(), which is called when creating the form object in the ::register function from flask_security/views.py
if 'csrf_token' not in session:
session['csrf_token'] = hashlib.sha1(os.urandom(64)).hexdigest()
It results in a CSRF TOKEN MISSING error.
An additionnal information, is that my front-end and back-end are delivered by the same server, as they have a different port number.
Last, when I use an href on front-end and display the page returned by the server on the 'GET' request, submitting the form works well. I just liked to display this registration form in a modal.
Thanks for your help
Okay, I finally figured out the solution to my problem. I feel like a noob (which I am).
The problem lied in the session credentials which were not sent to the server with the requests, so that the server coudldn't access the session cookie.
I found the solution in the following tutorial: http://backbonetutorials.com/cross-domain-sessions/
To send it, i added the following lines in my Backbone router initialize function:
// Use withCredentials to send the server cookies
// The server must allow this through response headers
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
options.xhrFields = {
withCredentials: true
};
});
This makes all AJAX requests include the withCredentials = true. On the server-side, I had to set Access-Control-Allow-Credentials:true. Since I'm using flask-cors, it is done with [supports_credentials=True][2] when creating the CORS object.
(I'm answering here since I can't comment)
#junnytony Yes I have the token in my modal and I send it in my POSt request. When I debug the Flask application, I can see the toekn I sent with my POST request, the problem is that it should be compared to the one in the session to be validated, but the one in the session has disappearred, so the flask-wtf lib generates a new one, which results in a failure when comparing with the one I sent.

Problem with POST request from APE server module

I use Ajax Push Engine as push engine and Django for main site. I wrote the server
module which must send the request to my Django-based application when
new user join the channel by using Http module. My Django-based project runs on the local
machine on local.jjjbbb.org.
Ape.addEvent("join", function(user, channel) {
var request = new Http('http://local.jjjbbb.org/test-
this/'); // this is a my test url
request.set('method', 'POST');
request.writeData('test-message', 'Hello APE!');
request.getContent( function(result) {
Ape.log(result); // this code never work
});
});
But this code doesn't work, request doesn't receive. When I change url
to anything else (like www.google.com or localhost for example) all
works correctly and I have a result. But when I try to send request to
my application request doesn't work. This problem is only when I try
to send request from server side, when I use jQuery for sending from
client side all works correctly.
Why I cannot send POST request from server side to my domain?
Sorry, I already found my problem. APE works fine, it was a little trouble with CSRF protection in Django.

Problem with json response in Python REST server I'm writing

For my own education I'm creating a simple daemon that will function as a REST server, listening on socket 9000. For my first test I'm trying to do a REST call of simply doing a GET on http://localhost:9000/getsettings.json.
The simple server I hacked up gets the request OK, but I think there's a problem with the response it's sending. I'm trying to send the response as JSON. The code for the server socket is below. Below that is the jQuery code I'm using to make the JSON request. The print statement in the Python server does print a valid set of settings in JSON format. Neither alert in the Javascript is being called when the page loads. Any ideas?
Python:
def socketThread(self):
while 1:
sock, address = self.serverSocket.accept()
fs = sock.makefile()
line = fs.readline();
if line.startswith('GET /settings.json'):
sock.sendall("HTTP/1.0 200 OK\r\n")
sock.sendall("Content-Type: application/json\r\n")
settings = json.dumps(self.currentSettings) #, indent=4
sock.sendall("Content-Length: " + str(len(settings)) + '\r\n\r\n')
sock.sendall(settings)
print settings
sock.close()
Javascript:
$(document).ready(function() {
$.ajax({
url: 'http://localhost:8080/settings.json',
cache: false,
success: function(json){
alert('json success ' + json);
},
error: function(xhr, textStatus, errorThrown) {
alert(xhr.statusText);
}
});
});
You need to return a 200 OK HTTP response and an empty line before sending your content.
You'll probably need some HTTP headers, too (Content-type would be an obvious one).
I would, however, recommend using one of Python's many HTTP libraries instead of implementing the protocol yourself.
Check that the server is actually being hit (eg, put an import pdb; pdb.set_trace() in your code. I found that jQuery executes the success callback with empty body when the server is not running (or listening on a different port...)
OK, the problem was on the jQuery side, my request was being thwarted by the cross domain origin protection issue - my request was going to localhost on a different port so jQuery wasn't pulling down the data. Now I need to figure out how to make that work. Thanks for the help guys.

Categories

Resources