Skip to content

Commit 1326e74

Browse files
authored
Add logging support to auth module and improve debug information (#989)
1 parent 6600475 commit 1326e74

File tree

2 files changed

+32
-5
lines changed

2 files changed

+32
-5
lines changed

apps/_scaffold/common.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,11 @@
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+
4045
# #######################################################
4146
# connect to db
4247
# #######################################################
@@ -133,7 +138,7 @@
133138
if settings.USE_LDAP:
134139
from py4web.utils.auth_plugins.ldap_plugin import LDAPPlugin
135140

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

138143
if settings.OAUTH2GOOGLE_CLIENT_ID:
139144
from py4web.utils.auth_plugins.oauth2google import OAuth2Google # TESTED

py4web/utils/auth.py

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import re
77
import time
88
import uuid
9+
import logging
910

1011
import jwt
1112

@@ -37,6 +38,18 @@
3738
[ ] Force new password every x days.
3839
"""
3940

41+
# 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")
47+
if not logger.hasHandlers():
48+
handler = logging.StreamHandler()
49+
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
50+
handler.setFormatter(formatter)
51+
logger.addHandler(handler)
52+
4053

4154
def b16e(text):
4255
"""convert unicode to b16 unicode"""
@@ -124,6 +137,7 @@ def on_request(self, context):
124137
message = self.auth.param.messages["flash"].get("login-required")
125138
self.goto_login(message=message)
126139

140+
user = self.auth.session.get("user")
127141
if callable(self.condition) and not self.condition(user):
128142
self.abort_or_redirect("not-authorized", "User not authorized")
129143

@@ -153,7 +167,7 @@ class Auth(Fixture):
153167
"user-logout": "User logout",
154168
"email-verified": "Email verified",
155169
"link-expired": "Link invalid or expired",
156-
"login-required": "Login required,",
170+
"login-required": "Login required",
157171
},
158172
"labels": {
159173
"username": "Username",
@@ -675,18 +689,20 @@ def login(self, email, password):
675689
for plugin in self.plugins.values():
676690
if not hasattr(plugin, "get_login_url"):
677691
prevent_db_lookup = True
692+
logger.debug(f"Trying plugin: {plugin.name}, mode: {getattr(plugin, 'mode', None)}")
678693
if plugin.check_credentials(email, password):
679-
# if the credentials are independently validated
680-
# get or create the user (if does not exist)
694+
logger.debug(f"Plugin {plugin.name} accepted credentials for {email}")
681695
user_info = {}
682696
user_info["sso_id"] = plugin.name + ":" + email
683697
if self.use_username or "@" not in email:
684698
user_info["username"] = email
685699
if "@" in email:
686700
user_info["email"] = email
687701
else:
702+
logger.debug(f"Constructing email from username: {email}@example.com")
688703
user_info["email"] = email + "@example.com"
689704
user = self.get_or_register_user(user_info)
705+
logger.debug(f"User after get_or_register_user: {user}")
690706
break
691707

692708
# else check against database
@@ -1278,7 +1294,10 @@ def login(auth):
12781294
# Prioritize PAM or LDAP logins if enabled
12791295
if "pam" in auth.plugins or "ldap" in auth.plugins:
12801296
plugin_name = "pam" if "pam" in auth.plugins else "ldap"
1281-
check = auth.plugins[plugin_name].check_credentials(username, password)
1297+
plugin = auth.plugins[plugin_name]
1298+
logger.debug(f"AuthAPI.login: Trying plugin {plugin_name} for user {username}")
1299+
check = plugin.check_credentials(username, password)
1300+
logger.debug(f"AuthAPI.login: plugin.check_credentials returned {check}")
12821301
if check:
12831302
data = {
12841303
"username": username,
@@ -1287,10 +1306,13 @@ def login(auth):
12871306
}
12881307
# and register the user if we have one, just in case
12891308
if auth.db:
1309+
logger.debug(f"AuthAPI.login: Calling get_or_register_user with data={data}")
12901310
user = auth.get_or_register_user(data)
1311+
logger.debug(f"AuthAPI.login: User after get_or_register_user: {user}")
12911312
auth.store_user_in_session(user["id"])
12921313
# else: if we're here - check is OK, but user is not in the session - is it right?
12931314
else:
1315+
logger.debug(f"AuthAPI.login: plugin.check_credentials failed for {username}")
12941316
data = auth._error(
12951317
auth.param.messages["errors"].get("invalid_credentials")
12961318
)

0 commit comments

Comments
 (0)