Create a response system for any dynamic pages requiring an authentication.
Module whakerkit.responses
Class WhakerkitAuthResponse
Description
Constructor
Create a HTTPD Response instance with a default response.
Parameters
- name: (str) Filename of the body main content.
View Source
def __init__(self, name: str | None=None, tree=None, title: str=whakerkit.sg.name):
"""Create a HTTPD Response instance with a default response.
:param name: (str) Filename of the body main content.
"""
super(WhakerkitAuthResponse, self).__init__(name, tree, title)
self._connection = Connection()
self._connection.enable_method(JwtAuthentication.name(), True, whakerkit.sg.secret_key)
self._connection.enable_method(LdapAuthentication.name(), True, whakerkit.sg.domain)
self._is_authenticated = False
self._author = ''
Public functions
create
Create the deposit page.
View Source
def create(self):
"""Create the deposit page.
"""
get_base_response_class().create(self)
css_type = 'text/css'
self._htree.head.link(rel='stylesheet', href=whakerkit.sg.whakerexa + 'css/dialog.css', link_type=css_type)
self._htree.head.script(src=whakerkit.sg.whakerexa + 'js/dialog.js', script_type='application/javascript')
self._htree.head.script(src=whakerkit.sg.path + 'statics/js/authenticate.js', script_type='module')
auth_script = HTMLNode(self._htree.head.identifier, None, 'script', value=HEADER_SCRIPT)
auth_script.add_attribute('type', 'module')
self._htree.head.append_child(auth_script)
authenticate
Authenticate a user with JWT from the given token.
Fix status code to 401 if authentication failed.
Parameters
- token: (str) the token string
View Source
def authenticate(self, token: str):
"""Authenticate a user with JWT from the given token.
Fix status code to 401 if authentication failed.
:param token: (str) the token string
"""
try:
(self._is_authenticated, msg) = self._connection.connect(JwtAuthentication.name(), token)
if self._is_authenticated is True:
self._author = msg
self._data = {'token': token}
logging.debug(' ... Token is validated.')
else:
self._data = {'error': get_msg(MSG_NOT_AUTHENTICATED) + msg}
logging.error('User not authenticated: JWT authentication failed.')
self._status.code = 401
except Exception as e:
logging.error(e)
self._data = {'error': get_msg(MSG_BASE_FAILED) + str(e)}
logging.error(f'JWT unexpected authentication error: {e}')
self.status.code = 401
login
Authenticate a user with LDAP from the given username and password.
Fix status code to 401 if login failed.
Parameters
- username: (str) Username in LDAP
- password: (str) Password in LDAP
View Source
def login(self, username: str, password: str):
"""Authenticate a user with LDAP from the given username and password.
Fix status code to 401 if login failed.
:param username: (str) Username in LDAP
:param password: (str) Password in LDAP
"""
logging.info(f"Login attempt by username='{username}'")
self._data = {'error': get_msg(MSG_LOGIN_FAILED)}
if len(username) * len(password) > 0:
if logging.getLogger().getEffectiveLevel() > 1:
(self._is_authenticated, msg) = self._connection.connect(LdapAuthentication.name(), username, password)
else:
self._is_authenticated = True
if self._is_authenticated is True:
if logging.getLogger().getEffectiveLevel() > 1:
ldap_connection = self._connection.get_authentication_method_by_name('ldap')
self._author = ldap_connection.get_full_name(username)
ldap_connection.close()
else:
self._author = 'Anne Ony-misée'
try:
jwt = self._connection.get_authentication_method_by_name(JwtAuthentication.name())
token = jwt.generate_token(self._author, whakerkit.sg.jwt_validity)
logging.debug(f' ... JWT generated token: {token}')
self.authenticate(token)
logging.info(f' ... login {username} succeeded. {self._author} is authenticated.')
return
except KeyError:
self._data = {'error': get_msg(MSG_MISSING_JWT)}
else:
self._data = {'error': get_msg(MSG_NOT_AUTHENTICATED) + msg}
else:
self._data = {'error': get_msg(MSG_LOGIN_FAILED)}
logging.info(f"Login failed. '{username}' is not authenticated: {self._data['error']}")
self.status.code = 401
logout
Logout a user from the given events.
View Source
def logout(self):
"""Logout a user from the given events.
"""
pass
Private functions
_process_events
Process the given events coming from the POST of any form.
Parameters
- events (dict): key=eventname, value=eventvalue
Returns
- (bool) True if the whole page must be re-created.
View Source
def _process_events(self, events: dict, **kwargs) -> bool:
"""Process the given events coming from the POST of any form.
:param events (dict): key=event_name, value=event_value
:return: (bool) True if the whole page must be re-created.
"""
logging.debug(f'WhakerkitAuthResponse._process_events: {events.keys()}.')
self._status.code = 200
event_name = events.get('event_name', '')
if event_name in ('login', 'logout'):
if event_name == 'login':
self.login(events.get('username', ''), events.get('password', ''))
else:
self.logout()
return True
return False