<commit_before>#!/usr/bin/python
# -*- coding: utf-8 -*-
#  privacyIDEA is a fork of LinOTP
#  May 08, 2014 <NAME>
#  License:  AGPLv3
#  contact:  http://www.privacyidea.org
#
#  Copyright (C) 2010 - 2014 LSE Leading Security Experts GmbH
#  License:  AGPLv3
#  contact:  http://www.linotp.org
#            http://www.lsexperts.de
#            <EMAIL>
from __future__ import print_function

__doc__ = """
This module is used for the communication of
the python based management clients "privacyidea"
"""

import logging.handlers
import pprint
import requests
import gettext
from requests.packages.urllib3.exceptions import InsecureRequestWarning

_ = gettext.gettext

__version__ = 3.0
TIMEOUT = 5
etng = False

file_opts = ['rf_file=']
ldap_opts = ['rl_uri=', 'rl_basedn=', 'rl_binddn=',
             'rl_bindpw=', 'rl_timeout=', 'rl_loginattr=',
             'rl_searchfilter=', 'rl_userfilter=',
             'rl_attrmap=']
ldap_opts_map = {'rl_uri': 'LDAPURI',
                 'rl_basedn': 'LDAPBASE',
                 'rl_binddn': 'BINDDN',
                 'rl_bindpw': 'BINDPW',
                 'rl_timeout': 'TIMEOUT',
                 'rl_searchfilter': 'LDAPSEARCHFILTER',
                 'rl_userfilter': 'LDAPFILTER',
                 'rl_attrmap': 'USERINFO',
                 'rl_loginattr': 'LOGINNAMEATTRIBUTE'
                 }


def showresult(rv):
    try:
        pp = pprint.PrettyPrinter(indent=4)
        print(pp.pformat(rv['result']))
    except:
        print(rv)


class PrivacyIDEAClientError(Exception):
    """
    This class is used to throw client exceptions.
    """
    def __init__(self, eid=10, description="PrivacyIDEAClientError"):
        self.id = eid
        self.description = description
        
    def __str__(self):
        # here we lookup the error id - to translate
        return repr("ERR" + str(self.id) + ": " + self.description)


class response_obj(object):
    def __init__(self, status_code, json_object, text):
        self.status = status_code
        self.data = json_object
        self.text = text


class privacyideaclient(object):
    """
    This class is created to hold a connection to the privacyIDEA server

    It creates an authorization token that is sent in the HTTP header on each
    request.
    """

    def __init__(self, username, password, baseuri="http://localhost:5000",
                 no_ssl_check=False, pi_authorization=False):
        """
        :param baseuri: The base of the server like http://localhost:5000
        :type baseuri: basestring
        """
        self.auth_token = None
        self.headers = None
        self.baseuri = baseuri
        self.log = logging.getLogger('privacyideaclient')
        self.verify_ssl = not no_ssl_check
        self.pi_authorization = pi_authorization
        if not self.verify_ssl:
            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
        # Do the first server communication and retrieve the auth token
        self.set_credentials(username, password)

    def _send_response(self, r):
        if r.status_code >= 300:
            raise PrivacyIDEAClientError(eid=r.status_code,
                                          description=r.text)
        try:
            json_response = r.json
            if callable(json_response):
                # requests > 2.0
                json_response = json_response()
        except:
            json_response = None

        return response_obj(r.status_code, json_response, r.text)

    def set_credentials(self, username, password):
        """
        set an authtoken from the privacyidea server by providing username
        and password

        :param username: The username of the administrator or user
        :param password: The credential of the user
        :return: None
        """
        r = requests.post("%s/auth" % self.baseuri,
                          data={"username": username,
                                "password": password},
                          verify=self.verify_ssl)

        if r.status_code == requests.codes.ok:
            res = r.json
            if callable(res):
                # requests > 2.0
                res = res()
            result = res.get("result")
            if result.get("status") is True:
                self.auth_token = result.get("value", {}).get("token")
                if self.pi_authorization:
                    self.headers = {"Authorization": self.auth_token}
                else:
                    self.headers = {"PI-Authorization": self.auth_token}
        else:
            raise Exception("Invalid Credentials: %s" % r.status_code)

    def get(self, uripath, param=None):
        r = requests.get("%s%s" % (self.baseuri, uripath),
                         headers=self.headers,
                         params=param,
                         verify=self.verify_ssl)
        return self._send_response(r)
<commit_msg>turn the header mapping around to match help<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
#  privacyIDEA is a fork of LinOTP
#  May 08, 2014 <NAME>
#  License:  AGPLv3
#  contact:  http://www.privacyidea.org
#
#  Copyright (C) 2010 - 2014 LSE Leading Security Experts GmbH
#  License:  AGPLv3
#  contact:  http://www.linotp.org
#            http://www.lsexperts.de
#            <EMAIL>
from __future__ import print_function

__doc__ = """
This module is used for the communication of
the python based management clients "privacyidea"
"""

import logging.handlers
import pprint
import requests
import gettext
from requests.packages.urllib3.exceptions import InsecureRequestWarning

_ = gettext.gettext

__version__ = 3.0
TIMEOUT = 5
etng = False

file_opts = ['rf_file=']
ldap_opts = ['rl_uri=', 'rl_basedn=', 'rl_binddn=',
             'rl_bindpw=', 'rl_timeout=', 'rl_loginattr=',
             'rl_searchfilter=', 'rl_userfilter=',
             'rl_attrmap=']
ldap_opts_map = {'rl_uri': 'LDAPURI',
                 'rl_basedn': 'LDAPBASE',
                 'rl_binddn': 'BINDDN',
                 'rl_bindpw': 'BINDPW',
                 'rl_timeout': 'TIMEOUT',
                 'rl_searchfilter': 'LDAPSEARCHFILTER',
                 'rl_userfilter': 'LDAPFILTER',
                 'rl_attrmap': 'USERINFO',
                 'rl_loginattr': 'LOGINNAMEATTRIBUTE'
                 }


def showresult(rv):
    try:
        pp = pprint.PrettyPrinter(indent=4)
        print(pp.pformat(rv['result']))
    except:
        print(rv)


class PrivacyIDEAClientError(Exception):
    """
    This class is used to throw client exceptions.
    """
    def __init__(self, eid=10, description="PrivacyIDEAClientError"):
        self.id = eid
        self.description = description
        
    def __str__(self):
        # here we lookup the error id - to translate
        return repr("ERR" + str(self.id) + ": " + self.description)


class response_obj(object):
    def __init__(self, status_code, json_object, text):
        self.status = status_code
        self.data = json_object
        self.text = text


class privacyideaclient(object):
    """
    This class is created to hold a connection to the privacyIDEA server

    It creates an authorization token that is sent in the HTTP header on each
    request.
    """

    def __init__(self, username, password, baseuri="http://localhost:5000",
                 no_ssl_check=False, pi_authorization=False):
        """
        :param baseuri: The base of the server like http://localhost:5000
        :type baseuri: basestring
        """
        self.auth_token = None
        self.headers = None
        self.baseuri = baseuri
        self.log = logging.getLogger('privacyideaclient')
        self.verify_ssl = not no_ssl_check
        self.pi_authorization = pi_authorization
        if not self.verify_ssl:
            requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
        # Do the first server communication and retrieve the auth token
        self.set_credentials(username, password)

    def _send_response(self, r):
        if r.status_code >= 300:
            raise PrivacyIDEAClientError(eid=r.status_code,
                                          description=r.text)
        try:
            json_response = r.json
            if callable(json_response):
                # requests > 2.0
                json_response = json_response()
        except:
            json_response = None

        return response_obj(r.status_code, json_response, r.text)

    def set_credentials(self, username, password):
        """
        set an authtoken from the privacyidea server by providing username
        and password

        :param username: The username of the administrator or user
        :param password: <PASSWORD>
        :return: None
        """
        r = requests.post("%s/auth" % self.baseuri,
                          data={"username": username,
                                "password": password},
                          verify=self.verify_ssl)

        if r.status_code == requests.codes.ok:
            res = r.json
            if callable(res):
                # requests > 2.0
                res = res()
            result = res.get("result")
            if result.get("status") is True:
                self.auth_token = result.get("value", {}).get("token")
                if self.pi_authorization:
                    self.headers = {"PI-Authorization": self.auth_token}
                else:
                    self.headers = {"Authorization": self.auth_token}
        else:
            raise Exception("Invalid Credentials: %s" % r.status_code)

    def get(self, uripath, param=None):
        r = requests.get("%s%s" % (self.baseuri, uripath),
                         headers=self.headers,
                         params=param,
                         verify=self.verify_ssl)
        return self._send_response(r)

{'fraction_non_alphanumeric': 0.10167427701674277, 'fraction_numerical': 0.008117706747843734, 'mean_word_length': 2.014067278287462, 'pattern_counts': {'":': 10, '<': 8, '<?xml version=': 0, '>': 14, 'https://': 0, 'lorem ipsum': 0, 'www.': 6, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2207430', 'n_tokens_mistral': 2882, 'n_tokens_neox': 2781, 'n_words': 695}