Skip to content

Commit 35d3543

Browse files
author
Massimo Di Pierro
committed
minor refactoring of auth logging
1 parent 1326e74 commit 35d3543

3 files changed

Lines changed: 44 additions & 30 deletions

File tree

apps/_scaffold/common.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,6 @@
3737
# #######################################################
3838
logger = make_logger("py4web:" + settings.APP_NAME, settings.LOGGERS)
3939

40-
# this export the logger to the auth module
41-
# so that it can be used in auth plugins
42-
import py4web.utils.auth as auth_module
43-
auth_module.logger = logger
44-
4540
# #######################################################
4641
# connect to db
4742
# #######################################################
@@ -66,7 +61,7 @@
6661
session = Session(secret=settings.SESSION_SECRET_KEY)
6762

6863
elif settings.SESSION_TYPE == "redis":
69-
import redis # type: ignore[reportMissingImports]
64+
import redis # type: ignore[reportMissingImports]
7065

7166
host, port = settings.REDIS_SERVER.split(":")
7267
# for more options: https://github.com/andymccurdy/redis-py/blob/master/redis/client.py
@@ -81,7 +76,7 @@
8176
elif settings.SESSION_TYPE == "memcache":
8277
import time
8378

84-
import memcache # type: ignore[reportMissingImports]
79+
import memcache # type: ignore[reportMissingImports]
8580

8681
conn = memcache.Client(settings.MEMCACHE_CLIENTS, debug=0)
8782
session = Session(secret=settings.SESSION_SECRET_KEY, storage=conn)
@@ -106,6 +101,7 @@
106101
auth.param.default_login_enabled = settings.DEFAULT_LOGIN_ENABLED
107102
auth.define_tables()
108103
auth.fix_actions()
104+
auth.logger = logger
109105

110106
flash = auth.flash
111107

@@ -138,7 +134,7 @@
138134
if settings.USE_LDAP:
139135
from py4web.utils.auth_plugins.ldap_plugin import LDAPPlugin
140136

141-
auth.register_plugin(LDAPPlugin(db=db, groups=groups, logger=logger, **settings.LDAP_SETTINGS))
137+
auth.register_plugin(LDAPPlugin(db=db, groups=groups, **settings.LDAP_SETTINGS))
142138

143139
if settings.OAUTH2GOOGLE_CLIENT_ID:
144140
from py4web.utils.auth_plugins.oauth2google import OAuth2Google # TESTED

py4web/utils/auth.py

Lines changed: 33 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -38,17 +38,17 @@
3838
[ ] Force new password every x days.
3939
"""
4040

41+
4142
# Allow logger to be set externally before importing this module
42-
try:
43-
logger # type: ignore # pylance: ignore undefined
44-
except NameError:
45-
# If not set, define a default logger
46-
logger = logging.getLogger("py4web.auth")
43+
def make_default_logger(name="py4web.auth"):
44+
"""Makes a default logger"""
45+
logger = logging.getLogger(name)
4746
if not logger.hasHandlers():
4847
handler = logging.StreamHandler()
4948
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
5049
handler.setFormatter(formatter)
5150
logger.addHandler(handler)
51+
return logger
5252

5353

5454
def b16e(text):
@@ -244,6 +244,7 @@ def __init__(
244244
two_factor_send=None,
245245
two_factor_validate=None,
246246
template_args=None,
247+
logger=None,
247248
):
248249
# configuration parameters
249250
self.param = Param(
@@ -290,6 +291,7 @@ def __init__(
290291
self.session = session
291292
self.sender = sender
292293
self.route = "auth"
294+
self.logger = logger or make_default_logger()
293295
self.use_username = use_username # if False, uses email only
294296
self.password_in_db = password_in_db # if False, password is never saved in db
295297
self.use_phone_number = use_phone_number
@@ -689,20 +691,26 @@ def login(self, email, password):
689691
for plugin in self.plugins.values():
690692
if not hasattr(plugin, "get_login_url"):
691693
prevent_db_lookup = True
692-
logger.debug(f"Trying plugin: {plugin.name}, mode: {getattr(plugin, 'mode', None)}")
694+
self.logger.debug(
695+
f"Trying plugin: {plugin.name}, mode: {getattr(plugin, 'mode', None)}"
696+
)
693697
if plugin.check_credentials(email, password):
694-
logger.debug(f"Plugin {plugin.name} accepted credentials for {email}")
698+
self.logger.debug(
699+
f"Plugin {plugin.name} accepted credentials for {email}"
700+
)
695701
user_info = {}
696702
user_info["sso_id"] = plugin.name + ":" + email
697703
if self.use_username or "@" not in email:
698704
user_info["username"] = email
699705
if "@" in email:
700706
user_info["email"] = email
701707
else:
702-
logger.debug(f"Constructing email from username: {email}@example.com")
708+
self.logger.debug(
709+
f"Constructing email from username: {email}@example.com"
710+
)
703711
user_info["email"] = email + "@example.com"
704712
user = self.get_or_register_user(user_info)
705-
logger.debug(f"User after get_or_register_user: {user}")
713+
self.logger.debug(f"User after get_or_register_user: {user}")
706714
break
707715

708716
# else check against database
@@ -1295,9 +1303,13 @@ def login(auth):
12951303
if "pam" in auth.plugins or "ldap" in auth.plugins:
12961304
plugin_name = "pam" if "pam" in auth.plugins else "ldap"
12971305
plugin = auth.plugins[plugin_name]
1298-
logger.debug(f"AuthAPI.login: Trying plugin {plugin_name} for user {username}")
1306+
self.logger.debug(
1307+
f"AuthAPI.login: Trying plugin {plugin_name} for user {username}"
1308+
)
12991309
check = plugin.check_credentials(username, password)
1300-
logger.debug(f"AuthAPI.login: plugin.check_credentials returned {check}")
1310+
self.logger.debug(
1311+
f"AuthAPI.login: plugin.check_credentials returned {check}"
1312+
)
13011313
if check:
13021314
data = {
13031315
"username": username,
@@ -1306,13 +1318,19 @@ def login(auth):
13061318
}
13071319
# and register the user if we have one, just in case
13081320
if auth.db:
1309-
logger.debug(f"AuthAPI.login: Calling get_or_register_user with data={data}")
1321+
self.logger.debug(
1322+
f"AuthAPI.login: Calling get_or_register_user with data={data}"
1323+
)
13101324
user = auth.get_or_register_user(data)
1311-
logger.debug(f"AuthAPI.login: User after get_or_register_user: {user}")
1325+
self.logger.debug(
1326+
f"AuthAPI.login: User after get_or_register_user: {user}"
1327+
)
13121328
auth.store_user_in_session(user["id"])
13131329
# else: if we're here - check is OK, but user is not in the session - is it right?
13141330
else:
1315-
logger.debug(f"AuthAPI.login: plugin.check_credentials failed for {username}")
1331+
self.logger.debug(
1332+
f"AuthAPI.login: plugin.check_credentials failed for {username}"
1333+
)
13161334
data = auth._error(
13171335
auth.param.messages["errors"].get("invalid_credentials")
13181336
)
@@ -1699,9 +1717,7 @@ def login(self, model=False):
16991717
# Get plain text password directly from request, on Windows this is needed
17001718
# because form.vars.get("password", "") returns an hashed password.
17011719
plain_password = request.forms.get("password", "")
1702-
user, error = self.auth.login(
1703-
form.vars.get("email", ""), plain_password
1704-
)
1720+
user, error = self.auth.login(form.vars.get("email", ""), plain_password)
17051721
form.accepted = not error
17061722

17071723
# Stops processing if there is a login error

py4web/utils/auth_plugins/ldap_plugin.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ def check_credentials(self, username, password):
242242
return False
243243
logger.debug(
244244
f"mode: {str(mode)}, manage_user: {str(manage_user)}, \
245-
custom_scope: {str(custom_scope)}, manage_groups: {str(manage_groups)}" \
245+
custom_scope: {str(custom_scope)}, manage_groups: {str(manage_groups)}"
246246
)
247247
if manage_user:
248248
if user_firstname_attrib.count(":") > 0:
@@ -279,7 +279,7 @@ def check_credentials(self, username, password):
279279
for x in base_dn.split(","):
280280
if "DC=" in x.upper():
281281
domain.append(x.split("=")[-1])
282-
username = f"{username}@{".".join(domain)}"
282+
username = f"{username}@{'.'.join(domain)}"
283283
username_bare = username.split("@")[0]
284284
con.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
285285
# In cases where ForestDnsZones and DomainDnsZones are found,
@@ -351,7 +351,7 @@ def check_credentials(self, username, password):
351351
con.simple_bind_s(bind_dn, bind_pw)
352352
dn = "uid=" + username + "," + base_dn
353353
dn = con.search_s(
354-
base_dn, ldap.SCOPE_SUBTREE, f"(uid={username, [""]})"
354+
base_dn, ldap.SCOPE_SUBTREE, f"(uid={username, ['']})"
355355
)[0][0]
356356
else:
357357
dn = "uid=" + username + "," + base_dn
@@ -393,7 +393,9 @@ def check_credentials(self, username, password):
393393
basedns = base_dn
394394
else:
395395
basedns = [base_dn]
396-
filter = f"(&(uid={ldap.filter.escape_filter_chars(username)})({filterstr}))"
396+
filter = (
397+
f"(&(uid={ldap.filter.escape_filter_chars(username)})({filterstr}))"
398+
)
397399
found = False
398400
for basedn in basedns:
399401
try:
@@ -726,7 +728,7 @@ def get_user_groups_from_ldap(self, username=None, password=None):
726728
for x in base_dn.split(","):
727729
if "DC=" in x.upper():
728730
domain.append(x.split("=")[-1])
729-
username = f"{username}@{".".join(domain)}"
731+
username = f"{username}@{'.'.join(domain)}"
730732
username_bare = username.split("@")[0]
731733
con = self._init_ldap()
732734
con.set_option(ldap.OPT_PROTOCOL_VERSION, 3)

0 commit comments

Comments
 (0)