# Path: drift/core/extensions/tenancy.py
# def drift_init_extension(app, **kwargs):
# def get_tenant_name(request_headers=None):
# def _flask_get_tenant_name():
# def _get_tenant_from_hostname(*args, **kw):
# def split_host(host):
# def _is_valid_ipv4_address(address):
# 
# Path: drift/core/extensions/urlregistry.py
# class Endpoints(object):
#     """
#     A class to register endpoint defitions functions
#     at import time
#     """
#     def __init__(self):
#         self.registry_funcs = []
# 
#     def init_app(self, app):
#         """
#         when app is initialized, the registered endpoints are handed to the registry
#         """
#         for f in self.registry_funcs:
#             registry.register_app_endpoints(app, f)
# 
#     def register(self, f):
#         """
#         At import time, register endpoint functions here
#         """
#         self.registry_funcs.append(f)
#         return f
# 
# Path: drift/fixers.py
# class CustomJSONEncoder(JSONEncoder):
#     '''Extend the JSON encoder to treat date-time objects as strict
#     rfc3339 types.
#     '''
#     def default(self, obj):
#         from drift.orm import ModelBase
#         if isinstance(obj, date):
#             return obj.isoformat() + "Z"
#         elif isinstance(obj, ModelBase):
#             return obj.as_dict()
#         else:
#             return JSONEncoder.default(self, obj)
# 
# Path: drift/utils.py
# def get_tier_name(fail_hard=True):
#     """
#     Get tier name from environment
#     """
#     if 'DRIFT_TIER' in os.environ:
#         return os.environ['DRIFT_TIER']
# 
#     if fail_hard:
#         raise RuntimeError(
#             "No tier specified. Specify one in "
#             "'DRIFT_TIER' environment variable, or use the --tier command "
#             "line argument."
#         )


import json
import logging
import re
import string
import copy
import jwt
import marshmallow as ma
from datetime import datetime, timedelta
from functools import wraps
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from flask import current_app, request, _request_ctx_stack, g, url_for, redirect, make_response
from flask.views import MethodView
from flask_smorest import Blueprint, abort
from six.moves import http_client
from werkzeug.local import LocalProxy
from werkzeug.security import gen_salt
from drift.core.extensions.tenancy import current_tenant_name, split_host
from drift.core.extensions.urlregistry import Endpoints
from drift.fixers import CustomJSONEncoder
from drift.utils import get_tier_name
    from drift.flaskfactory import load_flask_config
    from driftconfig.util import get_default_drift_config
        from driftconfig.util import get_default_drift_config
    if public_key is None:
        abort_unauthorized("Invalid JWT. Issuer '%s' not known or not trusted." % issuer)

    try:
        payload = jwt.decode(
            token, public_key,
            options=options,
            algorithms=[algorithm],
            leeway=leeway
        )
    except jwt.InvalidTokenError as e:
        abort_unauthorized("Invalid token: %s" % str(e))

    # Verify tier
    if 'tier' not in payload:
        abort_unauthorized("Invalid JWT. Token must specify 'tier'.")

    tier = payload['tier']
    tier_name = get_tier_name()
    if tier != tier_name:
        abort_unauthorized("Invalid JWT. Token is for tier '%s' but this is tier '%s'" % (tier, tier_name))

    # Verify tenant
    if 'tenant' not in payload:
        abort_unauthorized("Invalid JWT. Token must specify 'tenant'.")

    tenant = payload['tenant']
    if conf.tenant_name:
        this_tenant = conf.tenant_name['tenant_name']
    else:

# Path: drift/core/extensions/tenancy.py
# def drift_init_extension(app, **kwargs):
# def get_tenant_name(request_headers=None):
# def _flask_get_tenant_name():
# def _get_tenant_from_hostname(*args, **kw):
# def split_host(host):
# def _is_valid_ipv4_address(address):
# 
# Path: drift/core/extensions/urlregistry.py
# class Endpoints(object):
#     """
#     A class to register endpoint defitions functions
#     at import time
#     """
#     def __init__(self):
#         self.registry_funcs = []
# 
#     def init_app(self, app):
#         """
#         when app is initialized, the registered endpoints are handed to the registry
#         """
#         for f in self.registry_funcs:
#             registry.register_app_endpoints(app, f)
# 
#     def register(self, f):
#         """
#         At import time, register endpoint functions here
#         """
#         self.registry_funcs.append(f)
#         return f
# 
# Path: drift/fixers.py
# class CustomJSONEncoder(JSONEncoder):
#     '''Extend the JSON encoder to treat date-time objects as strict
#     rfc3339 types.
#     '''
#     def default(self, obj):
#         from drift.orm import ModelBase
#         if isinstance(obj, date):
#             return obj.isoformat() + "Z"
#         elif isinstance(obj, ModelBase):
#             return obj.as_dict()
#         else:
#             return JSONEncoder.default(self, obj)
# 
# Path: drift/utils.py
# def get_tier_name(fail_hard=True):
#     """
#     Get tier name from environment
#     """
#     if 'DRIFT_TIER' in os.environ:
#         return os.environ['DRIFT_TIER']
# 
#     if fail_hard:
#         raise RuntimeError(
#             "No tier specified. Specify one in "
#             "'DRIFT_TIER' environment variable, or use the --tier command "
#             "line argument."
#         )


# Path: drift/core/extensions/jwt.py
import json
import logging
import re
import string
import copy
import jwt
import marshmallow as ma
from datetime import datetime, timedelta
from functools import wraps
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_public_key
from flask import current_app, request, _request_ctx_stack, g, url_for, redirect, make_response
from flask.views import MethodView
from flask_smorest import Blueprint, abort
from six.moves import http_client
from werkzeug.local import LocalProxy
from werkzeug.security import gen_salt
from drift.core.extensions.tenancy import current_tenant_name, split_host
from drift.core.extensions.urlregistry import Endpoints
from drift.fixers import CustomJSONEncoder
from drift.utils import get_tier_name
    from drift.flaskfactory import load_flask_config
    from driftconfig.util import get_default_drift_config
        from driftconfig.util import get_default_drift_config

    if public_key is None:
        abort_unauthorized("Invalid JWT. Issuer '%s' not known or not trusted." % issuer)

    try:
        payload = jwt.decode(
            token, public_key,
            options=options,
            algorithms=[algorithm],
            leeway=leeway
        )
    except jwt.InvalidTokenError as e:
        abort_unauthorized("Invalid token: %s" % str(e))

    # Verify tier
    if 'tier' not in payload:
        abort_unauthorized("Invalid JWT. Token must specify 'tier'.")

    tier = payload['tier']
    tier_name = get_tier_name()
    if tier != tier_name:
        abort_unauthorized("Invalid JWT. Token is for tier '%s' but this is tier '%s'" % (tier, tier_name))

    # Verify tenant
    if 'tenant' not in payload:
        abort_unauthorized("Invalid JWT. Token must specify 'tenant'.")

    tenant = payload['tenant']
    if conf.tenant_name:
        this_tenant = conf.tenant_name['tenant_name']
    else:

        this_tenant = current_tenant_name