Ejemplo n.º 1
0
 def handle(self, *args, **options):
     path = os.path.join(settings.BASE_DIR, 'settings', '{}.py'.format(setting_local_settings_filename.value))
     if os.path.exists(path):
         self.stdout.write(self.style.NOTICE('Existing settings file at: {0}. Backup, remove this file, and try again.'.format(path)))
     else:
         with open(path, 'w+') as file_object:
             file_object.write(
                 SETTING_FILE_TEMPLATE.format(get_random_secret_key())
             )
Ejemplo n.º 2
0
    def initialize_system(self, force=False):
        system_path = os.path.join(settings.MEDIA_ROOT, SYSTEM_DIR)
        settings_path = os.path.join(settings.MEDIA_ROOT, 'mayan_settings')
        secret_key_file_path = os.path.join(system_path, SECRET_KEY_FILENAME)

        if not os.path.exists(settings.MEDIA_ROOT) or force:
            # Create the media folder
            try:
                os.makedirs(settings.MEDIA_ROOT)
            except OSError as exception:
                if exception.errno == errno.EEXIST and force:
                    pass

            # Touch media/__init__.py
            Command.touch(os.path.join(settings.MEDIA_ROOT, '__init__.py'))

            # Create media/settings
            try:
                os.makedirs(settings_path)
            except OSError as exception:
                if exception.errno == errno.EEXIST and force:
                    pass

            # Touch media/settings/__init__.py
            Command.touch(os.path.join(settings_path, '__init__.py'))

            # Create the media/system folder
            try:
                os.makedirs(system_path)
            except OSError as exception:
                if exception.errno == errno.EEXIST and force:
                    pass

            version_file_path = os.path.join(system_path, 'VERSION')
            with open(version_file_path, 'w') as file_object:
                file_object.write(mayan.__version__)

            with open(secret_key_file_path, 'w') as file_object:
                secret_key = get_random_secret_key()
                file_object.write(secret_key)

            settings.SECRET_KEY = secret_key
        else:
            self.stdout.write(
                self.style.NOTICE(
                    'Existing media files at: {0}. Backup, remove this folder, '
                    'and try again. Or use the --force argument'.format(
                        settings.MEDIA_ROOT
                    )
                )
            )
Ejemplo n.º 3
0
    def generate_secret_key(self):
        print('[Generating secret key]')
        from django.conf import settings
        from django.core.management.utils import get_random_secret_key

        if os.path.exists(settings.SECRET_KEY_FILE):
            print('- Secret file already exists!')
            return

        os.makedirs(settings.CONFIG_DIR, exist_ok=True)

        with open(settings.SECRET_KEY_FILE, 'w') as f:
            f.write(get_random_secret_key())
        print('- Secret key generated.')
Ejemplo n.º 4
0
def upload_local_settings():
    require('srvr', 'path', provided_by=env.servers)

    with cd(env.path):
        with settings(warn_only=True):
            if run('ls {}/settings/local.py'.format(PROJECT_NAME)).failed:
                db_host = prompt('Database host: ')
                db_pwd = prompt('Database password: '******'{}/settings/local_{}.py'.format(PROJECT_NAME, env.srvr),
                    '{}/settings/local.py'.format(PROJECT_NAME), mode='0664')

                run('echo >> {}/settings/local.py'.format(PROJECT_NAME))
                run('echo '
                    '"DATABASES[\'default\'][\'PASSWORD\'] = \'{}\'" >>'
                    '{}/settings/local.py'.format(db_pwd, PROJECT_NAME))
                run('echo '
                    '"DATABASES[\'default\'][\'HOST\'] = \'{}\'" >>'
                    '{}/settings/local.py'.format(db_host, PROJECT_NAME))
                run('echo '
                    '"SECRET_KEY = \'{}\'" >>'
                    '{}/settings/local.py'.format(
                        get_random_secret_key(), PROJECT_NAME))
Ejemplo n.º 5
0
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import os
import raven
from copy import deepcopy
from utils.shortcuts import get_env
from django.core.management import utils

production_env = get_env("OJ_ENV", "dev") == "production"
if production_env:
    from .production_settings import *
else:
    from .dev_settings import *

# with open(os.path.join(DATA_DIR, "config", "secret.key"), "r") as f:
SECRET_KEY = utils.get_random_secret_key()

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Applications
VENDOR_APPS = [
    'django.contrib.auth',
    'django.contrib.sessions',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'django_dramatiq',
    'django_dbconn_retry',
]
Ejemplo n.º 6
0
    def handle(self, *args, **options):
        env_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__), '../../../.env'))

        if Command.confirm(options):
            self.set_secret_key(env_path, get_random_secret_key())
Ejemplo n.º 7
0
env = Env()

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

ENV = env("ENVIRONMENT", default="local")
if ENV not in ("local", "dev", "staging", "production"):
    warnings.warn(
        "ENVIRONMENT env variable must be one of local, dev, staging or production"
    )

DEBUG = env("DEBUG", default=False)

SECRET_KEY = env("DJANGO_SECRET_KEY", default=get_random_secret_key())

HOSTED_SEATS_LIMIT = env.int("HOSTED_SEATS_LIMIT", default=0)

# Google Analytics Configuration
GOOGLE_ANALYTICS_KEY = env("GOOGLE_ANALYTICS_KEY", default="")
GOOGLE_SERVICE_ACCOUNT = env("GOOGLE_SERVICE_ACCOUNT", default=None)
if not GOOGLE_SERVICE_ACCOUNT:
    warnings.warn(
        "GOOGLE_SERVICE_ACCOUNT not configured, getting organisation usage will not work"
    )
GA_TABLE_ID = env("GA_TABLE_ID", default=None)
if not GA_TABLE_ID:
    warnings.warn(
        "GA_TABLE_ID not configured, getting organisation usage will not work")
Ejemplo n.º 8
0
heroku_url = match.group(2)

# Add the redis add-ons (the heroku one needs a config flag)
run_heroku_command([
    "addons:create", "heroku-redis:hobby-dev", "--maxmemory_policy",
    "allkeys-lru"
])

# Set build packs
run_heroku_command(
    ["buildpacks:set", "https://github.com/heroku/heroku-buildpack-nginx.git"])
run_heroku_command(["buildpacks:add", "--index", "1", "heroku/nodejs"])
run_heroku_command(["buildpacks:add", "--index", "2", "heroku/python"])

# Set config variables
secret_key = get_random_secret_key()
command = [
    "config:set", "DISABLE_COLLECTSTATIC=1",
    "DJANGO_SECRET_KEY=%s" % secret_key
]
command.append("DEBUG=1" if args.enable_debug else "DEBUG=0")
if args.fast_cache_timeout:
    command.append("PUBLIC_FAST_CACHE_TIMEOUT=%d" % args.fast_cache_timeout)
if args.slow_cache_timeout:
    command.append("PUBLIC_SLOW_CACHE_TIMEOUT=%d" % args.slow_cache_timeout)
if args.tab_cache_timeout:
    command.append("TAB_PAGES_CACHE_TIMEOUT=%d" % args.tab_cache_timeout)

run_heroku_command(command)

# Set up a remote, if applicable
Ejemplo n.º 9
0
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

data.makeDirs(data.getPath(data.user, 'authserver'))
CONFIG_PATH = data.getPath(data.user, 'authserver', 'config')
config = ConfigParser(interpolation=None)
config.add_section('security')
config.add_section('web')
config.read(CONFIG_PATH)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config.get('security', 'key', fallback=None)
if not SECRET_KEY:
    SECRET_KEY = get_random_secret_key().replace('%', '-')
    config.set('security', 'key', SECRET_KEY)
    with open(CONFIG_PATH, 'w') as f:
        config.write(f)

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config.getboolean('security', 'debug', fallback=False)
if DEBUG:
    os.environ['PYTHONASYNCIODEBUG'] = '1'


def build_allowed_hosts():
    result = {'localhost', '[::1]'}
    result.update(socket.gethostbyname_ex(socket.gethostname())[2])
    result.update(socket.gethostbyname_ex('localhost')[2])
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
Ejemplo n.º 10
0
def generate_secret_key(_ctx):
    from django.core.management.utils import get_random_secret_key

    print(get_random_secret_key())
Ejemplo n.º 11
0
"""
import os
import sys
import dj_database_url
from django.core.management.utils import get_random_secret_key

from pathlib import Path

# 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/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key())

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv("DEBUG", "False") == "True"

ALLOWED_HOSTS = os.getenv("DJANGO_ALLOWED_HOSTS",
                          "127.0.0.1,localhost").split(",")

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
Ejemplo n.º 12
0
        "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",
                "wagtail.contrib.settings.context_processors.settings",
            ],
        },
    },
]

WSGI_APPLICATION = "cms.wsgi.application"
# Set a SECRET_KEY in the environment when running multiple instances
SECRET_KEY = env("SECRET_KEY", default=utils.get_random_secret_key())

# Set the environment variable to the correct host when deployed
# https://docs.djangoproject.com/en/3.1/ref/settings/#std:setting-ALLOWED_HOSTS
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS", default=[".localhost", "127.0.0.1"])

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

DATABASES = {
    "default": env.db(default=f"sqlite:///{BASE_DIR}/db.sqlite3"),
}

# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
Ejemplo n.º 13
0
https://docs.djangoproject.com/en/2.0/ref/settings/
"""

import os
from django.core.management import utils

# 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.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
# See secret.py for how this is generated; uses a file 'secret.txt' in the root
# directory
SECRET_KEY = os.environ.get('DJANGO_SECRET', utils.get_random_secret_key())

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = bool(os.environ.get('DEBUG', False))

ALLOWED_HOSTS = os.environ.get('DJANGO_HOSTS', '*').split(',')

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
Ejemplo n.º 14
0
def create_new_secret_key(configuration):
    key = get_random_secret_key()
    configuration['Keys'] = {'SECRET_KEY': key}
Ejemplo n.º 15
0
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path
import os
import dj_database_url
from django.core.management.utils import get_random_secret_key

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent

SECRET_KEY = os.environ.get("SECRET_KEY", default=get_random_secret_key())

DEBUG = int(os.environ.get("DEBUG", default=0))

# 'DJANGO_ALLOWED_HOSTS' should be a single string of hosts with a space between each.
# For example: 'DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1]'
# ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS").split(" ")
ALLOWED_HOSTS = ["localhost", "127.0.0.1", "clothesmanager.herokuapp.com"]

# IPS for debug tool
INTERNAL_IPS = ["127.0.0.1"]

if os.environ.get("USE_DOCKER") == "yes":
    import socket

    ALLOWED_HOSTS += [socket.gethostbyname(socket.gethostname())]
Ejemplo n.º 16
0
class CheckSecretKeyFallbacksTest(SimpleTestCase):
    @override_settings(SECRET_KEY_FALLBACKS=[("abcdefghijklmnopqrstuvwx" * 2) + "ab"])
    def test_okay_secret_key_fallbacks(self):
        self.assertEqual(
            len(settings.SECRET_KEY_FALLBACKS[0]),
            base.SECRET_KEY_MIN_LENGTH,
        )
        self.assertGreater(
            len(set(settings.SECRET_KEY_FALLBACKS[0])),
            base.SECRET_KEY_MIN_UNIQUE_CHARACTERS,
        )
        self.assertEqual(base.check_secret_key_fallbacks(None), [])

    def test_no_secret_key_fallbacks(self):
        with self.settings(SECRET_KEY_FALLBACKS=None):
            del settings.SECRET_KEY_FALLBACKS
            self.assertEqual(
                base.check_secret_key_fallbacks(None),
                [
                    Warning(base.W025.msg % "SECRET_KEY_FALLBACKS", id=base.W025.id),
                ],
            )

    @override_settings(
        SECRET_KEY_FALLBACKS=[base.SECRET_KEY_INSECURE_PREFIX + get_random_secret_key()]
    )
    def test_insecure_secret_key_fallbacks(self):
        self.assertEqual(
            base.check_secret_key_fallbacks(None),
            [
                Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id),
            ],
        )

    @override_settings(SECRET_KEY_FALLBACKS=[("abcdefghijklmnopqrstuvwx" * 2) + "a"])
    def test_low_length_secret_key_fallbacks(self):
        self.assertEqual(
            len(settings.SECRET_KEY_FALLBACKS[0]),
            base.SECRET_KEY_MIN_LENGTH - 1,
        )
        self.assertEqual(
            base.check_secret_key_fallbacks(None),
            [
                Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id),
            ],
        )

    @override_settings(SECRET_KEY_FALLBACKS=["abcd" * 20])
    def test_low_entropy_secret_key_fallbacks(self):
        self.assertGreater(
            len(settings.SECRET_KEY_FALLBACKS[0]),
            base.SECRET_KEY_MIN_LENGTH,
        )
        self.assertLess(
            len(set(settings.SECRET_KEY_FALLBACKS[0])),
            base.SECRET_KEY_MIN_UNIQUE_CHARACTERS,
        )
        self.assertEqual(
            base.check_secret_key_fallbacks(None),
            [
                Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id),
            ],
        )

    @override_settings(
        SECRET_KEY_FALLBACKS=[
            ("abcdefghijklmnopqrstuvwx" * 2) + "ab",
            "badkey",
        ]
    )
    def test_multiple_keys(self):
        self.assertEqual(
            base.check_secret_key_fallbacks(None),
            [
                Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[1]", id=base.W025.id),
            ],
        )

    @override_settings(
        SECRET_KEY_FALLBACKS=[
            ("abcdefghijklmnopqrstuvwx" * 2) + "ab",
            "badkey1",
            "badkey2",
        ]
    )
    def test_multiple_bad_keys(self):
        self.assertEqual(
            base.check_secret_key_fallbacks(None),
            [
                Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[1]", id=base.W025.id),
                Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[2]", id=base.W025.id),
            ],
        )
Ejemplo n.º 17
0
"""

import os
import importlib
from pathlib import Path
from decouple import config
from django.urls import reverse_lazy
from django.core.management.utils import get_random_secret_key

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = Path(__file__).resolve().parent.parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY', default=get_random_secret_key())

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG_MODE', default=True, cast=bool)

# custom env
WORK_DIR = config('WORK_DIR', default='')
Path(WORK_DIR).mkdir(parents=True, exist_ok=True)

USE_HTTPS = config('USE_HTTPS', default=False, cast=bool)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default='*').split(',')
CORS_ORIGIN_ALLOW_ALL = True

with open(BASE_DIR / 'purpleserver' / 'VERSION', "r") as v:
    VERSION = v.read()
Ejemplo n.º 18
0
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
# Load secrety key
try:
    SECRET_KEY = config('SECRET_KEY')
# If error, generate a random secret key and save in secret_key.py
except:
    SETTINGS_DIR = os.path.abspath(os.path.dirname(__file__))
    get_random_secret_key(os.path.join(SETTINGS_DIR, 'secret_key.py'))
    from .secret_key import SECRET_KEY

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', cast=bool, default=False)

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.messages',
    'django.contrib.sessions',
Ejemplo n.º 19
0
from pathlib import Path
from django.core.management import utils

path = Path(__file__).resolve().parents[1] / 'var/secret.txt'
if not path.exists():
    print('Secret key generated')
    path.write_text(utils.get_random_secret_key())

SECRET_KEY = path.read_text()
Ejemplo n.º 20
0
from pathlib import Path
from decouple import config
from datetime import timedelta
from django.urls import reverse_lazy
from django.core.management.utils import get_random_secret_key

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = Path(__file__).resolve().parent.parent.parent

with open(BASE_DIR / "server" / "VERSION", "r") as v:
    VERSION = v.read().strip()

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config("SECRET_KEY", default=get_random_secret_key())

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config("DEBUG_MODE", default=True, cast=bool)

# custom env
WORK_DIR = config("WORK_DIR", default="")
Path(WORK_DIR).mkdir(parents=True, exist_ok=True)

USE_HTTPS = config("USE_HTTPS", default=False, cast=bool)
ALLOWED_HOSTS = config("ALLOWED_HOSTS", default="*").split(",")

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
Ejemplo n.º 21
0
 def handle(self, *args, **options):
     self.stdout.write(get_random_secret_key())
Ejemplo n.º 22
0
"""

import os
from django.urls import reverse_lazy
from django.core.management.utils import get_random_secret_key

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
CUR_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.join(CUR_DIR, "..")


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY', get_random_secret_key())

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = bool(os.environ.get('DEBUG_MODE', True))

SECURE_DOMAIN = os.environ.get('SECURE', False)

ALLOWED_HOSTS = [
    '127.0.0.1',
    'localhost'
]

CORS_ORIGIN_ALLOW_ALL = True

if SECURE_DOMAIN:
    global SECURE_SSL_REDIRECT
Ejemplo n.º 23
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# generate_secret.py
from django.core.management import utils

print(utils.get_random_secret_key())
Ejemplo n.º 24
0
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path
from django.core.management.utils import get_random_secret_key

# 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/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', default=get_random_secret_key())

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ["*"]

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin', 'django.contrib.auth',
    'django.contrib.contenttypes', 'django.contrib.sessions',
    'django.contrib.messages', 'django.contrib.staticfiles', 'correction_api',
    'rest_framework'
]
Ejemplo n.º 25
0
from django.core.management import utils
with open("temp", 'w') as tempFile:
    tempFile.write(utils.get_random_secret_key())

Ejemplo n.º 26
0
def get_env_value(env_variable):
    if not env_variable in os.environ:
        os.environ[env_variable] = get_random_secret_key()
    return os.environ[env_variable]
Ejemplo n.º 27
0
#!/usr/bin/env python3

from os.path import isfile
from django.core.management import utils

# Bail if .env exists already
if isfile('.env'):
    print('.env file already present; exiting.')
    exit(0)

try:
    new_secret = utils.get_random_secret_key()
    with open('example.env', 'rt') as env_in:
        with open('.env', 'wt') as env_out:
            for line in env_in:
                env_out.write(line.replace('replaceme', new_secret))
    print('.env written.')
except OSError as err:
    print('OS Error: {}'.format(err))
except:
    print('Unexpected error.')
Ejemplo n.º 28
0
import getpass
import os
import pathlib
import sys

from django.core.management.utils import get_random_secret_key
from invoke import task

BASE_DIR = os.path.dirname(__file__)
BASE_DIRNAME = os.path.dirname(BASE_DIR)
PROJECT_DIRNAME = os.path.basename(os.path.dirname(__file__))
EMPEROR_MODE = True
VASSALS = f'{BASE_DIRNAME}/vassals'
USERNAME = os.getlogin()
SECRET_FILE = f'{BASE_DIR}/{PROJECT_DIRNAME}/settings/secret.py'
SECRET_KEY = get_random_secret_key()


@task
def init(c):
    """Initialize project."""
    try:
        VENV_ROOT = str(pathlib.Path(os.environ['VIRTUAL_ENV']).parent).replace("/", "\/")  # noqa
    except KeyError:
        print('Activate your virtualenv and run the inv command again')
        return
    EMPEROR_MODE = confirm('Do you want to configure your uWSGI vassal in emperor mode? (no=stand-alone)')
    if EMPEROR_MODE:
        vassals = input(f'We will use "{VASSALS}" as the directory for the vassals, or specify the path: ') or VASSALS
        bonjour = confirm('Do you want to use Bonjour for OSX (Yes) or Avahi for Linux (No)? ')
        if bonjour:
import json
from django.core.management.utils import get_random_secret_key

secret = {}
secret['SECRET_KEY'] = get_random_secret_key()
secret['DB_HOST'] = ''
secret['DB_USER'] = ''
secret['DB_DATABASE'] = ''
secret['DB_PASSWORD'] = ''
secret['ALLOWED_HOSTS'] = ['localhost', '127.0.0.1']

secret = json.dumps(secret)

f = open('secret.json', 'w')
f.write(secret)
f.close()
Ejemplo n.º 30
0
"""

from decouple import config
from pathlib import Path
import os
from django.core.management import utils

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
# Use secret key from env variable or generate a random key
SECRET_KEY = config('PT_LINUX_SECRET_KEY',
                    default=utils.get_random_secret_key())

# SECURITY WARNING: don't run with debug turned on in production!
# Set 'PT_LINUX_DEBUG' env variable to '1' if you want to enable debug
DEBUG = config('PT_LINUX_DEBUG', default=False, cast=bool)

ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'linux-blog-django']

# Application definition

INSTALLED_APPS = [
    'frontend',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
Ejemplo n.º 31
0
from pathlib import Path

from django.core.management.utils import get_random_secret_key

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = Path(__file__).resolve().parents[1]

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

key_file = Path('key')
if not Path('key').exists():
    # gerar uma chave secreta caso nenhuma exista (projeto recém-instalado)
    key_file.touch()
    with open(key_file, 'w') as f:
        f.write(get_random_secret_key())

# SECURITY WARNING: keep the secret key used in production secret!
with open(key_file) as f:
    SECRET_KEY = f.read()

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['localhost']

# Application definition

INSTALLED_APPS = [
    'candlesticks',
]
Ejemplo n.º 32
0
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""

import os
import dj_database_url
from django.core.management.utils import get_random_secret_key

# 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.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('SECRET_KEY', get_random_secret_key())

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv('DEBUG', False)

ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', '').split(',')

# Application definition

INSTALLED_APPS = [
    'music_publisher.apps.MusicPublisherConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
Ejemplo n.º 33
0
import getpass
import os
import pathlib
import sys

from django.core.management.utils import get_random_secret_key
from invoke import task

BASE_DIR = os.path.dirname(__file__)
BASE_DIRNAME = os.path.dirname(BASE_DIR)
PROJECT_DIRNAME = os.path.basename(os.path.dirname(__file__))
EMPEROR_MODE = True
VASSALS = f'{BASE_DIRNAME}/vassals'
USERNAME = os.getlogin()
SECRET_FILE = f'{BASE_DIR}/{PROJECT_DIRNAME}/settings/secret.py'
SECRET_KEY = get_random_secret_key()


@task
def init(c):
    try:
        VENV_ROOT = str(pathlib.Path(
            os.environ['VIRTUAL_ENV']).parent).replace("/", "\/")  # noqa
    except KeyError:
        print('Activate your virtualenv and run the inv command again')
        return
    EMPEROR_MODE = confirm(
        'Do you want to configure your uWSGI vassal in emperor mode? (no=stand-alone)'
    )
    if EMPEROR_MODE:
        vassals = input(
Ejemplo n.º 34
0
# This file is a part of IntelOwl https://github.com/intelowlproject/IntelOwl
# See the file 'LICENSE' for copying permission.

# flake8: noqa
import os
from datetime import timedelta

from django.core.files.storage import FileSystemStorage
from django.core.management.utils import get_random_secret_key

from intel_owl import secrets

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("DJANGO_SECRET", None) or get_random_secret_key()

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get("DEBUG", False) == "True"

DJANGO_LOG_DIRECTORY = "/var/log/intel_owl/django"
PROJECT_LOCATION = "/opt/deploy/intel_owl"
MEDIA_ROOT = "/opt/deploy/files_required"
DISABLE_LOGGING_TEST = os.environ.get("DISABLE_LOGGING_TEST", False) == "True"
MOCK_CONNECTIONS = os.environ.get("MOCK_CONNECTIONS", False) == "True"
TEST_MODE = MOCK_CONNECTIONS
LDAP_ENABLED = os.environ.get("LDAP_ENABLED", False) == "True"
RADIUS_AUTH_ENABLED = os.environ.get("RADIUS_AUTH_ENABLED", False) == "True"
LOCAL_STORAGE = os.environ.get("LOCAL_STORAGE", "True") == "True"
# Storage settings
if LOCAL_STORAGE:
Ejemplo n.º 35
0
 def test_get_random_secret_key(self):
     key = get_random_secret_key()
     self.assertEqual(len(key), 50)
     for char in key:
         self.assertIn(char, 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
Ejemplo n.º 36
0
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

from django.core.management import utils

# 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/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = utils.get_random_secret_key()

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
Ejemplo n.º 37
0
def generate_secret_key():
    return get_random_secret_key()
Ejemplo n.º 38
0
    secret = ask_text("Facebook App Secret")
    client_id = ask_text("Facebook App ID (not client token)")
    return dict(secret=secret, client_id=client_id)


def ask_google():
    secret = ask_text("Google Secret")
    client_id = ask_text("Google Client ID")
    return dict(secret=secret, client_id=client_id)


if __name__ == "__main__":

    context = {
        'now': str(datetime.now()),
        'secret_key': get_random_secret_key(),
    }

    heading("Facebook")
    if ask_yes_no("Do you want to configure auth via Facebook?\n"
                  "You'll need the app secret and client."):
        context['facebook'] = ask_facebook()

    heading("Google")
    if ask_yes_no("Do you want to configure auth via Google?\n"
                  "You'll need the app secret and client."):
        context['google'] = ask_google()

    heading("Rendering settings...")
    with open('config/settings.py', 'w') as out:
        out.write(settings_template.render(context, request=None))
Ejemplo n.º 39
0
#!/usr/bin/env python

from django.core.management.utils import get_random_secret_key

print(get_random_secret_key())
Ejemplo n.º 40
0
# Use this to generate secret keys for each environment

from django.core.management.utils import get_random_secret_key

print(get_random_secret_key())
Ejemplo n.º 41
0
 def test_get_random_secret_key(self):
     key = get_random_secret_key()
     self.assertEqual(len(key), 50)
     for char in key:
         self.assertIn(char, 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
Ejemplo n.º 42
0
    def handle(self, *args, **options):
        # copy folder
        self.stdout.write('copy folder')
        copytree(getcwd(), self.DEPLOY_FOLDER)

        # modify settings
        lines = list()
        with open(join(self.DEPLOY_FOLDER, 'server', 'settings.py'),
                  'r') as settings:
            for line in settings:
                if 'DEBUG =' in line:
                    line = 'DEBUG = False\n'
                    self.stdout.write('disabled debug mode')
                if 'SECRET_KEY' in line:
                    line = "SECRET_KEY = '"
                    line += utils.get_random_secret_key() + "'\n"
                    self.stdout.write('generated secret key')
                if 'ALLOWED_HOSTS' in line:
                    line = "ALLOWED_HOSTS = ['*']\n"
                if 'STATIC_ROOT' in line:
                    line = "STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')\n"
                lines.append(line)

        with open(join(self.DEPLOY_FOLDER, 'server', 'settings.py'),
                  'w') as settings:
            for line in lines:
                settings.write(line)

        # update npm
        if isdir(join(self.DEPLOY_FOLDER, 'node_modules')):
            self.stdout.write('delete node_modules')
            rmtree(join(self.DEPLOY_FOLDER, 'node_modules'))

        call(['npm', 'install'], cwd=self.DEPLOY_FOLDER)

        # compile sass
        call(
            [
                'python3',
                'manage.py',
                'compilesass',
            ],
            cwd=self.DEPLOY_FOLDER,
        )

        # clone client
        call(
            ['git', 'clone', 'https://github.com/bp-flugsimulator/client.git'],
            cwd=join(self.DEPLOY_FOLDER, 'downloads'),
        )

        # update packages
        call(
            ['python3', 'install.py', '--update'],
            cwd=self.DEPLOY_FOLDER,
        )
        call(
            ['python3', 'install.py', '--update'],
            cwd=join(self.DEPLOY_FOLDER, 'downloads'),
        )

        # delete unused files
        for path, dir_names, file_names in walk(self.DEPLOY_FOLDER):
            for directory in dir_names:
                if ((len(directory) > 3) and
                    (directory[0] is '.')) or (directory in self.IGNORE_LIST):
                    rmtree(join(path, directory))
                    self.stdout.write('removed ' + join(path, directory))

            for file in file_names:
                if ((len(file) > 3) and
                    (file[0] is '.')) or (file in self.IGNORE_LIST):
                    remove(join(path, file))
                    self.stdout.write('removed ' + join(path, file))

        # zip client and delete folder
        print('zip client')
        make_archive(
            join(self.DEPLOY_FOLDER, 'downloads', 'client'),
            'zip',
            join(self.DEPLOY_FOLDER, 'downloads', 'client'),
        )
        self.stdout.write('delete client folder')
        rmtree(join(self.DEPLOY_FOLDER, 'downloads', 'client'))

        # collect static files
        self.stdout.write('collect static files')
        call(
            ['python3', 'manage.py', 'collectstatic', '--noinput'],
            cwd=self.DEPLOY_FOLDER,
        )

        # set up database
        if isfile(join(self.DEPLOY_FOLDER, 'db.sqlite3')):
            remove(join(self.DEPLOY_FOLDER, 'db.sqlite3'))
            self.stdout.write('deleted database')

        for file in listdir(join(self.DEPLOY_FOLDER, 'frontend',
                                 'migrations')):
            if isfile(
                    join(
                        self.DEPLOY_FOLDER,
                        'frontend',
                        'migrations',
                        file,
                    )) and not ('0001_initial.py' in file
                                or '__init__.py' in file):
                remove(
                    join(
                        self.DEPLOY_FOLDER,
                        'frontend',
                        'migrations',
                        file,
                    ))
                self.stdout.write('remove ' + join(
                    self.DEPLOY_FOLDER,
                    'frontend',
                    'migrations',
                    file,
                ))
        call(
            ['python3', 'manage.py', 'makemigrations'],
            cwd=self.DEPLOY_FOLDER,
        )
        call(
            ['python3', 'manage.py', 'migrate'],
            cwd=self.DEPLOY_FOLDER,
        )

        # zip
        self.stdout.write('zip server')
        make_archive(
            join(getcwd(), pardir, 'server'),
            'zip',
            self.DEPLOY_FOLDER,
        )
        self.stdout.write('delete deploy folder')
        rmtree(self.DEPLOY_FOLDER)
 def handle(self, *args, **options):
     return get_random_secret_key()
Ejemplo n.º 44
0
    def handle(self, **options):
        # pop standard args
        project_name = options.pop('name')
        target = options.pop('directory')

        # Make sure given name is not already in use by another python package/module.
        try:
            __import__(project_name)
        except ImportError:
            pass
        else:
            sys.exit("'%s' conflicts with the name of an existing "
                     "Python module and cannot be used as a project "
                     "name. Please try another name." % project_name)

        # Create a random SECRET_KEY to put it in the main settings.
        options['secret_key'] = get_random_secret_key()

        # Add custom args
        import coderedcms
        codered_path = os.path.dirname(coderedcms.__file__)
        template_path = os.path.join(codered_path, 'project_template')
        options['template'] = template_path
        options['extensions'] = ['py', 'html', 'rst', 'md']
        options['files'] = ['Dockerfile']

        # Set options
        message = "Creating a CodeRed CMS project called %(project_name)s"

        if options.get('sitename'):
            message += " for %(sitename)s"
        else:
            options['sitename'] = project_name

        if options.get('domain'):
            message += " (%(domain)s)"
            # Stip protocol out of domain if it is present.
            options['domain'] = options['domain'].split('://')[-1]
            # Figure out www logic.
            if options['domain'].startswith('www.'):
                options['domain_nowww'] = options['domain'].split('www.')[-1]
            else:
                options['domain_nowww'] = options['domain']
        else:
            options['domain'] = 'localhost'
            options['domain_nowww'] = options['domain']

        # Print a friendly message
        print(
            message % {
                'project_name': project_name,
                'sitename': options.get('sitename'),
                'domain': options.get('domain'),
            })

        # Run command
        super().handle('project', project_name, target, **options)

        # Be a friend once again.
        print("Success! %(project_name)s has been created" %
              {'project_name': project_name})

        nextsteps = """
Next steps:
    1. cd %(directory)s/
    2. python manage.py migrate
    3. python manage.py createsuperuser
    4. python manage.py runserver
    5. Go to http://localhost:8000/admin/ and start editing!
"""
        print(nextsteps % {'directory': target if target else project_name})