Flask Login Sessions Not Working - flask

I'm having an issue with Flask-Login where for some reason it seems to clear the data from my session. This issue only seem to happen to me when I run my application on AWS within a Docker container. There doesn't seem to be any issues when this is run locally within a Docker container. The container kick starts the application using supervisord to launch the nginx and gunicorn servers.
I'm using Flask-Login and SQLAlchemy to handle my user logins. I'm creating a custom token using the get_auth_token() method in my User model which stores the token with some session data in my database. I use the token_loader and user_loader callbacks to retrieve my User data from the database which works fine.
However, if I'm not actively using my application for a few minutes the session data seems to disappear when I change to a page that requires a login. My session cookie remains unchanged and my token_loader or user_loader callbacks never seem to be called. To work out what might be happening with the session I attached a #app.before_request handler to print the session contents:
[2015-09-29 14:47:21,348] DEBUG in __init__: <SecureCookieSession {u'csrf_token': '51b5b253c55ac954c1bc61dd2dca513e18c4d790', u'_fresh': True, u'user_id': 3, u'_id': 'd3adbd2ed3905986d515aeb04cd1ff7d'}>
[2015-09-29 14:47:21,382] DEBUG in __init__: <SecureCookieSession {u'_flashes': [('message', u'Please log in to access this page.')]}>
It appeared that all of the user information was there for me to be able to load my user but it has bailed out and re-directed to the login page with the Flask-Login flash error. This re-directs before it even touches my callbacks to load the user from the database.
Is this possibly just a set up issue with my server configs that is causing an issue with domains? I'm not really sure what I need to look at and try to debug this further.

This is a known bug in Flask-Login that was fixed around release 0.2.10 (by me). The bug reappeared in release 0.3.0 of Flask-Login, which as of today is the most current release. I submitted a new fix, plus a unit test to prevent this from ever happening again. The fix was merged a few days ago, but a 0.3.1 release has not been made yet.
Bug report: https://github.com/maxcountryman/flask-login/issues/231
My pull request with the fix: https://github.com/maxcountryman/flask-login/pull/237

Related

Spartacus integration with CDS, profile.consent.given cookie not being set after clearing site data

We're integrating SAP Commerce 2005 and Spartacus 2.0.3 with CDS (Context-Driven Services). We followed the instructions from https://sap.github.io/spartacus-docs/cds-integration/ and we got it work right.
Nevertheless, we've noticed one issue.
When we clear the site data (either from Chrome DevTool or via browser Settings), the cookie named profile.consent.given is not being set anew while refreshing the page - even though the PROFILE consent has consentState "GIVEN" in local storage in spartacus-local-data > anonymous-consents > consents.
Initially I thought that it's just not visible in DevTools, but when I've added the url parameter ?profileTagDebug=true, in the console there is a log saying:
"[Profile Tag] No cookie found with name profile.consent.given".
When I set this cookie manually with value true, everything starts to work just fine, all other needed cookies and local storage data responsible for tracking users behavior is being set properly.
Do you see any place where we could have done something wrong, which may have caused this cookie to work improperly? Which module or component of Spartacus library would be of any clue in resolving this issue?
Edit: the reason of this strange behavior was in profile tag created by our team in CDS. It contained:
"consentListener": "type":"cookie","cookieName":"profile.consent.given","cookieValue":"true"},
which made the cookie profile.consent.given necessary while it shouldn't be. Using profile tag without this part made all work just fine.
With Spartacus, this cookie doesn’t make sense anymore. It is created by the Commerce backend and works best in combination with an accelerator frontend. Cds-spartacus in combination with ProfileTag relies on the anonymous consents or the user consents (depending on the user being logged in or not) loaded by Spartacus. More information about anonymous consents can be found here: https://sap.github.io/spartacus-docs/anonymous-consent/.
Just a quick FYI about the CDS-Spartacus integration: the profile tag script is pulled from the configured URL by Spartacus, and the script is doing all the event and data "scraping". The cookie is also being placed in the browser by the script.
Your question and this comment lead me to think that the script is not handling this case.
I'm not even sure if it should handle it, so it might be a better idea to contact CDS team directly about this one.

django-allauth socialaccount not logging in?

I've recently switched server/database and am having trouble getting the google and facebook social apps to log in. I have the keys set up correctly and when hitting both facebook and google it successfully creates a django user and a social account, but it does not log the user in. Notably, it sends the user to LOGIN_REDIRECT_URL correctly.
When attempting to sign in with an existing user after it has already been created, it also does not log in, but also sends to LOGIN_REDIRECT_URL correctly.
I can't figure out why it is behaving this way in the new environment, and am struggling on finding where to look. My best guess is that somewhere the pre_social_login signal or the social_account_added signal? Any ideas?
EDIT:
Also worth noting, I switched from python 3.4 to python 2.7, but django remained 1.6.5
Turned out I was missing the allauth.account.auth_backends.AuthenticationBackend in the settings AUTHENTICATION_BACKENDS when i did the migrate.

Django authentication works on Chrome, but not on Firefox

I'm having a problem where Django's login is working okay on Chrome but not on Firefox: when trying to login to a restricted portion of the site on Firefox, it simply loops back again and again to the login page; furthermore, no error message appears on the log regarding that.
Interestingly, the error doesn't happen when the server is on the local machine.
Does someone have a general idea of what could be causing that strange behavior?
I'm using Django 1.6 on Python 2.7
this isn't much of an answer, but a linking to other similar problems. Because I don't have rep, all I can do is leave an answer.
A issue like this was encountered in 2012 but was never conclusively answered:
Django session doesn't work in Firefox
A similar question where the user could login via local server but not remote firefox was encoutered:
Unable log in to the django admin page with a valid username and password
The second was very well documented and had an accepted answer that was well liked.
Recommendations:
If you are not using https make sure you have this setting SESSION_COOKIE_SECURE = False.
If you are using a database backed, Check if the session is actually being created in the django_sessions table .
If you are using a cached backed, check that SESSION_ENGINE is django.contrib.sessions.backends.cache and that CACHE_BACKEND is properly configured.

Tricky issue with django sessions: sometimes session information is erased

I have a weird bug with django sessions in my app: some times (about 10 times for ~20000 per day) session information for user is erased. I traced it via log files: at page A there is information for user's session, after it he submits the form and at the next page his session is empty. I tried two types of storage: memcached+db and db only and this problem is for both of them. I tried to reproduce these scenarios, but all works as expected, as I said, it happens very rare. I also checked that this problem exists for different users, and for them is doesn't reproduce each time. I don't have any ideas how to catch the root cause and I don't know what else post here as a description. If someone has any ideas, please let me know. If it is important, I'm running my app with django 1.2 + FastCGI.
Thanks!
UPD: I checked and see that session key from uses is not changed during two sequential requests, at first request there is an actual session state, and at second session variables are relaced with empty.
As a way to debug this problem, I would subclass the standard Django session middleware (or whatever you're currently using):
django.contrib.sessions.middleware.SessionMiddleware
and wrap process_request and (probably more importantly) process_response in some extra logging. Then install your subclassed session middleware in the MIDDLEWARE_CLASSES, rather than the stock Django one.
You could also validate that session.save() has actually committed its changes by attempting to read it back. It could be that the problem lies in session-state serialisation, and it's failing on a particular key or value that you're attempting to store.
None of this will fix your problem, but it might help you to establish what's going on.
As #Steve Mayne mentioned, it would be good to do some logging on the sessions middleware and sessions model save method. That's something I'd start with.
In addition I'd like to say that this could be a database related issue, especially if you're using MySQL database backend for sessions. You can check the log for database locks and other concurrency issues. I had to deal with similar issues before and the solution is clear: optimization and additional performance.
If you have some specific application middleware, you can check for functionality that interferes with Django sessions. Such parallel operations can cause problems, if not implemented properly.
Another thing I would do is to upgrade to the latest stable release of Django and migrate to a mod_wsgi setup.

session issue with django+apache+mod_wsgi

I've written a django application, and put it on a CentOS server. It is definitely okay when I use django development web server.
Such as I start it by "python ./manage.py runserver", and access that server from browser on another computer. I can sign in one time, and access all the pages without issues.
However when I run it with apache+mod_wsgi, I just found I have to login with user and password time by time. I think maybe there is some problem with the session middleware, so, how can I find the root cause and fix it?
There are a couple of different options for this.
In order of likelyhood (imho):
The session backend uses the cache system to store the sessions and you're using the locmem cache backend
The session backend isn't storing the cookies (secure cookies enabled? cookie timeouts? incorrect date on the server?)
The session middleware might not be loaded (custom settings for production server?)
Storing the session in the cache is only a good solution if you use memcached as the cache backend. So if you're storing the sessions in cache, make sure you use memcache :)
Either way, check if SESSION_ENGINE is set to django.contrib.sessions.backends.db