Merge branch 'endpoints'
diff --git a/Vagrantfile b/Vagrantfile
new file mode 100644
index 0000000..5e7c632
--- /dev/null
+++ b/Vagrantfile
@@ -0,0 +1,77 @@
+# -*- mode: ruby -*-
+# vi: set ft=ruby :
+
+# All Vagrant configuration is done below. The "2" in Vagrant.configure
+# configures the configuration version (we support older styles for
+# backwards compatibility). Please don't change it unless you know what
+# you're doing.
+Vagrant.configure("2") do |config|
+  # The most common configuration options are documented and commented below.
+  # For a complete reference, please see the online documentation at
+  # https://docs.vagrantup.com.
+
+  # Every Vagrant development environment requires a box. You can search for
+  # boxes at https://atlas.hashicorp.com/search.
+  config.vm.box = "ubuntu/trusty64"
+
+  # Disable automatic box update checking. If you disable this, then
+  # boxes will only be checked for updates when the user runs
+  # `vagrant box outdated`. This is not recommended.
+  # config.vm.box_check_update = false
+
+  # Create a forwarded port mapping which allows access to a specific port
+  # within the machine from a port on the host machine. In the example below,
+  # accessing "localhost:8080" will access port 80 on the guest machine.
+  # config.vm.network "forwarded_port", guest: 80, host: 8080
+
+  # Create a private network, which allows host-only access to the machine
+  # using a specific IP.
+  config.vm.network "private_network", ip: "192.168.33.10"
+
+  # Create a public network, which generally matched to bridged network.
+  # Bridged networks make the machine appear as another physical device on
+  # your network.
+  # config.vm.network "public_network"
+
+  # Share an additional folder to the guest VM. The first argument is
+  # the path on the host to the actual folder. The second argument is
+  # the path on the guest to mount the folder. And the optional third
+  # argument is a set of non-required options.
+  # config.vm.synced_folder "../data", "/vagrant_data"
+
+  # Provider-specific configuration so you can fine-tune various
+  # backing providers for Vagrant. These expose provider-specific options.
+  # Example for VirtualBox:
+  #
+  config.vm.provider "virtualbox" do |vb|
+  #   # Display the VirtualBox GUI when booting the machine
+  #   vb.gui = true
+  #
+  #   # Customize the amount of memory on the VM:
+    vb.memory = "1024"
+    vb.cpus = 2
+  end
+  #
+  # View the documentation for the provider you are using for more
+  # information on available options.
+
+  # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies
+  # such as FTP and Heroku are also available. See the documentation at
+  # https://docs.vagrantup.com/v2/push/atlas.html for more information.
+  # config.push.define "atlas" do |push|
+  #   push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME"
+  # end
+
+  # Enable provisioning with a shell script. Additional provisioners such as
+  # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
+  # documentation for more information about their specific syntax and use.
+  # config.vm.provision "shell", inline: <<-SHELL
+  #   apt-get update
+  #   apt-get install -y apache2
+  # SHELL
+  config.vm.provision "file", source: "vagrant/bash_aliases", destination: ".bash_aliases"
+
+  config.vm.provision "shell", path: "vagrant/provision_as_root.sh"
+  config.vm.provision "shell", path: "vagrant/provision_as_vagrant.sh", privileged: false
+  config.vm.provision "shell", path: "vagrant/provision_databases.sh"
+end
diff --git a/app_mgr/apps.py b/app_mgr/apps.py
index 49d68b6..b9e48b3 100644
--- a/app_mgr/apps.py
+++ b/app_mgr/apps.py
@@ -19,5 +19,5 @@
     verbose_name = "Application Manager"
 
     def ready(self):
-        print 'Loading', self.verbose_name
+        print('Loading', self.verbose_name)
         import app_mgr.signals.handlers
diff --git a/app_mgr/distillviews.py b/app_mgr/distillviews.py
new file mode 100644
index 0000000..080b0f2
--- /dev/null
+++ b/app_mgr/distillviews.py
@@ -0,0 +1,48 @@
+from django.shortcuts import render, redirect, render_to_response
+from django.http import HttpResponseRedirect, HttpResponse
+from django.contrib.sites.shortcuts import get_current_site
+from django.core.urlresolvers import reverse
+from django.template import RequestContext
+from django.conf import settings
+
+
+from django.db import IntegrityError
+from django.db.models import Q
+
+from django.views.generic.base import RedirectView
+
+from axes.decorators import watch_login
+
+from rest_framework import generics
+from rest_framework.authentication import TokenAuthentication
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.response import Response
+#from rest_framework.authtoken import views as token_views
+
+from guardian.shortcuts import assign_perm, get_objects_for_user
+
+from app_mgr.permissions import ViewControlObjectPermissions
+from app_mgr.permissions import ApplicationObjectPermissions
+from app_mgr.models import UserProfile, Organization, Application, AppVersion
+from app_mgr.serializers import UserProfileSerializer, OrganizationSerializer, ApplicationSerializer
+
+import datetime
+import requests 
+
+distillURL = "msbx.draper.com:8091"
+
+def app_results_byname(request, appName, searchType):
+    completeurl = distillURL+'/search/'+appName+'/'+searchType
+    print (completeurl)
+    results = requests.get(completeurl)
+    
+    return HttpResponse(results)
+
+def app_results(request, appId, searchType):
+    print ("hello")
+    print (appId)
+    print (searchType)
+    return render(request, 'user_profile.html',
+                  {'user': request.user,
+                  }
+                 )
\ No newline at end of file
diff --git a/app_mgr/urls.py b/app_mgr/urls.py
index fefd594..7992345 100644
--- a/app_mgr/urls.py
+++ b/app_mgr/urls.py
@@ -30,13 +30,14 @@
 from django.contrib import admin
 
 from app_mgr import views
+from app_mgr import distillviews
 
 urlpatterns = [
     # USER AUTHENTICATION
     url(r'^register/', views.register, name='register'),
     url(r'^login/$', views.login_user, name='login'),
     url(r'^logout/$', views.logout_user, name='logout'),
-    url(r'^user_profile$', views.view_profile, name='view_profile'),
+    url(r'^user_profile/$', views.view_profile, name='view_profile'),
     url(r'^reset/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', views.reset_confirm, name='reset_confirm'),
     url(r'^reset/$', views.reset, name='reset'),
     url(r'^reset/sent/$', views.reset_sent, name='reset_sent'),
@@ -50,4 +51,14 @@
     url(r'^user/(?P<pk>current)/$', views.UserProfileInstanceView.as_view(), name='user-current'),
     url(r'^org/(?P<pk>[\d]+)/$', views.OrganizationInstanceView.as_view(), name='org-instance'),
     url(r'^app/(?P<pk>[\d]+)/$', views.ApplicationInstanceView.as_view(), name='app-instance'),
+    
+    url(r'^app/(?P<pk>current+)/$', views.AliasListView.as_view(), name='alias-list'),
+
+    url(r'^appresults/(?P<appId>[0-9]{1,2})/(?P<searchType>\w+)/$', distillviews.app_results, name='app-results'),
+    url(r'^appresults/(?P<appName>\w+)/(?P<searchType>\w+)/$', distillviews.app_results_byname, name='app-results'),
+    
+    # url(r'^appresults/(?P<pk>[\d]+)/fields/$', views.get_app_result_fields, name='data-fields'),
+    # url(r'^appresults/(?P<pk>[\d]+)/data/$', views.get_app_results, name='data'),
+    
+    
 ]
diff --git a/app_mgr/views.py b/app_mgr/views.py
index 9bb907b..7ce3dfa 100644
--- a/app_mgr/views.py
+++ b/app_mgr/views.py
@@ -22,6 +22,7 @@
 from django.template import RequestContext
 from django.conf import settings
 
+
 from django.db import IntegrityError
 from django.db.models import Q
 
@@ -33,6 +34,7 @@
 from rest_framework.authentication import TokenAuthentication
 from rest_framework.permissions import IsAuthenticated
 from rest_framework.response import Response
+#from rest_framework.authtoken import views as token_views
 
 from guardian.shortcuts import assign_perm, get_objects_for_user
 
@@ -42,6 +44,7 @@
 from app_mgr.serializers import UserProfileSerializer, OrganizationSerializer, ApplicationSerializer
 
 import datetime
+import requests 
 
 #
 # RESTFUL VIEWS
@@ -112,22 +115,22 @@
 
     def get(self, request, *args, **kwargs):
         if kwargs['pk'] == 'current':
-            self.kwargs['pk'] = unicode(request.user.id)
+            self.kwargs['pk'] = str(request.user.id)
         return self.retrieve(request, *args, **kwargs)
 
     def put(self, request, *args, **kwargs):
         if kwargs['pk'] == 'current':
-            self.kwargs['pk'] = unicode(request.user.id)
+            self.kwargs['pk'] = str(request.user.id)
         return self.update(request, *args, **kwargs)
 
     def patch(self, request, *args, **kwargs):
         if kwargs['pk'] == 'current':
-            self.kwargs['pk'] = unicode(request.user.id)
+            self.kwargs['pk'] = str(request.user.id)
         return self.partial_update(request, *args, **kwargs)
 
     def delete(self, request, *args, **kwargs):
         if kwargs['pk'] == 'current':
-            self.kwargs['pk'] = unicode(request.user.id)
+            self.kwargs['pk'] = str(request.user.id)
         return self.destroy(request, *args, **kwargs)
 
 class OrganizationInstanceView(generics.RetrieveUpdateDestroyAPIView):
@@ -152,6 +155,7 @@
     queryset = Application.objects.all()
     serializer_class = ApplicationSerializer
 
+
 # REDIRECTS
 #class UserRedirectView(RedirectView):
 #
@@ -223,7 +227,8 @@
         registrationSuccessful = True
 
         # add some logic to log events, log in users directly
-        print "successful registration of " + request.POST['email'] +" "+ datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+        #print "successful registration of " + request.POST['email'] +" "+ datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+        print( "successful registration of {0} {1}".format(request.POST['email'], datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) )
         request.POST['email_to'] = user.email
         request.POST['email_subject'] = 'Welcome to TAP'
         request.POST['email_message'] = 'Your registration was successful!\n\nIn case you forget your password, please go to the following page and reset your password:\n\nhttps://' + get_current_site(request).domain + '/app_mgr/reset/\n\nYour username, in case you\'ve forgotten, is the email address this message was sent to.\n\nThanks for using our site!\n\nThe ' + get_current_site(request).name + ' team'
@@ -240,7 +245,7 @@
     Log users out and re-direct them to the main page.
     """
     logout(request)
-    return HttpResponseRedirect('/app_mgr/login')
+    return HttpResponseRedirect('/app_mgr/login/')
 
 @watch_login
 def login_user(request):
@@ -268,13 +273,15 @@
                 # If the account is valid and active, we can log the user in.
                 # We'll send the user back to the homepage.
                 login(request, user)
-                return HttpResponseRedirect('/app_mgr/user_profile')
+                userToken = get_token(email, password)
+                print( "Successful Login: {0}, id: {1}, token: {2}".format(email, user.id, userToken) )
+                return HttpResponse(userToken)
             else:
                 # An inactive account was used - no logging in!
                 return HttpResponse("Your TAP account is disabled.")
         else:
             # Bad login details were provided. So we can't log the user in.
-            print "Invalid login details: {0}, {1}".format(email, password)
+            print( "Invalid login details: {0}, {1}".format(email, password) ) ###TODO - PASSWORD EXPOSED
             return HttpResponse("Invalid login details supplied.")
 
     # The request is not a HTTP POST, so display the login form.
@@ -288,6 +295,11 @@
 
         # return login_view(request, authentication_form=MyAuthForm)
 
+def get_token(email, password):
+    credentials = {'username':email, 'password':password}
+    tokenResponse = requests.post('http://localhost:8000/api-token-auth/', credentials)
+    return tokenResponse.text
+
 def reset_confirm(request, uidb64=None, token=None):
     return password_reset_confirm(request, template_name='registration/reset_password_confirm.html',
                                   uidb64=uidb64, token=token,
@@ -303,10 +315,42 @@
 def reset_sent(request):
     return render(request, 'registration/reset_password_done.html')
 
-@login_required(login_url='/app_mgr/login')
+@login_required(login_url='/app_mgr/login/')
 def view_profile(request):
     user = request.user
     return render(request, 'user_profile.html',
                   {'user': request.user,
                   }
                  )
+
+# def get_app_results_fields(request, check):
+#     user = request.user
+#     return render(request, 'user_profile.html',
+#                   {'user': request.user,
+#                   }
+#                  )
+
+# def get_app_results(request, check):
+#     user = request.user
+#     return render(request, 'user_profile.html',
+#                   {'user': request.user,
+#                   }
+#                  )
+
+def app_results(request, appId, searchType):
+    print ("hello")
+    print (appId)
+    print (searchType)
+    return render(request, 'user_profile.html',
+                  {'user': request.user,
+                  }
+                 )
+
+def app_results_byname(request, appName, searchType):
+    print ("hello")
+    print (appName)
+    print (searchType)
+    return render(request, 'user_profile.html',
+                  {'user': request.user,
+                  }
+                 )
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
index a620e48..befdd67 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -6,5 +6,8 @@
 django-guardian==1.4.4
 djangorestframework==3.3.3
 gunicorn==19.6.0
+httpie==0.9.3
 psycopg2==2.6.1
+Pygments==2.1.3
+requests==2.10.0
 six==1.10.0
diff --git a/tap/templates/index.html b/tap/templates/index.html
new file mode 100644
index 0000000..b25cad7
--- /dev/null
+++ b/tap/templates/index.html
@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="utf-8">
+    <title>Tap Home</title>
+    <!-- <link href="{{ STATIC_URL }}js/components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> -->
+</head>
+<body>
+    <div class="container">
+        <h1>Hello Tap!</h1>
+        <div class="react-container"></div>
+    </div>
+    <!-- <script src="{{ STATIC_URL }}js/components/jquery/dist/jquery.min.js"></script>
+    <script src="{{ STATIC_URL }}js/components/bootstrap/dist/js/bootstrap.min.js"></script>
+    <script src="{{ STATIC_URL }}js/es5-shim.min.js"></script> -->
+</body>
+</html>
\ No newline at end of file
diff --git a/tap/urls.py b/tap/urls.py
index b3f238f..582735a 100644
--- a/tap/urls.py
+++ b/tap/urls.py
@@ -28,6 +28,7 @@
 """
 from django.conf.urls import include, url
 from django.contrib import admin
+from django.views.generic import TemplateView
 
 from rest_framework.authtoken import views as token_views
 
@@ -35,6 +36,7 @@
     url(r'^grappelli/', include('grappelli.urls')),
     url(r'^admin/', include(admin.site.urls)),
     url(r'^app_mgr/', include('app_mgr.urls', namespace='app_mgr')),
-    #url(r'^api-auth/', include('rest_framework.urls')),
+    #url(r'^api-auth/', include('rest_framework.urls')), #used for basic authentication (cookies)
     url(r'^api-token-auth/', token_views.obtain_auth_token),
+    url(r'', TemplateView.as_view(template_name='index.html')),
 ]
diff --git a/vagrant/bash_aliases b/vagrant/bash_aliases
new file mode 100644
index 0000000..4e2a12e
--- /dev/null
+++ b/vagrant/bash_aliases
@@ -0,0 +1,3 @@
+alias runserver='cd /vagrant; /vagrant/manage.py runserver 0.0.0.0:8000'
+
+
diff --git a/vagrant/provision_as_root.sh b/vagrant/provision_as_root.sh
new file mode 100644
index 0000000..5d0458b
--- /dev/null
+++ b/vagrant/provision_as_root.sh
@@ -0,0 +1,34 @@
+#!/bin/bash
+
+date >> /etc/vagrant_provisioned_at
+
+# PostgreSQL server
+sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -cs`-pgdg main" >> /etc/apt/sources.list.d/pgdg.list'
+wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
+sudo apt-get update
+
+sudo apt-get install -y postgresql-9.5 postgresql-contrib-9.5 postgresql-server-dev-9.5 libpq-dev
+PGSQL_DB_PASSWORD="Dr@p3rUs3r"
+sudo -u postgres psql -c "CREATE DATABASE tapdb"
+sudo -u postgres psql -c "CREATE USER tapuser WITH PASSWORD '$PGSQL_DB_PASSWORD'"
+sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE tapdb TO tapuser"
+
+# Essentials
+#sudo apt-get update -q
+echo "Installing Essentials ..."
+sudo apt-get install -y git build-essential libssl-dev
+echo "Done"
+
+# Python
+sudo apt-get install -y python-pip python-dev python3-dev 
+#sudo pip install virtualenv virtualenvwrapper
+
+echo "Installing Python virtualenv ..."
+sudo pip install --upgrade virtualenv
+
+virtualenv --python=$(which python3) /home/vagrant/tappy3
+sudo chown -hR vagrant:vagrant /home/vagrant/tappy3
+echo "Done."
+
+# Restart services
+service postgresql restart
diff --git a/vagrant/provision_as_vagrant.sh b/vagrant/provision_as_vagrant.sh
new file mode 100644
index 0000000..8016e5a
--- /dev/null
+++ b/vagrant/provision_as_vagrant.sh
@@ -0,0 +1,72 @@
+#!/bin/bash
+BASHRC="/home/vagrant/.bashrc"
+PROFILE="/home/vagrant/.profile"
+
+sed -i 's/#force_color_prompt/force_color_prompt/' $BASHRC
+
+# Django
+cd /vagrant
+echo "Installing Python Tool and Django"
+CMD="source /home/vagrant/tappy3/bin/activate"
+$CMD
+pip install --upgrade pip
+pip install --upgrade setuptools
+#pip install --upgrade pip-tools
+#pip-sync
+#pip install django psycopg2 djangorestframework
+pip install -r /vagrant/requirements.txt
+deactivate
+grep -q -F "$CMD" $BASHRC || echo "$CMD" >> $BASHRC
+cd ~
+echo "Done"
+
+# NodeJS via nvm
+if [ ! -d /home/vagrant/.nvm ]; then
+    echo "Installing Node ..."
+    curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.31.1/install.sh | bash
+    CMD="source /home/vagrant/.nvm/nvm.sh"
+    grep -q -F "$CMD" $PROFILE || echo "$CMD" >> $PROFILE
+    source $PROFILE
+    nvm install 4.4.5 > /dev/null 2>&1
+    nvm alias default 4.4.5
+    npm install -g bower gulp
+else
+    echo "Node is already installed."
+fi
+echo "Done."
+
+# package.json
+# cd /vagrant
+# if [ ! -d /vagrant/node_modules ]; then
+#     echo "Installing Node packages ..."
+#     npm install
+# else
+#     echo "Node packages are already installed."
+# fi
+# cd ~
+# echo "Done."
+
+# bower.json
+# cd /vagrant
+# if [ ! -d /vagrant/static/js/components ]; then
+#     echo "Installing Bower packages ..."
+#     bower install
+# else
+#     echo "Bower packages are already installed."
+# fi
+# cd ~
+# echo "Done."
+
+# tap/settings.py
+# echo "Restoring Django tap/settings.py ..."
+# if [ ! -f /vagrant/tap/settings.py ]; then
+#     cp /vagrant/vagrant/settings.py /vagrant/tap/settings.py
+# fi
+# echo "Done."
+
+# secret.py
+echo "Restoring Django secret.py ..."
+if [ ! -f /vagrant/secret.py ]; then
+    cp /vagrant/vagrant/secret.py /vagrant/secret.py
+fi
+echo "Done."
diff --git a/vagrant/provision_databases.sh b/vagrant/provision_databases.sh
new file mode 100644
index 0000000..0944264
--- /dev/null
+++ b/vagrant/provision_databases.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+
+# Restore Django PostgreSQL database
+# tapadmin, tapadmin@draper.com, Dr@perAdm1n!
+echo "Restoring Django database ..."
+sudo -u postgres psql tapdb < /vagrant/vagrant/sql/appmgr.sql > /dev/null 2>&1
+echo "Done."
+
+