commit b82ed72185d34022e2b4cdf3da02f5d034465535 Author: downhill Date: Tue Oct 9 19:49:47 2018 +0200 initial commit diff --git a/dal/dal/__init__.py b/dal/dal/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/dal/dal/settings.py b/dal/dal/settings.py new file mode 100644 index 0000000..d3cf036 --- /dev/null +++ b/dal/dal/settings.py @@ -0,0 +1,162 @@ +""" +Django settings for dal project. + +Generated by 'django-admin startproject' using Django 1.10.7. + +For more information on this file, see +https://docs.djangoproject.com/en/1.10/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/1.10/ref/settings/ +""" + +import os + +import ldap + +from django_auth_ldap.config import LDAPSearch, LDAPSearchUnion + +# LDAP config + +# The search user +AUTH_LDAP_BIND_DN = "" +# The password for the search user +AUTH_LDAP_BIND_PASSWORD = "" +# Search union over two ou +AUTH_LDAP_USER_SEARCH = LDAPSearchUnion( + LDAPSearch("ou=users,dc=ungleich,dc=ch", ldap.SCOPE_SUBTREE, "(uid=%(user)s)"), + LDAPSearch("ou=customers,dc=ungleich,dc=ch", ldap.SCOPE_SUBTREE, "(uid=%(user)s)"), + ) + +# Basic User +#AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,ou=users,dc=ungleich,dc=ch" + +# Search over just one ou +#AUTH_LDAP_USER_SEARCH = LDAPSearch( LDAPSearch("ou=users,dc=ungleich,dc=ch", +# ldap.SCOPE_SUBTREE, "(uid=%(user)s)") +# ) + + +# Maps some user keys since ldap has extensive infos +#AUTH_LDAP_USER_ATTR_MAP = {"first_name": "givenName", "last_name": "sn"} + +# Maps some profile keys since ldap has extensive infos +#AUTH_LDAP_PROFILE_ATTR_MAP = {"home_directory": "homeDirectory"} + +# LDAP config end + + +# 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.10/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'rn=f&ecp#&#escxpk!0e%a$i3sbm$z@5+g4h9q+w7-83*f2f-i' + +# 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', +] + +# Backend for auth + +#AUTHENTICATION_BACKENDS = ( +# 'django_auth_ldap.backend.LDAPBackend', +# 'django.contrib.auth.backends.ModelBackend', +#) + + +ROOT_URLCONF = 'dal.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 = 'dal.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/1.10/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + } +} + + +# Password validation +# https://docs.djangoproject.com/en/1.10/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.10/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.10/howto/static-files/ + +STATIC_URL = '/static/' diff --git a/dal/dal/templates/changedataerror.html b/dal/dal/templates/changedataerror.html new file mode 100644 index 0000000..e69de29 diff --git a/dal/dal/templates/changeddata.html b/dal/dal/templates/changeddata.html new file mode 100644 index 0000000..e69de29 diff --git a/dal/dal/templates/changepassword.html b/dal/dal/templates/changepassword.html new file mode 100644 index 0000000..e69de29 diff --git a/dal/dal/templates/changeuserdata.html b/dal/dal/templates/changeuserdata.html new file mode 100644 index 0000000..e69de29 diff --git a/dal/dal/templates/error.html b/dal/dal/templates/error.html new file mode 100644 index 0000000..e69de29 diff --git a/dal/dal/templates/landing.html b/dal/dal/templates/landing.html new file mode 100644 index 0000000..e69de29 diff --git a/dal/dal/templates/loginfailed.html b/dal/dal/templates/loginfailed.html new file mode 100644 index 0000000..e69de29 diff --git a/dal/dal/templates/mustbeloggedin.html b/dal/dal/templates/mustbeloggedin.html new file mode 100644 index 0000000..e69de29 diff --git a/dal/dal/templates/registererror.html b/dal/dal/templates/registererror.html new file mode 100644 index 0000000..e69de29 diff --git a/dal/dal/templates/registeruser.html b/dal/dal/templates/registeruser.html new file mode 100644 index 0000000..e69de29 diff --git a/dal/dal/templates/resetpassword.html b/dal/dal/templates/resetpassword.html new file mode 100644 index 0000000..e69de29 diff --git a/dal/dal/templates/useroptions.html b/dal/dal/templates/useroptions.html new file mode 100644 index 0000000..e69de29 diff --git a/dal/dal/urls.py b/dal/dal/urls.py new file mode 100644 index 0000000..c6d57da --- /dev/null +++ b/dal/dal/urls.py @@ -0,0 +1,31 @@ +"""dal URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/1.10/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.urls import path +from django.conf.urls import url +from django.contrib import admin + +from .views import Register, ChangeData, ResetPassword, DeleteAccount, Index + +urlpatterns = [ + path('admin/', admin.site.urls), + path('register/', Register.as_view(), name="register"), + path('changedata/', ChangeData.as_view(), name="change_data"), + path('resetpassword/', ResetPassword.as_view(), name="reset_password"), + path('changepassword/', ChangePassword.as_view(), name="change_password"), + path('deleteaccount/', DeleteAccount.as_view(), name="account_delete"), + path('/', Index.as_view(), name="index") +] diff --git a/dal/dal/views.py b/dal/dal/views.py new file mode 100644 index 0000000..9facc1c --- /dev/null +++ b/dal/dal/views.py @@ -0,0 +1,221 @@ +from django.shortcuts import render +from django.views.generic import View +from django.contrib.auth import authenticate, login +from django.contrib.auth.models import User +from django.http import HttpResponse, HttpResponseRedirect +from django.core.validators import email_re +from django.urls import reverse_lazy + + +# Check to see if the username is already taken +# Helper function, not to be set up as a view +def check_user_exists(username): + if User.objects.filter(username=username).exists(): + return True + # TODO: Needs to look up the LDAP + else return False + + +# The index page +# If there's a session open, it will give the user the options he/she/it can do, if not, +# it will show a landing page explaining what this is and prompt them to login + +class Index(View): + + # Basic binary choice, if it is an authenticated user, go straight to the options page, + # if not, then show the landing page + def get(self, request): + if request.user: + return render(request, 'useroptions.html') + return render(request, 'landing.html') + + # Basically does the same as the GET request, just with trying to login the user beforehand + # Shows an errorpage if authentication fails, since just looping to the landing page + # would be frustrating + def post(self, request): + username = request.POST.get('username') + password = request.POST.get('password') + user = authenticate(request, username=username, password=password) + if user is not None: + login(request, user) + return render(request, 'useroptions.html') + return render(request, 'loginfailed.html') + + +# Registering a user + +class Register(View): + + # Someone wants to register, throw up the page for that + def get(self, request): + return render(request, 'registeruser.html') + + # Someone filled out the register page, do some basic checks and throw it at nameko + def post(self, request): + # message for the error template + service = 'Registering an user' + # urlname for 'go back' on the errorpage + urlname = 'register' + # some basic check against DoS, since a hidden reference=ungleich will be given on the registeruser page + # real defense against DoS will not be on django, but this protects a bit against filling up our ldap with a + # basic curl script + # TODO: Think about some better protection + reference = request.POST.get('reference') + if reference != 'ungleich': + return HttpResponseRedirect(reverse_lazy('index')) + username = request.POST.get('username') + # Check to see if username is already taken + if self.check_user_exists(username): + return render(request, 'registererror.html', { 'urlname': urlname, 'service': service, 'error': 'User already exists.' } ) + # isalnum() may be a bit harsh, but is the most logical choice to make sure it's a username we + # can use + elif not username.isalnum(): + return render(request, 'registererror.html', { 'urlname': urlname, 'service': service, 'error': 'Username has to be alphanumeric.' } ) + password1 = request.POST.get('password1') + password2 = request.POST.get('password2') + # check if the supplied passwords match + if password1 != password2: + return render(request, 'registererror.html', { 'urlname': urlname, 'service': service, + 'error': 'Your passwords didn\'t match. Please supply the same password twice.' } ) + email = request.POST.get('email') + # Is the emailaddress valid? + if not email_re.match(email): + return render(request, 'registererror.html', { 'urlname': urlname, 'service': service, 'error': 'The supplied email address is invalid.' } ) + firstname = request.POST.get('firstname') + lastname = request.POST.get('lastname') + if firstname == "" or not firstname or lastname == "" or not lastname + return render(request, 'registererror.html', { 'urlname': urlname, 'service': service, 'error': 'Please enter your firstname and lastname.' } ) + # TODO: throw it to nameko to create the user + return render(request, 'usercreated.html', { 'user': username } ) + + + + +# Change user data for logged in users + +class ChangeData(View): + + # provide the form for the change request + def get(self, request): + if not request.user.is_authenticated: + return render(request, 'mustbeloggedin.html') + user = request.user + #TODO: nameko get basic data (firstname, lastname, email) + (firstname, lastname, email) = self.get_data(user) + # The template puts the old data as standard in the fields + return render(request, 'changeuserdata.html', { 'user': user, 'firstname': firstname, 'lastname': lastname, 'email': email } ) + + # get the change request + def post(self, request): + # variables for the error page + service = 'changing user data' + urlname = 'change_data' + + if not request.user.is_authenticated: + return render(request, 'mustbeloggedin.html') + + user = request.user + firstname = request.POST.get('firstname') + lastname = request.POST.get('lastname') + email = request.POST.get('email') + + # Some sanity checks for the supplied data + if firstname == "": + return render(request, 'error.html', { 'urlname': urlname, 'service': service, 'error': 'Please enter a firstname.' } ) + elif lastname == "": + return render(request, 'error.html', { 'urlname': urlname, 'service': service, 'error': 'Please enter a lastname.' } ) + elif email == "": + return render(request, 'error.html', { 'urlname': urlname, 'service': service, 'error': 'Please enter an email.' } ) + elif not email_re.match(email): + return render(request, 'error.html', { 'urlname': urlname, 'service': service, 'error': 'The supplied email address is invalid.' } ) + #TODO: nameko change data (firstname, lastname, email) + if self.change_data(firstname, lastname, email): + return render(request, 'changeddata.html', { 'user': user, 'firstname': firstname, 'lastname': lastname, 'email': email } ) + return render(request, 'error.html', { 'urlname': urlname, 'service': service, 'error': 'An unknown error occurred.' } ) + + # TODO: call nameko to get basic data from user + def get_data(self, user): + return ("a", "b", "c") + + # TODO: call nameko to change user data and think about return value + def change_data(self, firstname, lastname, email): + return True + +# Resets the password for a user +# Will need to send a confirmation email to the user and we will need a backend +# to confirm the request came from someone who has access to the email +# Out of scope except for creating the workflow + +class ResetPassword(View): + + # Presents the form with some information + def get(self, request): + return render(request, 'resetpassword.html') + + # gets the data from confirming the reset request and checks if it was not a misclick + # (by having the user type in his username + def post(self, request): + user = request.POST.get('user') + if check_user_exists(user): + #TODO: call nameko for sending a reset request + self.send_resetrequest(user) + return render(request, 'send_resetrequest.html', { 'user': user } ) + return render(request, 'must_confirm_reset.html') + + def send_resetrequest(self, user): + #TODO: call nameko to get the associated email and send a confirmation mail + return True + + +# The logged in user can change the password here + +class ChangePassword(View): + + # Presents the page for a logged in user + def get(self, request): + if not request.user.is_authenticated: + return render(request, 'mustbeloggedin.html') + return render(request, 'changepassword.html', { 'user': request.user } ) + + # Does some checks on the supplied data and changes the password + def post(self, request): + # Variables for the error page + urlname = 'change_password' + service = 'change the password' + + if not request.user.is_authenticated: + return render(request, 'mustbeloggedin.html') + + user = request.user + oldpassword = request.POST.get('oldpassword') + check = authenticate(request, username=user, password=oldpassword) + # Is the right password for the user supplied? + if check is None: + return render(request, 'error.html', { 'urlname': urlname, 'service': service, 'error': 'Wrong password for the user.' } ) + + password1 = request.POST.get('password1') + password2 = request.POST.get('password2') + # Are both passwords from the form the same? + if password1 != password2: + return render(request, 'error.html', { 'urlname': urlname, 'service': service, + 'error': 'Please check if you typed the same password both times for the new password' } ) + + # TODO: nameko change password + if self.change_password(user, oldpassword, password1): + return render(request, 'changedpassword.html', { 'user': user } ) + else: + return render(request, 'error.html', { 'urlname': urlname, 'service': service, 'error': 'Unknown error while changing the password!' } ) + + + # Changes the password for the supplied user + def change_password(self, user, oldpassword, password): + #TODO: write nameko function to change a password + return True + + + +class DeleteAccount(View): + def get(self, request): + return HttpResponse("Work in progress") + + diff --git a/dal/dal/wsgi.py b/dal/dal/wsgi.py new file mode 100644 index 0000000..b40f902 --- /dev/null +++ b/dal/dal/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for dal 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.10/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dal.settings") + +application = get_wsgi_application() diff --git a/dal/manage.py b/dal/manage.py new file mode 100755 index 0000000..deef784 --- /dev/null +++ b/dal/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +import os +import sys + +if __name__ == "__main__": + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dal.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)