From f22ca60b3ffde4af7a3a439f00d707026ad1ad91 Mon Sep 17 00:00:00 2001 From: Dvid Silva Date: Fri, 28 Sep 2018 21:21:02 -0400 Subject: [PATCH 01/15] Initial commit --- LICENSE | 201 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. From 32d3f0215a2cb4660f6c3caa98c6bce6bca9ddbe Mon Sep 17 00:00:00 2001 From: David Silva Date: Fri, 28 Sep 2018 22:09:00 -0400 Subject: [PATCH 02/15] initial commit, sample django-postgres project --- .gitignore | 5 ++ Dockerfile | 6 +++ api/__init__.py | 0 api/settings.py | 122 +++++++++++++++++++++++++++++++++++++++++++++ api/urls.py | 21 ++++++++ api/wsgi.py | 16 ++++++ docker-compose.yml | 24 +++++++++ manage.py | 22 ++++++++ requirements.txt | 5 ++ 9 files changed, 221 insertions(+) create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 api/__init__.py create mode 100644 api/settings.py create mode 100644 api/urls.py create mode 100644 api/wsgi.py create mode 100644 docker-compose.yml create mode 100755 manage.py create mode 100644 requirements.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b0a25d6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +*.pyc +__pycache__/ +.DS_Store +.envrc +.vscode diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d8e8262 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,6 @@ + FROM python:3.6 + ENV PYTHONUNBUFFERED 1 + RUN mkdir /code + WORKDIR /code + ADD requirements.txt /code/ + RUN pip install -r requirements.txt diff --git a/api/__init__.py b/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/api/settings.py b/api/settings.py new file mode 100644 index 0000000..10d1e08 --- /dev/null +++ b/api/settings.py @@ -0,0 +1,122 @@ +""" +Django settings for api project. + +Generated by 'django-admin startproject' using Django 1.11.15. + +For more information on this file, see +https://docs.djangoproject.com/en/1.11/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/1.11/ref/settings/ +""" + +import os + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = '(@n$7n&3l_9-_j1cv$_-ao!=4$ug-s2=+)cmb51n0ue5246_8e' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ['*'] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] + +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', +] + +ROOT_URLCONF = 'api.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'api.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/1.11/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql', + 'NAME': 'postgres', + 'USER': 'postgres', + 'HOST': 'db', + 'PORT': 5432, + } +} + +# Password validation +# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/1.11/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/1.11/howto/static-files/ + +STATIC_URL = '/static/' diff --git a/api/urls.py b/api/urls.py new file mode 100644 index 0000000..2c7f7ef --- /dev/null +++ b/api/urls.py @@ -0,0 +1,21 @@ +"""api URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/1.11/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.conf.urls import url, include + 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) +""" +from django.conf.urls import url +from django.contrib import admin + +urlpatterns = [ + url(r'^admin/', admin.site.urls), +] diff --git a/api/wsgi.py b/api/wsgi.py new file mode 100644 index 0000000..925af73 --- /dev/null +++ b/api/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for api project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.settings") + +application = get_wsgi_application() diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..0639b12 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,24 @@ +version: '3' + +services: + db: + image: postgres + ports: + - "5432:5432" + expose: + - "5432" + volumes: + - ./backups:/home/backups + web: + build: . + command: python3 manage.py runserver 0.0.0.0:9000 + volumes: + - .:/code + ports: + - "9000:9000" + expose: + - "9000" + depends_on: + - db + links: + - db diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..2385de7 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +import os +import sys + +if __name__ == "__main__": + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api.settings") + 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 + 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 + execute_from_command_line(sys.argv) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..da4fd32 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +Django==1.11.3 +psycopg2==2.7.1 +Django==1.11.3 +djangorestframework==3.6.2 +djangorestframework-jsonapi==2.2.0 From a33fc9fdb8c24b48dd4fbd38f1cec93ae1ade350 Mon Sep 17 00:00:00 2001 From: David Silva Date: Fri, 28 Sep 2018 22:15:47 -0400 Subject: [PATCH 03/15] added a README --- README | 166 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 README diff --git a/README b/README new file mode 100644 index 0000000..e1b7fd5 --- /dev/null +++ b/README @@ -0,0 +1,166 @@ +# codecorgi + +Checkout our progress on [![Waffle.io](https://badge.waffle.io/corgicode/django-api.svg?columns=all)](https://waffle.io/corgicode/django-api) + +[![Build Status](https://circleci.com/gh/corgicode/django-api.svg?style=shield)](https://circleci.com/gh/corgicode/django-api) + + Codecorgi is a visual portfolio for front-end developers to showcase their + code and experience. Codecorgi's vision is to help employ the workforce by + providing developers continuous training and project experience. Our company + believes that junior developers have a difficulty landing their first + programming career. + +# Contributing + +Todo :( + +Follow our [code of conduct on github](https://github.com/corgicode/frontend-react/blob/dev/CODE_OF_CONDUCT.md). + +## Installing + +We're using docker and docker-compose to start the application. + +Install Docker. + +```bash +http://www.docker.com/products/docker#/mac +``` + +I used this tutorial to help me get the hang of things. I recommend it for getting started. + +```bash +https://prakhar.me/docker-curriculum/ +``` + +Grab the repo: + +```bash +git clone git@github.com:corgicode/django-api.git +``` + +Then start the containers: + +```bash +docker-compose up +``` + +It will take a long time running the first time while downloading all the +dependencies, but the future times it will be super quick. + +Run `docker-compose down` when you're not working to save resources in your machine, +and `docker-compose restart` if you need to restart the application. + +Now you can visit your local version going to `http://localhost:9000`. + +The watcher should restart the application everytime a file changes in the backend, +but if you notice that is not happening, run the restart command manually. + +If the application can't be accessed an error might have occurred, to look at the logs +run the command `docker-compose logs -f --tail=10 web`. + +## Env variables + +The four following variables are needed to run the application. + +``` +GITHUB_CLIENT_ID +GITHUB_CLIENT_SECRET +GITHUB_CALLBACK_URL +GITHUB_APP_NAME +ADMIN_API_KEY +BASE_URL +MAILCHIMP_LIST_ID +MAILCHIMP_API_KEY +``` + +The github ones are pretty self explanatory, register an application [here](https://github.com/settings/applications/new), +is used for authentication and to get some information about the users. + +The Admin api key is a key that can be included in the request headers to allow for admin access, temp solution. + +Base url is mostly used to redirect to routes in the front end. + +## Migrations (Seed data) + +Make an admin request to `docker-compose run web python3 manage.py migrate` to run the migrations. + +## Developing + + +### PyLint + +Linting will help identify: + +- formatting discrepancy +- non-adherence to coding standards and conventions +- pinpointing possible logical errors in your program + +Running a Lint program over your source code, helps to ensure that source code +is legible, readable, less polluted and easy to maintain. + +### Git Flow + +Git flow is a branching model and a plugin for git that +helps you manage your branches easier, that way we don't +overstep in each other codes, all the contributions should go through pull requests, +so git flow will help you manage your workflow easier. + +First you need to install and activate git flow, to install on mac use +[homebrew](https://brew.sh/): + +```bash +brew install git-flow +``` + +Then run `git flow init` on the root of the project to set up your git flow configuration. + +To start a new feature, like to close a ticket or add some code, run the command, where +NAME is a short description of the issue or the ticket number from gitlab. For example +`git flow feature start adding-users`. + +Commit often, and push to your branch, and when you're ready create a merge request on gitlab. +An admin will approve the request and merge your code into develop, and create new releases. + +For now that's all you need to know, you can find more information about git flow +[here](http://nvie.com/posts/a-successful-git-branching-model/). + +Detailed installation instructions [here](https://github.com/nvie/gitflow/wiki/Installation). + +## Dependencies + +The following are tools, packages or technologies used. + +### Django + +Django makes it easier to build better Web apps more quickly and with less code. + +[Homepage](https://www.djangoproject.com/). + +I recommend following a short django tutorial before jumping into the code, +to help you understand what requiring is, middleware, routes, etc. + +This [one in their documentation](https://www.djangoproject.com/start/) +seems complete enough, but feel free to use whatever one you prefer. + +### JSON Api + +[JSON Api](http://jsonapi.org/) is an specification for building APIs in JSON. +By following shared conventions, you can increase productivity, take advantage of +generalized tooling, and focus on what matters: your application + +### Postgres + +### Redis + +Redis is a fast, open source, in-memory key-value data structure store. + +Writing to Redis is a lot faster than writing to Mongo or other data stores, +the data can be set with an expiration date and it doesn't offer the same reliability. +Making it perfect for caching data. Every time we run a long operation we can store +the result of that operation in the redis database, and the next time that same result +is needed we can fetch it from redis instead of running the operation again, that will +make the users happier and save resources on the server. + +[What is redis](https://aws.amazon.com/elasticache/what-is-redis/). + +[Try a demon of redis online](http://try.redis.io/). From 1888d404ae1a0de1d6e80261dbee116bbc249543 Mon Sep 17 00:00:00 2001 From: David Silva Date: Sat, 29 Sep 2018 19:10:57 -0400 Subject: [PATCH 04/15] fixed docker-compose to do hot reload --- docker-compose.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docker-compose.yml b/docker-compose.yml index 0639b12..fef9f97 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -22,3 +22,5 @@ services: - db links: - db + volumes: + - .:/code From bdfcd610ab31cb247fa500870deaafc2ff1c3c5b Mon Sep 17 00:00:00 2001 From: David Silva Date: Sat, 29 Sep 2018 19:38:37 -0400 Subject: [PATCH 05/15] Created base app and user models and migrations --- api/settings.py | 4 + api/urls.py | 32 +++--- requirements.txt | 4 + usermanagement/__init__.py | 0 usermanagement/apps.py | 7 ++ usermanagement/migrations/0001_initial.py | 41 ++++++++ usermanagement/migrations/__init__.py | 0 usermanagement/models.py | 118 ++++++++++++++++++++++ usermanagement/urls.py | 10 ++ usermanagement/views.py | 29 ++++++ 10 files changed, 229 insertions(+), 16 deletions(-) create mode 100644 usermanagement/__init__.py create mode 100644 usermanagement/apps.py create mode 100644 usermanagement/migrations/0001_initial.py create mode 100644 usermanagement/migrations/__init__.py create mode 100644 usermanagement/models.py create mode 100644 usermanagement/urls.py create mode 100644 usermanagement/views.py diff --git a/api/settings.py b/api/settings.py index 10d1e08..6cc9e85 100644 --- a/api/settings.py +++ b/api/settings.py @@ -37,6 +37,10 @@ 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', + 'safedelete', + 'adminplus', + 'rest_framework', + 'usermanagement.apps.UsermanagementConfig', ] MIDDLEWARE = [ diff --git a/api/urls.py b/api/urls.py index 2c7f7ef..3cb3ba7 100644 --- a/api/urls.py +++ b/api/urls.py @@ -1,21 +1,21 @@ -"""api URL Configuration - -The `urlpatterns` list routes URLs to views. For more information please see: - https://docs.djangoproject.com/en/1.11/topics/http/urls/ -Examples: -Function views - 1. Add an import: from my_app import views - 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') -Class-based views - 1. Add an import: from other_app.views import Home - 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') -Including another URLconf - 1. Import the include() function: from django.conf.urls import url, include - 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) -""" -from django.conf.urls import url +from django.conf.urls import url, include from django.contrib import admin +# from adminplus.sites import AdminSitePlus urlpatterns = [ url(r'^admin/', admin.site.urls), ] + +# admin.site = AdminSitePlus() +# admin.sites.site = admin.site +# admin.autodiscover() + +admin.site.site_header = 'codecorgi Admin' + +admin_root_url = r'^services/admin/' + +urlpatterns = [ + url(admin_root_url, include(admin.site.urls)), + # url(r'^services/api/', include('usermanagement.urls')), + # url(r'^services/api/', include('challenges.urls')), +] diff --git a/requirements.txt b/requirements.txt index da4fd32..8ee6028 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,3 +3,7 @@ psycopg2==2.7.1 Django==1.11.3 djangorestframework==3.6.2 djangorestframework-jsonapi==2.2.0 +django-safedelete==0.4.5 +django-adminplus==0.5 +Markdown==2.6.8 +pyjwt==1.5.2 diff --git a/usermanagement/__init__.py b/usermanagement/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/usermanagement/apps.py b/usermanagement/apps.py new file mode 100644 index 0000000..ba77233 --- /dev/null +++ b/usermanagement/apps.py @@ -0,0 +1,7 @@ +from __future__ import unicode_literals +from django.apps import AppConfig + + +class UsermanagementConfig(AppConfig): + name = 'usermanagement' + verbose_name = 'User Management' diff --git a/usermanagement/migrations/0001_initial.py b/usermanagement/migrations/0001_initial.py new file mode 100644 index 0000000..99246ae --- /dev/null +++ b/usermanagement/migrations/0001_initial.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.3 on 2018-09-29 23:35 +from __future__ import unicode_literals + +import django.contrib.auth.password_validation +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='User', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('password', models.CharField(max_length=128, validators=[django.contrib.auth.password_validation.validate_password], verbose_name='password')), + ('email', models.EmailField(max_length=255, unique=True, verbose_name='email address')), + ('is_active', models.BooleanField(default=True)), + ('is_verified', models.BooleanField(default=False)), + ('is_admin', models.BooleanField(default=False)), + ('deleted', models.BooleanField(default=False)), + ('flagged', models.BooleanField(default=False)), + ('private', models.BooleanField(default=False)), + ('name', models.CharField(blank=True, max_length=50, null=True)), + ('avatar', models.TextField(blank=True, null=True)), + ('heroImage', models.TextField(blank=True, null=True)), + ('github_id', models.TextField(blank=True, max_length=255)), + ], + options={ + 'abstract': False, + }, + ), + ] diff --git a/usermanagement/migrations/__init__.py b/usermanagement/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/usermanagement/models.py b/usermanagement/models.py new file mode 100644 index 0000000..5ea778b --- /dev/null +++ b/usermanagement/models.py @@ -0,0 +1,118 @@ +from __future__ import unicode_literals +from django.db import models +from django.contrib.auth.models import BaseUserManager, AbstractBaseUser +from django.core.exceptions import ValidationError +from django.contrib.auth import password_validation +from django.utils import timezone as tz +from django.apps import apps +from django.contrib.auth.tokens import default_token_generator +from django.conf import settings +from safedelete.models import SafeDeleteModel, SOFT_DELETE +from safedelete.managers import SafeDeleteManager +import jwt + +class JWT: + + @staticmethod + def encode(payload): + return jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256') + + @staticmethod + def decode(encoded): + return jwt.decode(encoded, settings.SECRET_KEY) + +class UserManager(SafeDeleteManager, BaseUserManager): + def create_user(self, email, password=None, unusable_password=False, **kwargs): + user = self.model(email=email, password=password, **kwargs) + + user.save(using=self._db, unusable_password=unusable_password) + return user + + def create_superuser(self, email, password): + user = self.create_user(email, password=password,) + user.is_admin = True + user.save(using=self._db) + return user + + def get_by_natural_key(self, username): + case_insensitive_username_field = '{}__iexact'.format(self.model.USERNAME_FIELD) + return self.get(**{case_insensitive_username_field: username}) + +class User(SafeDeleteModel, AbstractBaseUser): + + _safedelete_policy = SOFT_DELETE + + USERNAME_FIELD = 'username' + + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + password = models.CharField(max_length=128, + verbose_name='password', + validators=[password_validation.validate_password]) + email = models.EmailField( + verbose_name='email address', + max_length=255, + unique=True, + ) + is_active = models.BooleanField(default=True) + is_verified = models.BooleanField(default=False) + is_admin = models.BooleanField(default=False) + deleted = models.BooleanField(default=False) + flagged = models.BooleanField(default=False) + private = models.BooleanField(default=False) + name = models.CharField(max_length=50, null=True, blank=True) + avatar = models.TextField(blank=True, null=True) + heroImage = models.TextField(blank=True, null=True) + github_id = models.TextField(max_length=255, blank=True) + + objects = UserManager() + + def __str__(self): + return self.username + + def save(self, *args, **kwargs): + + if self.tracker.has_changed('email'): + self.email = self.email.lower() + + if kwargs.get("unusable_password"): + self.set_unusable_password() + + self.full_clean(exclude=["id"]) + + if self.tracker.has_changed('password') and not kwargs.get("unusable_password"): + self.set_password(self.password) + + kwargs.pop("unusable_password", None) + + self.full_clean() + super(User, self).save(*args, **kwargs) + + def generate_profile_edit_token(self): + return JWT.encode({'user_id': self.id, + 'token': default_token_generator.make_token(self)}) + + def get_full_name(self): + return self.name + + def has_perm(self, perm, obj=None): + return True + + def has_module_perms(self, app_label): + "Does the user have permissions to view the app `app_label`?" + return True + + def profile_url(self): + return f'{settings.FRONTEND_DOMAIN}/profile/{ self.username }' + + @property + def is_staff(self): + return self.is_admin + + @property + def is_superuser(self): + return self.is_admin + + @property + def old_password(self): + pass diff --git a/usermanagement/urls.py b/usermanagement/urls.py new file mode 100644 index 0000000..2f4f101 --- /dev/null +++ b/usermanagement/urls.py @@ -0,0 +1,10 @@ +from django.conf.urls import url, include +from rest_framework import routers + +router = routers.DefaultRouter(trailing_slash=False) +# router.register(r'users', views.UserViewSet, base_name='User') +# router.register(r'currentuser', views.CurrentUserViewSet, base_name='User') + +urlpatterns = [ + url(r'^', include(router.urls)), +] diff --git a/usermanagement/views.py b/usermanagement/views.py new file mode 100644 index 0000000..3711970 --- /dev/null +++ b/usermanagement/views.py @@ -0,0 +1,29 @@ +from rest_framework import viewsets, mixins, status +from rest_framework.views import APIView +from rest_framework.generics import GenericAPIView +from rest_framework.response import Response +from rest_framework.permissions import IsAuthenticated, AllowAny +from usermanagement.models import User +from usermanagement.serializers import UserPracticeSerializer, SalutationSerializer, PasswordResetSerializer, TokenSetPasswordSerializer, TokenizedProfileSerializer, UserPatientSerializer, ProviderProfileSerializer +from usermanagement.permissions import IsCreationOrIsAuthenticatedOrHasValidToken +from django.contrib.auth.tokens import default_token_generator +from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode +from django.utils.encoding import force_bytes +from django.core.exceptions import ValidationError +from django.shortcuts import redirect +from django.conf import settings +from datetime import datetime + +class CurrentUserViewSet(viewsets.ReadOnlyModelViewSet): + permission_classes = [IsAuthenticated,] + + def get_queryset(self): + user = self.request.user + return User.objects.filter(pk=user.id) + + def get_serializer_class(self): + if self.request.user.is_patient: + return UserPatientSerializer + else: + return UserPracticeSerializer + From ad8b0eecb90ddd74df70fd1e0fbba8899c86a3ef Mon Sep 17 00:00:00 2001 From: David Silva Date: Sat, 29 Sep 2018 19:39:22 -0400 Subject: [PATCH 06/15] created profile models and migrations --- api/settings.py | 1 + profile/__init__.py | 0 profile/apps.py | 6 ++++ profile/migrations/0001_initial.py | 48 ++++++++++++++++++++++++++++++ profile/migrations/__init__.py | 0 profile/models.py | 37 +++++++++++++++++++++++ 6 files changed, 92 insertions(+) create mode 100644 profile/__init__.py create mode 100644 profile/apps.py create mode 100644 profile/migrations/0001_initial.py create mode 100644 profile/migrations/__init__.py create mode 100644 profile/models.py diff --git a/api/settings.py b/api/settings.py index 6cc9e85..a3c480f 100644 --- a/api/settings.py +++ b/api/settings.py @@ -41,6 +41,7 @@ 'adminplus', 'rest_framework', 'usermanagement.apps.UsermanagementConfig', + 'profile.apps.ProfileConfig', ] MIDDLEWARE = [ diff --git a/profile/__init__.py b/profile/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/profile/apps.py b/profile/apps.py new file mode 100644 index 0000000..89ddf62 --- /dev/null +++ b/profile/apps.py @@ -0,0 +1,6 @@ +from __future__ import unicode_literals +from django.apps import AppConfig + +class ProfileConfig(AppConfig): + name = 'profile' + verbose_name = 'Profile Management' diff --git a/profile/migrations/0001_initial.py b/profile/migrations/0001_initial.py new file mode 100644 index 0000000..08b7dd4 --- /dev/null +++ b/profile/migrations/0001_initial.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.3 on 2018-09-29 23:38 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('usermanagement', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Profile', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('tagline', models.CharField(blank=True, max_length=255)), + ('bio', models.TextField(blank=True)), + ('location', models.CharField(blank=True, max_length=255)), + ('linkedin_url', models.CharField(blank=True, max_length=255)), + ('twitter_url', models.CharField(blank=True, max_length=255)), + ('github_url', models.CharField(blank=True, max_length=255)), + ('company', models.CharField(blank=True, max_length=255)), + ('blog', models.CharField(blank=True, max_length=255)), + ('public_repos', models.CharField(blank=True, max_length=255)), + ('hireable', models.BooleanField(default=False)), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='user', to='usermanagement.User')), + ], + ), + migrations.CreateModel( + name='ProfileURL', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('name', models.CharField(max_length=250)), + ('description', models.TextField(blank=True)), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='usermanagement.User')), + ], + ), + ] diff --git a/profile/migrations/__init__.py b/profile/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/profile/models.py b/profile/models.py new file mode 100644 index 0000000..ad2b845 --- /dev/null +++ b/profile/models.py @@ -0,0 +1,37 @@ +from __future__ import unicode_literals +from django.db import models +from django.core.exceptions import ValidationError +from django.utils import timezone as tz +from django.apps import apps +import pytz +from django.conf import settings +from safedelete.models import SafeDeleteModel, SOFT_DELETE +from usermanagement.models import User + +class ProfileURL(models.Model): + def __str__(self): + return self.name + + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + name = models.CharField(max_length=250,) + description = models.TextField(blank=True) + user = models.ForeignKey(User, on_delete=models.DO_NOTHING) + +class Profile(models.Model): + def __str__(self): + return self.user.username + + user = models.ForeignKey(User, related_name='user', on_delete=models.DO_NOTHING) + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + tagline = models.CharField(max_length=255, blank=True) + bio = models.TextField(blank=True) + location = models.CharField(max_length=255, blank=True) + linkedin_url = models.CharField(max_length=255, blank=True) + twitter_url = models.CharField(max_length=255, blank=True) + github_url = models.CharField(max_length=255, blank=True) + company = models.CharField(max_length=255, blank=True) + blog = models.CharField(max_length=255, blank=True) + public_repos = models.CharField(max_length=255, blank=True) + hireable = models.BooleanField(default=False) From 2d9115259db54e63f6a5153c79b0ea860fef6f59 Mon Sep 17 00:00:00 2001 From: David Silva Date: Sat, 29 Sep 2018 19:39:57 -0400 Subject: [PATCH 07/15] Created challenge model and migrations --- api/settings.py | 1 + challenges/__init.py__ | 0 challenges/apps.py | 6 ++ challenges/migrations/0001_initial.py | 91 +++++++++++++++++++++++++++ challenges/migrations/__init__.py | 0 challenges/models.py | 56 +++++++++++++++++ 6 files changed, 154 insertions(+) create mode 100644 challenges/__init.py__ create mode 100644 challenges/apps.py create mode 100644 challenges/migrations/0001_initial.py create mode 100644 challenges/migrations/__init__.py create mode 100644 challenges/models.py diff --git a/api/settings.py b/api/settings.py index a3c480f..2144b30 100644 --- a/api/settings.py +++ b/api/settings.py @@ -41,6 +41,7 @@ 'adminplus', 'rest_framework', 'usermanagement.apps.UsermanagementConfig', + 'challenges.apps.ChallengesConfig', 'profile.apps.ProfileConfig', ] diff --git a/challenges/__init.py__ b/challenges/__init.py__ new file mode 100644 index 0000000..e69de29 diff --git a/challenges/apps.py b/challenges/apps.py new file mode 100644 index 0000000..13db77d --- /dev/null +++ b/challenges/apps.py @@ -0,0 +1,6 @@ +from __future__ import unicode_literals +from django.apps import AppConfig + +class ChallengesConfig(AppConfig): + name = 'challenges' + verbose_name = 'Challenge Management' diff --git a/challenges/migrations/0001_initial.py b/challenges/migrations/0001_initial.py new file mode 100644 index 0000000..f5d16ae --- /dev/null +++ b/challenges/migrations/0001_initial.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.3 on 2018-09-29 23:39 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('usermanagement', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Attachment', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('name', models.CharField(max_length=250)), + ('url', models.TextField()), + ('active', models.BooleanField(default=True)), + ], + ), + migrations.CreateModel( + name='Challenge', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('deleted', models.DateTimeField(editable=False, null=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('visible', models.BooleanField(default=True)), + ('title', models.CharField(max_length=250)), + ('short_title', models.CharField(max_length=250)), + ('owner', models.CharField(max_length=250)), + ('difficulty', models.CharField(max_length=250)), + ('challenge_type', models.CharField(max_length=250)), + ('date_created', models.DateTimeField()), + ('priority', models.CharField(max_length=250)), + ('description', models.TextField()), + ('short_description', models.TextField()), + ('extra_points', models.TextField()), + ('technical_notes', models.TextField()), + ('procedure', models.TextField()), + ('code_tips', models.TextField()), + ], + options={ + 'abstract': False, + }, + ), + migrations.CreateModel( + name='Source', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('name', models.CharField(max_length=250)), + ('url', models.TextField()), + ('active', models.BooleanField(default=True)), + ('challenge', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='challenges.Challenge')), + ], + ), + migrations.CreateModel( + name='Tag', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('name', models.CharField(max_length=250)), + ], + ), + migrations.AddField( + model_name='challenge', + name='tags', + field=models.ManyToManyField(to='challenges.Tag'), + ), + migrations.AddField( + model_name='challenge', + name='user', + field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='usermanagement.User'), + ), + migrations.AddField( + model_name='attachment', + name='challenge', + field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='challenges.Challenge'), + ), + ] diff --git a/challenges/migrations/__init__.py b/challenges/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/challenges/models.py b/challenges/models.py new file mode 100644 index 0000000..0de95b0 --- /dev/null +++ b/challenges/models.py @@ -0,0 +1,56 @@ +from django.db import models +from safedelete.models import SafeDeleteModel, SOFT_DELETE +from usermanagement.models import User + +class Tag(models.Model): + def __str__(self): + return self.name + + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + name = models.CharField(max_length=250,) + +class Challenge(SafeDeleteModel): + + _safedelete_policy = SOFT_DELETE + + user = models.ForeignKey(User, on_delete=models.DO_NOTHING) + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + visible = models.BooleanField(default=True) + title = models.CharField(max_length=250,) + short_title = models.CharField(max_length=250,) + owner = models.CharField(max_length=250,) + difficulty = models.CharField(max_length=250,) + challenge_type = models.CharField(max_length=250,) + date_created = models.DateTimeField() + priority = models.CharField(max_length=250) + description = models.TextField() + short_description = models.TextField() + extra_points = models.TextField() + technical_notes = models.TextField() + procedure = models.TextField() + code_tips = models.TextField() + tags = models.ManyToManyField(Tag) + +class Attachment(models.Model): + def __str__(self): + return self.name + + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + name = models.CharField(max_length=250,) + url = models.TextField() + active = models.BooleanField(default=True) + challenge = models.ForeignKey(Challenge, on_delete=models.DO_NOTHING) + +class Source(models.Model): + def __str__(self): + return self.name + + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + name = models.CharField(max_length=250,) + url = models.TextField() + active = models.BooleanField(default=True) + challenge = models.ForeignKey(Challenge, on_delete=models.DO_NOTHING) From 057d58d8d0a28b425b67071907f1a3ae0a059aae Mon Sep 17 00:00:00 2001 From: David Silva Date: Sun, 30 Sep 2018 23:38:29 -0400 Subject: [PATCH 08/15] Fixed extension on README --- README => README.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename README => README.md (100%) diff --git a/README b/README.md similarity index 100% rename from README rename to README.md From 473edd77e911d7bb15e2c4ae53e2f0d75d9415de Mon Sep 17 00:00:00 2001 From: David Silva Date: Mon, 1 Oct 2018 00:05:35 -0400 Subject: [PATCH 09/15] created admin screens for profile and profile urls --- profile/admin.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 profile/admin.py diff --git a/profile/admin.py b/profile/admin.py new file mode 100644 index 0000000..a597433 --- /dev/null +++ b/profile/admin.py @@ -0,0 +1,15 @@ +from django.contrib import admin +from .models import Profile, ProfileURL + +class ProfileAdmin(admin.ModelAdmin): + list_display = ('user', 'location', 'company') + + pass + +class ProfileURLAdmin(admin.ModelAdmin): + list_display = ('user', 'name') + + pass + +admin.site.register(Profile, ProfileAdmin) +admin.site.register(ProfileURL, ProfileURLAdmin) From 4753e0b66b62ccd8782a3a369a83a79fcae8e502 Mon Sep 17 00:00:00 2001 From: David Silva Date: Tue, 2 Oct 2018 00:07:16 -0400 Subject: [PATCH 10/15] Using a password and username diff than default for pg --- .gitignore | 2 ++ Dockerfile | 12 ++++++------ api/settings.py | 5 +++-- api/urls.py | 5 +---- docker-compose.yml | 7 ++++++- entrypoint.sh | 4 ++++ 6 files changed, 22 insertions(+), 13 deletions(-) create mode 100755 entrypoint.sh diff --git a/.gitignore b/.gitignore index b0a25d6..de02bc9 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,5 @@ __pycache__/ .DS_Store .envrc .vscode +backups +data diff --git a/Dockerfile b/Dockerfile index d8e8262..7b3f2b4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ - FROM python:3.6 - ENV PYTHONUNBUFFERED 1 - RUN mkdir /code - WORKDIR /code - ADD requirements.txt /code/ - RUN pip install -r requirements.txt +FROM python:3.6 +ENV PYTHONUNBUFFERED 1 +RUN mkdir /code +WORKDIR /code +ADD requirements.txt /code/ +RUN pip install -r requirements.txt diff --git a/api/settings.py b/api/settings.py index 2144b30..2dc7378 100644 --- a/api/settings.py +++ b/api/settings.py @@ -82,8 +82,9 @@ DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', - 'NAME': 'postgres', - 'USER': 'postgres', + 'NAME': 'dbName', + 'PASSWORD': 'dbPassword', + 'USER': 'dbUsername', 'HOST': 'db', 'PORT': 5432, } diff --git a/api/urls.py b/api/urls.py index 3cb3ba7..b199a00 100644 --- a/api/urls.py +++ b/api/urls.py @@ -1,14 +1,11 @@ from django.conf.urls import url, include from django.contrib import admin -# from adminplus.sites import AdminSitePlus urlpatterns = [ url(r'^admin/', admin.site.urls), ] -# admin.site = AdminSitePlus() -# admin.sites.site = admin.site -# admin.autodiscover() +admin.autodiscover() admin.site.site_header = 'codecorgi Admin' diff --git a/docker-compose.yml b/docker-compose.yml index fef9f97..4f2f8b7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,9 +9,14 @@ services: - "5432" volumes: - ./backups:/home/backups + - ./data/postgres:/var/lib/postgresql/data + environment: + - POSTGRES_PASSWORD=dbPassword + - POSTGRES_USER=dbUsername + - POSTGRES_DB=dbName web: build: . - command: python3 manage.py runserver 0.0.0.0:9000 + command: ./entrypoint.sh volumes: - .:/code ports: diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100755 index 0000000..312d8f6 --- /dev/null +++ b/entrypoint.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +sleep 5s +python3 manage.py migrate +python3 manage.py runserver 0.0.0.0:9000 From 408d9d9cc9882b715c0fb5df585316e6080502cc Mon Sep 17 00:00:00 2001 From: David Silva Date: Tue, 2 Oct 2018 01:43:00 -0400 Subject: [PATCH 11/15] Sleeping the django init to ensure the db has fully started --- entrypoint.sh | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/entrypoint.sh b/entrypoint.sh index 312d8f6..bcf162a 100755 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -1,4 +1,3 @@ #!/usr/bin/env bash -sleep 5s -python3 manage.py migrate +sleep 10s python3 manage.py runserver 0.0.0.0:9000 From 58f00121f06dce4bfd08208fdbcc6cc89e0ee6a5 Mon Sep 17 00:00:00 2001 From: David Silva Date: Tue, 2 Oct 2018 01:43:18 -0400 Subject: [PATCH 12/15] created a utils file for helpers --- api/utils.py | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 api/utils.py diff --git a/api/utils.py b/api/utils.py new file mode 100644 index 0000000..1342b39 --- /dev/null +++ b/api/utils.py @@ -0,0 +1,5 @@ +import string +import random + +def id_generator(size=18, chars=string.ascii_uppercase + string.digits): + return ''.join(random.choice(chars) for _ in range(size)) From 5e885b3e90446b121202260b3c0a10f842a5a00c Mon Sep 17 00:00:00 2001 From: David Silva Date: Tue, 2 Oct 2018 01:45:26 -0400 Subject: [PATCH 13/15] Reran makemigrations and ensured that createsuperuser works --- api/settings.py | 2 ++ challenges/migrations/0001_initial.py | 7 ++--- profile/migrations/0001_initial.py | 9 ++++--- requirements.txt | 1 + usermanagement/migrations/0001_initial.py | 12 ++++++--- usermanagement/models.py | 33 +++++++++++++++++------ 6 files changed, 46 insertions(+), 18 deletions(-) diff --git a/api/settings.py b/api/settings.py index 2dc7378..978bc4e 100644 --- a/api/settings.py +++ b/api/settings.py @@ -127,3 +127,5 @@ # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' + +AUTH_USER_MODEL = 'usermanagement.User' diff --git a/challenges/migrations/0001_initial.py b/challenges/migrations/0001_initial.py index f5d16ae..20758c9 100644 --- a/challenges/migrations/0001_initial.py +++ b/challenges/migrations/0001_initial.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- -# Generated by Django 1.11.3 on 2018-09-29 23:39 +# Generated by Django 1.11.3 on 2018-10-02 05:14 from __future__ import unicode_literals +from django.conf import settings from django.db import migrations, models import django.db.models.deletion @@ -11,7 +12,7 @@ class Migration(migrations.Migration): initial = True dependencies = [ - ('usermanagement', '0001_initial'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ @@ -81,7 +82,7 @@ class Migration(migrations.Migration): migrations.AddField( model_name='challenge', name='user', - field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='usermanagement.User'), + field=models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='attachment', diff --git a/profile/migrations/0001_initial.py b/profile/migrations/0001_initial.py index 08b7dd4..76462ed 100644 --- a/profile/migrations/0001_initial.py +++ b/profile/migrations/0001_initial.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- -# Generated by Django 1.11.3 on 2018-09-29 23:38 +# Generated by Django 1.11.3 on 2018-10-02 05:14 from __future__ import unicode_literals +from django.conf import settings from django.db import migrations, models import django.db.models.deletion @@ -11,7 +12,7 @@ class Migration(migrations.Migration): initial = True dependencies = [ - ('usermanagement', '0001_initial'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ @@ -31,7 +32,7 @@ class Migration(migrations.Migration): ('blog', models.CharField(blank=True, max_length=255)), ('public_repos', models.CharField(blank=True, max_length=255)), ('hireable', models.BooleanField(default=False)), - ('user', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='user', to='usermanagement.User')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, related_name='user', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( @@ -42,7 +43,7 @@ class Migration(migrations.Migration): ('updated_at', models.DateTimeField(auto_now=True)), ('name', models.CharField(max_length=250)), ('description', models.TextField(blank=True)), - ('user', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='usermanagement.User')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL)), ], ), ] diff --git a/requirements.txt b/requirements.txt index 8ee6028..1cd488c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,3 +7,4 @@ django-safedelete==0.4.5 django-adminplus==0.5 Markdown==2.6.8 pyjwt==1.5.2 +django-model-utils==3.0.0 diff --git a/usermanagement/migrations/0001_initial.py b/usermanagement/migrations/0001_initial.py index 99246ae..f92e5bb 100644 --- a/usermanagement/migrations/0001_initial.py +++ b/usermanagement/migrations/0001_initial.py @@ -1,9 +1,10 @@ # -*- coding: utf-8 -*- -# Generated by Django 1.11.3 on 2018-09-29 23:35 +# Generated by Django 1.11.3 on 2018-10-02 05:14 from __future__ import unicode_literals import django.contrib.auth.password_validation from django.db import migrations, models +import usermanagement.models class Migration(migrations.Migration): @@ -21,12 +22,13 @@ class Migration(migrations.Migration): ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), + ('deleted', models.DateTimeField(editable=False, null=True)), ('password', models.CharField(max_length=128, validators=[django.contrib.auth.password_validation.validate_password], verbose_name='password')), ('email', models.EmailField(max_length=255, unique=True, verbose_name='email address')), + ('username', models.CharField(max_length=100, unique=True)), ('is_active', models.BooleanField(default=True)), ('is_verified', models.BooleanField(default=False)), ('is_admin', models.BooleanField(default=False)), - ('deleted', models.BooleanField(default=False)), ('flagged', models.BooleanField(default=False)), ('private', models.BooleanField(default=False)), ('name', models.CharField(blank=True, max_length=50, null=True)), @@ -35,7 +37,11 @@ class Migration(migrations.Migration): ('github_id', models.TextField(blank=True, max_length=255)), ], options={ - 'abstract': False, + 'verbose_name': 'user', + 'verbose_name_plural': 'users', }, + managers=[ + ('objects', usermanagement.models.UserManager()), + ], ), ] diff --git a/usermanagement/models.py b/usermanagement/models.py index 5ea778b..43e7917 100644 --- a/usermanagement/models.py +++ b/usermanagement/models.py @@ -9,6 +9,7 @@ from django.conf import settings from safedelete.models import SafeDeleteModel, SOFT_DELETE from safedelete.managers import SafeDeleteManager +from model_utils import FieldTracker import jwt class JWT: @@ -22,14 +23,16 @@ def decode(encoded): return jwt.decode(encoded, settings.SECRET_KEY) class UserManager(SafeDeleteManager, BaseUserManager): + use_in_migrations = True + def create_user(self, email, password=None, unusable_password=False, **kwargs): user = self.model(email=email, password=password, **kwargs) user.save(using=self._db, unusable_password=unusable_password) return user - def create_superuser(self, email, password): - user = self.create_user(email, password=password,) + def create_superuser(self, email, username, password): + user = self.create_user(email, password=password, username=username) user.is_admin = True user.save(using=self._db) return user @@ -38,26 +41,29 @@ def get_by_natural_key(self, username): case_insensitive_username_field = '{}__iexact'.format(self.model.USERNAME_FIELD) return self.get(**{case_insensitive_username_field: username}) -class User(SafeDeleteModel, AbstractBaseUser): +class User(AbstractBaseUser, SafeDeleteModel): _safedelete_policy = SOFT_DELETE - USERNAME_FIELD = 'username' + USERNAME_FIELD = 'email' + REQUIRED_FIELDS = ['username'] created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) - password = models.CharField(max_length=128, - verbose_name='password', - validators=[password_validation.validate_password]) + password = models.CharField( + max_length=128, + verbose_name='password', + validators=[password_validation.validate_password] + ) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) + username = models.CharField(max_length=100, unique=True) is_active = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) - deleted = models.BooleanField(default=False) flagged = models.BooleanField(default=False) private = models.BooleanField(default=False) name = models.CharField(max_length=50, null=True, blank=True) @@ -65,8 +71,16 @@ class User(SafeDeleteModel, AbstractBaseUser): heroImage = models.TextField(blank=True, null=True) github_id = models.TextField(max_length=255, blank=True) + tracker = FieldTracker() + objects = UserManager() + + class Meta: + verbose_name = 'user' + verbose_name_plural = 'users' + + def __str__(self): return self.username @@ -95,6 +109,9 @@ def generate_profile_edit_token(self): def get_full_name(self): return self.name + def get_short_name(self): + return self.name + def has_perm(self, perm, obj=None): return True From 7cdf0a8798157de3f292db7dee47e9671807db59 Mon Sep 17 00:00:00 2001 From: David Silva Date: Tue, 2 Oct 2018 01:45:43 -0400 Subject: [PATCH 14/15] created admin pages for the usermanagement --- usermanagement/admin.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 usermanagement/admin.py diff --git a/usermanagement/admin.py b/usermanagement/admin.py new file mode 100644 index 0000000..f76ee48 --- /dev/null +++ b/usermanagement/admin.py @@ -0,0 +1,9 @@ +from django.contrib import admin +from .models import User + +class UserAdmin(admin.ModelAdmin): + list_display = ('email',) + + pass + +admin.site.register(User, UserAdmin) From d0b60c0b443d79bfc4dfda7bf505848c14ad6c93 Mon Sep 17 00:00:00 2001 From: David Silva Date: Tue, 2 Oct 2018 01:45:58 -0400 Subject: [PATCH 15/15] created a migration for the codecorgi user --- profile/migrations/0002_codecorgi_profile.py | 49 ++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 profile/migrations/0002_codecorgi_profile.py diff --git a/profile/migrations/0002_codecorgi_profile.py b/profile/migrations/0002_codecorgi_profile.py new file mode 100644 index 0000000..0c59507 --- /dev/null +++ b/profile/migrations/0002_codecorgi_profile.py @@ -0,0 +1,49 @@ +from django.db import migrations, models +from api.utils import id_generator + +def create_codecorgi_profile(apps, schema_editor): + User = apps.get_model('usermanagement', 'User') + Profile = apps.get_model('profile', 'Profile') + + corgiUser = User.objects.create( + password=id_generator(), + email='woof@codecorgi.co', + is_verified=True, + is_admin=True, + name='corginson', + username='codecorgi', + avatar='https://raw.githubusercontent.com/corgicode/frontend-react/dev/src/assets/images/logo-square-hover.png', + heroImage='https://raw.githubusercontent.com/corgicode/frontend-react/dev/src/assets/images/hero-image.jpg', + ) + + Profile.objects.create( + tagline = 'Woof Woof', + bio = 'Coder\'s best friend', + location = 'Brooklyn, NY', + linkedin_url = 'https://www.linkedin.com/company/codecorgi', + twitter_url = 'https://twitter.com/codecorgi', + github_url = 'https://github.com/corgicode', + company = 'codecorgi', + blog = 'https://medium.com/@codecorgi', + public_repos = '', + hireable = False, + user = corgiUser, + ) + +def delete_codecorgi_profile(apps, schema_editor): + User = apps.get_model('usermanagement', 'User') + Profile = apps.get_model('profile', 'Profile') + + corgiUser = User.objects.filter(email='woof@codecorgi.co').first() + Profile.objects.filter(user_id=corgiUser.id).delete() + corgiUser.delete() + + +class Migration(migrations.Migration): + dependencies = [ + ('profile', '0001_initial') + ] + + operations = [ + migrations.RunPython(create_codecorgi_profile, delete_codecorgi_profile), + ]