Issue
In my Django app I have a lot of if request.user.is_authenticated
logic and once I change some code other than in templates (like forms, models, views, etc.) I get logged out from the development server which makes it quite annoying to always have to re-login in the frontend to test my prior code changes again.
Is there any way to stay logged in (a superuser) when in Debug = True
(or other) mode?
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv("DEBUG", "False") == "True"
# Add s.th. here to keep me logged in?
# settings.py
SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key())
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
...
]
Solution
The problem is:
SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key())
You are generating a new secret key every time the server is restarted. The authentication details are stored in django_sessions
table, and the session details are hashed with the SECRET_KEY. So, every time the SECRET_KEY value is changed, the current session details are invalidated and you need to freshly login again.
For the solution: Generate a random secret key manually once and store it as an environment variable in every environment (be it staging, production, or development).
Hope you find this useful.
Answered By - Rohit Rahman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.