Thank you, I've attached the changes. My python knowledge is very limited, 
so I probably have made a mistake. 
Maybe a better error message or knowing the main cause of the error message 
would help me. The file "account_login.html" isn't missing and can be used 
by other parts of the plugin.

On Friday, May 19, 2023 at 1:36:51 PM UTC+2 Jun Omae wrote:

> On Fri, May 19, 2023 at 4:50 PM Anke Visser <[email protected]> wrote:
> > I'm trying to upgrade to Trac1.5.4, which allows to use a current 
> version of python. I've already migrated the PageAuthzPolicyEditor plugin, 
> but I'm stuck with the TracDirectoryAuth plugin, which implements the 
> IPasswordStore interface from TracAccountManager.
>
> I think that is due to your modified TracDirectoryAuth. Please share
> your TracDirectoryAuth. No one can help it without sharing the source.
>
> -- 
> Jun Omae <[email protected]> (大前 潤)
>

-- 
You received this message because you are subscribed to the Google Groups "Trac 
Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/trac-users/3c969d00-0390-4c95-a89c-64bc6411e5b4n%40googlegroups.com.
Index: trunk/setup.py
===================================================================
--- trunk/setup.py	(revision 18543)
+++ trunk/setup.py	(working copy)
@@ -32,7 +32,7 @@
     entry_points={
         'trac.plugins': [
             'dirauth.db = tracext.dirauth.db',
-            'dirauth = tracext.dirauth',
+            'dirauth = tracext.dirauth.auth',
             'dirauth.permissionstore = tracext.dirauth.api:UserExtensiblePermissionStore',
         ],
     },
Index: trunk/tracext/dirauth/__init__.py
===================================================================
--- trunk/tracext/dirauth/__init__.py	(revision 18544)
+++ trunk/tracext/dirauth/__init__.py	(working copy)
@@ -7,6 +7,8 @@
 # you should have received as part of this distribution.
 #
 # Author: John Hampton <[email protected]>
+import pkg_resources
+pkg_resources.require('Trac > 1.4')
 
-from api import *
-from auth import *
+#from auth import *
+#from api import *
Index: trunk/tracext/dirauth/auth.py
===================================================================
--- trunk/tracext/dirauth/auth.py	(revision 18544)
+++ trunk/tracext/dirauth/auth.py	(working copy)
@@ -9,7 +9,8 @@
 # Author: John Hampton <[email protected]>
 # Extended: Branson Matheson <[email protected]>
 
-import cPickle
+#import pickle
+import pickle
 import hashlib
 import ldap
 import time
@@ -33,7 +34,7 @@
 
 def to_utf8(text):
     # Account for poor behavior of to_utf8 in Trac < 1.0.2
-    if isinstance(text, unicode):
+    if isinstance(text, str):
         return text.encode('utf-8')
     else:
         from trac.util.text import to_utf8
@@ -128,8 +129,9 @@
     def __init__(self, ldap=None):
         self._ldap = ldap
         self._cache = {}
-        reload(sys)
-        sys.setdefaultencoding('utf8')
+        # only python 2.7
+        #importlib.reload(sys)
+        #sys.setdefaultencoding('utf8')
 
     # IPasswordStore methods
 
@@ -138,6 +140,7 @@
         raise NotImplementedError
 
     def get_users(self):
+        self.log.debug('get users start')
         """Grab a list of users from the session store."""
         all_users = self._cache_get('allusers')
         if all_users:
@@ -153,7 +156,7 @@
                 userinfo = self.expand_group_users(ldapCtx, self.group_validusers)
             else:
                 users = self._ldap_search(ldapCtx, self.dir_basedn, ldap.SCOPE_SUBTREE,
-                                      "objectClass=person",
+                                      "objectClass=x-jsc-webserviceUserAccount",
                                       [to_utf8(self.user_attr),
                                        to_utf8(self.email_attr),
                                        to_utf8(self.proxy_attr),
@@ -187,7 +190,7 @@
                 try:
                     e = self._ldap_search(ldapCtx, to_utf8(m), ldap.SCOPE_BASE)
                     if e:
-                        if 'person' in e[0][1]['objectClass']:
+                        if 'x-jsc-webserviceUserAccount' in e[0][1]['objectClass']:
                             u = self._get_userinfo(e[0][1])
                             self.log.debug("found user %s", u[0])
                             users.append(u)
@@ -199,7 +202,7 @@
                         self.log.debug('Unable to find user listed in group: %s', str(m))
                         self.log.debug('This is very strange and you should probably check '
                                        'the consistency of your LDAP directory.', str(m))
-                except Exception, e:
+                except Exception as e:
                     self.log.debug('expand_group_users: %s: Unable to find ldap user listed in group: %s', e, str(m))
             return users
         else:
@@ -213,6 +216,11 @@
         else:
             return False
 
+    def set_password(self, user, password):
+        """Can't set LDAP passwd"""
+        self.log.debug('set pass start')
+        raise NotImplementedError(_("Setting passwords is not supported."))
+
     def check_password(self, user, password):
         """Checks the password against LDAP."""
         success = None
@@ -249,7 +257,7 @@
         # Update the session data at each login,
         # Note the use of NoCache to force the update(s)
         attrs = [self.user_attr, self.email_attr, self.proxy_attr, self.name_attr]
-        lfilter = '(&(%s=%s)(objectClass=person))' % (self.user_attr, user)
+        lfilter = '(&(%s=%s)(objectClass=x-jsc-webserviceUserAccount))' % (self.user_attr, user)
         users = self._dir_search(self.dir_basedn, self.dir_scope,
                                  lfilter, attrs, NOCACHE)
 
@@ -263,7 +271,8 @@
         self._populate_user_session(user_info)
 
         # Update the users by doing a search w/o cache
-        self.get_users()
+        # get_users -> SIZELIMIT_EXCEEDED: {'desc': 'Size limit exceeded'} -> set [account-manager] dir_pagesize = 5000
+        #self.get_users()
 
         return success
 
@@ -298,7 +307,7 @@
                            self.dir_uri, unicode(user_dn, 'utf8'))
             try:
                 user_ldap.simple_bind_s(user_dn, passwd)
-            except Exception, e:
+            except Exception as e:
                 self.log.error("_bind_dir: binding failed. %s", e)
                 return None
             return 1
@@ -320,7 +329,7 @@
 
         try:
             self._ldap.simple_bind_s(self.dir_binddn, self.dir_bindpw)
-        except ldap.LDAPError, e:
+        except ldap.LDAPError as e:
             raise TracError("cannot bind to %s: %s" % (self.dir_uri, e))
 
         self.log.debug("_bind_dir: Bound to %s correctly.", self.dir_uri)
@@ -340,7 +349,7 @@
             return dn
 
         u = self._dir_search(self.dir_basedn, self.dir_scope,
-                             "(&(%s=%s)(objectClass=person))"
+                             "(&(%s=%s)(objectClass=x-jsc-webserviceUserAccount))"
                              % (self.user_attr, user),
                              [self.user_attr], cache)
 
@@ -597,8 +606,11 @@
         basedn = basedn
         lfilter = lfilter
 
+
+        # attrs is list of byte elements now -> ok to convert to fix the join call?
+        string_attrs = [byte_elem.decode() for byte_elem in attrs]
         # Create unique key from the filter and the attributes.
-        keystr = to_utf8(','.join([basedn, str(scope), lfilter, ':'.join(attrs)]))
+        keystr = to_utf8(','.join([basedn, str(scope), lfilter, ':'.join(string_attrs)]))
         key = hashlib.md5(keystr).hexdigest()
         self.log.debug("_dir_search: searching %s for %s(%s)",
                        basedn, lfilter, key)
@@ -621,7 +633,7 @@
 
                     if current_time < lut + self.cache_ttl:
                         self.log.debug("_dir_search: dbcache hit for %s", lfilter)
-                        ret = cPickle.loads(str(data))
+                        ret = pickle.loads(str(data))
                         self._cache_set(key, ret, lut)
                         return ret
                 else:
@@ -643,7 +655,7 @@
                 try:
                     res = self._ldap_search(ldapCtx, basedn.encode(self.dir_charset), scope,
                                  lfilter, attrs)
-                except ldap.LDAPError, e:
+                except ldap.LDAPError as e:
                     # second try - does not work properly without
                     self.log.info("got %s - doing one additional retry", e)
                     self._ldap = None
@@ -650,7 +662,7 @@
                     ldapCtx = self._bind_dir()
                     res = self._ldap_search(ldapCtx, basedn.encode(self.dir_charset), scope,
                                  lfilter, attrs)
-            except ldap.LDAPError, e:
+            except ldap.LDAPError as e:
                 self.log.error("_dir_search: Error searching %s using %s: %s",
                                basedn, lfilter, e)
 
@@ -663,7 +675,7 @@
                 return res
 
             # Set the db cache for the next search, even if results are empty.
-            res_str = cPickle.dumps(res, 0)
+            res_str = pickle.dumps(res, 0)
             try:
                 cur = db.cursor()
                 cur.execute("""
@@ -676,7 +688,7 @@
                     VALUES (%s, %s, %s)
                     """, (key, current_time, buffer(res_str)))
 #                db.commit()
-            except Exception, e:
+            except Exception as e:
                 db.rollback()
                 self.log.warn("_dir_search: db cache update failed. %s" % e)
 
@@ -760,8 +772,11 @@
         r = []
 
         while True:
-            msgid = context.search_ext(base, scope, filterstr, attrlist, 0, [lc], None, -1, sz)
 
+            attrlist_string = [byte_elem.decode() for byte_elem in attrlist]
+
+            msgid = context.search_ext(base.decode('utf-8'), scope, filterstr, attrlist_string, 0, [lc], None, -1, sz)
+
             resp_type, resp_data, resp_msgid, decoded_resp_ctrls = context.result3(msgid)
 
             r += resp_data
Index: trunk/tracext/dirauth/db.py
===================================================================
--- trunk/tracext/dirauth/db.py	(revision 18544)
+++ trunk/tracext/dirauth/db.py	(working copy)
@@ -42,7 +42,7 @@
 def to_sql(env, table):
     """ Convenience function to get the to_sql for the active connector."""
     from trac.db.api import DatabaseManager
-    dc = DatabaseManager(env)._get_connector()[0]
+    dc = DatabaseManager(env).get_connector()[0]
     return dc.to_sql(table)
 
 
@@ -67,30 +67,33 @@
     def environment_created(self):
         pass
 
-    def environment_needs_upgrade(self, db):
-        return self._get_version(db) != db_version
+    def environment_needs_upgrade(self):
+        with self.env.db_query as db:
+            return self._get_version() != db_version
 
-    def upgrade_environment(self, db):
-        current_ver = self._get_version(db)
-        if current_ver == 0:
-            create_tables(self.env, db)
-        else:
-            while current_ver + 1 <= db_version:
-                upgrade_map[current_ver + 1](self.env, db)
-                current_ver += 1
+    def upgrade_environment(self):
+        with self.env.db_transaction as db:
+            current_ver = self._get_version()
+            if current_ver == 0:
+                create_tables(self.env, db)
+            else:
+                while current_ver + 1 <= db_version:
+                    upgrade_map[current_ver + 1](self.env, db)
+                    current_ver += 1
+                cursor = db.cursor()
+                cursor.execute("""
+                    UPDATE system SET value=%s WHERE name='dirauthplugin_version'
+                    """, db_version)
+
+    def _get_version(self):
+        with self.env.db_query as db:
             cursor = db.cursor()
-            cursor.execute("""
-                UPDATE system SET value=%s WHERE name='dirauthplugin_version'
-                """, db_version)
-
-    def _get_version(self, db):
-        cursor = db.cursor()
-        try:
-            cursor.execute("""
-                SELECT value FROM system WHERE name='dirauthplugin_version'
-                """)
-            for row in cursor:
-                return int(row[0])
-            return 0
-        except:
-            return 0
+            try:
+                cursor.execute("""
+                    SELECT value FROM system WHERE name='dirauthplugin_version'
+                    """)
+                for row in cursor:
+                    return int(row[0])
+                return 0
+            except:
+                return 0

Reply via email to