# Path: IM/openid/JWT.py
# class JWT(object):
# 
#     @staticmethod
#     def b64d(b):
#         """Decode some base64-encoded bytes.
# 
#         Raises Exception if the string contains invalid characters or padding.
# 
#         :param b: bytes
#         """
# 
#         cb = b.rstrip(b"=")  # shouldn't but there you are
# 
#         # Python's base64 functions ignore invalid characters, so we need to
#         # check for them explicitly.
#         b64_re = re.compile(b"^[A-Za-z0-9_-]*$")
#         if not b64_re.match(cb):
#             raise Exception(cb, "base64-encoded data contains illegal characters")
# 
#         if cb == b:
#             b = JWT.add_padding(b)
# 
#         return base64.urlsafe_b64decode(b)
# 
#     @staticmethod
#     def add_padding(b):
#         # add padding chars
#         m = len(b) % 4
#         if m == 1:
#             # NOTE: for some reason b64decode raises *TypeError* if the
#             # padding is incorrect.
#             raise Exception(b, "incorrect padding")
#         elif m == 2:
#             b += b"=="
#         elif m == 3:
#             b += b"="
#         return b
# 
#     @staticmethod
#     def get_info(token):
#         """
#         Unpacks a JWT into its parts and base64 decodes the parts
#         individually, returning the part 1 json decoded, where the
#         token info is stored.
# 
#         :param token: The JWT token
#         """
#         part = tuple(token.encode("utf-8").split(b"."))
#         part = [JWT.b64d(p) for p in part]
#         return json.loads(part[1].decode("utf-8"))


import requests
import json
import time
from .JWT import JWT
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''
Class to contact with an OpenID server
'''


class OpenIDClient(object):

    @staticmethod
    def get_user_info_request(token, verify_ssl=False):
        """
        Get a the user info from a token
        """
        try:
            decoded_token = JWT().get_info(token)
            headers = {'Authorization': 'Bearer %s' % token}
            url = "%s%s" % (decoded_token['iss'], "/userinfo")
            resp = requests.request("GET", url, verify=verify_ssl, headers=headers)
            if resp.status_code != 200:
                return False, "Code: %d. Message: %s." % (resp.status_code, resp.text)
            return True, json.loads(resp.text)
        except Exception as ex:
            return False, str(ex)

    @staticmethod
    def get_token_introspection(token, client_id, client_secret, verify_ssl=False):
        """
        Get token introspection
        """
        try:

# Path: IM/openid/JWT.py
# class JWT(object):
# 
#     @staticmethod
#     def b64d(b):
#         """Decode some base64-encoded bytes.
# 
#         Raises Exception if the string contains invalid characters or padding.
# 
#         :param b: bytes
#         """
# 
#         cb = b.rstrip(b"=")  # shouldn't but there you are
# 
#         # Python's base64 functions ignore invalid characters, so we need to
#         # check for them explicitly.
#         b64_re = re.compile(b"^[A-Za-z0-9_-]*$")
#         if not b64_re.match(cb):
#             raise Exception(cb, "base64-encoded data contains illegal characters")
# 
#         if cb == b:
#             b = JWT.add_padding(b)
# 
#         return base64.urlsafe_b64decode(b)
# 
#     @staticmethod
#     def add_padding(b):
#         # add padding chars
#         m = len(b) % 4
#         if m == 1:
#             # NOTE: for some reason b64decode raises *TypeError* if the
#             # padding is incorrect.
#             raise Exception(b, "incorrect padding")
#         elif m == 2:
#             b += b"=="
#         elif m == 3:
#             b += b"="
#         return b
# 
#     @staticmethod
#     def get_info(token):
#         """
#         Unpacks a JWT into its parts and base64 decodes the parts
#         individually, returning the part 1 json decoded, where the
#         token info is stored.
# 
#         :param token: The JWT token
#         """
#         part = tuple(token.encode("utf-8").split(b"."))
#         part = [JWT.b64d(p) for p in part]
#         return json.loads(part[1].decode("utf-8"))


# Path: IM/openid/OpenIDClient.py
import requests
import json
import time
from .JWT import JWT

# along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''
Class to contact with an OpenID server
'''


class OpenIDClient(object):

    @staticmethod
    def get_user_info_request(token, verify_ssl=False):
        """
        Get a the user info from a token
        """
        try:
            decoded_token = JWT().get_info(token)
            headers = {'Authorization': 'Bearer %s' % token}
            url = "%s%s" % (decoded_token['iss'], "/userinfo")
            resp = requests.request("GET", url, verify=verify_ssl, headers=headers)
            if resp.status_code != 200:
                return False, "Code: %d. Message: %s." % (resp.status_code, resp.text)
            return True, json.loads(resp.text)
        except Exception as ex:
            return False, str(ex)

    @staticmethod
    def get_token_introspection(token, client_id, client_secret, verify_ssl=False):
        """
        Get token introspection
        """
        try:

            decoded_token = JWT().get_info(token)