From 82b75fc4fb1233e1ac0f9cf7363d38d47cd35054 Mon Sep 17 00:00:00 2001 From: ibrobabs Date: Sun, 14 Jan 2018 21:37:25 -0700 Subject: [PATCH] first commit --- .coveragerc | 5 + .editorconfig | 33 ++ .gitattributes | 1 + .gitignore | 308 ++++++++++++++++++ .pylintrc | 14 + .travis.yml | 11 + CONTRIBUTORS.txt | 1 + LICENSE | 10 + Procfile | 2 + README.rst | 110 +++++++ config/__init__.py | 0 config/settings/__init__.py | 0 config/settings/base.py | 306 +++++++++++++++++ config/settings/local.py | 72 ++++ config/settings/production.py | 237 ++++++++++++++ config/settings/test.py | 61 ++++ config/urls.py | 37 +++ config/wsgi.py | 43 +++ docs/Makefile | 153 +++++++++ docs/__init__.py | 1 + docs/conf.py | 243 ++++++++++++++ docs/deploy.rst | 4 + docs/docker_ec2.rst | 186 +++++++++++ docs/index.rst | 26 ++ docs/install.rst | 4 + docs/make.bat | 190 +++++++++++ env.example | 40 +++ letsbook/__init__.py | 2 + letsbook/contrib/__init__.py | 5 + letsbook/contrib/sites/__init__.py | 5 + .../contrib/sites/migrations/0001_initial.py | 31 ++ .../migrations/0002_alter_domain_unique.py | 20 ++ .../0003_set_site_domain_and_name.py | 42 +++ letsbook/contrib/sites/migrations/__init__.py | 5 + letsbook/static/css/project.css | 21 ++ letsbook/static/fonts/.gitkeep | 0 letsbook/static/images/favicon.ico | Bin 0 -> 8348 bytes letsbook/static/js/project.js | 21 ++ .../static/sass/custom_bootstrap_vars.scss | 0 letsbook/static/sass/project.scss | 100 ++++++ letsbook/taskapp/__init__.py | 0 letsbook/taskapp/celery.py | 58 ++++ letsbook/templates/403_csrf.html | 9 + letsbook/templates/404.html | 9 + letsbook/templates/500.html | 13 + .../templates/account/account_inactive.html | 12 + letsbook/templates/account/base.html | 10 + letsbook/templates/account/email.html | 80 +++++ letsbook/templates/account/email_confirm.html | 32 ++ letsbook/templates/account/login.html | 48 +++ letsbook/templates/account/logout.html | 22 ++ .../templates/account/password_change.html | 17 + .../templates/account/password_reset.html | 26 ++ .../account/password_reset_done.html | 17 + .../account/password_reset_from_key.html | 25 ++ .../account/password_reset_from_key_done.html | 10 + letsbook/templates/account/password_set.html | 17 + letsbook/templates/account/signup.html | 23 ++ letsbook/templates/account/signup_closed.html | 12 + .../templates/account/verification_sent.html | 13 + .../account/verified_email_required.html | 24 ++ letsbook/templates/base.html | 106 ++++++ letsbook/templates/bootstrap4/field.html | 49 +++ .../bootstrap4/layout/field_errors_block.html | 7 + letsbook/templates/pages/about.html | 1 + letsbook/templates/pages/home.html | 1 + letsbook/templates/users/user_detail.html | 36 ++ letsbook/templates/users/user_form.html | 17 + letsbook/templates/users/user_list.html | 17 + letsbook/users/__init__.py | 0 letsbook/users/adapters.py | 13 + letsbook/users/admin.py | 39 +++ letsbook/users/apps.py | 13 + letsbook/users/migrations/0001_initial.py | 43 +++ letsbook/users/migrations/__init__.py | 0 letsbook/users/models.py | 19 ++ letsbook/users/tests/__init__.py | 0 letsbook/users/tests/factories.py | 11 + letsbook/users/tests/test_admin.py | 40 +++ letsbook/users/tests/test_models.py | 19 ++ letsbook/users/tests/test_urls.py | 51 +++ letsbook/users/tests/test_views.py | 64 ++++ letsbook/users/urls.py | 26 ++ letsbook/users/views.py | 45 +++ manage.py | 29 ++ pytest.ini | 3 + requirements.txt | 1 + requirements/base.txt | 55 ++++ requirements/local.txt | 19 ++ requirements/production.txt | 28 ++ requirements/test.txt | 14 + runtime.txt | 1 + setup.cfg | 7 + utility/install_os_dependencies.sh | 96 ++++++ utility/install_python_dependencies.sh | 40 +++ utility/requirements-jessie.apt | 23 ++ utility/requirements-trusty.apt | 23 ++ utility/requirements-xenial.apt | 23 ++ 98 files changed, 3806 insertions(+) create mode 100644 .coveragerc create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 .pylintrc create mode 100644 .travis.yml create mode 100644 CONTRIBUTORS.txt create mode 100644 LICENSE create mode 100644 Procfile create mode 100644 README.rst create mode 100644 config/__init__.py create mode 100644 config/settings/__init__.py create mode 100644 config/settings/base.py create mode 100644 config/settings/local.py create mode 100644 config/settings/production.py create mode 100644 config/settings/test.py create mode 100644 config/urls.py create mode 100644 config/wsgi.py create mode 100644 docs/Makefile create mode 100644 docs/__init__.py create mode 100644 docs/conf.py create mode 100644 docs/deploy.rst create mode 100644 docs/docker_ec2.rst create mode 100644 docs/index.rst create mode 100644 docs/install.rst create mode 100644 docs/make.bat create mode 100644 env.example create mode 100644 letsbook/__init__.py create mode 100644 letsbook/contrib/__init__.py create mode 100644 letsbook/contrib/sites/__init__.py create mode 100644 letsbook/contrib/sites/migrations/0001_initial.py create mode 100644 letsbook/contrib/sites/migrations/0002_alter_domain_unique.py create mode 100644 letsbook/contrib/sites/migrations/0003_set_site_domain_and_name.py create mode 100644 letsbook/contrib/sites/migrations/__init__.py create mode 100644 letsbook/static/css/project.css create mode 100644 letsbook/static/fonts/.gitkeep create mode 100644 letsbook/static/images/favicon.ico create mode 100644 letsbook/static/js/project.js create mode 100644 letsbook/static/sass/custom_bootstrap_vars.scss create mode 100644 letsbook/static/sass/project.scss create mode 100644 letsbook/taskapp/__init__.py create mode 100644 letsbook/taskapp/celery.py create mode 100644 letsbook/templates/403_csrf.html create mode 100644 letsbook/templates/404.html create mode 100644 letsbook/templates/500.html create mode 100644 letsbook/templates/account/account_inactive.html create mode 100644 letsbook/templates/account/base.html create mode 100644 letsbook/templates/account/email.html create mode 100644 letsbook/templates/account/email_confirm.html create mode 100644 letsbook/templates/account/login.html create mode 100644 letsbook/templates/account/logout.html create mode 100644 letsbook/templates/account/password_change.html create mode 100644 letsbook/templates/account/password_reset.html create mode 100644 letsbook/templates/account/password_reset_done.html create mode 100644 letsbook/templates/account/password_reset_from_key.html create mode 100644 letsbook/templates/account/password_reset_from_key_done.html create mode 100644 letsbook/templates/account/password_set.html create mode 100644 letsbook/templates/account/signup.html create mode 100644 letsbook/templates/account/signup_closed.html create mode 100644 letsbook/templates/account/verification_sent.html create mode 100644 letsbook/templates/account/verified_email_required.html create mode 100644 letsbook/templates/base.html create mode 100644 letsbook/templates/bootstrap4/field.html create mode 100644 letsbook/templates/bootstrap4/layout/field_errors_block.html create mode 100644 letsbook/templates/pages/about.html create mode 100644 letsbook/templates/pages/home.html create mode 100644 letsbook/templates/users/user_detail.html create mode 100644 letsbook/templates/users/user_form.html create mode 100644 letsbook/templates/users/user_list.html create mode 100644 letsbook/users/__init__.py create mode 100644 letsbook/users/adapters.py create mode 100644 letsbook/users/admin.py create mode 100644 letsbook/users/apps.py create mode 100644 letsbook/users/migrations/0001_initial.py create mode 100644 letsbook/users/migrations/__init__.py create mode 100644 letsbook/users/models.py create mode 100644 letsbook/users/tests/__init__.py create mode 100644 letsbook/users/tests/factories.py create mode 100644 letsbook/users/tests/test_admin.py create mode 100644 letsbook/users/tests/test_models.py create mode 100644 letsbook/users/tests/test_urls.py create mode 100644 letsbook/users/tests/test_views.py create mode 100644 letsbook/users/urls.py create mode 100644 letsbook/users/views.py create mode 100755 manage.py create mode 100644 pytest.ini create mode 100644 requirements.txt create mode 100644 requirements/base.txt create mode 100644 requirements/local.txt create mode 100644 requirements/production.txt create mode 100644 requirements/test.txt create mode 100644 runtime.txt create mode 100644 setup.cfg create mode 100755 utility/install_os_dependencies.sh create mode 100755 utility/install_python_dependencies.sh create mode 100644 utility/requirements-jessie.apt create mode 100644 utility/requirements-trusty.apt create mode 100644 utility/requirements-xenial.apt diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000..5ef866a --- /dev/null +++ b/.coveragerc @@ -0,0 +1,5 @@ +[run] +include = letsbook/* +omit = *migrations*, *tests* +plugins = + django_coverage_plugin diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..9e7823f --- /dev/null +++ b/.editorconfig @@ -0,0 +1,33 @@ +# http://editorconfig.org + +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.{py,rst,ini}] +indent_style = space +indent_size = 4 + +[*.py] +line_length=120 +known_first_party=letsbook +multi_line_output=3 +default_section=THIRDPARTY + +[*.{html,css,scss,json,yml}] +indent_style = space +indent_size = 2 + +[*.md] +trim_trailing_whitespace = false + +[Makefile] +indent_style = tab + +[nginx.conf] +indent_style = space +indent_size = 2 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..176a458 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bbaaff3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,308 @@ +### Python template +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +staticfiles/ + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + + +### Node template +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Typescript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + + +### Linux template +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + + +### VisualStudioCode template +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + + + + + +### Windows template +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + + +### macOS template +# General +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + + +### SublimeText template +# Cache files for Sublime Text +*.tmlanguage.cache +*.tmPreferences.cache +*.stTheme.cache + +# Workspace files are user-specific +*.sublime-workspace + +# Project files should be checked into the repository, unless a significant +# proportion of contributors will probably not be using Sublime Text +# *.sublime-project + +# SFTP configuration file +sftp-config.json + +# Package control specific files +Package Control.last-run +Package Control.ca-list +Package Control.ca-bundle +Package Control.system-ca-bundle +Package Control.cache/ +Package Control.ca-certs/ +Package Control.merged-ca-bundle +Package Control.user-ca-bundle +oscrypto-ca-bundle.crt +bh_unicode_properties.cache + +# Sublime-github package stores a github token in this file +# https://packagecontrol.io/packages/sublime-github +GitHub.sublime-settings + + +### Vim template +# Swap +[._]*.s[a-v][a-z] +[._]*.sw[a-p] +[._]s[a-v][a-z] +[._]sw[a-p] + +# Session +Session.vim + +# Temporary +.netrwhist + +# Auto-generated tag files +tags + + +### VirtualEnv template +# Virtualenv +# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ +[Bb]in +[Ii]nclude +[Ll]ib +[Ll]ib64 +[Ll]ocal +[Ss]cripts +pyvenv.cfg +pip-selfcheck.json + + + + +letsbook/media/ + + diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..4bd6910 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,14 @@ +[MASTER] +load-plugins=pylint_common, pylint_django, pylint_celery + +[FORMAT] +max-line-length=120 + +[MESSAGES CONTROL] +disable=missing-docstring,invalid-name + +[DESIGN] +max-parents=13 + +[TYPECHECK] +generated-members=REQUEST,acl_users,aq_parent,"[a-zA-Z]+_set{1,2}",save,delete diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..216b870 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,11 @@ +sudo: true +before_install: + - sudo apt-get update -qq + - sudo apt-get install -qq build-essential gettext python-dev zlib1g-dev libpq-dev xvfb + - sudo apt-get install -qq libtiff4-dev libjpeg8-dev libfreetype6-dev liblcms1-dev libwebp-dev + - sudo apt-get install -qq graphviz-dev python-setuptools python3-dev python-virtualenv python-pip + - sudo apt-get install -qq firefox automake libtool libreadline6 libreadline6-dev libreadline-dev + - sudo apt-get install -qq libsqlite3-dev libxml2 libxml2-dev libssl-dev libbz2-dev wget curl llvm +language: python +python: + - "3.5" diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt new file mode 100644 index 0000000..08f7dcf --- /dev/null +++ b/CONTRIBUTORS.txt @@ -0,0 +1 @@ +Ibraheem diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..625c8f7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,10 @@ + +The MIT License (MIT) +Copyright (c) 2018, Ibraheem + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/Procfile b/Procfile new file mode 100644 index 0000000..e4832c8 --- /dev/null +++ b/Procfile @@ -0,0 +1,2 @@ +web: gunicorn config.wsgi:application +worker: celery worker --app=letsbook.taskapp --loglevel=info diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..946ed9c --- /dev/null +++ b/README.rst @@ -0,0 +1,110 @@ +Letsbook +======== + +ERP/CRM project + +.. image:: https://img.shields.io/badge/built%20with-Cookiecutter%20Django-ff69b4.svg + :target: https://github.com/pydanny/cookiecutter-django/ + :alt: Built with Cookiecutter Django + + +:License: MIT + + +Settings +-------- + +Moved to settings_. + +.. _settings: http://cookiecutter-django.readthedocs.io/en/latest/settings.html + +Basic Commands +-------------- + +Setting Up Your Users +^^^^^^^^^^^^^^^^^^^^^ + +* To create a **normal user account**, just go to Sign Up and fill out the form. Once you submit it, you'll see a "Verify Your E-mail Address" page. Go to your console to see a simulated email verification message. Copy the link into your browser. Now the user's email should be verified and ready to go. + +* To create an **superuser account**, use this command:: + + $ python manage.py createsuperuser + +For convenience, you can keep your normal user logged in on Chrome and your superuser logged in on Firefox (or similar), so that you can see how the site behaves for both kinds of users. + +Test coverage +^^^^^^^^^^^^^ + +To run the tests, check your test coverage, and generate an HTML coverage report:: + + $ coverage run manage.py test + $ coverage html + $ open htmlcov/index.html + +Running tests with py.test +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:: + + $ py.test + +Live reloading and Sass CSS compilation +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Moved to `Live reloading and SASS compilation`_. + +.. _`Live reloading and SASS compilation`: http://cookiecutter-django.readthedocs.io/en/latest/live-reloading-and-sass-compilation.html + + + +Celery +^^^^^^ + +This app comes with Celery. + +To run a celery worker: + +.. code-block:: bash + + cd letsbook + celery -A letsbook.taskapp worker -l info + +Please note: For Celery's import magic to work, it is important *where* the celery commands are run. If you are in the same folder with *manage.py*, you should be right. + + + + + +Sentry +^^^^^^ + +Sentry is an error logging aggregator service. You can sign up for a free account at https://sentry.io/signup/?code=cookiecutter or download and host it yourself. +The system is setup with reasonable defaults, including 404 logging and integration with the WSGI application. + +You must set the DSN url in production. + + +Deployment +---------- + +The following details how to deploy this application. + + +Heroku +^^^^^^ + +See detailed `cookiecutter-django Heroku documentation`_. + +.. _`cookiecutter-django Heroku documentation`: http://cookiecutter-django.readthedocs.io/en/latest/deployment-on-heroku.html + + + + +Custom Bootstrap Compilation +^^^^^^ + +To get automatic Bootstrap recompilation with variables of your choice, install bootstrap sass (`bower install bootstrap-sass`) and tweak your variables in `static/sass/custom_bootstrap_vars`. + +(You can find a list of available variables [in the bootstrap-sass source](https://github.com/twbs/bootstrap-sass/blob/master/assets/stylesheets/bootstrap/_variables.scss), or get explanations on them in the [Bootstrap docs](https://getbootstrap.com/customize/).) + + diff --git a/config/__init__.py b/config/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/config/settings/__init__.py b/config/settings/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/config/settings/base.py b/config/settings/base.py new file mode 100644 index 0000000..bc5b942 --- /dev/null +++ b/config/settings/base.py @@ -0,0 +1,306 @@ +""" +Base settings for Letsbook project. + +For more information on this file, see +https://docs.djangoproject.com/en/dev/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/dev/ref/settings/ +""" +from decouple import config +import environ + +ROOT_DIR = environ.Path(__file__) - 3 # (letsbook/config/settings/base.py - 3 = letsbook/) +APPS_DIR = ROOT_DIR.path('letsbook') + +# Load operating system environment variables and then prepare to use them +env = environ.Env() + +# .env file, should load only in development environment +READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False) + +if READ_DOT_ENV_FILE: + # Operating System Environment variables have precedence over variables defined in the .env file, + # that is to say variables from the .env files will only be used if not defined + # as environment variables. + env_file = str(ROOT_DIR.path('.env')) + print('Loading : {}'.format(env_file)) + env.read_env(env_file) + print('The .env file has been loaded. See base.py for more information') + +# APP CONFIGURATION +# ------------------------------------------------------------------------------ +DJANGO_APPS = [ + # Default Django apps: + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.sites', + 'django.contrib.messages', + 'django.contrib.staticfiles', + + # Useful template tags: + # 'django.contrib.humanize', + + # Admin + 'django.contrib.admin', +] +THIRD_PARTY_APPS = [ + 'crispy_forms', # Form layouts + 'allauth', # registration + 'allauth.account', # registration + 'allauth.socialaccount', # registration +] + +# Apps specific for this project go here. +LOCAL_APPS = [ + # custom users app + 'letsbook.users.apps.UsersConfig', + # Your stuff: custom apps go here +] + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps +INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS + +# MIDDLEWARE CONFIGURATION +# ------------------------------------------------------------------------------ +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', +] + +# MIGRATIONS CONFIGURATION +# ------------------------------------------------------------------------------ +MIGRATION_MODULES = { + 'sites': 'letsbook.contrib.sites.migrations' +} + +# DEBUG +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug +DEBUG = env.bool('DJANGO_DEBUG', False) + +# FIXTURE CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS +FIXTURE_DIRS = ( + str(APPS_DIR.path('fixtures')), +) + +# EMAIL CONFIGURATION +# ------------------------------------------------------------------------------ +EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend') + +# MANAGER CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins +ADMINS = [ + ("""Ibraheem""", 'kabaltech@gmail.com'), +] + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers +MANAGERS = ADMINS + +# DATABASE CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases +# Uses django-environ to accept uri format +# See: https://django-environ.readthedocs.io/en/latest/#supported-types +#DATABASES = { +# 'default': env.db('DATABASE_URL', default='postgres:///letsbook'), +# } +# DATABASES['default']['ATOMIC_REQUESTS'] = True + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'NAME': config('DATABASE_NAME'), + 'USER': config('DATABASE_USER'), + 'PASSWORD': config('DATABASE_PASSWORD'), + 'HOST': '127.0.0.1', + 'PORT': '5432', + }, + # 'extra': { + # 'ENGINE': 'django.db.backends.sqlite3', + # 'NAME': os.path.join(SITE_ROOT, 'database.sqlite') + # } +} + + + + + +# GENERAL CONFIGURATION +# ------------------------------------------------------------------------------ +# Local time zone for this installation. Choices can be found here: +# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name +# although not all choices may be available on all operating systems. +# In a Windows environment this must be set to your system time zone. +TIME_ZONE = 'America/Edmonton' + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code +LANGUAGE_CODE = 'en-us' + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id +SITE_ID = 1 + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n +USE_I18N = True + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n +USE_L10N = True + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz +USE_TZ = True + +# TEMPLATE CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#templates +TEMPLATES = [ + { + # See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs + 'DIRS': [ + str(APPS_DIR.path('templates')), + ], + 'OPTIONS': { + # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug + 'debug': DEBUG, + # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders + # https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types + 'loaders': [ + 'django.template.loaders.filesystem.Loader', + 'django.template.loaders.app_directories.Loader', + ], + # See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.template.context_processors.i18n', + 'django.template.context_processors.media', + 'django.template.context_processors.static', + 'django.template.context_processors.tz', + 'django.contrib.messages.context_processors.messages', + # Your stuff: custom template context processors go here + ], + }, + }, +] + +# See: http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs +CRISPY_TEMPLATE_PACK = 'bootstrap4' + +# STATIC FILE CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root +STATIC_ROOT = str(ROOT_DIR('staticfiles')) + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url +STATIC_URL = '/static/' + +# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS +STATICFILES_DIRS = [ + str(APPS_DIR.path('static')), +] + +# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders +STATICFILES_FINDERS = [ + 'django.contrib.staticfiles.finders.FileSystemFinder', + 'django.contrib.staticfiles.finders.AppDirectoriesFinder', +] + +# MEDIA CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root +MEDIA_ROOT = str(APPS_DIR('media')) + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url +MEDIA_URL = '/media/' + +# URL Configuration +# ------------------------------------------------------------------------------ +ROOT_URLCONF = 'config.urls' + +# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application +WSGI_APPLICATION = 'config.wsgi.application' + +# PASSWORD STORAGE SETTINGS +# ------------------------------------------------------------------------------ +# See https://docs.djangoproject.com/en/dev/topics/auth/passwords/#using-argon2-with-django +PASSWORD_HASHERS = [ + 'django.contrib.auth.hashers.Argon2PasswordHasher', + 'django.contrib.auth.hashers.PBKDF2PasswordHasher', + 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', + 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', + 'django.contrib.auth.hashers.BCryptPasswordHasher', +] + +# PASSWORD VALIDATION +# https://docs.djangoproject.com/en/dev/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', + }, +] + +# AUTHENTICATION CONFIGURATION +# ------------------------------------------------------------------------------ +AUTHENTICATION_BACKENDS = [ + 'django.contrib.auth.backends.ModelBackend', + 'allauth.account.auth_backends.AuthenticationBackend', +] + +# Some really nice defaults +ACCOUNT_AUTHENTICATION_METHOD = 'username' +ACCOUNT_EMAIL_REQUIRED = True +ACCOUNT_EMAIL_VERIFICATION = 'mandatory' + +ACCOUNT_ALLOW_REGISTRATION = env.bool('DJANGO_ACCOUNT_ALLOW_REGISTRATION', True) +ACCOUNT_ADAPTER = 'letsbook.users.adapters.AccountAdapter' +SOCIALACCOUNT_ADAPTER = 'letsbook.users.adapters.SocialAccountAdapter' + +# Custom user app defaults +# Select the correct user model +AUTH_USER_MODEL = 'users.User' +LOGIN_REDIRECT_URL = 'users:redirect' +LOGIN_URL = 'account_login' + +# SLUGLIFIER +AUTOSLUG_SLUGIFY_FUNCTION = 'slugify.slugify' + +########## CELERY +INSTALLED_APPS += ['letsbook.taskapp.celery.CeleryConfig'] +CELERY_BROKER_URL = env('CELERY_BROKER_URL', default='django://') +if CELERY_BROKER_URL == 'django://': + CELERY_RESULT_BACKEND = 'redis://' +else: + CELERY_RESULT_BACKEND = CELERY_BROKER_URL +########## END CELERY +# django-compressor +# ------------------------------------------------------------------------------ +INSTALLED_APPS += ['compressor'] +STATICFILES_FINDERS += ['compressor.finders.CompressorFinder'] + +# Location of root django.contrib.admin URL, use {% url 'admin:index' %} +ADMIN_URL = r'^admin/' + +# Your common stuff: Below this line define 3rd party library settings +# ------------------------------------------------------------------------------ diff --git a/config/settings/local.py b/config/settings/local.py new file mode 100644 index 0000000..7b84deb --- /dev/null +++ b/config/settings/local.py @@ -0,0 +1,72 @@ +""" +Local settings for Letsbook project. + +- Run in Debug mode + +- Use console backend for emails + +- Add Django Debug Toolbar +- Add django-extensions as app +""" + +from .base import * # noqa + +# DEBUG +# ------------------------------------------------------------------------------ +DEBUG = env.bool('DJANGO_DEBUG', default=True) +TEMPLATES[0]['OPTIONS']['debug'] = DEBUG + +# SECRET CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key +# Note: This key only used for development and testing. +SECRET_KEY = env('DJANGO_SECRET_KEY', default=',ug+{;xYok}._PwlC:>lPMIZ5X-kfPaV2+zLN}kunhK1_h8Z?%') + +# Mail settings +# ------------------------------------------------------------------------------ + +EMAIL_PORT = 1025 + +EMAIL_HOST = 'localhost' +EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', + default='django.core.mail.backends.console.EmailBackend') + + +# CACHING +# ------------------------------------------------------------------------------ +CACHES = { + 'default': { + 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', + 'LOCATION': '' + } +} + +# django-debug-toolbar +# ------------------------------------------------------------------------------ +MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware', ] +INSTALLED_APPS += ['debug_toolbar', ] + +INTERNAL_IPS = ['127.0.0.1', '10.0.2.2', ] + +DEBUG_TOOLBAR_CONFIG = { + 'DISABLE_PANELS': [ + 'debug_toolbar.panels.redirects.RedirectsPanel', + ], + 'SHOW_TEMPLATE_CONTEXT': True, +} + +# django-extensions +# ------------------------------------------------------------------------------ +INSTALLED_APPS += ['django_extensions', ] + +# TESTING +# ------------------------------------------------------------------------------ +TEST_RUNNER = 'django.test.runner.DiscoverRunner' + +########## CELERY +# In development, all tasks will be executed locally by blocking until the task returns +CELERY_ALWAYS_EAGER = True +########## END CELERY + +# Your local stuff: Below this line define 3rd party library settings +# ------------------------------------------------------------------------------ diff --git a/config/settings/production.py b/config/settings/production.py new file mode 100644 index 0000000..4cb56c5 --- /dev/null +++ b/config/settings/production.py @@ -0,0 +1,237 @@ +""" +Production settings for Letsbook project. + + +- Use Amazon's S3 for storing static files and uploaded media +- Use mailgun to send emails +- Use Redis for cache + +- Use sentry for error logging + + +- Use opbeat for error reporting + +""" + + +import logging + + +from .base import * # noqa + +# SECRET CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key +# Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ +SECRET_KEY = env('DJANGO_SECRET_KEY') + + +# This ensures that Django will be able to detect a secure connection +# properly on Heroku. +SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') +# raven sentry client +# See https://docs.sentry.io/clients/python/integrations/django/ +INSTALLED_APPS += ['raven.contrib.django.raven_compat', ] +RAVEN_MIDDLEWARE = ['raven.contrib.django.raven_compat.middleware.SentryResponseErrorIdMiddleware'] +MIDDLEWARE = RAVEN_MIDDLEWARE + MIDDLEWARE +# opbeat integration +# See https://opbeat.com/languages/django/ +INSTALLED_APPS += ['opbeat.contrib.django', ] +OPBEAT = { + 'ORGANIZATION_ID': env('DJANGO_OPBEAT_ORGANIZATION_ID'), + 'APP_ID': env('DJANGO_OPBEAT_APP_ID'), + 'SECRET_TOKEN': env('DJANGO_OPBEAT_SECRET_TOKEN') +} +MIDDLEWARE = ['opbeat.contrib.django.middleware.OpbeatAPMMiddleware', ] + MIDDLEWARE + + +# SECURITY CONFIGURATION +# ------------------------------------------------------------------------------ +# See https://docs.djangoproject.com/en/dev/ref/middleware/#module-django.middleware.security +# and https://docs.djangoproject.com/en/dev/howto/deployment/checklist/#run-manage-py-check-deploy + +# set this to 60 seconds and then to 518400 when you can prove it works +SECURE_HSTS_SECONDS = 60 +SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool( + 'DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True) +SECURE_CONTENT_TYPE_NOSNIFF = env.bool( + 'DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True) +SECURE_BROWSER_XSS_FILTER = True +SESSION_COOKIE_SECURE = True +SESSION_COOKIE_HTTPONLY = True +SECURE_SSL_REDIRECT = env.bool('DJANGO_SECURE_SSL_REDIRECT', default=True) +CSRF_COOKIE_SECURE = True +CSRF_COOKIE_HTTPONLY = True +X_FRAME_OPTIONS = 'DENY' + +# SITE CONFIGURATION +# ------------------------------------------------------------------------------ +# Hosts/domain names that are valid for this site +# See https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts +ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['letsbook.com', ]) +# END SITE CONFIGURATION + +INSTALLED_APPS += ['gunicorn', ] + + +# STORAGE CONFIGURATION +# ------------------------------------------------------------------------------ +# Uploaded Media Files +# ------------------------ +# See: http://django-storages.readthedocs.io/en/latest/index.html +INSTALLED_APPS += ['storages', ] + +AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID') +AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY') +AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME') +AWS_AUTO_CREATE_BUCKET = True +AWS_QUERYSTRING_AUTH = False + +# AWS cache settings, don't change unless you know what you're doing: +AWS_EXPIRY = 60 * 60 * 24 * 7 + +# TODO See: https://github.com/jschneier/django-storages/issues/47 +# Revert the following and use str after the above-mentioned bug is fixed in +# either django-storage-redux or boto +control = 'max-age=%d, s-maxage=%d, must-revalidate' % (AWS_EXPIRY, AWS_EXPIRY) +AWS_HEADERS = { + 'Cache-Control': bytes(control, encoding='latin-1') +} + +# URL that handles the media served from MEDIA_ROOT, used for managing +# stored files. + +# See:http://stackoverflow.com/questions/10390244/ +from storages.backends.s3boto3 import S3Boto3Storage +StaticRootS3BotoStorage = lambda: S3Boto3Storage(location='static') # noqa +MediaRootS3BotoStorage = lambda: S3Boto3Storage(location='media', file_overwrite=False) # noqa +DEFAULT_FILE_STORAGE = 'config.settings.production.MediaRootS3BotoStorage' + +MEDIA_URL = 'https://s3.amazonaws.com/%s/media/' % AWS_STORAGE_BUCKET_NAME + +# Static Assets +# ------------------------ + +STATIC_URL = 'https://s3.amazonaws.com/%s/static/' % AWS_STORAGE_BUCKET_NAME +STATICFILES_STORAGE = 'config.settings.production.StaticRootS3BotoStorage' +# See: https://github.com/antonagestam/collectfast +# For Django 1.7+, 'collectfast' should come before +# 'django.contrib.staticfiles' +AWS_PRELOAD_METADATA = True +INSTALLED_APPS = ['collectfast', ] + INSTALLED_APPS +# COMPRESSOR +# ------------------------------------------------------------------------------ +COMPRESS_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' +COMPRESS_URL = STATIC_URL +COMPRESS_ENABLED = env.bool('COMPRESS_ENABLED', default=True) +# EMAIL +# ------------------------------------------------------------------------------ +DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL', + default='Letsbook ') +EMAIL_SUBJECT_PREFIX = env('DJANGO_EMAIL_SUBJECT_PREFIX', default='[Letsbook]') +SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL) + +# Anymail with Mailgun +INSTALLED_APPS += ['anymail', ] +ANYMAIL = { + 'MAILGUN_API_KEY': env('DJANGO_MAILGUN_API_KEY'), + 'MAILGUN_SENDER_DOMAIN': env('MAILGUN_SENDER_DOMAIN') +} +EMAIL_BACKEND = 'anymail.backends.mailgun.EmailBackend' + +# TEMPLATE CONFIGURATION +# ------------------------------------------------------------------------------ +# See: +# https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader +TEMPLATES[0]['OPTIONS']['loaders'] = [ + ('django.template.loaders.cached.Loader', [ + 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]), +] + +# DATABASE CONFIGURATION +# ------------------------------------------------------------------------------ + +# Use the Heroku-style specification +# Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ +DATABASES['default'] = env.db('DATABASE_URL') +DATABASES['default']['CONN_MAX_AGE'] = env.int('CONN_MAX_AGE', default=60) + +# CACHING +# ------------------------------------------------------------------------------ + +REDIS_LOCATION = '{0}/{1}'.format(env('REDIS_URL', default='redis://127.0.0.1:6379'), 0) +# Heroku URL does not pass the DB number, so we parse it in +CACHES = { + 'default': { + 'BACKEND': 'django_redis.cache.RedisCache', + 'LOCATION': REDIS_LOCATION, + 'OPTIONS': { + 'CLIENT_CLASS': 'django_redis.client.DefaultClient', + 'IGNORE_EXCEPTIONS': True, # mimics memcache behavior. + # http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior + } + } +} + + +# Sentry Configuration +SENTRY_DSN = env('DJANGO_SENTRY_DSN') +SENTRY_CLIENT = env('DJANGO_SENTRY_CLIENT', default='raven.contrib.django.raven_compat.DjangoClient') +LOGGING = { + 'version': 1, + 'disable_existing_loggers': True, + 'root': { + 'level': 'WARNING', + 'handlers': ['sentry', ], + }, + 'formatters': { + 'verbose': { + 'format': '%(levelname)s %(asctime)s %(module)s ' + '%(process)d %(thread)d %(message)s' + }, + }, + 'handlers': { + 'sentry': { + 'level': 'ERROR', + 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', + }, + 'console': { + 'level': 'DEBUG', + 'class': 'logging.StreamHandler', + 'formatter': 'verbose' + } + }, + 'loggers': { + 'django.db.backends': { + 'level': 'ERROR', + 'handlers': ['console', ], + 'propagate': False, + }, + 'raven': { + 'level': 'DEBUG', + 'handlers': ['console', ], + 'propagate': False, + }, + 'sentry.errors': { + 'level': 'DEBUG', + 'handlers': ['console', ], + 'propagate': False, + }, + 'django.security.DisallowedHost': { + 'level': 'ERROR', + 'handlers': ['console', 'sentry', ], + 'propagate': False, + }, + }, +} +SENTRY_CELERY_LOGLEVEL = env.int('DJANGO_SENTRY_LOG_LEVEL', logging.INFO) +RAVEN_CONFIG = { + 'CELERY_LOGLEVEL': env.int('DJANGO_SENTRY_LOG_LEVEL', logging.INFO), + 'DSN': SENTRY_DSN +} + +# Custom Admin URL, use {% url 'admin:index' %} +ADMIN_URL = env('DJANGO_ADMIN_URL') + +# Your production stuff: Below this line define 3rd party library settings +# ------------------------------------------------------------------------------ diff --git a/config/settings/test.py b/config/settings/test.py new file mode 100644 index 0000000..e865c66 --- /dev/null +++ b/config/settings/test.py @@ -0,0 +1,61 @@ +""" +Test settings for Letsbook project. + +- Used to run tests fast on the continuous integration server and locally +""" + +from .base import * # noqa + + +# DEBUG +# ------------------------------------------------------------------------------ +# Turn debug off so tests run faster +DEBUG = False +TEMPLATES[0]['OPTIONS']['debug'] = False + +# SECRET CONFIGURATION +# ------------------------------------------------------------------------------ +# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key +# Note: This key only used for development and testing. +SECRET_KEY = env('DJANGO_SECRET_KEY', default='CHANGEME!!!') + +# Mail settings +# ------------------------------------------------------------------------------ +EMAIL_HOST = 'localhost' +EMAIL_PORT = 1025 + +# In-memory email backend stores messages in django.core.mail.outbox +# for unit testing purposes +EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend' + +# CACHING +# ------------------------------------------------------------------------------ +# Speed advantages of in-memory caching without having to run Memcached +CACHES = { + 'default': { + 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', + 'LOCATION': '' + } +} + +# TESTING +# ------------------------------------------------------------------------------ +TEST_RUNNER = 'django.test.runner.DiscoverRunner' + + +# PASSWORD HASHING +# ------------------------------------------------------------------------------ +# Use fast password hasher so tests run faster +PASSWORD_HASHERS = [ + 'django.contrib.auth.hashers.MD5PasswordHasher', +] + +# TEMPLATE LOADERS +# ------------------------------------------------------------------------------ +# Keep templates in memory so tests run faster +TEMPLATES[0]['OPTIONS']['loaders'] = [ + ['django.template.loaders.cached.Loader', [ + 'django.template.loaders.filesystem.Loader', + 'django.template.loaders.app_directories.Loader', + ], ], +] diff --git a/config/urls.py b/config/urls.py new file mode 100644 index 0000000..1545dbc --- /dev/null +++ b/config/urls.py @@ -0,0 +1,37 @@ +from django.conf import settings +from django.conf.urls import include, url +from django.conf.urls.static import static +from django.contrib import admin +from django.views.generic import TemplateView +from django.views import defaults as default_views + +urlpatterns = [ + url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'), + url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'), + + # Django Admin, use {% url 'admin:index' %} + url(settings.ADMIN_URL, admin.site.urls), + + # User management + url(r'^users/', include('letsbook.users.urls', namespace='users')), + url(r'^accounts/', include('allauth.urls')), + + # Your stuff: custom urls includes go here + + +] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + +if settings.DEBUG: + # This allows the error pages to be debugged during development, just visit + # these url in browser to see how these error pages look like. + urlpatterns += [ + url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}), + url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception('Permission Denied')}), + url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}), + url(r'^500/$', default_views.server_error), + ] + if 'debug_toolbar' in settings.INSTALLED_APPS: + import debug_toolbar + urlpatterns = [ + url(r'^__debug__/', include(debug_toolbar.urls)), + ] + urlpatterns diff --git a/config/wsgi.py b/config/wsgi.py new file mode 100644 index 0000000..eee5ed0 --- /dev/null +++ b/config/wsgi.py @@ -0,0 +1,43 @@ +""" +WSGI config for Letsbook project. + +This module contains the WSGI application used by Django's development server +and any production WSGI deployments. It should expose a module-level variable +named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover +this application via the ``WSGI_APPLICATION`` setting. + +Usually you will have the standard Django WSGI application here, but it also +might make sense to replace the whole Django WSGI application with a custom one +that later delegates to the Django one. For example, you could introduce WSGI +middleware here, or combine a Django application with an application of another +framework. + +""" +import os +import sys + +from django.core.wsgi import get_wsgi_application + +# This allows easy placement of apps within the interior +# letsbook directory. +app_path = os.path.dirname(os.path.abspath(__file__)).replace('/config', '') +sys.path.append(os.path.join(app_path, 'letsbook')) + +if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production': + from raven.contrib.django.raven_compat.middleware.wsgi import Sentry + +# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks +# if running multiple sites in the same mod_wsgi process. To fix this, use +# mod_wsgi daemon mode with each site in its own daemon process, or use +# os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.production" +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") + +# This application object is used by any WSGI server configured to use this +# file. This includes Django's development server, if the WSGI_APPLICATION +# setting points here. +application = get_wsgi_application() +if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production': + application = Sentry(application) +# Apply WSGI middleware here. +# from helloworld.wsgi import HelloWorldApplication +# application = HelloWorldApplication(application) diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..fcc45f5 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,153 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/letsbook.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/letsbook.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/letsbook" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/letsbook" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/docs/__init__.py b/docs/__init__.py new file mode 100644 index 0000000..8772c82 --- /dev/null +++ b/docs/__init__.py @@ -0,0 +1 @@ +# Included so that Django's startproject comment runs against the docs directory diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..3d9ba73 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,243 @@ +# Letsbook documentation build configuration file, created by +# sphinx-quickstart. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import os +import sys + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'Letsbook' +copyright = """2018, Ibraheem""" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.1' +# The full version, including alpha/beta/rc tags. +release = '0.1' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'letsbookdoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # 'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', + 'letsbook.tex', + 'Letsbook Documentation', + """Ibraheem""", 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'letsbook', 'Letsbook Documentation', + ["""Ibraheem"""], 1) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'letsbook', 'Letsbook Documentation', + """Ibraheem""", 'Letsbook', + """ERP/CRM project""", 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' diff --git a/docs/deploy.rst b/docs/deploy.rst new file mode 100644 index 0000000..1e642c7 --- /dev/null +++ b/docs/deploy.rst @@ -0,0 +1,4 @@ +Deploy +======== + +This is where you describe how the project is deployed in production. diff --git a/docs/docker_ec2.rst b/docs/docker_ec2.rst new file mode 100644 index 0000000..3e43ed7 --- /dev/null +++ b/docs/docker_ec2.rst @@ -0,0 +1,186 @@ +Developing with Docker +====================== + +You can develop your application in a `Docker`_ container for simpler deployment onto bare Linux machines later. This instruction assumes an `Amazon Web Services`_ EC2 instance, but it should work on any machine with Docker > 1.3 and `Docker compose`_ installed. + +.. _Docker: https://www.docker.com/ +.. _Amazon Web Services: http://aws.amazon.com/ +.. _Docker compose: https://docs.docker.com/compose/ + +Setting up +^^^^^^^^^^ + +Docker encourages running one container for each process. This might mean one container for your web server, one for Django application and a third for your database. Once you're happy composing containers in this way you can easily add more, such as a `Redis`_ cache. + +.. _Redis: http://redis.io/ + +The Docker compose tool (previously known as `fig`_) makes linking these containers easy. An example set up for your Cookiecutter Django project might look like this: + +.. _fig: http://www.fig.sh/ + +:: + + webapp/ # Your cookiecutter project would be in here + Dockerfile + ... + database/ + Dockerfile + ... + webserver/ + Dockerfile + ... + production.yml + +Each component of your application would get its own `Dockerfile`_. The rest of this example assumes you are using the `base postgres image`_ for your database. Your database settings in `config/base.py` might then look something like: + +.. _Dockerfile: https://docs.docker.com/reference/builder/ +.. _base postgres image: https://registry.hub.docker.com/_/postgres/ + +.. code-block:: python + + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'NAME': 'postgres', + 'USER': 'postgres', + 'HOST': 'database', + 'PORT': 5432, + } + } + +The `Docker compose documentation`_ explains in detail what you can accomplish in the `production.yml` file, but an example configuration might look like this: + +.. _Docker compose documentation: https://docs.docker.com/compose/#compose-documentation + +.. code-block:: yaml + + database: + build: database + webapp: + build: webapp: + command: /usr/bin/python3.4 manage.py runserver 0.0.0.0:8000 # dev setting + # command: gunicorn -b 0.0.0.0:8000 wsgi:application # production setting + volumes: + - webapp/your_project_name:/path/to/container/workdir/ + links: + - database + webserver: + build: webserver + ports: + - "80:80" + - "443:443" + links: + - webapp + +We'll ignore the webserver for now (you'll want to comment that part out while we do). A working Dockerfile to run your cookiecutter application might look like this: + +:: + + FROM ubuntu:14.04 + ENV REFRESHED_AT 2015-01-13 + + # update packages and prepare to build software + RUN ["apt-get", "update"] + RUN ["apt-get", "-y", "install", "build-essential", "vim", "git", "curl"] + RUN ["locale-gen", "en_GB.UTF-8"] + + # install latest python + RUN ["apt-get", "-y", "build-dep", "python3-dev", "python3-imaging"] + RUN ["apt-get", "-y", "install", "python3-dev", "python3-imaging", "python3-pip"] + + # prepare postgreSQL support + RUN ["apt-get", "-y", "build-dep", "python3-psycopg2"] + + # move into our working directory + # ADD must be after chown see http://stackoverflow.com/a/26145444/1281947 + RUN ["groupadd", "python"] + RUN ["useradd", "python", "-s", "/bin/bash", "-m", "-g", "python", "-G", "python"] + ENV HOME /home/python + WORKDIR /home/python + RUN ["chown", "-R", "python:python", "/home/python"] + ADD ./ /home/python + + # manage requirements + ENV REQUIREMENTS_REFRESHED_AT 2015-02-25 + RUN ["pip3", "install", "-r", "requirements.txt"] + + # uncomment the line below to use container as a non-root user + USER python:python + +Running `sudo docker-compose -f production.yml build` will follow the instructions in your `production.yml` file and build the database container, then your webapp, before mounting your cookiecutter project files as a volume in the webapp container and linking to the database. Our example yaml file runs in development mode but changing it to production mode is as simple as commenting out the line using `runserver` and uncommenting the line using `gunicorn`. + +Both are set to run on port `0.0.0.0:8000`, which is where the Docker daemon will discover it. You can now run `sudo docker-compose -f production.yml up` and browse to `localhost:8000` to see your application running. + +Deployment +^^^^^^^^^^ + +You'll need a webserver container for deployment. An example setup for `Nginx`_ might look like this: + +.. _Nginx: http://wiki.nginx.org/Main + +:: + + FROM ubuntu:14.04 + ENV REFRESHED_AT 2015-02-11 + + # get the nginx package and set it up + RUN ["apt-get", "update"] + RUN ["apt-get", "-y", "install", "nginx"] + + # forward request and error logs to docker log collector + RUN ln -sf /dev/stdout /var/log/nginx/access.log + RUN ln -sf /dev/stderr /var/log/nginx/error.log + VOLUME ["/var/cache/nginx"] + EXPOSE 80 443 + + # load nginx conf + ADD ./site.conf /etc/nginx/sites-available/your_cookiecutter_project + RUN ["ln", "-s", "/etc/nginx/sites-available/your_cookiecutter_project", "/etc/nginx/sites-enabled/your_cookiecutter_project"] + RUN ["rm", "-rf", "/etc/nginx/sites-available/default"] + + #start the server + CMD ["nginx", "-g", "daemon off;"] + +That Dockerfile assumes you have an Nginx conf file named `site.conf` in the same directory as the webserver Dockerfile. A very basic example, which forwards traffic onto the development server or gunicorn for processing, would look like this: + +:: + + # see http://serverfault.com/questions/577370/how-can-i-use-environment-variables-in-nginx-conf#comment730384_577370 + upstream localhost { + server webapp_1:8000; + } + server { + location / { + proxy_pass http://localhost; + } + } + +Running `sudo docker-compose -f production.yml build webserver` will build your server container. Running `sudo docker-compose -f production.yml up` will now expose your application directly on `localhost` (no need to specify the port number). + +Building and running your app on EC2 +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +All you now need to do to run your app in production is: + +* Create an empty EC2 Linux instance (any Linux machine should do). + +* Install your preferred source control solution, Docker and Docker compose on the news instance. + +* Pull in your code from source control. The root directory should be the one with your `production.yml` file in it. + +* Run `sudo docker-compose -f production.yml build` and `sudo docker-compose -f production.yml up`. + +* Assign an `Elastic IP address`_ to your new machine. + +.. _Elastic IP address: https://aws.amazon.com/articles/1346 + +* Point your domain name to the elastic IP. + +**Be careful with Elastic IPs** because, on the AWS free tier, if you assign one and then stop the machine you will incur charges while the machine is down (presumably because you're preventing them allocating the IP to someone else). + +Security advisory +^^^^^^^^^^^^^^^^^ + +The setup described in this instruction will get you up-and-running but it hasn't been audited for security. If you are running your own setup like this it is always advisable to, at a minimum, examine your application with a tool like `OWASP ZAP`_ to see what security holes you might be leaving open. + +.. _OWASP ZAP: https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..95615dc --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,26 @@ +.. Letsbook documentation master file, created by + sphinx-quickstart. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to Letsbook's documentation! +==================================================================== + +Contents: + +.. toctree:: + :maxdepth: 2 + + install + deploy + docker_ec2 + tests + + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/install.rst b/docs/install.rst new file mode 100644 index 0000000..1bc0333 --- /dev/null +++ b/docs/install.rst @@ -0,0 +1,4 @@ +Install +========= + +This is where you write how to get a new laptop to run this project. diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..c4292d2 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,190 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\letsbook.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\letsbook.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +:end diff --git a/env.example b/env.example new file mode 100644 index 0000000..bba7300 --- /dev/null +++ b/env.example @@ -0,0 +1,40 @@ + +# PostgreSQL +POSTGRES_PASSWORD=mysecretpass +POSTGRES_USER=postgresuser +CONN_MAX_AGE= + +# Domain name, used by caddy +DOMAIN_NAME=letsbook.com + +# General settings +# DJANGO_READ_DOT_ENV_FILE=True +DJANGO_ADMIN_URL= +DJANGO_SETTINGS_MODULE=config.settings.production +DJANGO_SECRET_KEY==9h?vgSKqN,pGx9&%|7J#{#e;nB#hrS:)BNt~)aWf.g$D3kMS} +DJANGO_ALLOWED_HOSTS=.letsbook.com + +# AWS Settings +DJANGO_AWS_ACCESS_KEY_ID= +DJANGO_AWS_SECRET_ACCESS_KEY= +DJANGO_AWS_STORAGE_BUCKET_NAME= + +# Used with email +DJANGO_MAILGUN_API_KEY= +DJANGO_SERVER_EMAIL= +MAILGUN_SENDER_DOMAIN= + +# Security! Better to use DNS for this task, but you can use redirect +DJANGO_SECURE_SSL_REDIRECT=False + +# django-allauth +DJANGO_ACCOUNT_ALLOW_REGISTRATION=True +# Sentry +DJANGO_SENTRY_DSN= + +DJANGO_OPBEAT_ORGANIZATION_ID= +DJANGO_OPBEAT_APP_ID= +DJANGO_OPBEAT_SECRET_TOKEN= + +COMPRESS_ENABLED= + diff --git a/letsbook/__init__.py b/letsbook/__init__.py new file mode 100644 index 0000000..e2fe6d6 --- /dev/null +++ b/letsbook/__init__.py @@ -0,0 +1,2 @@ +__version__ = '1.0.0' +__version_info__ = tuple([int(num) if num.isdigit() else num for num in __version__.replace('-', '.', 1).split('.')]) diff --git a/letsbook/contrib/__init__.py b/letsbook/contrib/__init__.py new file mode 100644 index 0000000..1c7ecc8 --- /dev/null +++ b/letsbook/contrib/__init__.py @@ -0,0 +1,5 @@ +""" +To understand why this file is here, please read: + +http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django +""" diff --git a/letsbook/contrib/sites/__init__.py b/letsbook/contrib/sites/__init__.py new file mode 100644 index 0000000..1c7ecc8 --- /dev/null +++ b/letsbook/contrib/sites/__init__.py @@ -0,0 +1,5 @@ +""" +To understand why this file is here, please read: + +http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django +""" diff --git a/letsbook/contrib/sites/migrations/0001_initial.py b/letsbook/contrib/sites/migrations/0001_initial.py new file mode 100644 index 0000000..a763986 --- /dev/null +++ b/letsbook/contrib/sites/migrations/0001_initial.py @@ -0,0 +1,31 @@ +import django.contrib.sites.models +from django.contrib.sites.models import _simple_domain_name_validator +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [] + + operations = [ + migrations.CreateModel( + name='Site', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('domain', models.CharField( + max_length=100, verbose_name='domain name', validators=[_simple_domain_name_validator] + )), + ('name', models.CharField(max_length=50, verbose_name='display name')), + ], + options={ + 'ordering': ('domain',), + 'db_table': 'django_site', + 'verbose_name': 'site', + 'verbose_name_plural': 'sites', + }, + bases=(models.Model,), + managers=[ + ('objects', django.contrib.sites.models.SiteManager()), + ], + ), + ] diff --git a/letsbook/contrib/sites/migrations/0002_alter_domain_unique.py b/letsbook/contrib/sites/migrations/0002_alter_domain_unique.py new file mode 100644 index 0000000..6a26ebc --- /dev/null +++ b/letsbook/contrib/sites/migrations/0002_alter_domain_unique.py @@ -0,0 +1,20 @@ +import django.contrib.sites.models +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('sites', '0001_initial'), + ] + + operations = [ + migrations.AlterField( + model_name='site', + name='domain', + field=models.CharField( + max_length=100, unique=True, validators=[django.contrib.sites.models._simple_domain_name_validator], + verbose_name='domain name' + ), + ), + ] diff --git a/letsbook/contrib/sites/migrations/0003_set_site_domain_and_name.py b/letsbook/contrib/sites/migrations/0003_set_site_domain_and_name.py new file mode 100644 index 0000000..9714499 --- /dev/null +++ b/letsbook/contrib/sites/migrations/0003_set_site_domain_and_name.py @@ -0,0 +1,42 @@ +""" +To understand why this file is here, please read: + +http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django +""" +from django.conf import settings +from django.db import migrations + + +def update_site_forward(apps, schema_editor): + """Set site domain and name.""" + Site = apps.get_model('sites', 'Site') + Site.objects.update_or_create( + id=settings.SITE_ID, + defaults={ + 'domain': 'letsbook.com', + 'name': 'Letsbook' + } + ) + + +def update_site_backward(apps, schema_editor): + """Revert site domain and name to default.""" + Site = apps.get_model('sites', 'Site') + Site.objects.update_or_create( + id=settings.SITE_ID, + defaults={ + 'domain': 'example.com', + 'name': 'example.com' + } + ) + + +class Migration(migrations.Migration): + + dependencies = [ + ('sites', '0002_alter_domain_unique'), + ] + + operations = [ + migrations.RunPython(update_site_forward, update_site_backward), + ] diff --git a/letsbook/contrib/sites/migrations/__init__.py b/letsbook/contrib/sites/migrations/__init__.py new file mode 100644 index 0000000..1c7ecc8 --- /dev/null +++ b/letsbook/contrib/sites/migrations/__init__.py @@ -0,0 +1,5 @@ +""" +To understand why this file is here, please read: + +http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django +""" diff --git a/letsbook/static/css/project.css b/letsbook/static/css/project.css new file mode 100644 index 0000000..a7725c9 --- /dev/null +++ b/letsbook/static/css/project.css @@ -0,0 +1,21 @@ +/* These styles are generated from project.scss. */ + +.alert-debug { + color: black; + background-color: white; + border-color: #d6e9c6; +} + +.alert-error { + color: #b94a48; + background-color: #f2dede; + border-color: #eed3d7; +} + +/* Display django-debug-toolbar. + See https://github.com/django-debug-toolbar/django-debug-toolbar/issues/742 + and https://github.com/pydanny/cookiecutter-django/issues/317 +*/ +[hidden][style="display: block;"] { + display: block !important; +} diff --git a/letsbook/static/fonts/.gitkeep b/letsbook/static/fonts/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/letsbook/static/images/favicon.ico b/letsbook/static/images/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..e1c1dd1a32a3a077c41a21e52bc7fb5ac90d3afb GIT binary patch literal 8348 zcmeHLX-gGh6rQ3V&`92%;lcmGu`Jl^WK@OV`^XKh08PZoaH%l?rdiiWq>kJ2@6vM zhAH8L6=kTRD1!xR`-2o^hS&}loN!U1#gF+=YxEq~uqf5#iBw%p0;w;5ehm+6a!sSu zh;X+$+}oF$X1Q6DwS~>Y_Hpw^(&QvJO<5ZCPrn5laNp%s{B3x1hf%*?eW>oS{<{4s^u_yG zpDyG!_iV#~G=q<~slG@0Sx47XXQ%O;HY7ILVf}B-)R$6GV^A78)t0tN9`tu3r9Z+xM?NgUd8geu=c`0?r;-KR&IQjKs zSB#VCpg8CPW&M}$sth@H=VS%t;23!!j};F)bb;W3EkA!4QmCsY_p81^TK0{;$g>e1Hl998^0M+r0-7ZSN+l_cMSRuEALTE@|d6+3{GMP^;_|<yhubb{FF1IPgH|0>SH%pC!c)uFI)H z?jv4y0uO{P5WE>~I<$r!RFo0lN4r{xm;Jy4p$h~b3S*a#)$Z*nI}&Kc_C+*zZHz1v zIR8TBVH7Y?Mp~ zofpsr+SP@>EX4e*bQ{nAUYtKrQ&-5d4j;FF{^-^Dt2^5I`HSb!|22PN26n3>hKPOy zW2D*A*v+c{bFKCwozbB{dObp~e&1Nxrj<4Ih4~w)M`nl08o}Wq2 z#Jt(k+M>+}JY(=2gm(gdUq)^@e%tX(F)RBtotnB2^y>YKz-5eg_qO&n%lJ1nuQmTY zxmyE1NWjl1EGvD?Z|n;neT;sa?Q;Ef-#%$BYxXAhD4xF+@M>*qrR!x^sPN98|BX4; z!$NJcKF`^C7f(<_vlp%b>`pxL^8Y<&?KFx{n_!5C9VqLA*CP@zhXs2t#dmrAKu?d_ y^&_r5_e@uesG}CO*g!3o?-kB+I^cA`>44J#rvpw0oDMi0a5~_0!0Eu>4*Uj$LD0AW literal 0 HcmV?d00001 diff --git a/letsbook/static/js/project.js b/letsbook/static/js/project.js new file mode 100644 index 0000000..91ab9e2 --- /dev/null +++ b/letsbook/static/js/project.js @@ -0,0 +1,21 @@ +/* Project specific Javascript goes here. */ + +/* +Formatting hack to get around crispy-forms unfortunate hardcoding +in helpers.FormHelper: + + if template_pack == 'bootstrap4': + grid_colum_matcher = re.compile('\w*col-(xs|sm|md|lg|xl)-\d+\w*') + using_grid_layout = (grid_colum_matcher.match(self.label_class) or + grid_colum_matcher.match(self.field_class)) + if using_grid_layout: + items['using_grid_layout'] = True + +Issues with the above approach: + +1. Fragile: Assumes Bootstrap 4's API doesn't change (it does) +2. Unforgiving: Doesn't allow for any variation in template design +3. Really Unforgiving: No way to override this behavior +4. Undocumented: No mention in the documentation, or it's too hard for me to find +*/ +$('.form-group').removeClass('row'); diff --git a/letsbook/static/sass/custom_bootstrap_vars.scss b/letsbook/static/sass/custom_bootstrap_vars.scss new file mode 100644 index 0000000..e69de29 diff --git a/letsbook/static/sass/project.scss b/letsbook/static/sass/project.scss new file mode 100644 index 0000000..e30d4e1 --- /dev/null +++ b/letsbook/static/sass/project.scss @@ -0,0 +1,100 @@ + +@import "variables"; +@import "custom_bootstrap_vars"; +@import "mixins"; + +// Reset and dependencies +@import "normalize"; +@import "print"; +@import "glyphicons"; + +// Core CSS +@import "scaffolding"; +@import "type"; +@import "code"; +@import "grid"; +@import "tables"; +@import "forms"; +@import "buttons"; + +// Components +@import "component-animations"; +@import "dropdowns"; +@import "button-groups"; +@import "input-groups"; +@import "navs"; +@import "navbar"; +@import "breadcrumbs"; +@import "pagination"; +@import "pager"; +@import "labels"; +@import "badges"; +@import "jumbotron"; +@import "thumbnails"; +@import "alerts"; +@import "progress-bars"; +@import "media"; +@import "list-group"; +@import "panels"; +@import "responsive-embed"; +@import "wells"; +@import "close"; + +// Components w/ JavaScript +@import "modals"; +@import "tooltip"; +@import "popovers"; +@import "carousel"; + +// Utility classes +@import "utilities"; +@import "responsive-utilities"; + + + + +// project specific CSS goes here + +//////////////////////////////// + //Variables// +//////////////////////////////// + +// Alert colors + +$white: #fff; +$mint-green: #d6e9c6; +$black: #000; +$pink: #f2dede; +$dark-pink: #eed3d7; +$red: #b94a48; + +//////////////////////////////// + //Alerts// +//////////////////////////////// + +// bootstrap alert CSS, translated to the django-standard levels of +// debug, info, success, warning, error + +.alert-debug { + background-color: $white; + border-color: $mint-green; + color: $black; +} + +.alert-error { + background-color: $pink; + border-color: $dark-pink; + color: $red; +} + +//////////////////////////////// + //Django Toolbar// +//////////////////////////////// + +// Display django-debug-toolbar. +// See https://github.com/django-debug-toolbar/django-debug-toolbar/issues/742 +// and https://github.com/pydanny/cookiecutter-django/issues/317 + +[hidden][style="display: block;"] { + display: block !important; +} diff --git a/letsbook/taskapp/__init__.py b/letsbook/taskapp/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/letsbook/taskapp/celery.py b/letsbook/taskapp/celery.py new file mode 100644 index 0000000..674fa65 --- /dev/null +++ b/letsbook/taskapp/celery.py @@ -0,0 +1,58 @@ + +import os +from celery import Celery +from django.apps import apps, AppConfig +from django.conf import settings + + +if not settings.configured: + # set the default Django settings module for the 'celery' program. + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') # pragma: no cover + + +app = Celery('letsbook') + + +class CeleryConfig(AppConfig): + name = 'letsbook.taskapp' + verbose_name = 'Celery Config' + + def ready(self): + # Using a string here means the worker will not have to + # pickle the object when using Windows. + app.config_from_object('django.conf:settings') + installed_apps = [app_config.name for app_config in apps.get_app_configs()] + app.autodiscover_tasks(lambda: installed_apps, force=True) + + if hasattr(settings, 'RAVEN_CONFIG'): + # Celery signal registration + + from raven import Client as RavenClient + from raven.contrib.celery import register_signal as raven_register_signal + from raven.contrib.celery import register_logger_signal as raven_register_logger_signal + + + raven_client = RavenClient(dsn=settings.RAVEN_CONFIG['DSN']) + raven_register_logger_signal(raven_client) + raven_register_signal(raven_client) + + if hasattr(settings, 'OPBEAT'): + + from opbeat.contrib.django.models import client as opbeat_client + from opbeat.contrib.django.models import logger as opbeat_logger + from opbeat.contrib.django.models import register_handlers as opbeat_register_handlers + from opbeat.contrib.celery import register_signal as opbeat_register_signal + + + try: + opbeat_register_signal(opbeat_client) + except Exception as e: + opbeat_logger.exception('Failed installing celery hook: %s' % e) + + if 'opbeat.contrib.django' in settings.INSTALLED_APPS: + opbeat_register_handlers() + + +@app.task(bind=True) +def debug_task(self): + print('Request: {0!r}'.format(self.request)) # pragma: no cover diff --git a/letsbook/templates/403_csrf.html b/letsbook/templates/403_csrf.html new file mode 100644 index 0000000..77db8ae --- /dev/null +++ b/letsbook/templates/403_csrf.html @@ -0,0 +1,9 @@ +{% extends "base.html" %} + +{% block title %}Forbidden (403){% endblock %} + +{% block content %} +

Forbidden (403)

+ +

CSRF verification failed. Request aborted.

+{% endblock content %} diff --git a/letsbook/templates/404.html b/letsbook/templates/404.html new file mode 100644 index 0000000..98327cd --- /dev/null +++ b/letsbook/templates/404.html @@ -0,0 +1,9 @@ +{% extends "base.html" %} + +{% block title %}Page not found{% endblock %} + +{% block content %} +

Page not found

+ +

This is not the page you were looking for.

+{% endblock content %} diff --git a/letsbook/templates/500.html b/letsbook/templates/500.html new file mode 100644 index 0000000..21df606 --- /dev/null +++ b/letsbook/templates/500.html @@ -0,0 +1,13 @@ +{% extends "base.html" %} + +{% block title %}Server Error{% endblock %} + +{% block content %} +

Ooops!!! 500

+ +

Looks like something went wrong!

+ +

We track these errors automatically, but if the problem persists feel free to contact us. In the meantime, try refreshing.

+{% endblock content %} + + diff --git a/letsbook/templates/account/account_inactive.html b/letsbook/templates/account/account_inactive.html new file mode 100644 index 0000000..17c2157 --- /dev/null +++ b/letsbook/templates/account/account_inactive.html @@ -0,0 +1,12 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% trans "Account Inactive" %}{% endblock %} + +{% block inner %} +

{% trans "Account Inactive" %}

+ +

{% trans "This account is inactive." %}

+{% endblock %} + diff --git a/letsbook/templates/account/base.html b/letsbook/templates/account/base.html new file mode 100644 index 0000000..8e1f260 --- /dev/null +++ b/letsbook/templates/account/base.html @@ -0,0 +1,10 @@ +{% extends "base.html" %} +{% block title %}{% block head_title %}{% endblock head_title %}{% endblock title %} + +{% block content %} +
+
+ {% block inner %}{% endblock %} +
+
+{% endblock %} diff --git a/letsbook/templates/account/email.html b/letsbook/templates/account/email.html new file mode 100644 index 0000000..0dc8d14 --- /dev/null +++ b/letsbook/templates/account/email.html @@ -0,0 +1,80 @@ + +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Account" %}{% endblock %} + +{% block inner %} +

{% trans "E-mail Addresses" %}

+ +{% if user.emailaddress_set.all %} +

{% trans 'The following e-mail addresses are associated with your account:' %}

+ + + +{% else %} +

{% trans 'Warning:'%} {% trans "You currently do not have any e-mail address set up. You should really add an e-mail address so you can receive notifications, reset your password, etc." %}

+ +{% endif %} + + +

{% trans "Add E-mail Address" %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+ +{% endblock %} + + +{% block javascript %} +{{ block.super }} + +{% endblock %} + diff --git a/letsbook/templates/account/email_confirm.html b/letsbook/templates/account/email_confirm.html new file mode 100644 index 0000000..46c7812 --- /dev/null +++ b/letsbook/templates/account/email_confirm.html @@ -0,0 +1,32 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account %} + +{% block head_title %}{% trans "Confirm E-mail Address" %}{% endblock %} + + +{% block inner %} +

{% trans "Confirm E-mail Address" %}

+ +{% if confirmation %} + +{% user_display confirmation.email_address.user as user_display %} + +

{% blocktrans with confirmation.email_address.email as email %}Please confirm that {{ email }} is an e-mail address for user {{ user_display }}.{% endblocktrans %}

+ +
+{% csrf_token %} + +
+ +{% else %} + +{% url 'account_email' as email_url %} + +

{% blocktrans %}This e-mail confirmation link expired or is invalid. Please issue a new e-mail confirmation request.{% endblocktrans %}

+ +{% endif %} + +{% endblock %} + diff --git a/letsbook/templates/account/login.html b/letsbook/templates/account/login.html new file mode 100644 index 0000000..2cadea6 --- /dev/null +++ b/letsbook/templates/account/login.html @@ -0,0 +1,48 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account socialaccount %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Sign In" %}{% endblock %} + +{% block inner %} + +

{% trans "Sign In" %}

+ +{% get_providers as socialaccount_providers %} + +{% if socialaccount_providers %} +

{% blocktrans with site.name as site_name %}Please sign in with one +of your existing third party accounts. Or, sign up +for a {{ site_name }} account and sign in below:{% endblocktrans %}

+ +
+ +
    + {% include "socialaccount/snippets/provider_list.html" with process="login" %} +
+ + + +
+ +{% include "socialaccount/snippets/login_extra.html" %} + +{% else %} +

{% blocktrans %}If you have not created an account yet, then please +sign up first.{% endblocktrans %}

+{% endif %} + + + +{% endblock %} + diff --git a/letsbook/templates/account/logout.html b/letsbook/templates/account/logout.html new file mode 100644 index 0000000..8e2e675 --- /dev/null +++ b/letsbook/templates/account/logout.html @@ -0,0 +1,22 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% trans "Sign Out" %}{% endblock %} + +{% block inner %} +

{% trans "Sign Out" %}

+ +

{% trans 'Are you sure you want to sign out?' %}

+ +
+ {% csrf_token %} + {% if redirect_field_value %} + + {% endif %} + +
+ + +{% endblock %} + diff --git a/letsbook/templates/account/password_change.html b/letsbook/templates/account/password_change.html new file mode 100644 index 0000000..b72ca06 --- /dev/null +++ b/letsbook/templates/account/password_change.html @@ -0,0 +1,17 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Change Password" %}{% endblock %} + +{% block inner %} +

{% trans "Change Password" %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+{% endblock %} + diff --git a/letsbook/templates/account/password_reset.html b/letsbook/templates/account/password_reset.html new file mode 100644 index 0000000..845bbda --- /dev/null +++ b/letsbook/templates/account/password_reset.html @@ -0,0 +1,26 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Password Reset" %}{% endblock %} + +{% block inner %} + +

{% trans "Password Reset" %}

+ {% if user.is_authenticated %} + {% include "account/snippets/already_logged_in.html" %} + {% endif %} + +

{% trans "Forgotten your password? Enter your e-mail address below, and we'll send you an e-mail allowing you to reset it." %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+ +

{% blocktrans %}Please contact us if you have any trouble resetting your password.{% endblocktrans %}

+{% endblock %} + diff --git a/letsbook/templates/account/password_reset_done.html b/letsbook/templates/account/password_reset_done.html new file mode 100644 index 0000000..c59534a --- /dev/null +++ b/letsbook/templates/account/password_reset_done.html @@ -0,0 +1,17 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load account %} + +{% block head_title %}{% trans "Password Reset" %}{% endblock %} + +{% block inner %} +

{% trans "Password Reset" %}

+ + {% if user.is_authenticated %} + {% include "account/snippets/already_logged_in.html" %} + {% endif %} + +

{% blocktrans %}We have sent you an e-mail. Please contact us if you do not receive it within a few minutes.{% endblocktrans %}

+{% endblock %} + diff --git a/letsbook/templates/account/password_reset_from_key.html b/letsbook/templates/account/password_reset_from_key.html new file mode 100644 index 0000000..0bd60d6 --- /dev/null +++ b/letsbook/templates/account/password_reset_from_key.html @@ -0,0 +1,25 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} +{% block head_title %}{% trans "Change Password" %}{% endblock %} + +{% block inner %} +

{% if token_fail %}{% trans "Bad Token" %}{% else %}{% trans "Change Password" %}{% endif %}

+ + {% if token_fail %} + {% url 'account_reset_password' as passwd_reset_url %} +

{% blocktrans %}The password reset link was invalid, possibly because it has already been used. Please request a new password reset.{% endblocktrans %}

+ {% else %} + {% if form %} +
+ {% csrf_token %} + {{ form|crispy }} + +
+ {% else %} +

{% trans 'Your password is now changed.' %}

+ {% endif %} + {% endif %} +{% endblock %} + diff --git a/letsbook/templates/account/password_reset_from_key_done.html b/letsbook/templates/account/password_reset_from_key_done.html new file mode 100644 index 0000000..89be086 --- /dev/null +++ b/letsbook/templates/account/password_reset_from_key_done.html @@ -0,0 +1,10 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% block head_title %}{% trans "Change Password" %}{% endblock %} + +{% block inner %} +

{% trans "Change Password" %}

+

{% trans 'Your password is now changed.' %}

+{% endblock %} + diff --git a/letsbook/templates/account/password_set.html b/letsbook/templates/account/password_set.html new file mode 100644 index 0000000..7786e9e --- /dev/null +++ b/letsbook/templates/account/password_set.html @@ -0,0 +1,17 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Set Password" %}{% endblock %} + +{% block inner %} +

{% trans "Set Password" %}

+ +
+ {% csrf_token %} + {{ form|crispy }} + +
+{% endblock %} + diff --git a/letsbook/templates/account/signup.html b/letsbook/templates/account/signup.html new file mode 100644 index 0000000..6a2954e --- /dev/null +++ b/letsbook/templates/account/signup.html @@ -0,0 +1,23 @@ +{% extends "account/base.html" %} + +{% load i18n %} +{% load crispy_forms_tags %} + +{% block head_title %}{% trans "Signup" %}{% endblock %} + +{% block inner %} +

{% trans "Sign Up" %}

+ +

{% blocktrans %}Already have an account? Then please sign in.{% endblocktrans %}

+ + + +{% endblock %} + diff --git a/letsbook/templates/account/signup_closed.html b/letsbook/templates/account/signup_closed.html new file mode 100644 index 0000000..2322f17 --- /dev/null +++ b/letsbook/templates/account/signup_closed.html @@ -0,0 +1,12 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% trans "Sign Up Closed" %}{% endblock %} + +{% block inner %} +

{% trans "Sign Up Closed" %}

+ +

{% trans "We are sorry, but the sign up is currently closed." %}

+{% endblock %} + diff --git a/letsbook/templates/account/verification_sent.html b/letsbook/templates/account/verification_sent.html new file mode 100644 index 0000000..ad093fd --- /dev/null +++ b/letsbook/templates/account/verification_sent.html @@ -0,0 +1,13 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% trans "Verify Your E-mail Address" %}{% endblock %} + +{% block inner %} +

{% trans "Verify Your E-mail Address" %}

+ +

{% blocktrans %}We have sent an e-mail to you for verification. Follow the link provided to finalize the signup process. Please contact us if you do not receive it within a few minutes.{% endblocktrans %}

+ +{% endblock %} + diff --git a/letsbook/templates/account/verified_email_required.html b/letsbook/templates/account/verified_email_required.html new file mode 100644 index 0000000..09d4fde --- /dev/null +++ b/letsbook/templates/account/verified_email_required.html @@ -0,0 +1,24 @@ +{% extends "account/base.html" %} + +{% load i18n %} + +{% block head_title %}{% trans "Verify Your E-mail Address" %}{% endblock %} + +{% block inner %} +

{% trans "Verify Your E-mail Address" %}

+ +{% url 'account_email' as email_url %} + +

{% blocktrans %}This part of the site requires us to verify that +you are who you claim to be. For this purpose, we require that you +verify ownership of your e-mail address. {% endblocktrans %}

+ +

{% blocktrans %}We have sent an e-mail to you for +verification. Please click on the link inside this e-mail. Please +contact us if you do not receive it within a few minutes.{% endblocktrans %}

+ +

{% blocktrans %}Note: you can still change your e-mail address.{% endblocktrans %}

+ + +{% endblock %} + diff --git a/letsbook/templates/base.html b/letsbook/templates/base.html new file mode 100644 index 0000000..bfe442b --- /dev/null +++ b/letsbook/templates/base.html @@ -0,0 +1,106 @@ +{% load static i18n compress%} + + + + + {% block title %}Letsbook{% endblock title %} + + + + + + + + {% block css %} + + + + + {% compress css %} + + + {% endcompress %} + {% endblock %} + + + + + +
+ + +
+ +
+ + {% if messages %} + {% for message in messages %} +
{{ message }}
+ {% endfor %} + {% endif %} + + {% block content %} +

Use this document as a way to quick start any new project.

+ {% endblock content %} + +
+ + {% block modal %}{% endblock modal %} + + + + {% block javascript %} + + + + + + + + + {% compress js %} + + {% endcompress %} + + {% endblock javascript %} + + + diff --git a/letsbook/templates/bootstrap4/field.html b/letsbook/templates/bootstrap4/field.html new file mode 100644 index 0000000..d08f5c6 --- /dev/null +++ b/letsbook/templates/bootstrap4/field.html @@ -0,0 +1,49 @@ + +{% load crispy_forms_field %} + +{% if field.is_hidden %} + {{ field }} +{% else %} + {% if field|is_checkbox %} +
+ {% if label_class %} +
+ {% endif %} + {% endif %} + <{% if tag %}{{ tag }}{% else %}div{% endif %} id="div_{{ field.auto_id }}" {% if not field|is_checkbox %}class="form-group{% if using_grid_layout %} row{% endif %}{% else %}class="checkbox{% endif %}{% if wrapper_class %} {{ wrapper_class }}{% endif %}{% if form_show_errors%}{% if field.errors %} has-danger{% endif %}{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}"> + {% if field.label and not field|is_checkbox and form_show_labels %} + + {% endif %} + + {% if field|is_checkboxselectmultiple %} + {% include 'bootstrap4/layout/checkboxselectmultiple.html' %} + {% endif %} + + {% if field|is_radioselect %} + {% include 'bootstrap4/layout/radioselect.html' %} + {% endif %} + + {% if not field|is_checkboxselectmultiple and not field|is_radioselect %} + {% if field|is_checkbox and form_show_labels %} + + {% else %} +
+ {% crispy_field field %} +
+ {% include 'bootstrap4/layout/help_text_and_errors.html' %} + {% endif %} + {% endif %} + + {% if field|is_checkbox %} + {% if label_class %} +
+ {% endif %} +
+ {% endif %} +{% endif %} diff --git a/letsbook/templates/bootstrap4/layout/field_errors_block.html b/letsbook/templates/bootstrap4/layout/field_errors_block.html new file mode 100644 index 0000000..e06e5f2 --- /dev/null +++ b/letsbook/templates/bootstrap4/layout/field_errors_block.html @@ -0,0 +1,7 @@ + +{% if form_show_errors and field.errors %} + {% for error in field.errors %} +

{{ error }}

+ {% endfor %} +{% endif %} + diff --git a/letsbook/templates/pages/about.html b/letsbook/templates/pages/about.html new file mode 100644 index 0000000..63913c1 --- /dev/null +++ b/letsbook/templates/pages/about.html @@ -0,0 +1 @@ +{% extends "base.html" %} \ No newline at end of file diff --git a/letsbook/templates/pages/home.html b/letsbook/templates/pages/home.html new file mode 100644 index 0000000..63913c1 --- /dev/null +++ b/letsbook/templates/pages/home.html @@ -0,0 +1 @@ +{% extends "base.html" %} \ No newline at end of file diff --git a/letsbook/templates/users/user_detail.html b/letsbook/templates/users/user_detail.html new file mode 100644 index 0000000..e86eda1 --- /dev/null +++ b/letsbook/templates/users/user_detail.html @@ -0,0 +1,36 @@ +{% extends "base.html" %} +{% load static %} + +{% block title %}User: {{ object.username }}{% endblock %} + +{% block content %} +
+ +
+
+ +

{{ object.username }}

+ {% if object.name %} +

{{ object.name }}

+ {% endif %} +
+
+ +{% if object == request.user %} + +
+ +
+ My Info + E-Mail + +
+ +
+ +{% endif %} + + +
+{% endblock content %} + diff --git a/letsbook/templates/users/user_form.html b/letsbook/templates/users/user_form.html new file mode 100644 index 0000000..a054047 --- /dev/null +++ b/letsbook/templates/users/user_form.html @@ -0,0 +1,17 @@ +{% extends "base.html" %} +{% load crispy_forms_tags %} + +{% block title %}{{ user.username }}{% endblock %} + +{% block content %} +

{{ user.username }}

+
+ {% csrf_token %} + {{ form|crispy }} +
+
+ +
+
+
+{% endblock %} diff --git a/letsbook/templates/users/user_list.html b/letsbook/templates/users/user_list.html new file mode 100644 index 0000000..47d3f85 --- /dev/null +++ b/letsbook/templates/users/user_list.html @@ -0,0 +1,17 @@ +{% extends "base.html" %} +{% load static i18n %} +{% block title %}Members{% endblock %} + +{% block content %} +
+

Users

+ +
+ {% for user in user_list %} + +

{{ user.username }}

+
+ {% endfor %} +
+
+{% endblock content %} diff --git a/letsbook/users/__init__.py b/letsbook/users/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/letsbook/users/adapters.py b/letsbook/users/adapters.py new file mode 100644 index 0000000..b31450a --- /dev/null +++ b/letsbook/users/adapters.py @@ -0,0 +1,13 @@ +from django.conf import settings +from allauth.account.adapter import DefaultAccountAdapter +from allauth.socialaccount.adapter import DefaultSocialAccountAdapter + + +class AccountAdapter(DefaultAccountAdapter): + def is_open_for_signup(self, request): + return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True) + + +class SocialAccountAdapter(DefaultSocialAccountAdapter): + def is_open_for_signup(self, request, sociallogin): + return getattr(settings, 'ACCOUNT_ALLOW_REGISTRATION', True) diff --git a/letsbook/users/admin.py b/letsbook/users/admin.py new file mode 100644 index 0000000..9b61512 --- /dev/null +++ b/letsbook/users/admin.py @@ -0,0 +1,39 @@ +from django import forms +from django.contrib import admin +from django.contrib.auth.admin import UserAdmin as AuthUserAdmin +from django.contrib.auth.forms import UserChangeForm, UserCreationForm +from .models import User + + +class MyUserChangeForm(UserChangeForm): + class Meta(UserChangeForm.Meta): + model = User + + +class MyUserCreationForm(UserCreationForm): + + error_message = UserCreationForm.error_messages.update({ + 'duplicate_username': 'This username has already been taken.' + }) + + class Meta(UserCreationForm.Meta): + model = User + + def clean_username(self): + username = self.cleaned_data["username"] + try: + User.objects.get(username=username) + except User.DoesNotExist: + return username + raise forms.ValidationError(self.error_messages['duplicate_username']) + + +@admin.register(User) +class MyUserAdmin(AuthUserAdmin): + form = MyUserChangeForm + add_form = MyUserCreationForm + fieldsets = ( + ('User Profile', {'fields': ('name',)}), + ) + AuthUserAdmin.fieldsets + list_display = ('username', 'name', 'is_superuser') + search_fields = ['name'] diff --git a/letsbook/users/apps.py b/letsbook/users/apps.py new file mode 100644 index 0000000..29e1841 --- /dev/null +++ b/letsbook/users/apps.py @@ -0,0 +1,13 @@ +from django.apps import AppConfig + + +class UsersConfig(AppConfig): + name = 'letsbook.users' + verbose_name = "Users" + + def ready(self): + """Override this to put in: + Users system checks + Users signal registration + """ + pass diff --git a/letsbook/users/migrations/0001_initial.py b/letsbook/users/migrations/0001_initial.py new file mode 100644 index 0000000..b2cfca3 --- /dev/null +++ b/letsbook/users/migrations/0001_initial.py @@ -0,0 +1,43 @@ +import django.contrib.auth.models +import django.contrib.auth.validators +from django.db import migrations, models +import django.utils.timezone + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('auth', '0008_alter_user_username_max_length'), + ] + + operations = [ + migrations.CreateModel( + name='User', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('password', models.CharField(max_length=128, verbose_name='password')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), + ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), + ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), + ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), + ('last_name', models.CharField(blank=True, max_length=30, verbose_name='last name')), + ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), + ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), + ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), + ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), + ('name', models.CharField(blank=True, max_length=255, verbose_name='Name of User')), + ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')), + ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')), + ], + options={ + 'verbose_name_plural': 'users', + 'verbose_name': 'user', + 'abstract': False, + }, + managers=[ + ('objects', django.contrib.auth.models.UserManager()), + ], + ), + ] diff --git a/letsbook/users/migrations/__init__.py b/letsbook/users/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/letsbook/users/models.py b/letsbook/users/models.py new file mode 100644 index 0000000..c06f15d --- /dev/null +++ b/letsbook/users/models.py @@ -0,0 +1,19 @@ +from django.contrib.auth.models import AbstractUser +from django.core.urlresolvers import reverse +from django.db import models +from django.utils.encoding import python_2_unicode_compatible +from django.utils.translation import ugettext_lazy as _ + + +@python_2_unicode_compatible +class User(AbstractUser): + + # First Name and Last Name do not cover name patterns + # around the globe. + name = models.CharField(_('Name of User'), blank=True, max_length=255) + + def __str__(self): + return self.username + + def get_absolute_url(self): + return reverse('users:detail', kwargs={'username': self.username}) diff --git a/letsbook/users/tests/__init__.py b/letsbook/users/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/letsbook/users/tests/factories.py b/letsbook/users/tests/factories.py new file mode 100644 index 0000000..e2c967d --- /dev/null +++ b/letsbook/users/tests/factories.py @@ -0,0 +1,11 @@ +import factory + + +class UserFactory(factory.django.DjangoModelFactory): + username = factory.Sequence(lambda n: 'user-{0}'.format(n)) + email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) + password = factory.PostGenerationMethodCall('set_password', 'password') + + class Meta: + model = 'users.User' + django_get_or_create = ('username', ) diff --git a/letsbook/users/tests/test_admin.py b/letsbook/users/tests/test_admin.py new file mode 100644 index 0000000..a1ff0b8 --- /dev/null +++ b/letsbook/users/tests/test_admin.py @@ -0,0 +1,40 @@ +from test_plus.test import TestCase + +from ..admin import MyUserCreationForm + + +class TestMyUserCreationForm(TestCase): + + def setUp(self): + self.user = self.make_user('notalamode', 'notalamodespassword') + + def test_clean_username_success(self): + # Instantiate the form with a new username + form = MyUserCreationForm({ + 'username': 'alamode', + 'password1': '7jefB#f@Cc7YJB]2v', + 'password2': '7jefB#f@Cc7YJB]2v', + }) + # Run is_valid() to trigger the validation + valid = form.is_valid() + self.assertTrue(valid) + + # Run the actual clean_username method + username = form.clean_username() + self.assertEqual('alamode', username) + + def test_clean_username_false(self): + # Instantiate the form with the same username as self.user + form = MyUserCreationForm({ + 'username': self.user.username, + 'password1': 'notalamodespassword', + 'password2': 'notalamodespassword', + }) + # Run is_valid() to trigger the validation, which is going to fail + # because the username is already taken + valid = form.is_valid() + self.assertFalse(valid) + + # The form.errors dict should contain a single error called 'username' + self.assertTrue(len(form.errors) == 1) + self.assertTrue('username' in form.errors) diff --git a/letsbook/users/tests/test_models.py b/letsbook/users/tests/test_models.py new file mode 100644 index 0000000..894ed18 --- /dev/null +++ b/letsbook/users/tests/test_models.py @@ -0,0 +1,19 @@ +from test_plus.test import TestCase + + +class TestUser(TestCase): + + def setUp(self): + self.user = self.make_user() + + def test__str__(self): + self.assertEqual( + self.user.__str__(), + 'testuser' # This is the default username for self.make_user() + ) + + def test_get_absolute_url(self): + self.assertEqual( + self.user.get_absolute_url(), + '/users/testuser/' + ) diff --git a/letsbook/users/tests/test_urls.py b/letsbook/users/tests/test_urls.py new file mode 100644 index 0000000..6e181cc --- /dev/null +++ b/letsbook/users/tests/test_urls.py @@ -0,0 +1,51 @@ +from django.core.urlresolvers import reverse, resolve + +from test_plus.test import TestCase + + +class TestUserURLs(TestCase): + """Test URL patterns for users app.""" + + def setUp(self): + self.user = self.make_user() + + def test_list_reverse(self): + """users:list should reverse to /users/.""" + self.assertEqual(reverse('users:list'), '/users/') + + def test_list_resolve(self): + """/users/ should resolve to users:list.""" + self.assertEqual(resolve('/users/').view_name, 'users:list') + + def test_redirect_reverse(self): + """users:redirect should reverse to /users/~redirect/.""" + self.assertEqual(reverse('users:redirect'), '/users/~redirect/') + + def test_redirect_resolve(self): + """/users/~redirect/ should resolve to users:redirect.""" + self.assertEqual( + resolve('/users/~redirect/').view_name, + 'users:redirect' + ) + + def test_detail_reverse(self): + """users:detail should reverse to /users/testuser/.""" + self.assertEqual( + reverse('users:detail', kwargs={'username': 'testuser'}), + '/users/testuser/' + ) + + def test_detail_resolve(self): + """/users/testuser/ should resolve to users:detail.""" + self.assertEqual(resolve('/users/testuser/').view_name, 'users:detail') + + def test_update_reverse(self): + """users:update should reverse to /users/~update/.""" + self.assertEqual(reverse('users:update'), '/users/~update/') + + def test_update_resolve(self): + """/users/~update/ should resolve to users:update.""" + self.assertEqual( + resolve('/users/~update/').view_name, + 'users:update' + ) diff --git a/letsbook/users/tests/test_views.py b/letsbook/users/tests/test_views.py new file mode 100644 index 0000000..23f30f0 --- /dev/null +++ b/letsbook/users/tests/test_views.py @@ -0,0 +1,64 @@ +from django.test import RequestFactory + +from test_plus.test import TestCase + +from ..views import ( + UserRedirectView, + UserUpdateView +) + + +class BaseUserTestCase(TestCase): + + def setUp(self): + self.user = self.make_user() + self.factory = RequestFactory() + + +class TestUserRedirectView(BaseUserTestCase): + + def test_get_redirect_url(self): + # Instantiate the view directly. Never do this outside a test! + view = UserRedirectView() + # Generate a fake request + request = self.factory.get('/fake-url') + # Attach the user to the request + request.user = self.user + # Attach the request to the view + view.request = request + # Expect: '/users/testuser/', as that is the default username for + # self.make_user() + self.assertEqual( + view.get_redirect_url(), + '/users/testuser/' + ) + + +class TestUserUpdateView(BaseUserTestCase): + + def setUp(self): + # call BaseUserTestCase.setUp() + super(TestUserUpdateView, self).setUp() + # Instantiate the view directly. Never do this outside a test! + self.view = UserUpdateView() + # Generate a fake request + request = self.factory.get('/fake-url') + # Attach the user to the request + request.user = self.user + # Attach the request to the view + self.view.request = request + + def test_get_success_url(self): + # Expect: '/users/testuser/', as that is the default username for + # self.make_user() + self.assertEqual( + self.view.get_success_url(), + '/users/testuser/' + ) + + def test_get_object(self): + # Expect: self.user, as that is the request's user object + self.assertEqual( + self.view.get_object(), + self.user + ) diff --git a/letsbook/users/urls.py b/letsbook/users/urls.py new file mode 100644 index 0000000..600ccfb --- /dev/null +++ b/letsbook/users/urls.py @@ -0,0 +1,26 @@ +from django.conf.urls import url + +from . import views + +urlpatterns = [ + url( + regex=r'^$', + view=views.UserListView.as_view(), + name='list' + ), + url( + regex=r'^~redirect/$', + view=views.UserRedirectView.as_view(), + name='redirect' + ), + url( + regex=r'^(?P[\w.@+-]+)/$', + view=views.UserDetailView.as_view(), + name='detail' + ), + url( + regex=r'^~update/$', + view=views.UserUpdateView.as_view(), + name='update' + ), +] diff --git a/letsbook/users/views.py b/letsbook/users/views.py new file mode 100644 index 0000000..777f42b --- /dev/null +++ b/letsbook/users/views.py @@ -0,0 +1,45 @@ +from django.core.urlresolvers import reverse +from django.views.generic import DetailView, ListView, RedirectView, UpdateView + +from django.contrib.auth.mixins import LoginRequiredMixin + +from .models import User + + +class UserDetailView(LoginRequiredMixin, DetailView): + model = User + # These next two lines tell the view to index lookups by username + slug_field = 'username' + slug_url_kwarg = 'username' + + +class UserRedirectView(LoginRequiredMixin, RedirectView): + permanent = False + + def get_redirect_url(self): + return reverse('users:detail', + kwargs={'username': self.request.user.username}) + + +class UserUpdateView(LoginRequiredMixin, UpdateView): + + fields = ['name', ] + + # we already imported User in the view code above, remember? + model = User + + # send the user back to their own page after a successful update + def get_success_url(self): + return reverse('users:detail', + kwargs={'username': self.request.user.username}) + + def get_object(self): + # Only get the User record for the user making the request + return User.objects.get(username=self.request.user.username) + + +class UserListView(LoginRequiredMixin, ListView): + model = User + # These next two lines tell the view to index lookups by username + slug_field = 'username' + slug_url_kwarg = 'username' diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..a9580b9 --- /dev/null +++ b/manage.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +import os +import sys + +if __name__ == '__main__': + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') + + try: + from django.core.management import execute_from_command_line + except ImportError: + # The above import may fail for some other reason. Ensure that the + # issue is really that Django is missing to avoid masking other + # exceptions on Python 2. + try: + import django # noqa + except ImportError: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) + raise + + # This allows easy placement of apps within the interior + # letsbook directory. + current_path = os.path.dirname(os.path.abspath(__file__)) + sys.path.append(os.path.join(current_path, 'letsbook')) + + execute_from_command_line(sys.argv) diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..196b654 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +DJANGO_SETTINGS_MODULE=config.settings.test + diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..ea77c2d --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +-r requirements/production.txt diff --git a/requirements/base.txt b/requirements/base.txt new file mode 100644 index 0000000..f7de948 --- /dev/null +++ b/requirements/base.txt @@ -0,0 +1,55 @@ +# Wheel 0.25+ needed to install certain packages on CPython 3.5+ +# like Pillow and psycopg2 +# See http://bitly.com/wheel-building-fails-CPython-35 +# Verified bug on Python 3.5.1 +wheel==0.30.0 + + +# Conservative Django +django==1.11.9 # pyup: <2.0 + +# Configuration +django-environ==0.4.4 + + + +# Forms +django-crispy-forms==1.7.0 + +# Models +django-model-utils==3.1.1 + +# Images +Pillow==5.0.0 + +# Password storage +argon2-cffi==18.1.0 + +# For user registration, either via email or social +# Well-built with regular release cycles! +django-allauth==0.34.0 + + +# Python-PostgreSQL Database Adapter +psycopg2==2.7.3.2 + +# Unicode slugification +awesome-slugify==1.6.5 + +# Time zones support +pytz==2017.3 + +# Redis support +django-redis==4.8.0 +redis>=2.10.5 + + +celery==3.1.25 + + + +rcssmin==1.0.6 +django-compressor==2.2 + + +# Your custom requirements go here diff --git a/requirements/local.txt b/requirements/local.txt new file mode 100644 index 0000000..2622b77 --- /dev/null +++ b/requirements/local.txt @@ -0,0 +1,19 @@ +# Local development dependencies go here +-r base.txt + +coverage==4.4.2 +django-coverage-plugin==1.5.0 + +Sphinx==1.6.6 +django-extensions==1.9.9 +Werkzeug==0.14.1 +django-test-plus==1.0.22 +factory-boy==2.9.2 + +django-debug-toolbar==1.9.1 + +# improved REPL +ipdb==0.10.3 + +pytest-django==3.1.2 +pytest-sugar==0.9.0 diff --git a/requirements/production.txt b/requirements/production.txt new file mode 100644 index 0000000..9a9061d --- /dev/null +++ b/requirements/production.txt @@ -0,0 +1,28 @@ +# Pro-tip: Try not to put anything here. Avoid dependencies in +# production that aren't in development. +-r base.txt + + + +# WSGI Handler +# ------------------------------------------------ +gevent==1.2.2 +gunicorn==19.7.1 + +# Static and Media Storage +# ------------------------------------------------ +boto3==1.5.14 +django-storages==1.6.5 +Collectfast==0.6.0 + +# Email backends for Mailgun, Postmark, SendGrid and more +# ------------------------------------------------------- +django-anymail==1.2 + +# Raven is the Sentry client +# -------------------------- +raven==6.4.0 + +# Opbeat agent for performance monitoring +# ----------------------------------------- +opbeat==3.6.0 diff --git a/requirements/test.txt b/requirements/test.txt new file mode 100644 index 0000000..d07c8a1 --- /dev/null +++ b/requirements/test.txt @@ -0,0 +1,14 @@ +# Test dependencies go here. +-r base.txt + + + +coverage==4.4.2 +flake8==3.5.0 # pyup: != 2.6.0 +django-test-plus==1.0.22 +factory-boy==2.9.2 +django-coverage-plugin==1.5.0 + +# pytest +pytest-django==3.1.2 +pytest-sugar==0.9.0 diff --git a/runtime.txt b/runtime.txt new file mode 100644 index 0000000..5c45380 --- /dev/null +++ b/runtime.txt @@ -0,0 +1 @@ +python-3.6.4 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..2b26ba6 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,7 @@ +[flake8] +max-line-length = 120 +exclude = .tox,.git,*/migrations/*,*/static/CACHE/*,docs,node_modules + +[pycodestyle] +max-line-length = 120 +exclude=.tox,.git,*/migrations/*,*/static/CACHE/*,docs,node_modules diff --git a/utility/install_os_dependencies.sh b/utility/install_os_dependencies.sh new file mode 100755 index 0000000..ec9372f --- /dev/null +++ b/utility/install_os_dependencies.sh @@ -0,0 +1,96 @@ +#!/bin/bash + +WORK_DIR="$(dirname "$0")" +DISTRO_NAME=$(lsb_release -sc) +OS_REQUIREMENTS_FILENAME="requirements-$DISTRO_NAME.apt" + +cd $WORK_DIR + +# Check if a requirements file exist for the current distribution. +if [ ! -r "$OS_REQUIREMENTS_FILENAME" ]; then + cat <<-EOF >&2 + There is no requirements file for your distribution. + You can see one of the files listed below to help search the equivalent package in your system: + $(find ./ -name "requirements-*.apt" -printf " - %f\n") + EOF + exit 1; +fi + +# Handle call with wrong command +function wrong_command() +{ + echo "${0##*/} - unknown command: '${1}'" >&2 + usage_message +} + +# Print help / script usage +function usage_message() +{ + cat <<-EOF + Usage: $WORK_DIR/${0##*/} + Available commands are: + list Print a list of all packages defined on ${OS_REQUIREMENTS_FILENAME} file + help Print this help + + Commands that require superuser permission: + install Install packages defined on ${OS_REQUIREMENTS_FILENAME} file. Note: This + does not upgrade the packages already installed for new versions, even if + new version is available in the repository. + upgrade Same that install, but upgrade the already installed packages, if new + version is available. + EOF +} + +# Read the requirements.apt file, and remove comments and blank lines +function list_packages(){ + grep -v "#" "${OS_REQUIREMENTS_FILENAME}" | grep -v "^$"; +} + +function install_packages() +{ + list_packages | xargs apt-get --no-upgrade install -y; +} + +function upgrade_packages() +{ + list_packages | xargs apt-get install -y; +} + +function install_or_upgrade() +{ + P=${1} + PARAN=${P:-"install"} + + if [[ $EUID -ne 0 ]]; then + cat <<-EOF >&2 + You must run this script with root privilege + Please do: + sudo $WORK_DIR/${0##*/} $PARAN + EOF + exit 1 + else + + apt-get update + + # Install the basic compilation dependencies and other required libraries of this project + if [ "$PARAN" == "install" ]; then + install_packages; + else + upgrade_packages; + fi + + # cleaning downloaded packages from apt-get cache + apt-get clean + + exit 0 + fi +} + +# Handle command argument +case "$1" in + install) install_or_upgrade;; + upgrade) install_or_upgrade "upgrade";; + list) list_packages;; + help|"") usage_message;; + *) wrong_command "$1";; +esac diff --git a/utility/install_python_dependencies.sh b/utility/install_python_dependencies.sh new file mode 100755 index 0000000..4334218 --- /dev/null +++ b/utility/install_python_dependencies.sh @@ -0,0 +1,40 @@ +#!/bin/bash + +WORK_DIR="$(dirname "$0")" +PROJECT_DIR="$(dirname "$WORK_DIR")" + +pip --version >/dev/null 2>&1 || { + echo >&2 -e "\npip is required but it's not installed." + echo >&2 -e "You can install it by running the following command:\n" + echo >&2 "wget https://bootstrap.pypa.io/get-pip.py --output-document=get-pip.py; chmod +x get-pip.py; sudo -H python3 get-pip.py" + echo >&2 -e "\n" + echo >&2 -e "\nFor more information, see pip documentation: https://pip.pypa.io/en/latest/" + exit 1; +} + +virtualenv --version >/dev/null 2>&1 || { + echo >&2 -e "\nvirtualenv is required but it's not installed." + echo >&2 -e "You can install it by running the following command:\n" + echo >&2 "sudo -H pip3 install virtualenv" + echo >&2 -e "\n" + echo >&2 -e "\nFor more information, see virtualenv documentation: https://virtualenv.pypa.io/en/latest/" + exit 1; +} + +if [ -z "$VIRTUAL_ENV" ]; then + echo >&2 -e "\nYou need activate a virtualenv first" + echo >&2 -e 'If you do not have a virtualenv created, run the following command to create and automatically activate a new virtualenv named "venv" on current folder:\n' + echo >&2 -e "virtualenv venv --python=\`which python3\`" + echo >&2 -e "\nTo leave/disable the currently active virtualenv, run the following command:\n" + echo >&2 "deactivate" + echo >&2 -e "\nTo activate the virtualenv again, run the following command:\n" + echo >&2 "source venv/bin/activate" + echo >&2 -e "\nFor more information, see virtualenv documentation: https://virtualenv.pypa.io/en/latest/" + echo >&2 -e "\n" + exit 1; +else + + pip install -r $PROJECT_DIR/requirements/local.txt + pip install -r $PROJECT_DIR/requirements/test.txt + pip install -r $PROJECT_DIR/requirements.txt +fi diff --git a/utility/requirements-jessie.apt b/utility/requirements-jessie.apt new file mode 100644 index 0000000..5c49365 --- /dev/null +++ b/utility/requirements-jessie.apt @@ -0,0 +1,23 @@ +##basic build dependencies of various Django apps for Debian Jessie 8.x +#build-essential metapackage install: make, gcc, g++, +build-essential +#required to translate +gettext +python3-dev + +##shared dependencies of: +##Pillow, pylibmc +zlib1g-dev + +##Postgresql and psycopg2 dependencies +libpq-dev + +##Pillow dependencies +libtiff5-dev +libjpeg62-turbo-dev +libfreetype6-dev +liblcms2-dev +libwebp-dev + +##django-extensions +graphviz-dev diff --git a/utility/requirements-trusty.apt b/utility/requirements-trusty.apt new file mode 100644 index 0000000..455f1a8 --- /dev/null +++ b/utility/requirements-trusty.apt @@ -0,0 +1,23 @@ +##basic build dependencies of various Django apps for Ubuntu Trusty 14.04 +#build-essential metapackage install: make, gcc, g++, +build-essential +#required to translate +gettext +python3-dev + +##shared dependencies of: +##Pillow, pylibmc +zlib1g-dev + +##Postgresql and psycopg2 dependencies +libpq-dev + +##Pillow dependencies +libtiff4-dev +libjpeg8-dev +libfreetype6-dev +liblcms1-dev +libwebp-dev + +##django-extensions +graphviz-dev diff --git a/utility/requirements-xenial.apt b/utility/requirements-xenial.apt new file mode 100644 index 0000000..ba84ef1 --- /dev/null +++ b/utility/requirements-xenial.apt @@ -0,0 +1,23 @@ +##basic build dependencies of various Django apps for Ubuntu Xenial 16.04 +#build-essential metapackage install: make, gcc, g++, +build-essential +#required to translate +gettext +python3-dev + +##shared dependencies of: +##Pillow, pylibmc +zlib1g-dev + +##Postgresql and psycopg2 dependencies +libpq-dev + +##Pillow dependencies +libtiff5-dev +libjpeg8-dev +libfreetype6-dev +liblcms2-dev +libwebp-dev + +##django-extensions +graphviz-dev