Django logges out from admin panel

Viewed 25

I have a Django 4.1.1 app in production with Redis 7.0.4 cache backend, here is my settings.py:

import os
from pathlib import Path
from datetime import timedelta
from dotenv import dotenv_values
config = dotenv_values(".env")

BASE_DIR = Path(__file__).resolve().parent.parent

    
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'some-secret'

DEBUG = True

ALLOWED_HOSTS = ['production.com']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    # 'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'core',
    'staticpages',
    'rest',
    'user',
    'rest_framework',
    'rest_framework.authtoken',
    'django_celery_results',
    'django_extensions',
    "allauth",  # allauth
    "allauth.account",  # allauth
    "allauth.socialaccount",  # allauth
    "allauth.socialaccount.providers.google",  # allauth
]

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',
    # 'django.middleware.locale.LocaleMiddleware'
]

ROOT_URLCONF = 'app.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates', 'allauth')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'app.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': config['SQLDB'],
        'USER': config['SQLDBUSER'],
        'PASSWORD': config['SQKDBPASS'],
        'HOST': config['SQLDBHOST'],
        'PORT': '5432',
        # 'OPTIONS': {'sslmode': 'require'},
    }
}

   
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.redis.RedisCache',
        'LOCATION': config['REDISHOST'],
    }
}
    
LANGUAGE_CODE = 'fa'

TIME_ZONE = 'Asia/Tehran'

USE_I18N = True

USE_TZ = True

    
STATIC_URL = 'static/'
STATICFILES_DIRS = [BASE_DIR / "static"]

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

CELERY_RESULT_BACKEND = 'django-db'
CELERY_CACHE_BACKEND = 'default'

ACCOUNT_AUTHENTICATION_METHOD = ('username_email')
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True

####
#SOCIALACCOUNT_AUTO_SIGNUP = True
SOCIALACCOUNT_EMAIL_VERIFICATION = "none"
#SOCIALACCOUNT_EMAIL_REQUIRED = True
####
SOCIALACCOUNT_ADAPTER = 'core.views.mixed.MyAdapter'

SITE_ID = 5
LOGIN_REDIRECT_URL = '/custom/path'
#LOGIN_REDIRECT_URL = None


AUTHENTICATION_BACKENDS = [
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',
    # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
]

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': [
            'email',
            'profile'
        ],
        'AUTH_PARAMS': {
            'access_type': 'offline',
        }
    }
}


CSRF_TRUSTED_ORIGINS = ['https://production.com']
CSRF_COOKIE_HTTPONLY = False

SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
SESSION_COOKIE_AGE= 24*60*60*7

when I go to production.com/admin after about 4 minutes I logged out automatically from admin panel and redirect to admin login page. The confusing thing is that I checked Redis cache server contents using "redis-cli" and I saw that all cache keys were preserved, but after a page refresh the associated session_key was deleted from cache server!

I used Django allauth package for implementation of google login, but the strange thing is that login sessions with google login preserved normally and user don't log out.

0 Answers
Related