Beispiel #1
0
    async def get_api_version(self):
        if self.__api_version is not None:
            return self.__api_version

        with Querier.__lock:
            if self.__api_version is not None:
                return self.__api_version

            async def f(url):
                headers = {}
                if self.__api_key is not None:
                    headers = {API_KEY_HEADER: self.__api_key}
                return await AsyncClient().get(url, headers=headers)

            response = await self.__send_request_helper(
                API_VERSION, 'GET', f, len(self.__hosts))
            cdi_supported_by_server = response['versions']
            api_version = find_max_version(cdi_supported_by_server,
                                           SUPPORTED_CDI_VERSIONS)

            if api_version is None:
                raise_general_exception(
                    'The running SuperTokens core version is not compatible with this Flask SDK. '
                    'Please visit https://supertokens.io/docs/community/compatibility to find the '
                    'right versions')

            self.__api_version = api_version
            return self.__api_version
Beispiel #2
0
    async def __send_request_helper(self, path, method, http_function, no_of_tries):
        if no_of_tries == 0:
            raise_general_exception('No SuperTokens core available to query')

        try:
            current_host = self.__hosts[self.__last_tried_index]
            self.__last_tried_index += 1
            self.__last_tried_index %= len(self.__hosts)
            url = current_host + path

            response = await http_function(url)
            if ('SUPERTOKENS_ENV' in environ) and (
                    environ['SUPERTOKENS_ENV'] == 'testing'):
                self.__hosts_alive_for_testing.add(current_host)

            if is_4xx_error(response.status_code) or is_5xx_error(response.status_code):
                raise_general_exception('SuperTokens core threw an error for a ' + method + ' request to path: ' +
                                        path + ' with status code: ' + str(response.status_code) + ' and message: ' +
                                        response.text)

            try:
                return response.json()
            except JSONDecodeError:
                return response.text

        except (ConnectionError, NetworkError, ConnectTimeout):
            return await self.__send_request_helper(
                path, method, http_function, no_of_tries - 1)

        except Exception as e:
            raise_general_exception(e)
Beispiel #3
0
 def get_hosts_alive_for_testing(self):
     if ('SUPERTOKENS_ENV'
             not in environ) or (environ['SUPERTOKENS_ENV'] != 'testing'):
         raise_general_exception(
             'calling testing function in non testing env')
     return self.__hosts_alive_for_testing
Beispiel #4
0
 def reset():
     if ('SUPERTOKENS_ENV'
             not in environ) or (environ['SUPERTOKENS_ENV'] != 'testing'):
         raise_general_exception(
             'calling testing function in non testing env')
     Querier.__instance = None
Beispiel #5
0
def reset():
    if ('SUPERTOKENS_ENV' not in environ) or (
            environ['SUPERTOKENS_ENV'] != 'testing'):
        raise_general_exception('calling testing function in non testing env')
    ProcessState.reset()
Beispiel #6
0
async def auth0_handler(
    request: Request,
    domain: str,
    client_id: str,
    client_secret: str,
    callback: Union[Callable[[str, str, str, Union[str, None]],
                             Awaitable[any]], None] = None
) -> Response:
    try:
        request_json = await request.json()
        action = request_json['action']
        if action == 'logout':
            if not hasattr(request.state, 'supertokens'):
                request.state.supertokens = await __supertokens_session(
                    request, True)
            await request.state.supertokens.revoke_session()
            return JSONResponse({})
        auth_code = None
        if 'code' in request_json:
            auth_code = request_json['code']
        is_login = action == 'login'
        if not is_login:
            request.state.supertokens = await __supertokens_session(
                request, True)
        form_data = {}
        if auth_code is None and action == 'refresh':
            session_data = await request.state.supertokens.get_session_data()
            if 'refresh_token' not in session_data:
                return JSONResponse(content={}, status_code=403)
            form_data = {
                'grant_type': 'refresh_token',
                'client_id': client_id,
                'client_secret': client_secret,
                'refresh_token': session_data['refresh_token']
            }
        else:
            form_data = {
                'grant_type': 'authorization_code',
                'client_id': client_id,
                'client_secret': client_secret,
                'code': auth_code,
                'redirect_uri': request_json['redirect_uri']
            }
        response = await AsyncClient().post(
            url='https://' + domain + '/oauth/token',
            data=form_data,
            headers={'content-type': 'application/x-www-form-urlencoded'})
        if response.status_code != 200:
            return JSONResponse(content={}, status_code=response.status_code)
        response_json = response.json()
        id_token = response_json['id_token']
        expires_in = response_json['expires_in']
        access_token = response_json['access_token']
        refresh_token = None
        if 'refresh_token' in response_json:
            refresh_token = response_json['refresh_token']

        if is_login:
            payload = decode(jwt=id_token, verify=False)
            if callback is not None:
                try:
                    await callback(payload['sub'], id_token, access_token,
                                   refresh_token)
                except TypeError:
                    callback(payload['sub'], id_token, access_token,
                             refresh_token)
            else:
                session_data = {}
                if refresh_token is not None:
                    session_data['refresh_token'] = refresh_token
                await create_new_session(request, payload['sub'], {},
                                         session_data)
        elif auth_code is not None:
            session_data = await request.state.supertokens.get_session_data()
            if refresh_token is not None:
                session_data['refresh_token'] = refresh_token
            elif 'refresh_token' in session_data:
                del session_data['refresh_token']
            await request.state.supertokens.update_session_data(session_data)
        return JSONResponse(content={
            'id_token': id_token,
            'expires_in': expires_in
        })
    except HTTPException as e:
        # if the exception is of type HTTPException, we don't modify the exception and raise it as it is
        raise e
    except Exception as err:
        raise_general_exception(err)