Source code for tanium_kit.pytanx
"""Pytan Extensions."""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
LOG = logging.getLogger(__name__.split(".")[-1])
"""
Usage:
user_obj = get_user_obj(handler, taniumpy)
check_allowed_roles(user_obj=user_obj, role_names=["Question Author"])
check_required_role(user_obj=user_obj, role_name="Administrator")
"""
[docs]def session_user_id(handler):
"""Get the user ID from handler.session.session_id."""
try:
result = int(handler.session.session_id.split('-')[0])
except Exception as e:
m = "Unable to parse user ID from session {!r}, error: {}"
raise Exception(m.format(handler.session.session_id, e))
return result
[docs]def get_user_obj(handler, taniumpy):
"""Fetch the user info for user ID."""
user_id = session_user_id(handler)
m = "Parsed user id {} from session id: {}"
LOG.debug(m.format(user_id, handler.session.session_id))
obj = taniumpy.User()
obj.id = user_id
try:
result = handler._find(obj)
except Exception as e:
m = "Failed to fetch user info for user ID: {}, error: {}"
raise Exception(m.format(user_id, e))
m = "Successfully retrieved user id {} info: {}"
LOG.debug(m.format(user_id, result))
return result
[docs]def check_allowed_roles(user_obj, role_names=[]):
"""Validate that the roles for user are in role_names."""
check = False
for role in user_obj.roles:
if role.name in role_names:
check = True
else:
m = "Role '{}' attached to user name '{}', id '{}' is not allowed! Allowed roles: {}"
m = m.format(role.name, user_obj.name, user_obj.id, ", ".join(role_names))
raise Exception(m)
if not check:
m = "User name '{}', id '{}' has none of the allowed roles: {}"
m = m.format(user_obj.name, user_obj.id, ", ".join(role_names))
raise Exception(m)
else:
m = "User name '{}', id '{}' has at least one of the allowed roles: {}"
m = m.format(user_obj.name, user_obj.id, ", ".join(role_names))
LOG.debug(m)
[docs]def check_required_role(user_obj, role_name=""):
"""Validate that one of the roles for user equals role."""
check = False
for role in user_obj.roles:
if role.name == role_name:
check = True
if not check:
m = "User name '{}', id '{}' does not have required role: {}"
m = m.format(user_obj.name, user_obj.id, role_name)
raise Exception(m)
else:
m = "User name '{}', id '{}' has required role: {}"
m = m.format(user_obj.name, user_obj.id, role_name)
LOG.debug(m)