On Sep 9, 3:35 pm, Christian Hammond <chip...@chipx86.com> wrote:
> Can you attach that backends.py file? Something seems very fishy.

I'm using a customized backends.py file. Maybe it's incompatible with
1.6?  I successfully set up a 1.5 installation several months ago
using the same configuration.  Here's the backend:

========= backends.py ==============

from django.conf import settings
from django.contrib.auth.models import User, Permission,
check_password, Group, UserManager
from djblets.util.misc import get_object_or_none
import crypt
import nis
import ldap
import P4

class NISBackend:
    """
    Authenticate against a user on an NIS server.
    """

    def authenticate(self, username, password):
        try:
            passwd = nis.match(username, 'passwd').split(':')
            original_crypted = passwd[1]
            new_crypted = crypt.crypt(password, original_crypted[:2])

            if original_crypted == new_crypted:
                return self.get_or_create_user(username, passwd)
        except nis.error:
            # FIXME I'm not sure under what situations this would fail
(maybe if
            # their NIS server is down), but it'd be nice to inform
the user.
            pass

    def get_or_create_user(self, username, passwd=None):
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            try:
                if not passwd:
                    passwd = nis.match(username, 'passwd').split(':')

                names = passwd[4].split(' ', 1)
                first_name = names[0]
                last_name = None
                if len(names) > 1:
                  last_name = names[1]

                email = u'%s@%s' % (username,
settings.NIS_EMAIL_DOMAIN)

                user = User(username=username,
                            password='',
                            first_name=first_name,
                            last_name=last_name or '',
                            email=email)
                user.is_staff = False
                user.is_superuser = False
                user.save()
            except nis.error:
                pass
        return user

    def get_user(self, user_id):
        return get_object_or_none(User, pk=user_id)


class LDAPBackend:
    """
    Authenticate against a user on an LDAP server.
    """

    def authenticate(self, username, password):
        try:
            import ldap
            ldapo = ldap.initialize(settings.LDAP_URI)
            ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
            if settings.LDAP_TLS:
                ldapo.start_tls_s()
            ldapo.simple_bind_s(settings.LDAP_UID_MASK % username,
password)

            return self.get_or_create_user(username)

        except ImportError:
            pass
        except ldap.INVALID_CREDENTIALS:
            pass

    def get_or_create_user(self, username):
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            try:
                import ldap
                ldapo = ldap.initialize(settings.LDAP_URI)
                ldapo.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
                if settings.LDAP_TLS:
                    ldapo.start_tls_s()
                ldapo.simple_bind_s(settings.LDAP_ANON_BIND_UID,
settings.LDAP_ANON_BIND_PASSWD)

                passwd = ldapo.search_s(settings.LDAP_UID_MASK %
username,
                                        ldap.SCOPE_SUBTREE,
"objectclass=*")

                first_name, last_name = passwd[0][1]['cn'][0].split('
', 1)
                email = u'%s@%s' % (username,
settings.LDAP_EMAIL_DOMAIN)

                user = User(username=username,
                            password='',
                            first_name=first_name,
                            last_name=last_name,
                            email=email)
                user.is_staff = False
                user.is_superuser = False
                user.save()
            except ImportError:
                pass
            except ldap.INVALID_CREDENTIALS:
                # FIXME I'd really like to warn the user that their
                # ANON_BIND_UID and ANON_BIND_PASSWD are wrong, but I
don't
                # know how
                pass
            except ldap.NO_SUCH_OBJECT:
                pass
            except ldap.LDAPError:
                pass
        return user

    def get_user(self, user_id):
        return get_object_or_none(User, pk=user_id)

class SettingsBackend:
    """
    Authenticate against the settings ADMIN_LOGIN and ADMIN_PASSWORD.

    Use the login name, and a hash of the password. For example:

    ADMIN_LOGIN = 'admin'
    ADMIN_PASSWORD = 'sha1$blah'
    """
    def authenticate(self, username=None, password=None):
        login_valid = (settings.ADMIN_LOGIN == username)
        pwd_valid = check_password(password, settings.ADMIN_PASSWORD)
        if login_valid and pwd_valid:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                # Create a new user. Note that we can set password
                # to anything, because it won't be checked; the
password
                # from settings.py will.
                user = User(username=username, password='get from
settings.py')
                user.is_staff = True
                user.is_superuser = True
                user.save()
            return user
        return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None


class ActiveDirectoryGroupMembershipSSLBackend:

   def authenticate(self,username=None,password=None):
       user=None;
       try:
            debug=0

            # debug info
            if len(settings.AD_DEBUG_FILE) > 0:
                if settings.AD_DEBUG:
                   debug=open(settings.AD_DEBUG_FILE,'a')
                   print >>debug, "authenticate user: %s" % username

            ldap.set_option(ldap.OPT_X_TLS_CACERTFILE,settings.AD_CERT_FILE)
            ldap.set_option(ldap.OPT_REFERRALS,0) # DO NOT TURN THIS
OFF OR SEARCH WON'T WORK!

            # reset the random password
            try:
               if settings.ADMIN_LOGIN != username and username !=
'root' :
                   user = User.objects.get(username=username)
                   if debug:
                       print >> debug, 'set random password for usr %s' % 
username
                   random =
User.objects.make_random_password(length=10,allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
                   user.set_password(random)
                   user.save()
            except Exception, e:
                if debug:
                    print >> debug, 'could not reset random password
for %s' % username
                    print >> debug, e

            # initialize
            if debug:
               print >>debug, 'ldap.initialize...'
            l = ldap.initialize(settings.AD_LDAP_URL)
            l.set_option(ldap.OPT_PROTOCOL_VERSION, 3)

            # bind
            if debug:
               print >>debug, 'bind...'
            binddn = "%s@%s" % (username,settings.AD_NT4_DOMAIN)
            l.bind_s(binddn,password)

            # search
            if debug:
               print >>debug, 'search...'
            result =
l.search_ext_s(settings.AD_SEARCH_DN,ldap.SCOPE_SUBTREE,"sAMAccountName=
%s" % username,settings.AD_SEARCH_FIELDS)[0][1]
            if debug:
               print >>debug, result

            # Validate that they are a member of review board group
            if result.has_key('memberOf'):
                membership = result['memberOf']
            else:
                membership = None
            if debug:
               print >>debug, "required:%s" %
settings.AD_MEMBERSHIP_REQ
            bValid=0
            for req_group in settings.AD_MEMBERSHIP_REQ:
               if debug:
                  print >>debug, "Check for %s group..." % req_group
               for group in membership:
                   group_str="CN=%s," % req_group
                   if group.find(group_str) >= 0:
                        if debug:
                           print >>debug, "User authorized: group_str
membership found!"
                        bValid=1
                        break
            if bValid == 0:
               if debug:
                   print >>debug, "User not in an authorized NT group!"
               # Check if they are in a valid p4 group or not
               if self.in_valid_p4_group(username,debug):
                   if debug:
                        print >>debug, "User is in a valid p4 group, allow!"
                   bValid=1
               else:
                   if debug:
                        print >>debug, "User is NOT in valid p4
group!"
               if bValid == 0:
                   return None

            # get email
            if result.has_key('mail'):
                mail = result['mail'][0]
            else:
                mail = None
            if debug:
                print >>debug, "mail=%s" % mail

            # get surname
            if result.has_key('sn'):
                last_name = result['sn'][0]
            else:
                last_name = None
            if debug:
                print >>debug, "sn=%s" % last_name

            # get display name
            if result.has_key('givenName'):
                first_name = result['givenName'][0]
            else:
                first_name = None
            if debug:
               print >>debug, "first_name=%s" % first_name

            l.unbind_s()

            try:
               user = User.objects.get(username=username)
               if debug:
                  print >>debug, "User exists: %s" % username
            except User.DoesNotExist:
               if debug:
                  print >>debug, "Create user=%s" % username
               # Create user
               user =
User(username=username,first_name=first_name,last_name=last_name,email=mail)
               # grant user permissions
               user.is_staff = False
               user.is_superuser = False
               random =
User.objects.make_random_password(length=10,allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
               user.set_password(random)
               #user.set_unusable_password() # couldn't get this to
work, so set to random password instead
               user.save()

               # add user to default group
               group=Group.objects.get(pk=1)
               if debug:
                   print >>debug, group
               if debug:
                   print >>debug, "add %s to group %s" %
(username,group)
               user.groups.add(group)
               user.save()
               if debug:
                   print >>debug, "successful group add"

       except Exception, e:
          if debug:
             print >>debug, "exception caught!"
             print >>debug, e
             debug.close()
          return None

       if debug:
          debug.close()

       return user

   def in_valid_p4_group(self,username,debug):
       bValid=0
       try:
          if debug:
             print >>debug, "validate p4 group";
          if debug:
             print >>debug, "create p4 connection...";
          p4c = P4.P4();
          p4c.port = settings.AD_P4_PORT
          p4c.user = settings.AD_P4_USER
          if not p4c.connected():
              if debug:
                  print >>debug, "connect...";
              p4c.connect()
          if debug:
              print >>debug, "p4 groups -i %s" % username;
          groups_dict = p4c.run("groups","-i",username)
          groups=[]
          for group_dict in groups_dict:
                groups.append(group_dict.get('group'));
          if debug:
             print >>debug,"p4 groups = %s " % groups
          for req_group in settings.AD_P4_GROUP_MEMBERSHIP_ALLOWED:
               if debug:
                  print >>debug, "Check for %s group..." % req_group
               for group in groups:
                   if req_group.find(group) >= 0:
                        if debug:
                           print >>debug, "User authorized: p4 group
membership found %s!" % req_group
                        bValid=1
          if p4c.connected:
              if debug:
                  print >>debug, "disconnect...";
              p4c.disconnect()
          return bValid
       except ImportError, ie:
          if debug:
             print >>debug, "Import error exception caught!"
             print >>debug, ie
          pass
       except Exception, e:
          if debug:
             print >>debug, "exception caught!"
             print >>debug, e
          pass
       return bValid

   def get_user(self, user_id):
       try:
          return User.objects.get(pk=user_id)
       except User.DoesNotExist:
          return None


-- 
Want to help the Review Board project? Donate today at 
http://www.reviewboard.org/donate/
Happy user? Let us know at http://www.reviewboard.org/users/
-~----------~----~----~----~------~----~------~--~---
To unsubscribe from this group, send email to 
reviewboard+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/reviewboard?hl=en

Reply via email to