##// END OF EJS Templates
feat(system-info): expose rhodecode config for better visibility of set settings
feat(system-info): expose rhodecode config for better visibility of set settings

File last commit:

r5397:46138ab9 default
r5552:f3356a66 default
Show More
auth_pam.py
170 lines | 6.0 KiB | text/x-python | PythonLexer
copyrights: updated for 2023
r5088 # Copyright (C) 2012-2023 RhodeCode GmbH
project: added all source files and assets
r1 #
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License, version 3
# (only), as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# This program is dual-licensed. If you wish to learn more about the
# RhodeCode Enterprise Edition, including its added features, Support services,
# and proprietary license terms, please see https://rhodecode.com/licenses/
auth: refactor code and simplified instructions....
r1454
project: added all source files and assets
r1 """
RhodeCode authentication library for PAM
"""
import colander
import grp
import logging
import pam
import pwd
import re
import socket
auth: refactor code and simplified instructions....
r1454 from rhodecode.translation import _
from rhodecode.authentication.base import (
RhodeCodeExternalAuthPlugin, hybrid_property)
feat(2fa): added 2fa for more auth plugins and moved 2fa forced functionality to ee edition. Fixes: RCCE-68
r5397 from rhodecode.authentication.schema import AuthnPluginSettingsSchemaBase, TwoFactorAuthnPluginSettingsSchemaMixin
project: added all source files and assets
r1 from rhodecode.authentication.routes import AuthnPluginResourceBase
authn: Add whitespace stripping to authentication plugin settings.
r55 from rhodecode.lib.colander_utils import strip_whitespace
project: added all source files and assets
r1
log = logging.getLogger(__name__)
auth-plugins: some code cleanup + added docs for main plugin.
r3253 def plugin_factory(plugin_id, *args, **kwargs):
project: added all source files and assets
r1 """
Factory function that is called during plugin discovery.
It returns the plugin instance.
"""
plugin = RhodeCodeAuthPlugin(plugin_id)
return plugin
class PamAuthnResource(AuthnPluginResourceBase):
pass
feat(2fa): added 2fa for more auth plugins and moved 2fa forced functionality to ee edition. Fixes: RCCE-68
r5397 class PamSettingsSchema(TwoFactorAuthnPluginSettingsSchemaMixin, AuthnPluginSettingsSchemaBase):
project: added all source files and assets
r1 service = colander.SchemaNode(
colander.String(),
default='login',
description=_('PAM service name to use for authentication.'),
authn: Add whitespace stripping to authentication plugin settings.
r55 preparer=strip_whitespace,
project: added all source files and assets
r1 title=_('PAM service name'),
widget='string')
gecos = colander.SchemaNode(
colander.String(),
python3: fixed various code issues...
r4973 default=r'(?P<last_name>.+),\s*(?P<first_name>\w+)',
project: added all source files and assets
r1 description=_('Regular expression for extracting user name/email etc. '
'from Unix userinfo.'),
authn: Add whitespace stripping to authentication plugin settings.
r55 preparer=strip_whitespace,
project: added all source files and assets
r1 title=_('Gecos Regex'),
widget='string')
class RhodeCodeAuthPlugin(RhodeCodeExternalAuthPlugin):
authentication: use registerd UID for plugin definition for more consistent loading of auth plugins.
r3246 uid = 'pam'
project: added all source files and assets
r1 # PAM authentication can be slow. Repository operations involve a lot of
# auth calls. Little caching helps speedup push/pull operations significantly
AUTH_CACHE_TTL = 4
def includeme(self, config):
config.add_authn_plugin(self)
config.add_authn_resource(self.get_id(), PamAuthnResource(self))
config.add_view(
'rhodecode.authentication.views.AuthnPluginViewBase',
attr='settings_get',
templating: use .mako as extensions for template files.
r1282 renderer='rhodecode:templates/admin/auth/plugin_settings.mako',
project: added all source files and assets
r1 request_method='GET',
route_name='auth_home',
context=PamAuthnResource)
config.add_view(
'rhodecode.authentication.views.AuthnPluginViewBase',
attr='settings_post',
templating: use .mako as extensions for template files.
r1282 renderer='rhodecode:templates/admin/auth/plugin_settings.mako',
project: added all source files and assets
r1 request_method='POST',
route_name='auth_home',
context=PamAuthnResource)
auth: allow custom name for plugins if defined in the settings.
r4545 def get_display_name(self, load_from_settings=False):
project: added all source files and assets
r1 return _('PAM')
auth-plugins: expose docs and icon methods for authentication.
r3232 @classmethod
def docs(cls):
return "https://docs.rhodecode.com/RhodeCode-Enterprise/auth/auth-pam.html"
project: added all source files and assets
r1 @hybrid_property
def name(self):
authentication: run modernize for python3
r5094 return "pam"
project: added all source files and assets
r1
def get_settings_schema(self):
return PamSettingsSchema()
def use_fake_password(self):
return True
def auth(self, userobj, username, password, settings, **kwargs):
if not username or not password:
log.debug('Empty username or password skipping...')
return None
dependencies: bumped python-pam to 1.8.4 and fixed pam auth.
r2918 _pam = pam.pam()
auth_result = _pam.authenticate(username, password, settings["service"])
project: added all source files and assets
r1
if not auth_result:
logging: use lazy parameter evaluation in log calls.
r3061 log.error("PAM was unable to authenticate user: %s", username)
project: added all source files and assets
r1 return None
logging: use lazy parameter evaluation in log calls.
r3061 log.debug('Got PAM response %s', auth_result)
project: added all source files and assets
r1
# old attrs fetched from RhodeCode database
authentication: run modernize for python3
r5094 default_email = "{}@{}".format(username, socket.gethostname())
project: added all source files and assets
r1 admin = getattr(userobj, 'admin', False)
active = getattr(userobj, 'active', True)
email = getattr(userobj, 'email', '') or default_email
username = getattr(userobj, 'username', username)
firstname = getattr(userobj, 'firstname', '')
lastname = getattr(userobj, 'lastname', '')
extern_type = getattr(userobj, 'extern_type', '')
user_attrs = {
'username': username,
'firstname': firstname,
'lastname': lastname,
'groups': [g.gr_name for g in grp.getgrall()
if username in g.gr_mem],
authentication: introduce a group sync flag for plugins....
r2495 'user_group_sync': True,
project: added all source files and assets
r1 'email': email,
'admin': admin,
'active': active,
'active_from_extern': None,
'extern_name': username,
'extern_type': extern_type,
}
try:
user_data = pwd.getpwnam(username)
regex = settings["gecos"]
match = re.search(regex, user_data.pw_gecos)
if match:
user_attrs["firstname"] = match.group('first_name')
user_attrs["lastname"] = match.group('last_name')
except Exception:
log.warning("Cannot extract additional info for PAM user")
pass
authn: don't use formatted_json to log statements. It totally screws up...
r12 log.debug("pamuser: %s", user_attrs)
logging: expose extra metadata to various important logs for loki
r4816 log.info('user `%s` authenticated correctly', user_attrs['username'],
logging: changed module in logs extra as it is a reserved keyword
r4818 extra={"action": "user_auth_ok", "auth_module": "auth_pam", "username": user_attrs["username"]})
project: added all source files and assets
r1 return user_attrs
core: change from homebrew plugin system into pyramid machinery....
r3240
def includeme(config):
authentication: run modernize for python3
r5094 plugin_id = f'egg:rhodecode-enterprise-ce#{RhodeCodeAuthPlugin.uid}'
core: change from homebrew plugin system into pyramid machinery....
r3240 plugin_factory(plugin_id).includeme(config)