Code Spatter » OpenID http://codespatter.com Fri, 04 Sep 2009 14:59:15 +0000 http://wordpress.org/?v=2.8.4 en hourly 1 How to Write Reusable Apps for Pinax and Django http://codespatter.com/2009/01/15/how-to-write-reusable-apps-for-pinax-and-django/ http://codespatter.com/2009/01/15/how-to-write-reusable-apps-for-pinax-and-django/#comments Thu, 15 Jan 2009 17:07:09 +0000 Greg Allard http://codespatter.com/?p=158 // = 0) { links[i].innerHTML = 'View Comments'; query += 'wpid' + i + '=' + encodeURIComponent(links[i].getAttribute('wpid')) + '&'; } } document.write(' Pinax is a collection of reusable django apps that brings together features that are common to many websites. It allows developers to focus on what makes their site unique. Here is an example of adding your own functionality to Pinax. It will also be an example of writing a reusable app since every individual app [...] Related posts:
  1. How to Write Django Template Tags Template tags can be useful for making your applications more...
  2. How to Add Locations to Python Path for Reusable Django Apps In my previous post I talk about reusable apps, but...
  3. How to Display Realtime Traffic Analytics Users of Presskit’n have been asking for traffic statistics on...
]]>
Pinax is a collection of reusable django apps that brings together features that are common to many websites. It allows developers to focus on what makes their site unique. Here is an example of adding your own functionality to Pinax. It will also be an example of writing a reusable app since every individual app currently in Pinax can be used separately. Also, I’ve bundled the example files into a google code project.

My example will be to create a list of books and allow them to be tied to any object using Django’s ContentType framework. The books could be recommended reading for the members of a tribe (pinax group), a class, or anything in your project and will include title, description, and tags (requires django-tagging). In another post I’ve shown how to create template tags to make it easy to show the list of books and a form to add a book. Obviously, there is a lot more that could be done with this app, but I will leave it out of the example to keep it simple.

Starting the App

Create a folder in the apps directory or any place that is on the python path (ex. /path/to/pinax/projects/complete_project/apps/books/) and include these files:

  • __init__.py even though it might be empty, it is required
  • forms.py
  • models.py
  • urls.py
  • views.py

models.py

I will start with creating the model for the project. Below is all of the code I am placing in the file. I’ve added a lot of comments to explain everything that is happening.

#import all of the things we will be using
from django.db                          import models
from tagging.fields                     import TagField
# to help with translation of field names
from django.utils.translation  import ugettext_lazy as _
# to have a generic foreign key for any model
from django.contrib.contenttypes        import generic
# stores model info so this can be applied to any model
from django.contrib.contenttypes.models import ContentType
 
class Book(models.Model):
    """
    The details of a Book
    """
    # fields that describe this book
    name        = models.CharField(_('name'), max_length=48)
    description = models.TextField(_('description'))
 
    # to add to any model
    content_type   = models.ForeignKey(ContentType)
    object_id      = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type',
        'object_id')
 
    # for the list of tags for this book
    tags        = TagField()
 
    # misc fields
    deleted     = models.BooleanField(default=0)
    created     = models.DateTimeField(auto_now_add=True)
    # so that {{book.get_absolute_url}} outputs the whole url
    @models.permalink
    def get_absolute_url(self):
        return ("book_details", [self.pk])
    # outputs name when printing this object as a string
    def __unicode__(self):
        return self.name

forms.py

Use Django’s ModelForm to create a form for our book model.

from django import forms
from books.models import Book
 
class NewBookForm(forms.ModelForm):
    class Meta:
        model = Book
        exclude = ('deleted', 'content_type',
            'object_id', 'created')

views.py

In this file we create a view to show the details of a book and a view to create a new book for an object.

from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.decorators import login_required
 
from tribes.models import Tribe
from books.models import Book
from django.contrib.contenttypes.models import ContentType
 
@login_required
def new(request, content_type_id, object_id,
            template_name="books/new.html"):
    """
    creates a new book
    """
    from books.forms import NewBookForm
 
    # if a new book was posted
    if request.method == 'POST':
        book_form = NewBookForm(request.POST)
        if book_form.is_valid():
            # create it
            book = book_form.save(commit=False)
            content_type        = \
                ContentType.objects.get(id=content_type_id)
            content_object      = \
                content_type.get_object_for_this_type(
                id=object_id)
            book.content_object = content_object
            book.save()
            request.user.message_set.create(
                message=
                _("Successfully created book '%s'")
                % book.name)
            # send to object page or book page
            try:
                return HttpResponseRedirect(
                    content_object.get_absolute_url()
                )
            except:
                return HttpResponseRedirect(reverse(
                    'book_details', args=(book.id,)))
        # if invalid, it gets displayed below
    else:
        book_form = NewBookForm()
 
    return render_to_response(template_name, {
        'book_form': book_form,
    }, context_instance=RequestContext(request))
 
@login_required
def details(request, book_id,
    template_name="books/details.html"):
    """
    displays details of a book
    """
    book = get_object_or_404(Book, id=book_id)
    return render_to_response(template_name, {
        'book': book,
    }, context_instance=RequestContext(request))

urls.py

To tie our views to some urls, add this to the urls.py file.

from django.conf.urls.defaults import *
from django.conf.urls.defaults import *
 
urlpatterns = patterns('',    
    # new book for object
    url(r'^new/(?P<content_type_id>\d+)/(?P<object_id>\d+)', 
        'books.views.new', name="new_book"),
    # display details of a book
    url(r'^details/(?P<book_id>\d+)$', 'books.views.details', 
        name="book_details"),
)

More Features

The rest of the application is described in the post titled: How to Write Django Template Tags. You can also check out all of the code from the google project by doing the following command:

svn co http://django-books.googlecode.com/svn/trunk books

in a directory on the python path.

Related posts:

  1. How to Write Django Template Tags Template tags can be useful for making your applications more...
  2. How to Add Locations to Python Path for Reusable Django Apps In my previous post I talk about reusable apps, but...
  3. How to Display Realtime Traffic Analytics Users of Presskit’n have been asking for traffic statistics on...
]]>
http://codespatter.com/2009/01/15/how-to-write-reusable-apps-for-pinax-and-django/feed/ 26
OpenID vs OAuth http://codespatter.com/2008/04/15/openid-vs-oauth/ http://codespatter.com/2008/04/15/openid-vs-oauth/#comments Tue, 15 Apr 2008 21:07:27 +0000 Greg Allard http://codespatter.com/?p=34
  • OpenID Enabled If you haven’t stumbled upon any sites that use OpenID...
  • Secure Your OpenID There are a lot of phishing vulnerabilities with OpenID: see...
  • CyTE g9 Released CyTE g9 is now available for download. See http://cyte.googlecode.com for...
  • ]]>
    After attending the recent BarCamp, I realized how much talent the Orlando community has. Central Florida seems to be booming with web developers and start-ups. There was one such company that did about 3.5 presentations on the first day (I missed out on the second day). The .5 part was what interested me most. It was titled “ Fuck OpenID“. Which I was definitely interested in since Jason Buckner and I did a presentation at the previous BarCamp about OpenID, and threw in a quick plug for TinyID.us.

    Their main point as a downside was usability. Which I can agree isn’t perfect, but I don’t see their solution as any better since the same thing can be achieved by OpenID. They suggested using OAuth with Google and directing your users towards a Google page that will authenticate you and send you back. OpenID enabled sites can do something similar. Since many people already use AIM, Yahoo, or LiveJournal, you can provide your users with a list they can choose from. A great example of this is Pibb’s sign in page where they populate the login field for you so you only need to type your username.

    At the time of the presentation there wasn’t a Google OpenID provider, but after Google launched the beta of their app engine, someone made one.

    Hopefully browsers will begin to start implementing OpenID support (so I don’t have to use VeriSign’s SeatBelt) to help with the usability challenge and phishing vulnerabilities, but for that to happen, I think more websites need to be supporting OpenID as a log in option. Also, more websites need to take the Pibb route with having it as the only option and making it easy, instead of hiding it behind a normal login page.

    Related posts:

    1. OpenID Enabled If you haven’t stumbled upon any sites that use OpenID...
    2. Secure Your OpenID There are a lot of phishing vulnerabilities with OpenID: see...
    3. CyTE g9 Released CyTE g9 is now available for download. See http://cyte.googlecode.com for...
    ]]>
    http://codespatter.com/2008/04/15/openid-vs-oauth/feed/ 0
    New Stuff http://codespatter.com/2008/01/17/new-stuff/ http://codespatter.com/2008/01/17/new-stuff/#comments Fri, 18 Jan 2008 04:33:44 +0000 Greg Allard http://codespatter.com/?p=3
  • CyTE g9 Released CyTE g9 is now available for download. See http://cyte.googlecode.com for...
  • OpenID Enabled If you haven’t stumbled upon any sites that use OpenID...
  • Secure Your OpenID There are a lot of phishing vulnerabilities with OpenID: see...
  • ]]>
    I installed WordPress since I didn’t have enough time to commit to making MorfU as awesome as I would like. The old Code Spatter layout was also getting stale, so I found some fresh WordPress skins that were listed on this list of 100.

    I copied all of the old posts into here and made sure the date was the proper time. The comments don’t display a date, but they would be off since I didn’t bother to make them all correct. The threadedness of the discussion was also lost, but luckily there weren’t many posts using it anyways.

    There was an easy-to-add OpenID plugin so everyone can still post comments easily.

    Related posts:

    1. CyTE g9 Released CyTE g9 is now available for download. See http://cyte.googlecode.com for...
    2. OpenID Enabled If you haven’t stumbled upon any sites that use OpenID...
    3. Secure Your OpenID There are a lot of phishing vulnerabilities with OpenID: see...
    ]]>
    http://codespatter.com/2008/01/17/new-stuff/feed/ 1
    Secure Your OpenID http://codespatter.com/2007/10/02/secure-your-openid/ http://codespatter.com/2007/10/02/secure-your-openid/#comments Tue, 02 Oct 2007 17:25:12 +0000 Greg Allard http://codespatter.com/?p=12
  • OpenID vs OAuth After attending the recent BarCamp, I realized how much talent...
  • OpenID Enabled If you haven’t stumbled upon any sites that use OpenID...
  • CyTE g9 Released CyTE g9 is now available for download. See http://cyte.googlecode.com for...
  • ]]>
    There are a lot of phishing vulnerabilities with OpenID: see http://marcoslot.net/apps/openid/ if you haven’t. One awesome solution I’ve come across is using https://pip.verisignlabs.com/ as your OpenID provider and using their security key.

    PayPal uses the security key also (and sells it for much cheaper). They send you a small device that fits on your key chain that has a token that is updated every thirty seconds. This adds an extra layer of security to your login and will help protect your accounts from unauthorized users.

    The same device can be used in multiple places like PayPal, eBay, and VeriSign’s OpenID provider. When you use it for your VeriSign OpenID you add that additional layer of security to all places you use that OpenID.

    To learn more about the security key, check this out https://idprotect.verisign.com/learnmoretoken.v

    When logged in to PayPal, go to this link
    https://www.paypal.com/us/cgi-bin/webscr?cmd=xpt/cps/securitycenter/general/PPSecurityKey to order the security key for $5.

    When the device arrives, log in to your VeriSign provider and go to https://pip.verisignlabs.com/managevipcred.do to add it to your VeriSign OpenID.

    Since the URI given by them is quite long, it might be useful to use a website to shorten that to a smaller id. Signing in to tinyid.us will create a user on that site that will redirect to your other OpenID.

    Related posts:

    1. OpenID vs OAuth After attending the recent BarCamp, I realized how much talent...
    2. OpenID Enabled If you haven’t stumbled upon any sites that use OpenID...
    3. CyTE g9 Released CyTE g9 is now available for download. See http://cyte.googlecode.com for...
    ]]>
    http://codespatter.com/2007/10/02/secure-your-openid/feed/ 0
    OpenID Enabled http://codespatter.com/2007/08/10/openid-enabled/ http://codespatter.com/2007/08/10/openid-enabled/#comments Fri, 10 Aug 2007 21:45:46 +0000 Greg Allard http://codespatter.com/?p=10
  • OpenID vs OAuth After attending the recent BarCamp, I realized how much talent...
  • Secure Your OpenID There are a lot of phishing vulnerabilities with OpenID: see...
  • CyTE g9 Released CyTE g9 is now available for download. See http://cyte.googlecode.com for...
  • ]]>
    If you haven’t stumbled upon any sites that use OpenID yet, I’ll fill you in on why you might be seeing it in more places soon. OpenID is a decentralized, single sign on system which allows visitors to use one set of credentials for multiple websites. And, since it’s decentralized, there are many providers to choose from.

    This is a benefit for visitors as well as developers. It allows users to gain access to more websites without having to remember or create usernames and passwords. It helps developers by removing the requirements to authenticate usernames and passwords of users.

    Once you sign up for an OpenID at a provider like http://myopenid.com you will use a URL (this URL is your OpenID) on websites that allow OpenID authentication. The application will redirect you to your provider so you can sign in there. The provider will then ask if you wish to authenticate to the requesting website. When you select allow once or allow forever, you will be redirected back to the requesting website.

    If you want to try it now, get an OpenID from http://myopenid.com , sign in here, and post a comment on this article.

    If you are interested in reducing the length of your OpenID, you can check out http://tinyid.us for a shorter ID.

    Related posts:

    1. OpenID vs OAuth After attending the recent BarCamp, I realized how much talent...
    2. Secure Your OpenID There are a lot of phishing vulnerabilities with OpenID: see...
    3. CyTE g9 Released CyTE g9 is now available for download. See http://cyte.googlecode.com for...
    ]]>
    http://codespatter.com/2007/08/10/openid-enabled/feed/ 0
    More CyTE Improvements http://codespatter.com/2007/08/10/more-cyte-improvements/ http://codespatter.com/2007/08/10/more-cyte-improvements/#comments Fri, 10 Aug 2007 19:08:43 +0000 Greg Allard http://codespatter.com/?p=15
  • CyTE g7 to CyTE g8 Change Log General Changes Error reporting is no longer set to E_ALL...
  • CyTE g9 Released CyTE g9 is now available for download. See http://cyte.googlecode.com for...
  • CyTE g8 Available CyTE g8 is now available for download. See http://cyte.googlecode.com for...
  • ]]>
    In addition to the changes listed at http://dev.cyproject.net/ , I will be modifying the OpenID authorization to be more usable.
    The OpenID stuff packaged in the last release was just copied from http://tinyid.us when I was writing it for that.

    I will add another auth_routine that doesn’t require a database and will just use sessions like the ldap version without the database. To follow the naming trend that I used for the ldap routines, I will rename the current one to openid_with_db and the new one will be named openid.

    I will also set up a working example of using openid out of the box.

    Limitations

    I should probably note somewhere that this won’t work on all servers out of the box. I’ll list a few server requirements here and maybe include a readme.

    • Enable either the GMP extension or Bcmath extension. (GMP is STRONGLY recommended because it’s MUCH faster!)
    • Enable the CURL extension.

    Related posts:

    1. CyTE g7 to CyTE g8 Change Log General Changes Error reporting is no longer set to E_ALL...
    2. CyTE g9 Released CyTE g9 is now available for download. See http://cyte.googlecode.com for...
    3. CyTE g8 Available CyTE g8 is now available for download. See http://cyte.googlecode.com for...
    ]]>
    http://codespatter.com/2007/08/10/more-cyte-improvements/feed/ 10
    CyTE g9 Released http://codespatter.com/2007/08/07/cyte-g9-released/ http://codespatter.com/2007/08/07/cyte-g9-released/#comments Tue, 07 Aug 2007 05:36:15 +0000 Greg Allard http://codespatter.com/?p=16
  • CyTE g7 to CyTE g8 Change Log General Changes Error reporting is no longer set to E_ALL...
  • CyTE g8 Available CyTE g8 is now available for download. See http://cyte.googlecode.com for...
  • More CyTE Improvements In addition to the changes listed at http://dev.cyproject.net/ , I...
  • ]]>
    CyTE g9 is now available for download.
    See http://cyte.googlecode.com for all versions.

    Miscellaneous Changes

    • Added the include_files function to the utility functions. It will include all files in a directory. Used for including all files in the classes directory. (make sure dependencies are required in the class file since the order in which this function includes is … uhh … seemingly random.)
    • Files in /cyte/classes are now included automatically
    • Added singleton DB connection in the data_access class.
    • Added folder support in the keys folder so that keys may be organized. If there are multiple keys with the same name, the last one to be found will be used.
    • Added class_path to template conf array in config file.

    OpenID Stuff Added

    • Added OpenID auth routine
    • Added OpenID post handler that handles the initial post of the OpenID.
    • Added a way to grab an OpenID when being sent back from an OpenID provider to the abstract authorizer class.
    • Added functions to user.class.php for managing OpenID stuff.
    • Added some PEAR modules for OpenID authentication.
    • Added sample SQL for creating tables for OpenID management.

    Related posts:

    1. CyTE g7 to CyTE g8 Change Log General Changes Error reporting is no longer set to E_ALL...
    2. CyTE g8 Available CyTE g8 is now available for download. See http://cyte.googlecode.com for...
    3. More CyTE Improvements In addition to the changes listed at http://dev.cyproject.net/ , I...
    ]]>
    http://codespatter.com/2007/08/07/cyte-g9-released/feed/ 2