diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6ff3849 --- /dev/null +++ b/.gitignore @@ -0,0 +1,228 @@ +# Created by https://www.toptal.com/developers/gitignore/api/django,python,vim +# Edit at https://www.toptal.com/developers/gitignore?templates=django,python,vim + +### Django ### +*.log +*.pot +*.pyc +__pycache__/ +local_settings.py +db.sqlite3 +db.sqlite3-journal +media + +# If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ +# in your Git repository. Update and uncomment the following line accordingly. +# /staticfiles/ + +### Django.Python Stack ### +# Byte-compiled / optimized / DLL files +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# 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/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo + +# Django stuff: + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +### Python ### +# Byte-compiled / optimized / DLL files + +# C extensions + +# Distribution / packaging + +# 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. + +# Installer logs + +# Unit test / coverage reports + +# Translations + +# Django stuff: + +# Flask stuff: + +# Scrapy stuff: + +# Sphinx documentation + +# PyBuilder + +# Jupyter Notebook + +# IPython + +# pyenv + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow + +# Celery stuff + +# SageMath parsed files + +# Environments + +# Spyder project settings + +# Rope project settings + +# mkdocs documentation + +# mypy + +# Pyre type checker + +# pytype static type analyzer + +### Vim ### +# Swap +[._]*.s[a-v][a-z] +!*.svg # comment out if you don't need vector files +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +*~ +# Auto-generated tag files +tags +# Persistent undo +[._]*.un~ + +# End of https://www.toptal.com/developers/gitignore/api/django,python,vim + +.vscode/ diff --git a/apps/__init__.py b/apps/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/__init__.py b/apps/users/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/admin.py b/apps/users/admin.py new file mode 100644 index 0000000..4a106f4 --- /dev/null +++ b/apps/users/admin.py @@ -0,0 +1,31 @@ +from django.contrib import admin +from django.contrib.auth.admin import UserAdmin as BaseUserAdmin +from .models import User, UserProfile + + +class UserAdmin(BaseUserAdmin): + list_display = ('email', 'is_student', 'is_staff', 'is_admin') + list_filter = ('is_student', 'is_admin') + fieldsets = ( + (None, {'fields': ('email', 'password')}), + ('Permissions', {'fields': ('is_student', 'is_admin', 'is_staff')}), + ) + + add_fieldsets = ( + (None, { + 'classes': ('wide',), + 'fields': ('email', 'password1', 'password2'), + }), + ) + + search_fields = ('email',) + ordering = ('email',) + filter_horizontal = () + + +class UserProfileAdmin(admin.ModelAdmin): + pass + + +admin.site.register(User, UserAdmin) +admin.site.register(UserProfile, UserProfileAdmin) diff --git a/apps/users/apps.py b/apps/users/apps.py new file mode 100644 index 0000000..4ce1fab --- /dev/null +++ b/apps/users/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class UsersConfig(AppConfig): + name = 'users' diff --git a/apps/users/migrations/0001_initial.py b/apps/users/migrations/0001_initial.py new file mode 100644 index 0000000..d5a83f5 --- /dev/null +++ b/apps/users/migrations/0001_initial.py @@ -0,0 +1,49 @@ +# Generated by Django 3.0.7 on 2020-06-14 16:12 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +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')), + ('password', models.CharField(max_length=128, verbose_name='password')), + ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), + ('email', models.EmailField(max_length=255, unique=True, verbose_name='email address')), + ('is_student', models.BooleanField(default=False)), + ('is_active', models.BooleanField(default=True)), + ('is_admin', models.BooleanField(default=False)), + ('is_staff', models.BooleanField(default=False)), + ], + options={ + 'abstract': False, + }, + ), + migrations.CreateModel( + name='UserProfile', + fields=[ + ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)), + ('first_name', models.CharField(max_length=100)), + ('last_name', models.CharField(max_length=100)), + ('preferred_name', models.CharField(max_length=100)), + ('image', models.ImageField(upload_to='profile-images')), + ('discord_name', models.CharField(max_length=100)), + ('github_username', models.CharField(max_length=100)), + ('codepen_username', models.CharField(max_length=100)), + ('fcc_profile_url', models.CharField(max_length=255)), + ('current_level', models.IntegerField(choices=[(1, 'Level One'), (2, 'Level Two')])), + ('phone', models.CharField(max_length=50)), + ('timezone', models.CharField(max_length=50)), + ], + ), + ] diff --git a/apps/users/migrations/__init__.py b/apps/users/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apps/users/models.py b/apps/users/models.py new file mode 100644 index 0000000..f1fc34f --- /dev/null +++ b/apps/users/models.py @@ -0,0 +1,85 @@ +from django.db import models +from django.contrib.auth.models import ( + BaseUserManager, AbstractBaseUser +) + + +class CustomUserManager(BaseUserManager): + def create_user(self, email, password=None): + if not email: + raise ValueError('Users must have an email address') + + user = self.model( + email=self.normalize_email(email), + ) + + user.set_password(password) + user.save(using=self._db) + return user + + def create_superuser(self, email, password=None): + user = self.create_user( + email, + password=password, + ) + user.is_admin = True + user.is_staff = True + user.save(using=self._db) + return user + + +class User(AbstractBaseUser): + email = models.EmailField( + verbose_name='email address', + max_length=255, + unique=True, + ) + is_student = models.BooleanField(default=False) + is_active = models.BooleanField(default=True) + is_admin = models.BooleanField(default=False) + is_staff = models.BooleanField(default=False) + + USERNAME_FIELD = 'email' + + objects = CustomUserManager() + + def __str__(self): + return self.email + + def has_perm(self, perm, obj=None): + "Does the user have a specific permission?" + # Simplest possible answer: Yes, always + return True + + def has_module_perms(self, app_label): + "Does the user have permissions to view the app `app_label`?" + # Simplest possible answer: Yes, always + return True + + +class UserProfile(models.Model): + user = models.OneToOneField( + User, + on_delete=models.CASCADE, + primary_key=True, + ) + first_name = models.CharField(max_length=100) + last_name = models.CharField(max_length=100) + preferred_name = models.CharField(max_length=100) + image = models.ImageField(upload_to='profile-images') + discord_name = models.CharField(max_length=100) + github_username = models.CharField(max_length=100) + codepen_username = models.CharField(max_length=100) + fcc_profile_url = models.CharField(max_length=255) + + LEVELS = ( + (1, 'Level One'), + (2, 'Level Two'), + ) + current_level = models.IntegerField(choices=LEVELS) + + phone = models.CharField(max_length=50) + timezone = models.CharField(max_length=50) + + def __str__(self): + return f'{self.first_name} {self.last_name}' diff --git a/apps/users/tests.py b/apps/users/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/apps/users/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/apps/users/urls.py b/apps/users/urls.py new file mode 100644 index 0000000..aaf8b68 --- /dev/null +++ b/apps/users/urls.py @@ -0,0 +1,10 @@ +from django.urls import path, include +from rest_framework import routers +from .views import UserViewSet + +router = routers.DefaultRouter() +router.register(r'', UserViewSet) + +urlpatterns = [ + path('', include(router.urls)), +] diff --git a/apps/users/views.py b/apps/users/views.py new file mode 100644 index 0000000..1654146 --- /dev/null +++ b/apps/users/views.py @@ -0,0 +1,17 @@ +from rest_framework import serializers, viewsets +from django.contrib.auth import get_user_model + + +class UserSerializer(serializers.ModelSerializer): + class Meta: + model = get_user_model() + fields = ('id', 'email', 'password') + extra_kwargs = {'password': {'write_only': True, 'min_length': 8}} + + def create(self, validated_data): + return get_user_model().objects.create_user(**validated_data) + + +class UserViewSet(viewsets.ModelViewSet): + queryset = get_user_model().objects.all() + serializer_class = UserSerializer diff --git a/config/__init__.py b/config/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/config/asgi.py b/config/asgi.py new file mode 100644 index 0000000..bc70790 --- /dev/null +++ b/config/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for freeCodeSchoolAPI project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') + +application = get_asgi_application() diff --git a/config/settings.py b/config/settings.py new file mode 100644 index 0000000..27205dd --- /dev/null +++ b/config/settings.py @@ -0,0 +1,131 @@ +""" +Django settings for freeCodeSchoolAPI project. + +Generated by 'django-admin startproject' using Django 3.0.5. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = '(l#*c#t%+ln$ofzg=-^&#-mqws!5cf8jcwfoh7$-+*31lbeqts' + +# 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', + 'rest_framework', + 'apps.users', +] + +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', +] + +AUTH_USER_MODEL = 'users.User' + +ROOT_URLCONF = 'config.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 = 'config.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/3.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'NAME': 'freecodeschool', + 'USER': 'fcs_admin', + 'PASSWORD': '', + 'HOST': 'localhost', + 'PORT': '', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/3.0/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/3.0/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/3.0/howto/static-files/ + +STATIC_URL = '/static/' + +MEDIA_ROOT = 'media' +MEDIA_URL = '/media/' diff --git a/config/urls.py b/config/urls.py new file mode 100644 index 0000000..1b5b11a --- /dev/null +++ b/config/urls.py @@ -0,0 +1,22 @@ +"""freeCodeSchoolAPI URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/3.0/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path, include + +urlpatterns = [ + path('admin/', admin.site.urls), + path('api/v1/users/', include('apps.users.urls')) +] diff --git a/config/wsgi.py b/config/wsgi.py new file mode 100644 index 0000000..25a1964 --- /dev/null +++ b/config/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for freeCodeSchoolAPI 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/3.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') + +application = get_wsgi_application() diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..58c5f10 --- /dev/null +++ b/manage.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + 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?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..895340d --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +asgiref==3.2.7 +Django==3.0.7 +djangorestframework==3.11.0 +pytz==2020.1 +sqlparse==0.3.1