Basic HTTP Authentication

def basic(request, response, verify_user, realm='simple', context=None, **kwargs):
    """Basic HTTP Authentication"""
    http_auth = request.auth
    response.set_header('WWW-Authenticate', 'Basic')
    if http_auth is None:
        return

    if isinstance(http_auth, bytes):
        http_auth = http_auth.decode('utf8')
    try:
        auth_type, user_and_key = http_auth.split(' ', 1)
    except ValueError:
        raise HTTPUnauthorized('Authentication Error',
                               'Authentication header is improperly formed',
                               challenges=('Basic realm="{}"'.format(realm), ))

    if auth_type.lower() == 'basic':
        try:
            user_id, key = base64.decodebytes(bytes(user_and_key.strip(), 'utf8')).decode('utf8').split(':', 1)
            try:
                user = verify_user(user_id, key)
            except TypeError:
                user = verify_user(user_id, key, context)
            if user:
                response.set_header('WWW-Authenticate', '')
                return user
        except (binascii.Error, ValueError):
            raise HTTPUnauthorized('Authentication Error',
                                   'Unable to determine user and password with provided encoding',
                                   challenges=('Basic realm="{}"'.format(realm), ))
    return False