Commit ad732b63 authored by David Haynes's avatar David Haynes 🙆

Simplified settings model + API bootstrap

- SessionAuth and TokenAuth
- utilizing some built in models
- ready for adoption in other issues
parent 8cac2674
Pipeline #2623 failed with stage
in 1 minute and 49 seconds
......@@ -6,7 +6,6 @@
venv
.venv
/provisioning/playbook.retry
/go/settings/settings.py
/go/settings/secret.py
/go/static/admin
/go/media
......
......@@ -13,3 +13,10 @@ Docs may not exist.
I wouldn't go so far as to say we are hitting the reset button.
But it's close.
```sh
pipenv install
pipenv shell
code .
docker-compose up
```
......@@ -14,10 +14,14 @@ from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils import timezone
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
# Other Imports
from hashids import Hashids
from .validators import regex_short_validator, unique_short_validator
from rest_framework.authtoken.models import Token
# Generate the salt and initialize Hashids
# Note: the Hashids library already implements several restrictions oncharacter
......@@ -88,6 +92,12 @@ def handle_reguser_creation(sender, instance, created, **kwargs):
if created:
RegisteredUser.objects.create(user=instance)
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
token = Token.objects.create(user=instance)
print(token.key)
class URL(models.Model):
"""
The representation of a stored URL redirection rule. Each URL has
......
"""
go/serializers.py
Define how data is translated from the database to json/API representation.
"""
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
......@@ -25,6 +25,25 @@ from .forms import EditForm, SignupForm, URLForm
from .models import URL, RegisteredUser
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from .serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
def index(request):
"""
If a user is logged in, this view displays all the information about all
......
......@@ -2,13 +2,8 @@
import os
import sys
if os.environ['GO_ENV'] == 'production':
settings = "settings.production"
else:
settings = "settings.local"
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.settings")
from django.core.management import execute_from_command_line
......
"""
settings/local.py
Local development settings and globals.
"""
from .base import *
# DEBUG mode is used to view more details when errors occur
# Do not have set True in production
DEBUG = True
#CAS_SERVER_URL = "https://cas.srct.gmu.edu/"
CAS_SERVER_URL = "https://login.gmu.edu"
# dummy cache for development-- doesn't actually cache things
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
"""
settings/production.py
Production settings and globals.
"""
from .base import *
# DEBUG mode is used to view more details when errors occur
# Do not have set True in production
DEBUG = False
CAS_SERVER_URL = "https://login.gmu.edu"
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': 'localhost:6379',
},
}
"""
settings/base.py
settings/settings.py
Base Settings.
Settings that are applied project wide.
"""
# Python stdlib Imports
import os
import sys
# DEV vs PROD
if os.environ['GO_ENV'] != 'production':
DEBUG = True
# dummy cache for development-- doesn't actually cache things
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
else:
DEBUG = False
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': 'localhost:6379',
},
}
# STANDALONE VARS
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
......@@ -109,6 +127,8 @@ INSTALLED_APPS = (
# Third party
'crispy_forms',
'cas',
'rest_framework',
'rest_framework.authtoken'
)
CRISPY_TEMPLATE_PACK = 'bootstrap4'
......@@ -166,6 +186,7 @@ CAS_RESPONSE_CALLBACKS = (
'go.cas_callbacks.create_user',
)
CAS_SERVER_URL = "https://login.gmu.edu"
"""
Mail Settings
......@@ -180,3 +201,16 @@ EMAIL_TO = os.environ['GO_EMAIL_TO']
# Domain used to email to users. See implementation in views.py
# ie. '@gmu.edu'
EMAIL_DOMAIN = os.environ['GO_EMAIL_DOMAIN']
"""
Django Rest Framework Settings
"""
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated'
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
}
......@@ -5,66 +5,74 @@ The URLs of the project and their associated view that requests are routed to.
"""
# Django Imports
import django.contrib.auth.views
from django.urls import path, re_path
from django.urls import path, re_path, include
from django.contrib import admin
from django.views.decorators.cache import cache_page
from django.views.generic import TemplateView
# App Imports
import go.views
from go import views
# Third Party
from rest_framework import routers
router = routers.DefaultRouter()
router.register('users', views.UserViewSet)
router.register('groups', views.GroupViewSet)
# This function attempts to import an admin module in each installed
# application. Such modules are expected to register models with the admin.
admin.autodiscover()
urlpatterns = [
# / - Homepage url. Cached for 1 second (this is the page you see after
# logging in, so having it show as not logged in is strange)
path('', cache_page(1)(go.views.index), name='index'),
# # / - Homepage url. Cached for 1 second (this is the page you see after
# # logging in, so having it show as not logged in is strange)
# path('', cache_page(1)(go.views.index), name='index'),
# /view/<short> - View URL data. Cached for 15 minutes
re_path(r'^view/(?P<short>([\U00010000-\U0010ffff][\U0000200D]?)+)$',
cache_page(60 * 15)(go.views.view), name='view'),
re_path(r'^view/(?P<short>[-\w]+)$',
cache_page(60 * 15)(go.views.view), name='view'),
# # /view/<short> - View URL data. Cached for 15 minutes
# re_path(r'^view/(?P<short>([\U00010000-\U0010ffff][\U0000200D]?)+)$',
# cache_page(60 * 15)(go.views.view), name='view'),
# re_path(r'^view/(?P<short>[-\w]+)$',
# cache_page(60 * 15)(go.views.view), name='view'),
# /about - About page. Cached for 15 minutes
path('about', cache_page(60 * 15)
(TemplateView.as_view(template_name='core/about.html')), name='about'),
# # /about - About page. Cached for 15 minutes
# path('about', cache_page(60 * 15)
# (TemplateView.as_view(template_name='core/about.html')), name='about'),
# /signup - Signup page for access. Cached for 15 minutes
path('signup', cache_page(60 * 15)(go.views.signup), name='signup'),
# # /signup - Signup page for access. Cached for 15 minutes
# path('signup', cache_page(60 * 15)(go.views.signup), name='signup'),
# /new - Create a new Go Link
path('new', go.views.new_link, name='new_link'),
# # /new - Create a new Go Link
# path('new', go.views.new_link, name='new_link'),
# /my - My-Links page, view and review links.
path('my', go.views.my_links, name='my_links'),
# # /my - My-Links page, view and review links.
# path('my', go.views.my_links, name='my_links'),
# /edit/<short> - Edit link form
path('edit/<slug:short>', go.views.edit, name='edit'),
# # /edit/<short> - Edit link form
# path('edit/<slug:short>', go.views.edit, name='edit'),
# /delete/<short> - Delete a link, no content display.
path('delete/<slug:short>', go.views.delete, name='delete'),
# # /delete/<short> - Delete a link, no content display.
# path('delete/<slug:short>', go.views.delete, name='delete'),
# /registered - registration complete page. Cached for 15 minutes
path('registered', cache_page(60 * 15)
(TemplateView.as_view(template_name='registered.html')), name='registered'),
# # /registered - registration complete page. Cached for 15 minutes
# path('registered', cache_page(60 * 15)
# (TemplateView.as_view(template_name='registered.html')), name='registered'),
# /admin - Administrator interface.
path('admin', admin.site.urls, name='go_admin'),
# # /admin - Administrator interface.
# path('admin', admin.site.urls, name='go_admin'),
# /manage - user approval interface
path('manage', go.views.useradmin, name='useradmin'),
# # /manage - user approval interface
# path('manage', go.views.useradmin, name='useradmin'),
# Authentication URLs
path('login', django.contrib.auth.views.login, name='go_login'),
path('logout', django.contrib.auth.views.logout,
{'next_page': '/'}, name='go_logout'),
# Authentication URLs
path('login', django.contrib.auth.views.login, name='go_login'),
path('logout', django.contrib.auth.views.logout, {'next_page': '/'}, name='go_logout'),
# Redirection regex.
re_path(r'^(?P<short>([\U00010000-\U0010ffff][\U0000200D]?)+)$',
go.views.redirection, name='redirection'),
re_path(r'^(?P<short>[-\w]+)$',
go.views.redirection, name='redirection'),
# # Redirection regex.
# re_path(r'^(?P<short>([\U00010000-\U0010ffff][\U0000200D]?)+)$',
# go.views.redirection, name='redirection'),
# re_path(r'^(?P<short>[-\w]+)$',
# go.views.redirection, name='redirection'),
path("", include(router.urls)),
]
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment