encryption functions and logging in views.py; AXES throttling prevention in settings.py
diff --git a/op_tasks/views.py b/op_tasks/views.py
index b35c41b..b7ea8e0 100755
--- a/op_tasks/views.py
+++ b/op_tasks/views.py
@@ -9,12 +9,21 @@
from django.contrib.auth.models import User
from django.utils import timezone
from elasticsearch import Elasticsearch
+from Crypto.Cipher import AES
import exp_portal
import datetime
from op_tasks.models import Product, UserProfile, TaskListItem, Experiment
+import exceptions
+import hashlib
+import logging
+#import zlib
+#import sqlite
+
+from op_tasks.models import Dataset, Product, OpTask, UserProfile, TaskListItem, Experiment
+logger = logging.getLogger('op_tasks')
def set_cookie(response, key, value, days_expire = 7):
if days_expire is None:
@@ -156,8 +165,46 @@
return render(request, 'task_launch.html', {'tasklistitem': tasklistitem})
+# Get unencrypted username
+def decryptUsername(request):
+ user = request.user
+ return aesDecryptor(user.username)
+
+# decrypt the text passed in
+def aesDecryptor(encryptedText):
+ key = readInKey('fileLocation') #'0123456789abcdef0123456789abcdef'
+ IV = 16 * '\x00' # Initialization vector: discussed later
+ mode = AES.MODE_CBC
+ decryptor = AES.new(key, mode, IV=IV)
+ plainText = decryptor.decrypt(ciphertext)
+ return plainText
+
+# encrypt the text passed in
+def aesEncryptor(plainText):
+ key = readInKey('fileLocation') #'0123456789abcdef0123456789abcdef'
+ IV = 16 * '\x00' # Initialization vector: discussed later
+ mode = AES.MODE_CBC
+ encryptor = AES.new(key, mode, IV=IV)
+ if len(plainText) % 16 != 0:
+ plainText += ' ' * (16 - len(plainText) % 16)
+ cipherText = encryptor.encrypt(plainText)
+ return cipherText;
+
+def readInKey(fileLocation):
+ # Open file and read in key (TODO)
+ # For now, create a 32-bit key from a phrase
+ key = createKeyFromPhrase("WouldYouLike12Muffins?")
+ return key
+
+# Will not need this function when key is read in from file while running operationally
+def createKeyFromPhrase(phrase):
+ key = hashlib.sha256(phrase).digest()
+ return key
+
# cretaes a new user and assigns tasks
def register(request):
+ logging.basicConfig(filename='/home/ubuntu/logs/log.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
+ logger.debug("Logging is working.")
# Like before, get the request's context.
context = RequestContext(request)
@@ -172,6 +219,10 @@
# Once hashed, we can update the user object.
user = User(username=request.POST['username'])
user.set_password(request.POST['password'])
+ logger.debug("This is the username: ", user.username, " and password, before encryption: ", user.password)
+ user.username = aesEncryptor(user.username).decode('utf-16')
+ #user.username = sqlite3.Binary(zlib.compress(aesEncryptor(user.username)))
+ logger.debug("This is the username: ", user.username, " and password, after encryption: ", user.password)
user.email = user.username
user.save()
@@ -187,6 +238,7 @@
# Now we save the UserProfile model instance.
userprofile.save()
+ logger.debug("Saved the user profile successfully")
# Finally we assign tasks to the new user
# Get a random product, get a random order of tasks
@@ -243,6 +295,8 @@
# Gather the username and password provided by the user.
# This information is obtained from the login form.
username = request.POST['username']
+ #username = sqlite3.Binary(zlib.compress(aesEncryptor(username)))
+ username = aesEncryptor(username).decode('utf-16')
password = request.POST['password']
# print "Login attempt by " + username + " at " + datetime
@@ -357,4 +411,4 @@
def view_profile(request):
- return render(request, 'user_profile.html', {'user': request.user})
\ No newline at end of file
+ return render(request, 'user_profile.html', {'user': request.user})
diff --git a/xdata/settings.py b/xdata/settings.py
index b1f45a8..493429f 100755
--- a/xdata/settings.py
+++ b/xdata/settings.py
@@ -46,6 +46,7 @@
'exp_portal',
'developer',
'uploads',
+ 'axes',
)
MIDDLEWARE_CLASSES = (
@@ -55,6 +56,7 @@
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
+ 'axes.middleware.FailedLoginMiddleware',
)
ROOT_URLCONF = 'xdata.urls'
@@ -72,9 +74,17 @@
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
+# 'default': {
+# 'ENGINE': 'django.db.backends.sqlite3',
+# 'NAME': os.path.join(BASE_DIR, '../db', 'db.sqlite3'),
+# }
'default': {
- 'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': os.path.join(BASE_DIR, '../db', 'db.sqlite3'),
+ 'ENGINE': 'django.db.backends.postgresql_psycopg2',
+ 'NAME': 'xdatadb',
+ 'USER': 'xdatauser',
+ 'PASSWORD': 'xd@t@!',
+ 'HOST': '127.0.0.1',
+ 'PORT': '',
}
}
@@ -118,4 +128,9 @@
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'xdataonline@gmail.com'
EMAIL_HOST_PASSWORD = MY_EMAIL_PASSWORD
-EMAIL_PORT = 587
\ No newline at end of file
+EMAIL_PORT = 587
+
+# After three failed logins, require users to wait 5 minutes before they can attempt to log in again
+AXES_LOGIN_FAILURE_LIMIT = 3
+from datetime import timedelta
+AXES_COOLOFF_TIME=timedelta(seconds = 300)