Skip to content

Commit

Permalink
Django project so far... Milestone 1
Browse files Browse the repository at this point in the history
  • Loading branch information
nahrens007 committed Jan 25, 2018
1 parent 72b5dbb commit b2ffb7d
Show file tree
Hide file tree
Showing 26 changed files with 979 additions and 0 deletions.
138 changes: 138 additions & 0 deletions bblearn/BlackboardLearn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import requests
# For AuthToken
import datetime
import time

import json

requests.packages.urllib3.disable_warnings()

# class responsible for managing authentication with the bb server
class AuthToken():
target_url = ''

def __init__(self, URL, key, secret):

self.KEY = key
self.SECRET = secret
self.PAYLOAD = {
'grant_type':'client_credentials'
}

self.TOKEN = None
self.target_url = URL
self.EXPIRES_AT = ''

def getKey(self):
return self.KEY

def getSecret(self):
return self.SECRET

def setNewToken(self):
oauth_path = '/learn/api/public/v1/oauth2/token'
OAUTH_URL = self.target_url + oauth_path

session = requests.session()

# Authenticate
r = session.post(OAUTH_URL, data=self.PAYLOAD, auth=(self.KEY, self.SECRET), verify=False)

if r.status_code == 200:
parsed_json = json.loads(r.text)
self.TOKEN = parsed_json['access_token']
self.EXPIRES = parsed_json['expires_in']
m, s = divmod(self.EXPIRES, 60)

self.NOW = datetime.datetime.now()
self.EXPIRES_AT = self.NOW + datetime.timedelta(seconds = s, minutes = m)

return r.status_code

def setToken(self):
if self.setNewToken() == 200:
if self.isExpired(self.EXPIRES_AT):
self.setToken()

else:
# Auth error!!!
self.EXPIRES = 0
m, s = divmod(self.EXPIRES, 60)

self.NOW = datetime.datetime.now()
self.EXPIRES_AT = self.NOW + datetime.timedelta(seconds = s, minutes = m)

def getToken(self):
#if token time is less than a one second then
# print that we are pausing to clear
# re-auth and return the new token
if self.isExpired(self.EXPIRES_AT):
self.setToken()
return self.TOKEN

def getTokenExpires(self):
return self.EXPIRES_AT

def revokeToken(self):
revoke_path = '/learn/api/public/v1/oauth2/revoke'
revoke_URL = self.target_url + revoke_path

self.PAYLOAD = {
'token':self.TOKEN
}

if self.TOKEN != '':
for keys,values in self.PAYLOAD.items():
print("\t\t\t" + keys + ":" + values)
session = requests.session()

# revoke token
r = session.post(revoke_URL, data=self.PAYLOAD, auth=(self.KEY, self.SECRET), verify=False)

if r.status_code == 200:
# successful revoke
pass
else:
# could not revoke
pass
else:
# Token is not currently set
pass


def isExpired(self, expiration_datetime):
expired = False

time_left = (expiration_datetime - datetime.datetime.now()).total_seconds()
if time_left < 1:
expired = True

return expired

# class responsible for providing an interface with the bb server, using AuthTocken class
class LearnInterface:
def __init__(self, url, key, secret):

self.server_url = url
self.auth_instance = AuthToken(url, key, secret)
self.auth_instance.setToken()
self.session = requests.session()

#return the response from the post call
def post(self, url, json_data):
return self.session.post(self.server_url + url,data=json_data,auth=(self.auth_instance.getKey(),self.auth_instance.getSecret()),verify=False)

#return the response of the get call
def get(self, url):
return self.session.get(self.server_url + url, headers={'Authorization':'Bearer ' + self.auth_instance.getToken()}, verify=False)

#return the response of the delete call
def delete(self, url):
return self.session.delete(self.server_url + url, auth=(self.auth_instance.getKey(),self.auth_instance.getSecret()), verify=False)

#return the response of the patch call
def patch(self, url, json_data):
return self.session.patch(self.server_url + url,data=json_data,auth=(self.auth_instance.getKey(),self.auth_instance.getSecret()),verify=False)

def getTokenExpires(self):
return self.auth_instance.getTokenExpires()
Binary file added bblearn/_DS_Store
Binary file not shown.
Empty file added bblearn/bblearn/__init__.py
Empty file.
121 changes: 121 additions & 0 deletions bblearn/bblearn/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
"""
Django settings for bblearn project.
Generated by 'django-admin startproject' using Django 2.0.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.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/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '279qyov3khb!34p4t36f1^0&g_1y(m@cjhkk3o!)7i53dup+3j'

# 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',
'learn',
]

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 = 'bblearn.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 = 'bblearn.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.0/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/2.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/2.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/2.0/howto/static-files/

STATIC_URL = '/static/'
22 changes: 22 additions & 0 deletions bblearn/bblearn/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""bblearn URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.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 include, path

urlpatterns = [
path('', include('learn.urls')),
path('admin/', admin.site.urls),
]
16 changes: 16 additions & 0 deletions bblearn/bblearn/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for bblearn 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/2.0/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bblearn.settings")

application = get_wsgi_application()
Empty file added bblearn/db.sqlite3
Empty file.
Binary file added bblearn/learn/_DS_Store
Binary file not shown.
Empty file added bblearn/learn/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions bblearn/learn/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
5 changes: 5 additions & 0 deletions bblearn/learn/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class LearnConfig(AppConfig):
name = 'learn'
Empty file.
3 changes: 3 additions & 0 deletions bblearn/learn/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
Binary file added bblearn/learn/static/_DS_Store
Binary file not shown.
Loading

0 comments on commit b2ffb7d

Please sign in to comment.