Procházet zdrojové kódy

integrating OpenID into the settings

Marco Quezada před 10 roky
revize
7bf2f3384e

+ 7 - 0
.hgignore

@@ -0,0 +1,7 @@
+syntax: glob
+
+.DS_Store
+db.sqlite3
+*.pyc
+bower_components/
+migrations/

+ 48 - 0
README.md

@@ -0,0 +1,48 @@
+Django Hackathon Starter
+------------------------
+
+## What is Django Hackathon Starter
+
+> Django Hackathon Starter aims to be a project which will aggegrate data from several APIs, producing a RESTful API which can be consumed by a client (also intended to be built). 
+
+## Running this project
+
+In order to run this project, do the following:
+
+    # Install the requirements
+    pip install -r requirements.txt
+
+    # Perform database migrations
+    python manage.py migrate
+
+    # Run the server
+    python manage.py runserver
+
+## Front End dependencies
+
+This project relies on Bower for all front end libraries, to avoid pushing up large libraries such as `jQuery` and `Bootstrap`. To install `bower`, you will need to install `npm`, which now comes bundled with `node.js`. To install `npm`, simply install [node as follows](https://github.com/joyent/node/wiki/installing-node.js-via-package-manager). 
+
+First, install `bower`:
+
+    npm install -g bower
+
+Then:
+
+    bower install
+
+This will download and extract all the packages listed within `bower.json`. **Under no circumstance should any front-end libraries manually be pushed up to the repository.**
+
+Two routes have currently been set up, which are located at:
+
+    # First test route
+    http://127.0.0.1:8000/hackathon/
+
+    # Second test route
+    http://127.0.0.1:8000/hackathon/test
+
+## Contributors
+
+* David Leonard
+* Eswari Swarna
+* Marco Quezada 
+* Wan Kim Mok

+ 19 - 0
bower.json

@@ -0,0 +1,19 @@
+{
+  "name": "django-hackathon-starter",
+  "version": "0.0.0",
+  "authors": [
+    "David Leonard <sephirothcloud1025@yahoo.com>"
+  ],
+  "description": "Django boilerplate project for hackathons",
+  "keywords": [
+    "Django",
+    "Python",
+    "API",
+    "RESTful"
+  ],
+  "license": "MIT",
+  "dependencies": {
+    "bootstrap": "~3.3.4",
+    "jquery": "~2.1.3"
+  }
+}

+ 0 - 0
hackathon_starter/hackathon/__init__.py


+ 5 - 0
hackathon_starter/hackathon/admin.py

@@ -0,0 +1,5 @@
+from django.contrib import admin
+from hackathon.models import UserProfile
+
+# Register your models here.
+admin.site.register(UserProfile)

+ 15 - 0
hackathon_starter/hackathon/forms.py

@@ -0,0 +1,15 @@
+from django.contrib.auth.forms import UserCreationForm
+from django.contrib.auth.models import User
+from django import forms
+from hackathon.models import UserProfile
+
+class UserForm(forms.ModelForm):
+    password = forms.CharField(widget=forms.PasswordInput())
+
+    class Meta:
+        model = User
+        fields = ('username', 'email', 'password')
+
+class UserProfileForm(forms.ModelForm):
+    class Meta:
+        model = UserProfile

+ 0 - 0
hackathon_starter/hackathon/migrations/__init__.py


+ 11 - 0
hackathon_starter/hackathon/models.py

@@ -0,0 +1,11 @@
+from django.db import models
+from django.contrib.auth.models import User
+
+# Create your models here.
+class UserProfile(models.Model):
+    # This line is required. Links UserProfile to a User model instance.
+    user = models.OneToOneField(User)
+
+    # Override the __unicode__() method to return out something meaningful!
+    def __unicode__(self):
+        return self.user.username

+ 52 - 0
hackathon_starter/hackathon/templates/hackathon/base.html

@@ -0,0 +1,52 @@
+<!DOCTYPE html>
+  <html lang="en">
+    <head>
+      <title> Django Hackathon Starter </title>
+      <script src="/static/bower_components/jquery/dist/jquery.js"></script>
+      <script type="text/javascript" src="/static/bower_components/bootstrap/dist/bootstrap.min.js"></script>
+      
+      
+      <link rel="stylesheet" href="/static/bower_components/bootstrap/dist/css/bootstrap.min.css">
+      <link rel="stylesheet" href="/static/bower_components/bootstrap/dist/css/bootstrap-theme.min.css">
+    </head>
+    
+  <body>
+    <nav class="navbar navbar-default" role="navigation">
+      <div class="container-fluid">
+        <!-- Brand and toggle get grouped for better mobile display -->
+        <div class="navbar-header">
+          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
+            <span class="sr-only">Toggle navigation</span>
+            <span class="icon-bar"></span>
+            <span class="icon-bar"></span>
+            <span class="icon-bar"></span>
+          </button>
+          <a class="navbar-brand" href="#">Django Hackathon Starter</a>
+      </div>
+
+      <!-- Collect the nav links, forms, and other content for toggling -->
+      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
+        <ul class="nav navbar-nav navbar-right">
+          {% if not user.is_authenticated %}
+            <li class="active"><a href="/hackathon/register">Register <span class="sr-only">(current)</span></a></li>
+            
+            <li><a href="/hackathon/login">Login</a></li>
+          {% endif %}
+            
+        </ul>
+        
+        <ul  class="nav navbar-nav navbar-right">
+          {% if user.is_authenticated %}
+    
+            <li><a>Hello {{user}}</a></li>
+            <li><a href="/hackathon/logout/">Logout</a></li>
+          {% endif %}
+        </ul>
+          
+          
+          </li>
+         </ul>
+        </div><!-- /.navbar-collapse -->
+      </div><!-- /.container-fluid -->
+    </nav>
+  </body>

+ 10 - 0
hackathon_starter/hackathon/templates/hackathon/index.html

@@ -0,0 +1,10 @@
+<!DOCTYPE html>
+
+<html>
+    {% include 'hackathon/base.html' %}
+
+    <body>
+        <h1>Api Example</h1>
+        <strong>{{ boldmessage }}</strong><br />
+    </body>
+</html>

+ 19 - 0
hackathon_starter/hackathon/templates/hackathon/login.html

@@ -0,0 +1,19 @@
+<!DOCTYPE html>
+<html>
+    {% include 'hackathon/base.html' %}
+
+    <body>
+        <h1>Login to Django Hackathon Starter</h1>
+
+        <form id="login_form" method="post" action="/hackathon/login/">
+            {% csrf_token %}
+            Username: <input type="text" name="username" value="" size="50" />
+            <br />
+            Password: <input type="password" name="password" value="" size="50" />
+            <br />
+
+            <input type="submit" value="submit" />
+        </form>
+
+    </body>
+</html>

+ 40 - 0
hackathon_starter/hackathon/templates/hackathon/navbar.html

@@ -0,0 +1,40 @@
+<body>
+  <nav class="navbar navbar-default" role="navigation">
+      <div class="container-fluid">
+        <!-- Brand and toggle get grouped for better mobile display -->
+        <div class="navbar-header">
+          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
+            <span class="sr-only">Toggle navigation</span>
+            <span class="icon-bar"></span>
+            <span class="icon-bar"></span>
+            <span class="icon-bar"></span>
+          </button>
+          <a class="navbar-brand" href="#">Django Hackathon Starter</a>
+      </div>
+
+      <!-- Collect the nav links, forms, and other content for toggling -->
+      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
+        <ul class="nav navbar-nav navbar-right">
+          {% if not user.is_authenticated %}
+            <li class="active"><a href="/hackathon/register">Register <span class="sr-only">(current)</span></a></li>
+            
+            <li><a href="/hackathon/login">Login</a></li>
+          {% endif %}
+            
+        </ul>
+        
+        <ul  class="nav navbar-nav navbar-right">
+          {% if user.is_authenticated %}
+    
+            <li><a>Hello {{user}}</a></li>
+            <li><a href="/hackathon/logout/">Logout</a></li>
+          {% endif %}
+        </ul>
+          
+          
+          </li>
+        </ul>
+      </div><!-- /.navbar-collapse -->
+    </div><!-- /.container-fluid -->
+  </nav>
+</body>

+ 28 - 0
hackathon_starter/hackathon/templates/hackathon/register.html

@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<html>
+    {% include 'hackathon/base.html' %}
+    <body>
+        <h1>Register with Django Hackathon Starter</h1>
+
+        {% if registered %}
+        Django Hackathon says: <strong>thank you for registering!</strong>
+        <a href="/hackathon/">Return to the homepage.</a><br />
+        {% else %}
+        Django Hackathon says: <strong>register here!</strong><br />
+
+        <form id="user_form" method="post" action="/hackathon/register/"
+                enctype="multipart/form-data">
+
+            {% csrf_token %}
+
+            <!-- Display each form. The as_p method wraps each element in a paragraph
+                 (<p>) element. This ensures each element appears on a new line,
+                 making everything look neater. -->
+            {{ user_form.as_p }}
+
+            <!-- Provide a button to click to submit the form. -->
+            <input type="submit" name="submit" value="Register" />
+        </form>
+        {% endif %}
+    </body>
+</html>

+ 3 - 0
hackathon_starter/hackathon/tests.py

@@ -0,0 +1,3 @@
+from django.test import TestCase
+
+# Create your tests here.

+ 11 - 0
hackathon_starter/hackathon/urls.py

@@ -0,0 +1,11 @@
+from django.conf.urls import patterns, url
+
+from hackathon import views
+
+urlpatterns = patterns('',
+    url(r'^$', views.index, name='index'),
+    url(r'^test/$', views.test, name='test'),
+    url(r'^register/$', views.register, name='register'),
+    url(r'^login/$', views.user_login, name='login'),
+    url(r'^logout/$', views.user_logout, name='logout'),
+)

+ 102 - 0
hackathon_starter/hackathon/views.py

@@ -0,0 +1,102 @@
+from django.shortcuts import render
+from hackathon.forms import UserForm
+from django.contrib.auth import logout
+from django.template import RequestContext, loader
+from django.contrib.auth import authenticate, login
+from django.http import HttpResponse, HttpResponseRedirect
+
+def index(request):
+	context = {'hello': 'world'}
+	return render(request, 'hackathon/index.html', context)
+
+def test(request):
+	return HttpResponse('meow')
+
+def register(request):
+
+    # A boolean value for telling the template whether the registration was successful.
+    # Set to False initially. Code changes value to True when registration succeeds.
+    registered = False
+
+    # If it's a HTTP POST, we're interested in processing form data.
+    if request.method == 'POST':
+        # Attempt to grab information from the raw form information.
+        # Note that we make use of both UserForm and UserProfileForm.
+        user_form = UserForm(data=request.POST)
+
+        # If the two forms are valid...
+        if user_form.is_valid():
+            # Save the user's form data to the database.
+            user = user_form.save()
+
+            # Now we hash the password with the set_password method.
+            # Once hashed, we can update the user object.
+            user.set_password(user.password)
+            user.save()
+
+            # Update our variable to tell the template registration was successful.
+            registered = True
+
+        # Invalid form or forms - mistakes or something else?
+        # Print problems to the terminal.
+        # They'll also be shown to the user.
+        else:
+            print user_form.errors
+
+    # Not a HTTP POST, so we render our form using two ModelForm instances.
+    # These forms will be blank, ready for user input.
+    else:
+        user_form = UserForm()
+
+    # Render the template depending on the context.
+    return render(request,
+            'hackathon/register.html',
+            {'user_form': user_form, 'registered': registered} )
+
+def user_login(request):
+
+    # If the request is a HTTP POST, try to pull out the relevant information.
+    if request.method == 'POST':
+        # Gather the username and password provided by the user.
+        # This information is obtained from the login form.
+                # We use request.POST.get('<variable>') as opposed to request.POST['<variable>'],
+                # because the request.POST.get('<variable>') returns None, if the value does not exist,
+                # while the request.POST['<variable>'] will raise key error exception
+        username = request.POST.get('username')
+        password = request.POST.get('password')
+
+        # Use Django's machinery to attempt to see if the username/password
+        # combination is valid - a User object is returned if it is.
+        user = authenticate(username=username, password=password)
+
+        # If we have a User object, the details are correct.
+        # If None (Python's way of representing the absence of a value), no user
+        # with matching credentials was found.
+        if user:
+            # Is the account active? It could have been disabled.
+            if user.is_active:
+                # 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('/hackathon/')
+            else:
+                # An inactive account was used - no logging in!
+                return HttpResponse("Your Django Hackathon account is disabled.")
+        else:
+            # Bad login details were provided. So we can't log the user in.
+            print "Invalid login details: {0}, {1}".format(username, password)
+            return HttpResponse("Invalid login details supplied.")
+
+    # The request is not a HTTP POST, so display the login form.
+    # This scenario would most likely be a HTTP GET.
+    else:
+        # No context variables to pass to the template system, hence the
+        # blank dictionary object...
+        return render(request, 'hackathon/login.html', {})
+
+def user_logout(request):
+    # Since we know the user is logged in, we can now just log them out.
+    logout(request)
+
+    # Take the user back to the homepage.
+    return HttpResponseRedirect('/hackathon/')

+ 0 - 0
hackathon_starter/hackathon_starter/__init__.py


+ 89 - 0
hackathon_starter/hackathon_starter/settings.py

@@ -0,0 +1,89 @@
+"""
+Django settings for hackathon_starter project.
+
+For more information on this file, see
+https://docs.djangoproject.com/en/1.7/topics/settings/
+
+For the full list of settings and their values, see
+https://docs.djangoproject.com/en/1.7/ref/settings/
+"""
+
+# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
+import os
+BASE_DIR = os.path.dirname(os.path.dirname(__file__))
+
+
+# Quick-start development settings - unsuitable for production
+# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
+
+# SECURITY WARNING: keep the secret key used in production secret!
+SECRET_KEY = 'keuhh=0*%do-ayvy*m2k=vss*$7)j8q!@u0+d^na7mi2(^!l!d'
+
+# SECURITY WARNING: don't run with debug turned on in production!
+DEBUG = True
+
+TEMPLATE_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',
+    'hackathon',
+    'django_openid',
+)
+
+MIDDLEWARE_CLASSES = (
+    'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.middleware.common.CommonMiddleware',
+    'django.middleware.csrf.CsrfViewMiddleware',
+    'django.contrib.auth.middleware.AuthenticationMiddleware',
+    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
+    'django.contrib.messages.middleware.MessageMiddleware',
+    'django.middleware.clickjacking.XFrameOptionsMiddleware',
+    'django_openid_consumer.SessionConsumer',
+)
+
+ROOT_URLCONF = 'hackathon_starter.urls'
+
+WSGI_APPLICATION = 'hackathon_starter.wsgi.application'
+
+
+# Database
+# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
+
+DATABASES = {
+    'default': {
+        'ENGINE': 'django.db.backends.sqlite3',
+        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
+    }
+}
+
+# Internationalization
+# https://docs.djangoproject.com/en/1.7/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.7/howto/static-files/
+
+STATIC_URL = '/static/'
+
+TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
+

+ 8 - 0
hackathon_starter/hackathon_starter/urls.py

@@ -0,0 +1,8 @@
+from django.conf.urls import patterns, include, url
+from django.contrib import admin
+
+urlpatterns = patterns('',
+    url(r'^hackathon/', include('hackathon.urls')),
+    url(r'^admin/', include(admin.site.urls)),
+    url(r'^openid/(.*)', SessionConsumer()),
+)

+ 14 - 0
hackathon_starter/hackathon_starter/wsgi.py

@@ -0,0 +1,14 @@
+"""
+WSGI config for hackathon_starter 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.7/howto/deployment/wsgi/
+"""
+
+import os
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hackathon_starter.settings")
+
+from django.core.wsgi import get_wsgi_application
+application = get_wsgi_application()

+ 10 - 0
hackathon_starter/manage.py

@@ -0,0 +1,10 @@
+#!/usr/bin/env python
+import os
+import sys
+
+if __name__ == "__main__":
+    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hackathon_starter.settings")
+
+    from django.core.management import execute_from_command_line
+
+    execute_from_command_line(sys.argv)

+ 6 - 0
requirements.txt

@@ -0,0 +1,6 @@
+Django==1.7.6
+django-bower==5.0.2
+requests==2.6.0
+six==1.9.0
+wsgiref==0.1.2
+django-openid-auth==0.5