Commits

Anonymous committed ae2b87b

initial

Comments (0)

Files changed (10)

+syntax: glob
+.project
+.pydevproject
+.settings
+*~
+*.orig
+*.pyc
+*.pyo
+*.swp
+*.tmp
+_generated_media*
+desktop.ini
+settings_overrides.py
+nbproject
+django
+django_mongodb_engine
+djangotoolbox
+mediagenerator
Empty file added.
+from django import forms
+from django.contrib import admin
+from django.contrib.auth.admin import UserAdmin, GroupAdmin, GroupAdmin
+from django.contrib.auth.models import User, Group, Permission, Permission
+
+from django.contrib.admin.options import ModelAdmin, TabularInline
+from djangogaeauth.models import gpermission, groupuserjoin
+
+
+class UserForm(forms.ModelForm):
+    class Meta:
+        model = User
+        fields = ('username', 'email', 'first_name', 'last_name', 'is_active',
+                  'is_staff', 'is_superuser')
+
+
+class GPermissionInline(TabularInline):
+    model= gpermission
+
+class GroupUserInline(TabularInline):
+    model= groupuserjoin
+
+class GroupForm(forms.ModelForm):
+    class Meta:
+        model = Group
+        fields = ('name',)
+
+class CustomGroupAdmin(GroupAdmin):
+    fieldsets = None
+    form = GroupForm
+    inlines = [GPermissionInline,GroupUserInline]
+
+
+class CustomUserAdmin(UserAdmin):
+    fieldsets = None
+    form = UserForm
+
+
+
+class PermissionAdmin(ModelAdmin):
+    inlines = [GPermissionInline]
+
+
+    
+admin.site.unregister(User)
+try:
+    admin.site.unregister(Group)
+except Exception:
+    pass
+
+admin.site.register(User, CustomUserAdmin)
+admin.site.register(Group, CustomGroupAdmin)
+admin.site.register(Permission,PermissionAdmin)
+
+from django.db import connection
+from django.contrib.auth.models import User
+
+
+class ModelBackend(object):
+    """
+    Authenticates against django.contrib.auth.models.User.
+    """
+    supports_object_permissions = False
+    supports_anonymous_user = True
+
+    # TODO: Model, login attribute name and password attribute name should be
+    # configurable.
+    def authenticate(self, username=None, password=None):
+        try:
+            user = User.objects.get(username=username)
+            if user.check_password(password):
+                return user
+        except User.DoesNotExist:
+            return None
+
+    def get_group_permissions(self, user_obj):
+        """
+        Returns a set of permission strings that this user has through his/her
+        groups.
+        """
+
+        if not hasattr(user_obj, '_group_perm_cache'):
+            groups_user = user_obj.groupuserjoin_set.all()
+            perms = []
+            for group_user in groups_user:
+                for gperm in group_user.group.gpermission_set.all():
+                    perms.append("%s.%s" % (gperm.perm.content_type.app_label,gperm.perm.codename))
+
+
+            user_obj._group_perm_cache = set(perms)
+        return user_obj._group_perm_cache
+
+    def get_all_permissions(self, user_obj):
+        if user_obj.is_anonymous():
+            return set()
+        if not hasattr(user_obj, '_perm_cache'):
+            user_obj._perm_cache = set([u"%s.%s" % (p.perm.content_type.app_label, p.perm.codename) for p in user_obj.dpermission_set.all()])
+            user_obj._perm_cache.update(self.get_group_permissions(user_obj))
+        return user_obj._perm_cache
+
+    def has_perm(self, user_obj, perm):
+        return perm in self.get_all_permissions(user_obj)
+
+    def has_module_perms(self, user_obj, app_label):
+        """
+        Returns True if user_obj has any permissions in the given app_label.
+        """
+        # return user_obj.is_superuser
+        for perm in self.get_all_permissions(user_obj):
+            if perm[:perm.index('.')] == app_label:
+                return True
+        return False
+
+    def get_user(self, user_id):
+        try:
+            return User.objects.get(pk=user_id)
+        except User.DoesNotExist:
+            return None
+
+
+class RemoteUserBackend(ModelBackend):
+    """
+    This backend is to be used in conjunction with the ``RemoteUserMiddleware``
+    found in the middleware module of this package, and is used when the server
+    is handling authentication outside of Django.
+
+    By default, the ``authenticate`` method creates ``User`` objects for
+    usernames that don't already exist in the database.  Subclasses can disable
+    this behavior by setting the ``create_unknown_user`` attribute to
+    ``False``.
+    """
+
+    # Create a User object if not already in the database?
+    create_unknown_user = True
+
+    def authenticate(self, remote_user):
+        """
+        The username passed as ``remote_user`` is considered trusted.  This
+        method simply returns the ``User`` object with the given username,
+        creating a new ``User`` object if ``create_unknown_user`` is ``True``.
+
+        Returns None if ``create_unknown_user`` is ``False`` and a ``User``
+        object with the given username is not found in the database.
+        """
+        if not remote_user:
+            return
+        user = None
+        username = self.clean_username(remote_user)
+
+        # Note that this could be accomplished in one try-except clause, but
+        # instead we use get_or_create when creating unknown users since it has
+        # built-in safeguards for multiple threads.
+        if self.create_unknown_user:
+            user, created = User.objects.get_or_create(username=username)
+            if created:
+                user = self.configure_user(user)
+        else:
+            try:
+                user = User.objects.get(username=username)
+            except User.DoesNotExist:
+                pass
+        return user
+
+    def clean_username(self, username):
+        """
+        Performs any cleaning on the "username" prior to using it to get or
+        create the user object.  Returns the cleaned username.
+
+        By default, returns the username unchanged.
+        """
+        return username
+
+    def configure_user(self, user):
+        """
+        Configures a user after creation and returns the updated user.
+
+        By default, returns the user unmodified.
+        """
+        return user
+from django.contrib.auth.decorators import login_required
+from google.appengine.api import users
+from django.utils.decorators import available_attrs
+from django.utils.functional import  wraps
+from django.http import HttpResponseRedirect
+from django.utils.http import urlquote
+from django.core.urlresolvers import reverse
+
+def user_passes_test(test_func,use_federate):
+    """
+    Decorator for views that checks that the user passes the given test,
+    redirecting to the log-in page if necessary. The test should be a callable
+    that takes the user object and returns True if the user passes.
+    """
+
+    def decorator(view_func):
+        def _wrapped_view(request, *args, **kwargs):
+            if test_func():
+                return view_func(request, *args, **kwargs)
+            path = urlquote(request.get_full_path())
+            if use_federate:
+                 federated_login_url = '/federatedlogin/?path=%s'%(path) #reverse('federated-login', args=[path])
+                 return HttpResponseRedirect(federated_login_url)
+            else:
+                return HttpResponseRedirect(users.create_login_url(dest_url=path))
+        return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
+    return decorator
+
+
+def gae_login_required(function=None,use_federate = False):
+    """
+    Decorator for views that checks that the user is logged in, redirecting
+    to the log-in page if necessary.
+    """
+    actual_decorator = user_passes_test(
+        lambda : users.get_current_user(),use_federate
+    )
+    if function:
+        return actual_decorator(function)
+    return actual_decorator
+  
+from django.contrib.auth import login, authenticate
+from django.core.context_processors import request
+import settings
+from djangogaeauth.models import groupuserjoin
+from django.utils.http import urlquote
+
+unusable_apssword = 'xnotusabley'
+from django.contrib.auth.models import User, Group
+
+__author__ = 'sreghenzi'
+
+from google.appengine.api import users
+
+class GaeSSOMiddleware():
+    def process_request(self,request):
+        #try:
+            if not request.user.is_authenticated():
+                if  users.get_current_user():
+                     gae_user = users.get_current_user()
+                     try:
+                        user = User.objects.get(email=gae_user.email())
+                     except User.DoesNotExist:
+                        # Create a new user.
+                        nickname = urlquote(gae_user.email())
+                        if gae_user.federated_provider():
+                            nickname = '%s - %s' % (gae_user.nickname(),gae_user.federated_provider())
+
+                        user = User.objects.create_user(nickname, gae_user.email(), unusable_apssword)
+                        if hasattr(settings,'GAESSO_AUTO_STAFF') and settings.GAESSO_AUTO_STAFF:
+                             user.is_staff = True
+                        if hasattr(settings,'GAESSO_AUTO_ADMIN') and settings.GAESSO_AUTO_ADMIN:
+                             user.is_superuser = True
+                        user.save()
+                        if hasattr(settings,'GAESSO_AUTO_GROUP') and settings.GAESSO_AUTO_GROUP:
+                            auto_group = Group.objects.get(name=settings.GAESSO_AUTO_GROUP)
+                            groupJoin = groupuserjoin(group =auto_group, user = user)
+                            groupJoin.save()
+
+
+
+
+                     user.backend = 'djangogaeauth.backends.ModelBackend'
+                     login(request,user)
+
+
+  
+from django.db import models
+from django.contrib.auth.models import User , Group , Permission
+
+
+class dpermission(models.Model):
+    owner = models.ForeignKey(User)
+    perm = models.ForeignKey(Permission)
+
+class gpermission(models.Model):
+    owner = models.ForeignKey(Group)
+    perm = models.ForeignKey(Permission)
+
+class groupuserjoin(models.Model):
+    group = models.ForeignKey(Group)
+    user = models.ForeignKey(User)

templates/federate_login.html

+{% extends 'base.html' %}
+{% block title %}OpenId login{% endblock %}
+
+{% block extra-head %}
+<script type="text/javascript" src="/media/js/jQueryOpenIdPlugin/jquery.openid.js"></script>
+<script type="text/javascript">  $(function() { $("form.openid:eq(0)").openid();
+                                               // $("form.openid:eq(0)").openid();
+                                               });</script>
+ <link rel="stylesheet" type="text/css" media="screen" href="/media/js/jQueryOpenIdPlugin/openid.css" />
+{% endblock %}
+
+{% block content %}
+<form class="openid" method="post" action="/gofederated/">
+  <div><ul class="providers">
+  <li class="openid" title="OpenID"><img src="/media/js/jQueryOpenIdPlugin/images/openidW.png" alt="icon" />
+  <span><strong>http://{your-openid-url}</strong></span></li>
+  <li class="username" title="Google">
+		<img src="/media/js/jQueryOpenIdPlugin/images/googleW.png" alt="icon" /><span>https://www.google.com/accounts/o8/id</span></li>
+  <li class="username" title="Yahoo">
+		<img src="/media/js/jQueryOpenIdPlugin/images/yahooW.png" alt="icon" /><span>http://yahoo.com/</span></li>
+  <li class="username" title="AOL screen name">
+		<img src="/media/js/jQueryOpenIdPlugin/images/aolW.png" alt="icon" /><span>http://openid.aol.com/<strong>username</strong></span></li>
+  <li class="username" title="MyOpenID user name">
+		<img src="/media/js/jQueryOpenIdPlugin/images/myopenid.png" alt="icon" /><span>http://<strong>username</strong>.myopenid.com/</span></li>
+  <li class="username" title="Flickr user name">
+		<img src="/media/js/jQueryOpenIdPlugin/images/flickr.png" alt="icon" /><span>http://flickr.com/<strong>username</strong>/</span></li>
+  <li class="username" title="Technorati user name">
+		<img src="/media/js/jQueryOpenIdPlugin/images/technorati.png" alt="icon" /><span>http://technorati.com/people/technorati/<strong>username</strong>/</span></li>
+  <li class="username" title="Wordpress blog name">
+		<img src="/media/js/jQueryOpenIdPlugin/images/wordpress.png" alt="icon" /><span>http://<strong>username</strong>.wordpress.com</span></li>
+  <li class="username" title="Blogger blog name">
+		<img src="/media/js/jQueryOpenIdPlugin/images/blogger.png" alt="icon" /><span>http://<strong>username</strong>.blogspot.com/</span></li>
+  <li class="username" title="LiveJournal blog name">
+		<img src="/media/js/jQueryOpenIdPlugin/images/livejournal.png" alt="icon" /><span>http://<strong>username</strong>.livejournal.com</span></li>
+  <li class="username" title="ClaimID user name">
+		<img src="/media/js/jQueryOpenIdPlugin/images/claimid.png" alt="icon" /><span>http://claimid.com/<strong>username</strong></span></li>
+  <li class="username" title="Vidoop user name">
+		<img src="/media/js/jQueryOpenIdPlugin/images/vidoop.png" alt="icon" /><span>http://<strong>username</strong>.myvidoop.com/</span></li>
+  <li class="username" title="Verisign user name">
+		<img src="/media/js/jQueryOpenIdPlugin/images/verisign.png" alt="icon" /><span>http://<strong>username</strong>.pip.verisignlabs.com/</span></li>
+  </ul></div>
+  <fieldset>
+  <label for="openid_username">Enter your <span>Provider user name</span></label>
+  <div><span></span><input type="text" name="openid_username" id="openid_username" /><span></span>
+  <input type="submit" value="Login" /></div>
+  </fieldset>
+  <fieldset>
+  <label for="openid_identifier">Enter your <a class="openid_logo" href="http://openid.net">OpenID</a></label>
+  <div><input type="text" name="openid_identifier" id="openid_identifier" />
+  <input type="submit" value="Login" /></div>
+  <input type="hidden" value="{{ next }}" name="path">
+  {% csrf_token %}
+
+  </fieldset>
+</form>
+
+
+{% endblock %}
+"""
+This file demonstrates two different styles of tests (one doctest and one
+unittest). These will both pass when you run "manage.py test".
+
+Replace these with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+class SimpleTest(TestCase):
+    def test_basic_addition(self):
+        """
+        Tests that 1 + 1 always equals 2.
+        """
+        self.failUnlessEqual(1 + 1, 2)
+
+__test__ = {"doctest": """
+Another way to test that 1 + 1 is equal to 2.
+
+>>> 1 + 1 == 2
+True
+"""}
+
+from django.shortcuts import render_to_response
+from django.http import HttpResponseRedirect
+from google.appengine.api import users
+
+def federated_login(request):
+    return render_to_response('federate_login.html',{'next':request.GET['path']})
+
+def go_federated(request):
+    return HttpResponseRedirect(users.create_login_url(dest_url=request.POST['path'],federated_identity=request.POST['openid_username']))
+