Authentication credentials were not provided Django on All calls - django

I am quite new to django and i am trying to use Djoser for Authentication but i am getting "Authentication credentials were not provided" on every call. Following is my settings file.
"""
Django settings for django_dir project.
Generated by 'django-admin startproject' using Django 1.11.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
import environ
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ROOT_DIR = environ.Path(__file__) - 2
APPS_DIR = ROOT_DIR.path('my_apps')
MEDIA_ROOT = str(APPS_DIR('media'))
# https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/'
# APPS_DIR = os.path.join(BASE_DIR, 'my_apps'),
env = environ.Env()
# STATIC FILE CONFIGURATION
# ----------------------------------------------
STATIC_ROOT = str(ROOT_DIR('staticfiles'))
# STATIC_URL = '/static/'
STATICFILES_DIRS = (
str(APPS_DIR.path('static')),
# str(ROOT_DIR.path('frontend')),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
TEMPLATES_DIR = os.path.join(BASE_DIR, 'my_apps/templates')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'm!nh54$kig!!=in(fqny#grtd!e(_$jjrph-95g0_52xsdw*&c'
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
# django apps
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites', # new
'allauth', # new
'allauth.account', # new
'allauth.socialaccount',
'rest_auth',
'rest_auth.registration',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
# local apps
'my_apps.users.apps.UsersConfig',
]
# CORS conf
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = (
'http://localhost:4200',
'http://127.0.0.1:4200'
)
# djangorestframework CONFIGURATION
# ------------------------------------------------------------------------------
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 10,
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DATETIME_FORMAT': "%Y-%m-%d %H:%M:%S",
}
# myproject/settings.py
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
SITE_ID = 1
# LOGIN_REDIRECT_URL = '/auth/login/'#'/auth-token/token/create/'
AUTH_USER_MODEL = 'users.User'
SESSION_COOKIE_AGE = 7200
REST_AUTH_SERIALIZERS = {
}
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER': 'my_apps.users.serializers.RegisterSerializer',
}
# LOGIN_REDIRECT_URL = 'users:redirect'
LOGIN_URL = 'account_login'
# djoser settings
DJOSER = {
'PASSWORD_RESET_CONFIRM_URL': '#/password/reset/confirm/{uid}/{token}',
'USERNAME_RESET_CONFIRM_URL': '#/username/reset/confirm/{uid}/{token}',
'ACTIVATION_URL': '#/activate/{uid}/{token}',
'SEND_ACTIVATION_EMAIL': True,
'SERIALIZERS': {
'user_create': 'my_apps.users.serializers.RegisterSerializer',
'user': 'my_apps.users.serializers.UserSerializer',
'current_user': 'my_apps.users.serializers.UserSerializer'
},
}
# Important default settings
ACCOUNT_EMAIL_VERIFICATION = 'none'
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_CONFIRM_EMAIL_ON_GET = True
ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = None
# EMAIL CONFIGURATION
# --------------------
# EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# Production
DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',
default='changethis <info#changethis.org>')
SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)
ACCOUNT_EMAIL_SUBJECT_PREFIX = ''
'''
SERVER_EMAIL = 'mazharabbasazhar72#gmail.com'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'mazharabbasazhar72#gmail.com' #'mazharabbasazhar72#gmail.com'# os.environ['SENDGRID_USER_NAME']
EMAIL_HOST_PASSWORD = 'change' #os.environ['SENDGRID_PASSWORD']
EMAIL_PORT = 587
EMAIL_USE_TLS = True
'''
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'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',
]
ROOT_URLCONF = 'covid.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'my_apps/templates')],
'OPTIONS': {
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
AUTH_TEMPLATE_CONSTANTS = {
'project_name': 'Gateway Platform',
'support_email': 'support#gatewayplatform.com',
}
WSGI_APPLICATION = 'covid.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {}
# DEPLOYMENT_MODE = env('DEPLOYMENT_MODE')
DEPLOYMENT_MODE = 'local'
if DEPLOYMENT_MODE == 'local':
DEBUG = True
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase',
}
}
elif DEPLOYMENT_MODE == 'staging':
DEBUG = False
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'

That's because you aren't sending the token in your request (Authorization: Bearer+{{token}})
If you're trying to log in but you see that message it's because you put
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
In REST_FRAMEWORK so by default, all your endpoints are gonna check if the user is authenticated, you need to allow any in the login. You can see more information here. Link

Related

Django logges out from admin panel

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.

403 Forbidden Error in Django Iframe on Safari Browser

I have a Django Iframe that is working fine on Chrome and Mozilla but in Safari I'm getting the above mentioned error. I think the cookies are not detected because when I checked it was empty and no CSRF tokens were found. I am attaching the screenshots.
Error Displayed in browsers console log Browser Cookies is empty. This is my settings.py file:
"""
Django settings for shopify_django_app project.
Generated by 'django-admin startproject' using Django 3.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
from shopify_app import *
from decouple import config
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Make this unique and store it as an environment variable.
# Do not share it with anyone or commit it to version control.
SECRET_KEY = config('DJANGO_SECRET')
DEBUG = int(config('DEBUG'))
# SHOPIFY SETTINGS
SHOPIFY_API_KEY = config('SHOPIFY_API_KEY')
SHOPIFY_API_SECRET = config('SHOPIFY_API_SECRET')
SHOPIFY_APP_NAME = config('SHOPIFY_APP_NAME')
SHOPIFY_API_VERSION = 'unstable'
SHOPIFY_TEST = config('SHOPIFY_TEST') # For the purpose of Shopify Payments
INTERNAL_IPS = ('127.0.0.1',)
ALLOWED_HOSTS = config('DJANGO_ALLOWED_HOSTS').split(" ")
CSP_FRAME_ANCESTORS = ("'self'", 'https://*.myshopify.com')
# default source as self
CSP_DEFAULT_SRC = ("'self'", "'unsafe-inline'", "'unsafe-eval'", "https://fonts.gstatic.com")
# style from our domain and bootstrapcdn
CSP_STYLE_SRC = ("'self'", "'unsafe-inline'", "https://fonts.googleapis.com")
# scripts from our domain and other domains
CSP_SCRIPT_SRC = ("'self'", "'unsafe-inline'", "'unsafe-eval'")
# images from our domain and other domains
CSP_IMG_SRC = ("'self'",
"https://*.s3.amazonaws.com", "data:", "https://cdn.shopify.com")
SESSION_COOKIE_SAMESITE = None
SESSION_COOKIE_SECURE = True
XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'PUT']
CSRF_COOKIE_SAMESITE = None
CSRF_COOKIE_SECURE = True
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
CSRF_TRUSTED_ORIGINS = [config('CSRF_TRUSTED_ORIGINS')]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Local
'shopify_app.apps.ShopifyAppConfig',
'home.apps.HomeConfig',
'notification',
'api',
'payment',
'debug_toolbar',
# 3rd party
'django_extensions',
'rest_framework',
'rest_framework.authtoken',
'django_celery_beat',
'storages',
# 'iframetoolbox',
]
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',
'csp.middleware.CSPMiddleware',
'shopify_app.middleware.LoginProtection',
'debug_toolbar.middleware.DebugToolbarMiddleware',
# 'iframetoolbox.middleware.IFrameFixMiddleware',
# 'shopify_app.iframe_middleware.SafariIFrameFixMiddleware'
]
ROOT_URLCONF = 'shopify_django_app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
"APP_DIRS": True,
'DIRS': [],
'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',
'shopify_app.context_processors.current_shop',
],
},
},
]
WSGI_APPLICATION = 'shopify_django_app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
# }
DATABASES = {
'default': {
'ENGINE': config('SQL_ENGINE'),
'NAME': config('SQL_DATABASE'),
'USER': config('SQL_USER'),
"PASSWORD": config('SQL_PASSWORD'),
"HOST": config('SQL_HOST'),
"PORT": config('SQL_PORT'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
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',
},
]
DATA_UPLOAD_MAX_MEMORY_SIZE = None
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
# AWS Settings
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
DEFAULT_FILE_STORAGE = config('DEFAULT_FILE_STORAGE')
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
if DEBUG:
AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'
AWS_QUERYSTRING_AUTH = False
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
else:
CLOUDFRONT_DOMAIN = config('AWS_CLOUDFRONT_DOMAIN')
CLOUDFRONT_DOMAIN_ID = config('AWS_CLOUDFRONT_ID')
AWS_S3_CUSTOM_DOMAIN = CLOUDFRONT_DOMAIN
AWS_DEFAULT_ACL = None
AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}
MEDIAFILES_LOCATION = 'media'
MEDIA_URL = f'{AWS_S3_CUSTOM_DOMAIN}/{MEDIAFILES_LOCATION}/'
STATICFILES_LOCATION = 'static'
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
# Redis Settings
REDIS_HOST = config('REDIS_HOST')
REDIS_PORT = config('REDIS_PORT')
# SNS Settings
SNS_ACCESS_KEY_ID = config('SNS_ACCESS_KEY_ID')
SNS_SECRET_ACCESS_KEY = config('SNS_SECRET_ACCESS_KEY')
SNS_REGION_NAME = config('SNS_REGION_NAME')
ANDROID_PLATFORM_APP_ARN = config('ANDROID_PLATFORM_APP_ARN')
IOS_PLATFORM_APP_ARN = config('IOS_PLATFORM_APP_ARN')
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
AUTH_USER_MODEL = 'shopify_app.User'
# CELERY SETTINGS
CELERY_BROKER_URL = config('CELERY_BROKER_URL')
CELERY_RESULT_BACKEND = config('CELERY_RESULT_BACKEND')
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Kolkata'
# CELERY BEAT SETTINGS
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# EMAIL SETTINGS
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = config('EMAIL_HOST')
EMAIL_USE_TLS = True
EMAIL_PORT = config('EMAIL_PORT')
EMAIL_HOST_USER = config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')
Need help. I am stuck with this issue for days.

Unable to retrieve static files into a django project from S3 bucket, but able to upload. Any suggestions?

Following is the settings.py file.
I've tried varying combinations of enabling and disabling STATIC_ROOT, status quo remains disabled.
Have added CORS and Bucket policy as per templates available on AWS.
Alas ! Still no CSS rendered.
Django settings for baatcheet project.
Generated by 'django-admin startproject' using Django 4.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
import os
from pathlib import Path
import sec
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
with open(os.path.join(BASE_DIR, 'secret_key.txt')) as f:
SECRET_KEY=f.read().strip()
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['https://test-astratechztestapp.pagekite.me', 'localhost', '127.0.0.1', '*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'base.apps.BaseConfig',
'rest_framework',
'corsheaders',
]
AUTH_USER_MODEL = 'base.User'
MIDDLEWARE = [
'django.middleware.csrf.CsrfViewMiddleware',
'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',
'corsheaders.middleware.CorsMiddleware',
]
ROOT_URLCONF = 'baatcheet.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR / 'templates'
],
'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 = 'baatcheet.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
MEDIA_URL = '/images/'
STATICFILES_DIRS = [
BASE_DIR / 'static',
'static/'
]
MEDIA_ROOT = BASE_DIR / 'static/images'
# #HTTPS settings
# SESSION_COOKIE_SECURE = True
# CSRF_COOKIE_SECURE = True
# SECURE_SSL_REDIRECT = True
#STATIC_ROOT = BASE_DIR / 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CORS_ALLOW_ALL_ORIGINS = True
CSRF_TRUSTED_ORIGINS = ['https://test-astratechztestapp.pagekite.me']
AWS_ACCESS_KEY_ID = sec.AWS_KEY
AWS_SECRET_ACCESS_KEY = sec.AWS_ACC_KEY
AWS_STORAGE_BUCKET_NAME = sec.BUCKET_NAME
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
#STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage'

Facing Issue With Django Machina Templates

I am Working on Rating Professor Website Using Django Framework.So That's Why I am Using Machina Forum But Facing Templates Issue In Settings .Loaders Are Not Working 'APP_DIRS': True, But When I Change 'APP_DIRS': False ,And Add MACHINA_MAIN_TEMPLATE_DIR To Templates Directory Machina Website Forum Works Fine But My Actual Website Goes Off Because of No Templates Exits Error.
Question is That Can i Use Both Machina And My Template Directory at Same time And how ?
If I add Machina Templates to Pycharm Project Templates and Make them as Templates then it's Work Or not ?
There is Only Issue With Machina Templates Everything is Working Excellent . I Just Wanted Both Templates to Work On My Website .
Setting.py
import os
from machina import MACHINA_MAIN_TEMPLATE_DIR
from machina import MACHINA_MAIN_STATIC_DIR
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'SECRET_KEY'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'users.apps.UsersConfig',
'crispy_forms',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'djangoproject.apps.DjangoprojectConfig',
'axes',
'widget_tweaks',
'pinax.comments',
'sslserver',
'simple_history',
'admin_honeypot',
'captcha',
# Machina dependencies:
'mptt',
'haystack',
# Machina apps:
'machina',
'machina.apps.forum',
'machina.apps.forum_conversation',
'machina.apps.forum_conversation.forum_attachments',
'machina.apps.forum_conversation.forum_polls',
'machina.apps.forum_feeds',
'machina.apps.forum_moderation',
'machina.apps.forum_search',
'machina.apps.forum_tracking',
'machina.apps.forum_member',
'machina.apps.forum_permission',
]
AUTHENTICATION_BACKENDS = [
# AxesBackend should be the first backend in the AUTHENTICATION_BACKENDS list.
'axes.backends.AxesBackend',
# Django ModelBackend is the default authentication backend.
'django.contrib.auth.backends.ModelBackend',
]
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',
'axes.middleware.AxesMiddleware',
'simple_history.middleware.HistoryRequestMiddleware',
'machina.apps.forum_permission.middleware.ForumPermissionMiddleware',
]
SILENCED_SYSTEM_CHECKS = ['axes.W003']
ROOT_URLCONF = 'review.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'djangoproject/../templates')],
'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',
'machina.core.context_processors.metadata',
],
},
},
]
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
'machina_attachments': {
'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
'LOCATION': '/tmp',
}
}
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
},
}
WSGI_APPLICATION = 'review.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
MACHINA_MAIN_STATIC_DIR,
]
STATICFILES_DIRS = (
# ...
MACHINA_MAIN_STATIC_DIR,
)
MACHINA_DEFAULT_AUTHENTICATED_USER_FORUM_PERMISSIONS = [
'can_see_forum',
'can_read_forum',
'can_start_new_topics',
'can_reply_to_topics',
'can_edit_own_posts',
'can_post_without_approval',
'can_create_polls',
'can_vote_in_polls',
'can_download_file',
]
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SETTINGS_PATH = os.path.realpath(os.path.dirname(__file__))
TEMPLATE_DIRS = (
os.path.join(SETTINGS_PATH, r'C:\Users\Windows 10\PycharmProjects\review\templates\djangoproject'),
)
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
AXES_ENABLED = False
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
CRISPY_TEMPLATE_PACK = 'bootstrap4'
LOGIN_REDIRECT_URL='blog-home'
LOGIN_URL='login'
MAX_UPLOAD_SIZE = "5242880"
if DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = 'SECRET'
EMAIL_HOST_PASSWORD = 'SECRET'

Django session working on local server but not on AWS server

In my Django view I use self.request.user to identify the user of a REST Framework API call. This works fine when the Django project is running on a server on my laptop, the code correctly picks up the user.
I am now trying to run my Django project on AWS EB and am having the problem that the self.request.user no longer identifies the user. The app code that is making the API call is exactly the same as is the Django server code.
Do I have to adjust my server settings in some way? My settings.py looks like this:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '9-s0gj3$)(--+mgc^3qhy=iva#azu+7a#3='
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'grappelli',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.google',
'allauth.socialaccount.providers.linkedin',
'allauth.socialaccount.providers.twitter',
'corsheaders',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'imagekit',
#'blog',
'storages',
'items',
'userprofile',
'dashboard',
'twip',
'django.contrib.gis'
]
SITE_ID = 1
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'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',
"django.core.context_processors.request",
],
},
},
]
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
LOGIN_REDIRECT_URL = '/'
SOCIALACCOUNT_QUERY_EMAIL = True
SOCIALACCOUNT_PROVIDERS = {
'facebook': {
'SCOPE': ['email', 'publish_stream'],
'METHOD': 'js_sdk' # instead of 'oauth2'
}
}
# :TO DO: Remove this when we test proper email confirmation on the EB server. This sends confirmation email to the console
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
WSGI_APPLICATION = 'mysite.wsgi.application'
# Postgresql database on AWS server
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '',
'USER' : '',
'PASSWORD' : '',
'HOST': '',
'PORT': '5432',
}
}
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',
},
]
# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Europe/Berlin'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# STORE STATIC AND MEDIA FILES
AWS_STORAGE_BUCKET_NAME = 'yhistory'
AWS_ACCESS_KEY_ID = 'AKAAAA6AAAAYQ5JODCEA'
AWS_SECRET_ACCESS_KEY = 'AAAATtVeCZLaAAAAQQxZ9g5biTJnAAAA7PP8YrlC'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
# Location of static files
STATICFILES_LOCATION = 'static'
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = ( os.path.join('static'), )
# Location of media files (photos etc.)
MEDIAFILES_LOCATION = 'media'
MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION)
DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': ['rest_framework.authentication.TokenAuthentication'],
'DEFAULT_PERMISSION_CLASSES': [],
'PAGE_SIZE': 1000, # Max number of results returned from a list API call
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),
# Use JSONRender so the Web API interface is not shown. This is needed when testing the app on the same server
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
CORS_ORIGIN_ALLOW_ALL = True # :PRODUCTION: Change this! If set to False the CORS whitelist is used
CORS_ORIGIN_WHITELIST = ()
"""
CORS_ORIGIN_WHITELIST = (
'twip.co',
'127.0.0.1'
)
"""
CORS_ORIGIN_REGEX_WHITELIST = ()
CORS_URLS_REGEX = '^.*$'
CORS_ALLOW_METHODS = (
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'UPDATE',
'OPTIONS'
)
CORS_ALLOW_HEADERS = (
'x-requested-with',
'content-type',
'accept',
'origin',
'authorization',
'x-csrftoken'
)
CORS_EXPOSE_HEADERS = ()
CORS_ALLOW_CREDENTIALS = False
GRAPPELLI_ADMIN_TITLE = "The World Image Archive Admin Panel"
possible solving options:
replace rest framework default authentication with the following snippet code
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
)
add this line in your settings.py file for details click here
WSGIPassAuthorization On