How do I create a session variable in Python? - python

I use Python 3 as a serverside scripting language, and I want a way to keep users logged into my site. I don't use any framework, since I prefer to hand code pages, so how do I create session variables like in PHP in Python 3?

The logic of a session is storing a unique session id inside the user cookie ( uuid package will do a perfect job for that ). And you store the sessions data inside a file, database or other semi-permanent datastore.
The idea is matching the sessionid that you receive from your user cookie, to some data stored somewhere on your server.
I assume that you know how to add the right header to set a cookie via the response header.
Otherwise there is more information here : http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Responses

Related

How can i make MongoDB safe from other users?

I've heard that MongoDB is very good Database, especially for placing large data inside, However i'm not sure how safe can it really be.
I'm not experienced at MongoDB, but before i choose, i want to know how safe it can be for important data.
So for example, if i specified uri, i would type this:
uri = "mongodb://test1:test1#ds051990.mongolab.com:51990/base1"
I'm trying to make a P2P text chat, It can be accessed on user's PC with root permissions, Whenever user registers, User's Latest IP, Username and will be added to database, as code was shown below.
But the "Hacker" would easily access it by simply getting into code, and viewing all the information, then he would read/write all the data inside.
What would be the best solution to prevent this issue? I think high-level Databases like MongoDB would have some-kind of protection against other users accessing it.
How can make sure only necessary users can access database and other users can't enter it by viewing uri variable?
If not is there ANY other way i can do it? So user can't access Database at all, But i would read and write files from database.
You have no easy way of hiding the credentials. Instead, create a user with the minimal required permissions in the database, and use these credentials in your distributed code.
If you are worried about the users being able to see plain-text IP addresses, you should hash and salt them before inserting them to the database.

Can I create more session objects in Flask?

Basically what I want to do is to save some user-specific data, which I do not intend the user to be able to read.
This data should be stored for a week or so, but I can't use the session object, because I don't want to set session.permanent = True (I already use it to manage logins).
So basically I need a signed cookie, like session. Can I create an other instance of the session object somehow, or is there an easy way of making cookies signed?
Cookies contents are up to you, it's more or less a key value store in your users' browsers with an expiration date.
Regarding the content, for your use case you can use any kind of symmetric encryption like Fernet for instance (available in the cryptography package, cf https://cryptography.io/en/latest/).
As far as I know, itsdangerous (from Flask author, cf http://pythonhosted.org/itsdangerous/) enables you to sign the content of a cookie, but it doesn't "encrypt" it (the user will still be able to see the content, but not modify it). itsdangerous is a Flask dependency btw.

How I can get user input from browser using python

I am in the middle of my personal website development and I am using python to create a "Comment section" which my visitors could leave comments at there in public (which means, everybody can see it, so don't worry about the user name registration things). I already set up the sql database to store those data but only thing I haven't figured out yet was how to get the user input (their comments) from the browser. So, is there any modules in python could do that? (Like, the "Charfield" things in django, but unfortunately I don't use django)
For that you would need a web framework like Bottle or Flask. Bottle is a simple WSGI based web framework for Python.
Using either of these you may write simple REST based APIs, one for set and other for get. The "set" one could accept data from your client side and store it on your database where as your "get" api should return the data by reading it from your DB.
Hope it helps.

How to get access to the URL segments after a # in Python Flask?

I'm trying to support OAuth2 login through Python Flask, so I want to handle a URL that looks like this:
http://myserver/loggedIn#accessToken=thisIsReallyImportant
but when I handle the callback it just seems to drop all the characters after the # in the URL, which contains the important Oauth access token. How do I get this info? It's not included in request.url
ETA: I can retrieve it in client-side javascript using window.location in Javascript, but then I'd have to pass it back to the server, which feels a little hokey but maybe Oauth2 is meant to be done that way?
From the RFC:
Fragment identifiers have a special role in information retrieval
systems as the primary form of client-side indirect referencing
[...]
the fragment identifier is not used in the scheme-specific
processing of a URI; instead, the fragment identifier is separated
from the rest of the URI prior to a dereference
As such, flask drops everything after the '#'. If you want to forward these to the server, you'll have to extract them on the client and pass them to the server via a query parameter or part of the URL path.
You are using the incorrect OAuth 2 grant type (implicit grant) for what you want to do. Implicit grant supplies the token in the fragment as you observed to be used by a javascript client. There is another type of grant, authorization code, which is similar but supplies it in the URI query which you can access from Flask.
You can tell the two apart from the the redirect URI you create for authorization, if it has response_code=code you are on the right track. You currently use response_code=token.
If you are using Facebook look at https://developers.facebook.com/docs/facebook-login/login-flow-for-web-no-jssdk/
For Google look at https://developers.google.com/accounts/docs/OAuth2WebServer
You might also be interested in https://flask-oauthlib.readthedocs.org/en/latest/ which can help you with OAuth.

Generating unique and opaque user IDs in Google App Engine

I'm working on an application that lets registered users create or upload content, and allows anonymous users to view that content and browse registered users' pages to find that content - this is very similar to how a site like Flickr, for example, allows people to browse its users' pages.
To do this, I need a way to identify the user in the anonymous HTTP GET request. A user should be able to type http://myapplication.com/browse/<userid>/<contentid> and get to the right page - should be unique, but mustn't be something like the user's email address, for privacy reasons.
Through Google App Engine, I can get the email address associated with the user, but like I said, I don't want to use that. I can have users of my application pick a unique user name when they register, but I would like to make that optional if at all possible, so that the registration process is as short as possible.
Another option is to generate some random cookie (a GUID?) during the registration process, and use that, I don't see an obvious way of guaranteeing uniqueness of such a cookie without a trip to the database.
Is there a way, given an App Engine user object, of getting a unique identifier for that object that can be used in this way?
I'm looking for a Python solution - I forgot that GAE also supports Java now. Still, I expect the techniques to be similar, regardless of the language.
Your timing is impeccable: Just yesterday, a new release of the SDK came out, with support for unique, permanent user IDs. They meet all the criteria you specified.
I think you should distinguish between two types of users:
1) users that have logged in via Google Accounts or that have already registered on your site with a non-google e-mail address
2) users that opened your site for the first time and are not logged in in any way
For the second case, I can see no other way than to generate some random string (e.g. via uuid.uuid4() or from this user's session cookie key), as an anonymous user does not carry any unique information with himself.
For users that are logged in, however, you already have a unique identifier -- their e-mail address. I agree with your privacy concerns -- you shouldn't use it as an identifier. Instead, how about generating a string that seems random, but is in fact generated from the e-mail address? Hashing functions are perfect for this purpose. Example:
>>> import hashlib
>>> email = 'user#host.com'
>>> salt = 'SomeLongStringThatWillBeAppendedToEachEmail'
>>> key = hashlib.sha1('%s$%s' % (email, salt)).hexdigest()
>>> print key
f6cd3459f9a39c97635c652884b3e328f05be0f7
As hashlib.sha1 is not a random function, but for given data returns always the same result, but it is proven to be practically irreversible, you can safely present the hashed key on the website without compromising user's e-mail address. Also, you can safely assume that no two hashes of distinct e-mails will be the same (they can be, but probability of it happening is very, very small). For more information on hashing functions, consult the Wikipedia entry.
Do you mean session cookies?
Try http://code.google.com/p/gaeutilities/
What DzinX said. The only way to create an opaque key that can be authenticated without a database roundtrip is using encryption or a cryptographic hash.
Give the user a random number and hash it or encrypt it with a private key. You still run the (tiny) risk of collisions, but you can avoid this by touching the database on key creation, changing the random number in case of a collision. Make sure the random number is cryptographic, and add a long server-side random number to prevent chosen plaintext attacks.
You'll end up with a token like the Google Docs key, basically a signature proving the user is authenticated, which can be verified without touching the database.
However, given the pricing of GAE and the speed of bigtable, you're probably better off using a session ID if you really can't use Google's own authentication.

Categories