I am trying to understand how to use AJAX with Python Sessions. I understand the basics of how sessions work. When I add AJAX to the mix, my mind is having a difficult time understanding the technical details. Part of me thinks AJAX and Python Sessoins are not possible. I know web frameworks exist that probably do all this magic but I want to learn how to do it myself before jumping into a framework.
I am trying to create a webpage with a login form using HTML, AJAX, Python, and Sessions. If the user is able to log in, a session should be created (I assume that's correct). Otherwise, an error message should be returned.
Here is the basic application layout:
login.html : HTML form with username & password input boxes and
submit button
ajax.js : contains AJAX function that communicates with server-side
script
check_user.py : checks if username & password are correct, creates
session or returns error
welcome.html : only accessible if username & password are correct
welcome_1.html : only accessible if username & password are correct
I prefer to keep the HTML, Javascript, and Python code in separate files as opposed to creating HTML with Python or using inline Javascript in HTML.
Here is the application logic:
user visits login.html
enters username & password
clicks submit button
submit button calls ajax function
ajax function sends username & password to check_user.py
check_user.py checks if username & password are correct
if not correct, return JSON formatted error message
else, correct
create session ID (SID)
place SID in cookie
return cookie to ajax function
redirect user to welcome.html
welcome.html
on page load, ajax function requests user's cookie
if no cookie, redirect to login.html
else, ajax function sends cookie to check_user.py
check_user.py opens cookie & verifies the SID
if not correct, redirect user to login.html
else, correct
redirect user to welcome.html
I think I am misunderstanding how ajax is supposed to handle the returned cookie information. It is also possible that I am misunderstanding other parts, too. Please clarify :-)
I think I will follow this document when writing my Python session code. Sound ok?
I am considering using jQuery for the AJAX stuff and other Javascript coding.
Thank you!
Remember that the AJAX request is the same as any other HTTP request to the server. The session is maintained on the server side, but as far as the server can tell, a request from the browser is a request from the browser. An AJAX request can get and set the cookie just like any other request can. The method you've outlined above should work fine. Alternately, you could check for the existence of the session on your front page, and write the cookie then.
Related
I want to log in via a Python script to a website and do some operations there. The process will be:
Login to the website.
Press a specific button to get forwarded to the new page.
Get specific data from the forwarded page and do operations like putting values in fields and press the save button.
My problem is, I can't get access to the website.
The error message in PyCharm(IDE):
<div class="content-container"><fieldset>
<h2>401 - Unauthorized: Access denied due to invalid credentials.</h2>
<h3>The credentials provided do not authorize you to view this directory or page.</h3>
</fieldset></div>
I linked an image with the wanted website login form:
Login window.
I am unsure if I need a http/s request or if it's done with JavaScript because I have no knowledge about both.
I can reach some kind of success with this:
Result on main page.
But it's just giving me like 10% of the information I need. Since it's also hard to visualize, I can't really tell if it is the site I expected.
I have used the requests module for this:
user_name = file[0]
password = file[1]
login_url = r"https://.../..."
response = requests.get(login_url,
auth=HTTPBasicAuth(user_name, password))
print(response.text)
What I have used:
PyCharm IDE
Python module Requests
The wanted website
I also tried to get it to work with the mechanize module. But I could not even login into the website at all.
Is there anyway in django that if user has two open tabs, both logged out, then logs in in one tab, tell that he has logged in in another tab? I mean something like github that tells you you have signed in, please refresh the page.
The problem is now If I login in one tab and then in the second tab, I get csrf token missing incorrect.
You get csrf token missing incorrect. because when user relogins, the server generates a new csrf token to the cookie. The cookie persists across the same domain. And when you're trying to do smth on the current page, the request fails because csrf in your <form> differs from the cookie which has been changed. That's why github refreshes the page (instead of conitnuing doing request from it). Thus server will return new csrf in html to your form.
Edit:
Consider the following choices :
If your cookie is not readonly: . Set setInterval where you check the session which user loaded the page and current session from cookie.
Render 4 first characters too page and save it to a variable. Set this variable when page loads. And with every request pass the variable with headers. Add a middleware which checks if first 4 characters in headers matcher first 4 characters from cookie, and if it doesn't tell the client to refresh the page.
If you want to automatically detect your case, you need to frequently spam the server and ask if the session has changed. From the client you can send the old session and the new one (if session is readonly you can send like few first characters from the server).
I don't know exactly how github does this. But one possibility is to use a visibilitychange event handler. This will trigger when you switch tabs. The event handler can check the cookies for the current site, and determine if someone logged in another tab.
https://developer.mozilla.org/en-US/docs/Web/Events/visibilitychange
Usually tabs share no state. But two tabs have the same origin (domain name), they share cookies. In django you typically render the csrf token to the html dom with the template tag {% csrf_token %}, which means that if the current tab's csrf token was invalidated (which happens when you sign in), you must refresh the page to get a fresh token.
One way to do attach such an event listener is this:
// check cookie for `logged_in` substring (this only works for insecure cookies. Not http-only)
const isLoggedIn = () => document.cookie.includes('logged_in')
// check cookie for changes when you open this tab
const signInSpy = () => {
document.visibilitystate === 'visible' &&
isLoggedIn() &&
alert('refresh, please')
}
// only attach event handler when not signed in.
document.onvisibilitychange = isLoggedIn() ? null : signInSpy
This example only works if logged_in is not a http-only cookie. For other options for communicating between tabs, see this question:
Communication between tabs or windows
This is my first application using Flask and Python.
I am using below URL format to send a POST request from Arduino to the flask application running on Pythonanywhere server instance.
Valid POST request: 3 URL parameters
http://voyagers.pythonanywhere.com/senddata?node=1234&lat=18.5580&lng=73.8075
I need to block the request from further processing by validating the URL in some form. I want this to secure my app from un-authenticated POST requests.
Say something like this:Anything more than 3 URL Parameters
http://voyagers.pythonanywhere.com/senddata?node=324&lat=18.5580&lng=73.8075&a=c&a=d
How can I achieve this in Flask ?
Also suggest , If there is any better way which could be used to secure application from un-authorised requests.
You can get flask to validate the parameters and throw an error automatically if you are willing to switch from URL parameters (i.e. anything after the '?' symbol in the URL) to path parameters (i.e. anything that is in the Path HTTP header, or the part of the URL after the first '/' and abefore the '?').
Your example could look like this:
#app.route('/post/<int:node_id>/<float:lat>/<float:lng>', methods=['POST'])
def process_post_request(node_id, lat, lng):
# do some work
return your_result
Then you could send request to URL that would look for example like this: http://example.com/post/1234/-11.45/21.34
You can find more about this here: http://flask.pocoo.org/docs/0.12/quickstart/#variable-rules
For securing access you can use some of the example snippets here: http://flask.pocoo.org/snippets/category/authentication/
I would recommend restricting access to HTTPS only and using the basic auth if you are just playing around. This is something you can do with a simple decorator as described here: http://flask.pocoo.org/snippets/8/
You will get a prompt in your browser asking you for username and password and browser will remember it for the duration of the session. Alternatively, you can set the username and password in base64 encoded form in the Authorization header: https://en.wikipedia.org/wiki/Basic_access_authentication
I am learning web-scraping with python-mechanize. At the moment, to enter a secure site, I have been entering data into forms manually then submitting. Like this:
br.open("www.example.org/login.hmtl")
br.select_form(nr=0)
br['uname'] = "USERNAME"
br['pword'] = "PASSWORD"
br.submit()
I assume that under the hood, this is being sent to the server as a 'GET' or 'POST' request and the information I type in is encoded in a url. Is there a way for me to find out what the format of this url is so that I can encode the information myself? I am using chrome, it would be great to be able to somehow identify the structure of a form's submit request.
you can enable logging in mechanize. for a tutorial see http://wwwsearch.sourceforge.net/mechanize/hints.html#logging
I have the following problem. I have my script login.py
and two pages, login.html and welcome.html.
When I log in login.html with email-id and password, then login.py would extract exact user information from mysql. Now I'd like start welcome.html page from login.cgi and passing user information through parameters and display it on welcome page.
Can anybody help me, to solve this problem how to write the python cgi ?
what i actually mean is: you have forward action in jsp to do this....
is there anything similar in python cgi...??
http does support redirect as part of the protocol. Those are the 3xx responses.
After a POST request, you will probably reply with HTTP 303 See other to redirect to the correct document after login. You may pass parameters as usual.
print "HTTP/1.1 303 See Other"
print "Location: http://example.org/other?user=xyz"
See Webpage redirect to the main page with CGI Python