Can I create more session objects in Flask? - python

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.

Related

Read Flask Session Cookie

I currently have the following:
from flask import Flask, session,request
#app.route('/venue/login', methods=['GET', 'POST'])
def venue_login():
token = generate_token()
session['venue_id'] = token
return json.dumps(...)
When I look at the response in Chrome, I can see that Set-Cookie:session=... has been set.
I have 2 questions:
1) How do I read this cookie on the `server?
I have tried:
venue_id = request.cookies.get('venue_id')
but this doesn't seem to be picking it up.
2) With my code above, all my cookies will be set with the same name. After reading the cookie value, I would like to delete the corresponding entry in session. How should I go about doing this? Also if two requests come in one after the other, will the line:
session['venue_id'] = token
override the first entry with the second? Or does every request start a new session?
I am kind of confused with how this all should work. Any help would be greatly appreciated.
Well. Cookies and sessions are a bit different.
If you want to use cookies and make venue_id = request.cookies.get('venue_id') work - You need to use set_cookie:
set_cookie('venue_id', token)
In cookies case - you can solve general problems that cookies can solve (have a long lasting cookie for example)
If you want to use session (which is intended for session uniqueness and auth) you need to just use session and put the "username" or the unique ID of the venue in your case.
Which to use - It really depends what you are trying to achieve
Have a look at:
http://flask.pocoo.org/docs/0.10/quickstart/#cookies
http://flask.pocoo.org/docs/0.10/quickstart/#sessions

Python caching for multiple users

I'm creating a python wrapper for Vimeo API and this is my first time creating a python distribution. I'm having questions with python caching.
I referred this existing python-vimeo wrapper for caching the request token. That guy implemented like this
"""By default, this client will cache API requests for 120 seconds. To
override this setting, pass in a different cache_timeout parameter (in
seconds), or to disable caching, set cache_timeout to 0."""
I'm wondering whether it will create a problem or not. If there is more than one user using that feature for connecting vimeo exactly at the same time, and storing the information like this in the server
return self._cache.setdefault(key, processor(headers, content))
doesn't it create problem(informations will be overwritten in the cache)?
If it creates a problem, could you tell me the best solution? I think It would be storing in the filename with the name of authenticated username. Am I right?
Thanks!
I'm not sure I understand the issue, but you could create a prefixed key where the prefix of the key is the username. So a naive but possibly good approach is to save to the
username+"_"+key
key instead
There most likely wouldn't be any key collisions.

How do I create a session variable in 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

Google App Engine, Python, deleting a cookie or changing its value?

I've been searching on this but can't seem to figure out how I can delete a specific cookie using Google Apps Engine, Python version. I am setting the cookie like below and I need to update its value, I figure I may not be able to update and just need to delete and re-create but can't seem to find the way to do that, I am creating it as below:
str = 'if_loggedin_username='+ self.username
self.from_obj.response.headers.add_header(
'Set-Cookie', str)
Thanks for any advice.
There is no way for the server to delete an HTTP cookie. To update the value, just send a new cookie with the same name and it will be updated; to "delete" the cookie, set an expiration time in the past.
Just to add more, send a new cookie with same name with value None (NoneType)
self.response.headers.add_header("Set-Cookie", None)
Hope it helps

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