Skip to content
Snippets Groups Projects
Select Git revision
  • d3d6b24e2848357c3420badd661ad878bc925bed
  • master default
  • clement
  • fix_requirements
  • new_signup
  • interface_admin
  • hamza
  • dev
  • test
  • melissa
  • context_sheet
  • sorties_new
  • Seon82-patch-2
  • export_bdd
  • refactor/participation-user-link
15 results

common.py

Blame
  • common.py 7.92 KiB
    """
    Django settings for oser_backend project.
    
    Common settings suitable for all environmebts.
    """
    
    import os
    from dotenv import load_dotenv
    
    import dj_database_url
    import pymdownx.emoji
    import mimetypes
    mimetypes.add_type("text/css", ".css", True)
    
    load_dotenv()
    
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    dn = os.path.dirname
    BASE_DIR = dn(dn(dn(os.path.abspath(__file__))))
    # SECURITY WARNING: keep the secret key used in production secret!
    # One way to do this is to store it in an environment variable on the server
    SECRET_KEY = os.environ.get('SECRET_KEY',
                                'odfuioTvdfvkdhvjeT9659dbnkcn2332fk564jvdf034')
    
    # Admin generation settings
    ADMINS = (
        ('Secteur Geek', 'oser.geek@gmail.com'),
    )
    ADMIN_INITIAL_PASSWORD = 'admin'  # to be changed after first login
    
    # Application definition
    
    DJANGO_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'whitenoise.runserver_nostatic',
        'django.contrib.staticfiles',
        'django.forms',
        'django.contrib.sites',
        "verify_email.apps.VerifyEmailConfig",
    ]
    
    THIRD_PARTY_APPS = [
        # Markdown integration
        'markdownx',
        # Django REST Framework (DRF)
        'rest_framework',
        'rest_framework.authtoken',
        # DRY REST permissions (rules-based API permissions)
        # https://github.com/dbkaplan/dry-rest-permissions
        'dry_rest_permissions',
        # CORS headers for Frontend integration
        'corsheaders',
        # Sortable models in Admin
        'adminsortable2',
        # Django Guardian: per object permissions
        # https://github.com/django-guardian/django-guardian
        'guardian',
        # Extra Django file storage backends
        'storages',
        # Country fields
        'django_countries',
        # Easy filtering on the API
        'django_filters',
        'rest_auth',
    ]
    
    PROJECT_APPS = [
        'core.apps.CoreConfig',
        'users.apps.UsersConfig',
        'profiles.apps.ProfilesConfig',
        'visits.apps.VisitsConfig',
        'register.apps.RegisterConfig',
        'api.apps.ApiConfig',
        'mails.apps.MailsConfig',
        'dynamicforms.apps.DynamicformsConfig',
        'projects.apps.ProjectsConfig',
    ]
    
    INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + PROJECT_APPS
    
    # Activate the sites framework
    # It is used to define the domain of the frontend website in
    # the admin (via the 'Sites' section)
    SITE_ID = 1
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'corsheaders.middleware.CorsMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.locale.LocaleMiddleware',
        'django.middleware.common.CommonMiddleware',
        'whitenoise.middleware.WhiteNoiseMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
    ROOT_URLCONF = 'oser_backend.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.template.context_processors.i18n',
                ],
            },
        },
    ]
    FORM_RENDERER = 'django.forms.renderers.TemplatesSetting'
    
    WSGI_APPLICATION = 'oser_backend.wsgi.application'
    
    # Django rest framework
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'rest_framework.authentication.TokenAuthentication',
            # v Enable session authentication in the browsable API
            'rest_framework.authentication.SessionAuthentication',
        ],
    }
    
    # Security
    CORS_ORIGIN_REGEX_WHITELIST = (
        # Allow local hosts on any port
        r'^(https?://)?localhost(:\d+)?$',
        r'^(https?://)?127\.0\.0\.1(:\d+)?$',
        # Allow hosts such as:
        # - https://oser-cs.herokuapp.com
        # - https://oser-frontend-dev.herokuapp.com
        # (but also https://unknown.herokuapp.com...)
        # Essentially allows any frontend hosted on Heroku to send CORS requests.
        r'^(https?://)?(.+\.)?herokuapp\.com$',
        # Allow any app hosted on *oser-cs.fr
        r'^(https?://)?(.+\.)?oser-cs\.fr$',
    )
    X_FRAME_OPTIONS = 'DENY'  # refuse to serve in an <iframe>
    
    # Pymdown-extensions Emoji configuration
    extension_configs = {
        'emoji_index': pymdownx.emoji.twemoji,
        'emoji_generator': pymdownx.emoji.to_png,
        'alt': 'short',
        'options': {
            'attributes': {
                'align': 'absmiddle',
                'height': '20px',
                'width': '20px'
            },
            'image_path': 'https://assets-cdn.github.com/images/icons/emoji/unicode/',
            'non_standard_image_path': 'https://assets-cdn.github.com/images/icons/emoji/'
        }
    }
    
    # Markdownx settings
    MARKDOWNX_MARKDOWN_EXTENSIONS = [
        'pymdownx.emoji',
    ]
    MARKDOWNX_MARKDOWN_EXTENSION_CONFIGS = {
        'pymdownx.emoji': extension_configs,
    }
    
    # Database
    
    # Config be retrieved through the DATABASE_URL environment variable
    # DATABASE_URL format: postgres://USERNAME:PASSWORD@HOST:PORT/NAME
    DATABASES = {
        'default': dj_database_url.config(
            # Provide a default for dev environment
            default='postgres://postgres:postgres@127.0.0.1:5432/oser_backend_db'),
    }
    
    
    # Authentication
    
    AUTH_USER_MODEL = 'users.User'
    AUTHENTICATION_BACKENDS = [
        'django.contrib.auth.backends.ModelBackend',  # default
        'guardian.backends.ObjectPermissionBackend',
    ]
    
    # Password validation
    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',
        },
    ]
    
    
    # Logging
    
    # NOTE: all loggers within this project should be named 'web.<logger_name>'
    # so that the same configuration is applied to them.
    
    # Connect custom PasswordResetSerializer to override default
    
    REST_AUTH_SERIALIZERS = {
        'PASSWORD_RESET_SERIALIZER':
            'oser_backend.serializers.PasswordResetSerializer',
    }
    
    DEFAULT_FROM_EMAIL = "contact@oser-cs.fr"
    # Email configuration
    
    EMAIL_BACKEND = 'sendgrid_backend.SendgridBackend'
    SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')
    
    # Sendgrid configuration
    
    EMAIL_HOST = 'smtp.sendgrid.net'
    EMAIL_HOST_USER = 'apikey'
    EMAIL_HOST_PASSWORD = SENDGRID_API_KEY
    EMAIL_PORT = 587
    EMAIL_USE_TLS = True
    LOGIN_URL = os.getenv('LOGIN_URL')
    
    # Toggle sandbox mode (when running in DEBUG mode)
    SENDGRID_SANDBOX_MODE_IN_DEBUG = False
    
    # echo to stdout or any other file-like object that is passed to the backend via the stream kwarg.
    SENDGRID_ECHO_TO_STDOUT = True
    
    # Mails app config
    
    MAILS_ENABLED = True
    MAILS_NOTIFICATIONS_ADDRESS = 'notifications@oser-cs.fr'
    MAILS_RAISE_EXCEPTIONS = False
    HTML_MESSAGE_TEMPLATE = BASE_DIR + \
        "/profiles/templates/profiles/template_email_verification.html"
    
    # Visits app config
    VISITS_TEAM_EMAIL = os.environ.get('VISITS_TEAM_EMAIL',
                                       'florimond.manca@gmail.com')
    
    # Internationalization
    
    LANGUAGE_CODE = 'fr-fr'
    TIME_ZONE = 'Europe/Paris'
    USE_I18N = True
    USE_L10N = True
    USE_TZ = True
    
    # Static files (CSS, JavaScript, Images) and media files (user-uploaded)
    
    STATIC_URL = '/static/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'staticfiles'),
    ]
    
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    
    # Telegram bot
    TELEGRAM_BOT_TOKEN = os.getenv(
        "TELEGRAM_BOT_TOKEN")
    TELEGRAM = {
        'bot_token': TELEGRAM_BOT_TOKEN,
        'channel_name': 'oserSECGEN',
        'production': False,
    }
    
    VERIFICATION_SUCCESS_TEMPLATE = None