~ubuntuone-pqm-team/canonical-identity-provider/trunk

« back to all changes in this revision

Viewing changes to identityprovider/middleware/useraccount.py

  • Committer: Danny Tamez
  • Date: 2010-04-21 15:29:24 UTC
  • Revision ID: danny.tamez@canonical.com-20100421152924-lq1m92tstk2iz75a
Canonical SSO Provider (Open Source) - Initial Commit

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright 2010 Canonical Ltd.  This software is licensed under the
 
2
# GNU Affero General Public License version 3 (see the file LICENSE).
 
3
 
 
4
from django.contrib.auth import logout
 
5
from django.contrib.auth.models import User
 
6
 
 
7
from identityprovider.models import Account
 
8
 
 
9
 
 
10
class UserAccountConversionMiddleware(object):
 
11
    """ This middleware will try to convert request.user to the
 
12
    corresponding Account objects, if it's a User object, and the
 
13
    request is outside of the admin, and vice versa.
 
14
 
 
15
    If it cannot do the conversion, simply log out the user from
 
16
    the session. """
 
17
 
 
18
    def is_admin_area(self, url):
 
19
        return url.startswith('/admin/') or url.startswith('/readonly')
 
20
 
 
21
    def process_request(self, request):
 
22
        if request.user.is_authenticated():
 
23
            is_admin_url = self.is_admin_area(request.get_full_path())
 
24
            if isinstance(request.user, User) and not is_admin_url:
 
25
                try:
 
26
                    account = Account.objects.get(
 
27
                        openid_identifier=request.user.username)
 
28
                    request.user = account
 
29
                except Account.DoesNotExist:
 
30
                    logout(request)
 
31
            elif isinstance(request.user, Account) and is_admin_url:
 
32
                try:
 
33
                    user = User.objects.get(
 
34
                        username=request.user.openid_identifier)
 
35
                    request.user = user
 
36
                except User.DoesNotExist:
 
37
                    logout(request)