Skip to content

Commit

Permalink
Merge pull request #152 from edubadges/feature/session_exp
Browse files Browse the repository at this point in the history
Added SESSION_COOKIE_AGE and ruff.toml
  • Loading branch information
Iso5786 authored Oct 30, 2024
2 parents dcf5a46 + 8bf2dc9 commit eaeb618
Show file tree
Hide file tree
Showing 2 changed files with 118 additions and 52 deletions.
89 changes: 37 additions & 52 deletions apps/mainsite/settings.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import os
import django

from mainsite import TOP_DIR
from mainsite.environment import env_settings

Expand All @@ -9,8 +9,10 @@ def legacy_boolean_parsing(env_key, default_value):
val = '1' if val == 'True' else '0' if val == 'False' else val
return bool(int(val))


env_settings()

SESSION_COOKIE_AGE = 60 * 60 # 1 hour session validity
SESSION_COOKIE_SAMESITE = None # should be set as 'None' for Django >= 3.1
SESSION_COOKIE_SECURE = True # should be True in case of HTTPS usage (production)
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
Expand Down Expand Up @@ -56,7 +58,6 @@ def legacy_boolean_parsing(env_key, default_value):
'django_celery_results',
'drf_spectacular',
'drf_spectacular_sidecar',

# OAuth 2 provider
'oauth2_provider',
# eduBadges apps
Expand Down Expand Up @@ -96,11 +97,12 @@ def legacy_boolean_parsing(env_key, default_value):
# 'mainsite.middleware.TrailingSlashMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',

]

ROOT_URLCONF = 'mainsite.urls'
ALLOWED_HOSTS = ['*', ]
ALLOWED_HOSTS = [
'*',
]
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

##
Expand All @@ -123,7 +125,7 @@ def legacy_boolean_parsing(env_key, default_value):
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.request',
'mainsite.context_processors.extra_settings'
'mainsite.context_processors.extra_settings',
],
},
},
Expand Down Expand Up @@ -171,7 +173,7 @@ def legacy_boolean_parsing(env_key, default_value):
AUTHENTICATION_BACKENDS = [
'oauth2_provider.backends.OAuth2Backend',
# Needed to login by username in Django admin, regardless of `allauth`
"badgeuser.backends.CachedModelBackend",
'badgeuser.backends.CachedModelBackend',
]

ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https'
Expand All @@ -185,9 +187,7 @@ def legacy_boolean_parsing(env_key, default_value):
ACCOUNT_AUTHENTICATION_METHOD = 'username'
ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username'
ACCOUNT_UNIQUE_EMAIL = False
ACCOUNT_FORMS = {
'add_email': 'badgeuser.account_forms.AddEmailForm'
}
ACCOUNT_FORMS = {'add_email': 'badgeuser.account_forms.AddEmailForm'}
ACCOUNT_SIGNUP_FORM_CLASS = 'badgeuser.forms.BadgeUserCreationForm'
ACCOUNT_SALT = os.environ['ACCOUNT_SALT']

Expand Down Expand Up @@ -223,7 +223,7 @@ def legacy_boolean_parsing(env_key, default_value):
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
'OPTIONS': {
'min_length': 8,
}
},
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
Expand Down Expand Up @@ -279,19 +279,15 @@ def legacy_boolean_parsing(env_key, default_value):
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': [],
'class': 'django.utils.log.AdminEmailHandler'
},
'mail_admins': {'level': 'ERROR', 'filters': [], 'class': 'django.utils.log.AdminEmailHandler'},
'badgr_events': {
'level': 'INFO',
'formatter': 'json',
'class': 'logging.handlers.TimedRotatingFileHandler',
'when': 'H',
'interval': 1,
'backupCount': 30*24, # 30 days times 24 hours
'filename': os.path.join(LOGS_DIR, 'badgr_events.log')
'backupCount': 30 * 24, # 30 days times 24 hours
'filename': os.path.join(LOGS_DIR, 'badgr_events.log'),
},
'badgr_debug': {
'level': 'INFO',
Expand Down Expand Up @@ -333,20 +329,16 @@ def legacy_boolean_parsing(env_key, default_value):
'handlers': ['badgr_debug'],
'level': 'DEBUG',
'propagate': True,
}
},
},
'formatters': {
'default': {
'format': '%(asctime)s %(levelname)s %(module)s %(message)s'
},
'badgr': {
'format': '%(asctime)s | %(levelname)s | %(message)s'
},
'default': {'format': '%(asctime)s %(levelname)s %(module)s %(message)s'},
'badgr': {'format': '%(asctime)s | %(levelname)s | %(message)s'},
'json': {
'()': 'mainsite.formatters.JsonFormatter',
'format': '%(asctime)s',
'datefmt': '%Y-%m-%dT%H:%M:%S%z',
}
},
},
'filters': {
'require_debug_true': {
Expand Down Expand Up @@ -400,9 +392,7 @@ def legacy_boolean_parsing(env_key, default_value):
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'],
'DEFAULT_RENDERER_CLASSES': (
'mainsite.renderers.JSONLDRenderer',
'rest_framework.renderers.JSONRenderer',
Expand All @@ -417,7 +407,7 @@ def legacy_boolean_parsing(env_key, default_value):
'DEFAULT_VERSION': 'v1',
'ALLOWED_VERSIONS': ['v1', 'v2'],
'EXCEPTION_HANDLER': 'entity.views.exception_handler',
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema'
'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema',
}

##
Expand All @@ -437,7 +427,7 @@ def legacy_boolean_parsing(env_key, default_value):

LTI_STORE_IN_SESSION = False
TIME_STAMPED_OPEN_BADGES_BASE_URL = os.environ['TIME_STAMPED_OPEN_BADGES_BASE_URL']
CAIROSVG_VERSION_SUFFIX = "2"
CAIROSVG_VERSION_SUFFIX = '2'

USE_I18N = True
USE_L10N = False
Expand All @@ -456,7 +446,12 @@ def legacy_boolean_parsing(env_key, default_value):
##

MARKDOWNIFY_WHITELIST_TAGS = [
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'a',
'abbr',
'acronym',
Expand All @@ -471,7 +466,7 @@ def legacy_boolean_parsing(env_key, default_value):
'ul',
'code',
'pre',
'hr'
'hr',
]

OAUTH2_PROVIDER = {
Expand All @@ -481,16 +476,13 @@ def legacy_boolean_parsing(env_key, default_value):
'r:backpack': "List assertions in a User's Backpack",
'rw:backpack': "Upload badges into a User's Backpack",
'rw:issuer': 'Create and update Issuers, create and update Badgeclasses, and award Assertions',

# private scopes used for integrations
'rw:issuer:*': 'Create and update Badgeclasses, and award Assertions for a single Issuer',
'r:assertions': 'Batch receive assertions',
},
'DEFAULT_SCOPES': ['r:profile'],

'OAUTH2_VALIDATOR_CLASS': 'mainsite.oauth_validator.BadgrRequestValidator',
'ACCESS_TOKEN_EXPIRE_SECONDS': 86400

'ACCESS_TOKEN_EXPIRE_SECONDS': 86400,
}
OAUTH2_PROVIDER_APPLICATION_MODEL = 'oauth2_provider.Application'
OAUTH2_PROVIDER_ACCESS_TOKEN_MODEL = 'oauth2_provider.AccessToken'
Expand Down Expand Up @@ -536,9 +528,7 @@ def legacy_boolean_parsing(env_key, default_value):

SESSION_COOKIE_SAMESITE = None

GRAPHENE = {
'SCHEMA': 'apps.mainsite.schema.schema'
}
GRAPHENE = {'SCHEMA': 'apps.mainsite.schema.schema'}

# Database
DATABASES = {
Expand All @@ -551,7 +541,7 @@ def legacy_boolean_parsing(env_key, default_value):
'PORT': os.environ.get('BADGR_DB_PORT', 3306),
'TEST': {
'CHARSET': 'utf8',
}
},
}
}
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
Expand All @@ -566,20 +556,20 @@ def legacy_boolean_parsing(env_key, default_value):
# Seeds
ALLOW_SEEDS = legacy_boolean_parsing('ALLOW_SEEDS', '0')
EDU_ID_SECRET = os.environ['EDU_ID_SECRET']
EDU_ID_CLIENT = os.environ.get('EDU_ID_CLIENT', "edubadges")
EDU_ID_CLIENT = os.environ.get('EDU_ID_CLIENT', 'edubadges')

OIDC_RS_ENTITY_ID = os.environ.get('OIDC_RS_ENTITY_ID', 'edubadges')
OIDC_RS_SECRET = os.environ['OIDC_RS_SECRET']

SURF_CONEXT_SECRET = os.environ.get('SURF_CONEXT_SECRET', 'secret')
SURF_CONEXT_CLIENT = os.environ.get('SURF_CONEXT_CLIENT', "test.edubadges.nl")
SURF_CONEXT_CLIENT = os.environ.get('SURF_CONEXT_CLIENT', 'test.edubadges.nl')

SUPERUSER_NAME = os.environ.get('SUPERUSER_NAME', '')
SUPERUSER_EMAIL = os.environ.get('SUPERUSER_EMAIL', '')
SUPERUSER_PWD = os.environ.get('SUPERUSER_PWD', '')

# Used in 01_setup sed
EDUID_BADGE_CLASS_NAME = "Edubadge account complete"
EDUID_BADGE_CLASS_NAME = 'Edubadge account complete'

# Debug
DEBUG = legacy_boolean_parsing('DEBUG', '0')
Expand All @@ -593,7 +583,6 @@ def legacy_boolean_parsing(env_key, default_value):
VALIDATOR_URL = os.environ.get('VALIDATOR_URL', 'http://localhost:5000')
EXTENSIONS_ROOT_URL = os.environ.get('EXTENSIONS_ROOT_URL', 'http://127.0.0.1:8000/static')


MAX_IMAGE_UPLOAD_SIZE = 256000 # 256Kb
MAX_IMAGE_UPLOAD_SIZE_LABEL = '256 kB' # used in error messaging

Expand All @@ -607,18 +596,14 @@ def legacy_boolean_parsing(env_key, default_value):
'SWAGGER_UI_DIST': 'SIDECAR', # shorthand to use the sidecar instead
'SWAGGER_UI_FAVICON_HREF': 'SIDECAR',
'REDOC_DIST': 'SIDECAR',
'SERVERS': [{'url':os.environ['DEFAULT_DOMAIN']}],
'PREPROCESSING_HOOKS': [
'mainsite.drf_spectacluar.custom_preprocessing_hook'
],
'SERVERS': [{'url': os.environ['DEFAULT_DOMAIN']}],
'PREPROCESSING_HOOKS': ['mainsite.drf_spectacluar.custom_preprocessing_hook'],
'POSTPROCESSING_HOOKS': [
'drf_spectacular.hooks.postprocess_schema_enums',
'mainsite.drf_spectacluar.custom_postprocessing_hook'
'mainsite.drf_spectacluar.custom_postprocessing_hook',
],

}

# settings.py
API_PROXY = {
'HOST': OB3_AGENT_URL_UNIME
}
}
81 changes: 81 additions & 0 deletions ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Exclude a variety of commonly ignored directories.
exclude = [
".bzr",
".direnv",
".eggs",
".git",
".git-rewrite",
".hg",
".ipynb_checkpoints",
".mypy_cache",
".nox",
".pants.d",
".pyenv",
".pytest_cache",
".pytype",
".ruff_cache",
".svn",
".tox",
".venv",
".vscode",
"__pypackages__",
"_build",
"buck-out",
"build",
"dist",
"node_modules",
"site-packages",
"venv",
]

# Same as Black.
line-length = 120
indent-width = 4

# Assume Python 3.8
target-version = "py38"

[lint]
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
# McCabe complexity (`C901`) by default.
select = ["E4", "E7", "E9", "F"]
ignore = []

# Allow fix for all enabled rules (when `--fix`) is provided.
fixable = ["ALL"]
unfixable = []

# Allow unused variables when underscore-prefixed.
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"

[format]
# Like Black, use double quotes for strings.
quote-style = "single"

# Like Black, indent with spaces, rather than tabs.
indent-style = "space"

# Like Black, respect magic trailing commas.
skip-magic-trailing-comma = false

# Like Black, automatically detect the appropriate line ending.
line-ending = "auto"

# Enable auto-formatting of code examples in docstrings. Markdown,
# reStructuredText code/literal blocks and doctests are all supported.
#
# This is currently disabled by default, but it is planned for this
# to be opt-out in the future.
docstring-code-format = false

# Set the line length limit used when formatting code snippets in
# docstrings.
#
# This only has an effect when the `docstring-code-format` setting is
# enabled.
docstring-code-line-length = "dynamic"

[lint.per-file-ignores]
"__init__.py" = ["E402"]
"**/{tests,docs,tools}/*" = ["E402"]

0 comments on commit eaeb618

Please sign in to comment.