示例#1
0
    async def test_emulator_msa_header_correct_app_id_and_service_url_should_validate(
            self):
        header = (
            "Bearer " +
            MicrosoftAppCredentials("2cd87869-38a0-4182-9251-d056e8f0ac24",
                                    "2.30Vs3VQLKt974F").get_access_token())
        credentials = SimpleCredentialProvider(
            "2cd87869-38a0-4182-9251-d056e8f0ac24", "")
        result = await JwtTokenValidation.validate_auth_header(
            header, credentials, "", "https://webchat.botframework.com/")

        assert result
示例#2
0
 def __handle_conversation_update_activity(self, activity):
     self.send_response(202)
     self.end_headers()
     if activity.members_added[0].id != activity.recipient.id:
         credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
         reply = BotRequestHandler.__create_reply_activity(
             activity, 'Welcome to Summarize Bot')
         reply.attachments = [self.create_adaptive_card_attachment()]
         connector = ConnectorClient(credentials,
                                     base_url=reply.service_url)
         connector.conversations.send_to_conversation(
             reply.conversation.id, reply)
示例#3
0
 async def test_connector_auth_header_with_different_bot_app_id_should_not_validate(
         self):
     header = (
         "Bearer " +
         MicrosoftAppCredentials("2cd87869-38a0-4182-9251-d056e8f0ac24",
                                 "2.30Vs3VQLKt974F").get_access_token())
     credentials = SimpleCredentialProvider(
         "00000000-0000-0000-0000-000000000000", "")
     with pytest.raises(Exception) as excinfo:
         await JwtTokenValidation.validate_auth_header(
             header, credentials, "", "https://webchat.botframework.com/")
     assert "Unauthorized" in str(excinfo.value)
示例#4
0
 async def test_emulator_msa_header_and_no_credential_should_not_validate(
         self):
     header = (
         "Bearer " +
         MicrosoftAppCredentials("2cd87869-38a0-4182-9251-d056e8f0ac24",
                                 "2.30Vs3VQLKt974F").get_access_token())
     credentials = SimpleCredentialProvider(
         "00000000-0000-0000-0000-000000000000", "")
     with pytest.raises(Exception) as excinfo:
         await JwtTokenValidation.validate_auth_header(
             header, credentials, "", None)
         assert "Unauthorized" in excinfo
async def get_auth_token():
    try:
        # pylint: disable=import-outside-toplevel
        from .app_creds_real import MICROSOFT_APP_ID, MICROSOFT_APP_PASSWORD

        # Define a "app_creds_real.py" file with your bot credentials as follows:
        # MICROSOFT_APP_ID = '...'
        # MICROSOFT_APP_PASSWORD = '******'
        return MicrosoftAppCredentials(
            MICROSOFT_APP_ID, MICROSOFT_APP_PASSWORD).get_access_token()
    except ImportError:
        return "STUB_ACCESS_TOKEN"
示例#6
0
 def __handle_message_activity(self, activity):
     self.send_response(200)
     self.end_headers()
     credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
     connector = ConnectorClient(credentials, base_url=activity.service_url)
     userIntent = Analyze_User_Intent_LUIS(activity.text)
     response = Cafeteria_Response_Query(userIntent)
     #        reply = BotRequestHandler.__create_reply_activity(activity, 'You said: %s' % activity.text)
     reply = BotRequestHandler.__create_reply_activity(
         activity, 'CafeteiaBot: %s' % response)
     connector.conversations.send_to_conversation(reply.conversation.id,
                                                  reply)
示例#7
0
    async def test_channel_authentication_disabled_service_url_should_not_be_trusted(
        self,
    ):
        activity = Activity(service_url="https://webchat.botframework.com/")
        header = ""
        credentials = SimpleCredentialProvider("", "")

        await JwtTokenValidation.authenticate_request(activity, header, credentials)

        assert not MicrosoftAppCredentials.is_trusted_service(
            "https://webchat.botframework.com/"
        )
示例#8
0
    def __handle_message_activity(self, activity):
        self.send_response(200)
        self.end_headers()
        credentials = MicrosoftAppCredentials(
            MICROSOFT_CLIENT.get_microsoft_app_id(),
            MICROSOFT_CLIENT.get_microsoft_app_password())
        connector = ConnectorClient(credentials, base_url=activity.service_url)

        response = MICROSOFT_CLIENT.ask_question(activity.text)
        reply = BotRequestHandler.__create_reply_activity(activity, response)

        connector.conversations.send_to_conversation(reply.conversation.id,
                                                     reply)
示例#9
0
 def __handle_conversation_update_activity(self, activity):
     self.send_response(202)
     self.end_headers()
     if activity.members_added[0].id != activity.recipient.id:
         credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
         reply = BotRequestHandler.__create_reply_activity(
             activity, 'Hello, welcome to Doctor Bot.\n' +
             'If you are not feeling well, tell me whats wrong, ' +
             'and I will try to help you out')
         connector = ConnectorClient(credentials,
                                     base_url=reply.service_url)
         connector.conversations.send_to_conversation(
             reply.conversation.id, reply)
    async def test_channel_msa_header_from_user_specified_tenant(self):
        activity = Activity(
            service_url='https://smba.trafficmanager.net/amer-client-ss.msg/')
        header = 'Bearer ' + MicrosoftAppCredentials(
            '2cd87869-38a0-4182-9251-d056e8f0ac24', '2.30Vs3VQLKt974F',
            'microsoft.com').get_access_token(True)
        credentials = SimpleCredentialProvider(
            '2cd87869-38a0-4182-9251-d056e8f0ac24', '')

        claims = await JwtTokenValidation.authenticate_request(
            activity, header, credentials)

        assert claims.get_claim_value(
            "tid") == '72f988bf-86f1-41af-91ab-2d7cd011db47'
示例#11
0
 def __handle_conversation_update_activity(self, activity):
     self.send_response(202)
     self.end_headers()
     if activity.members_added[0].id != activity.recipient.id:
         credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
         Bot.init = True
         Bot.sub = False
         Bot.menu_opt = False
         Bot.query = False
         reply = Bot.__create_reply_activity(activity, WELCOME)
         connector = ConnectorClient(credentials,
                                     base_url=reply.service_url)
         connector.conversations.send_to_conversation(
             reply.conversation.id, reply)
示例#12
0
 def __init__(self, config, opsdroid):
     self.name = self.__class__.__name__
     self.loop = asyncio.get_event_loop()
     self.config = config
     self.opsdroid = opsdroid
     self.endpoint = config.get("endpoint", ENDPOINT)
     self.app_id = config.get("app_id", APP_ID)
     self.app_pass = config.get("app_pass", APP_PASS)
     self.credentials = MicrosoftAppCredentials(self.app_id, self.app_pass)
     self.credential_provider = SimpleCredentialProvider(
         self.app_id, self.app_pass)
     self.authenticated = False
     self.counter = 0
     self._queue = asyncio.Queue()  # message queue
     self._closing = asyncio.Event()
示例#13
0
    async def test_channel_msa_header_Valid_service_url_should_be_trusted(
            self):
        activity = Activity(
            service_url='https://smba.trafficmanager.net/amer-client-ss.msg/')
        header = 'Bearer ' + await MicrosoftAppCredentials(
            '2cd87869-38a0-4182-9251-d056e8f0ac24',
            '2.30Vs3VQLKt974F').get_access_token()
        credentials = SimpleCredentialProvider(
            '2cd87869-38a0-4182-9251-d056e8f0ac24', '')

        await JwtTokenValidation.authenticate_request(activity, header,
                                                      credentials)

        assert MicrosoftAppCredentials.is_trusted_service(
            'https://smba.trafficmanager.net/amer-client-ss.msg/')
示例#14
0
    async def test_get_user_token_returns_null(self):
        adapter = TestAdapter()
        activity = Activity(
            channel_id="directline", from_property=ChannelAccount(id="testuser")
        )

        turn_context = TurnContext(adapter, activity)

        token_response = await adapter.get_user_token(turn_context, "myConnection")
        assert not token_response

        oauth_app_credentials = MicrosoftAppCredentials(None, None)
        token_response = await adapter.get_user_token(
            turn_context, "myConnection", oauth_app_credentials=oauth_app_credentials
        )
        assert not token_response
示例#15
0
async def send_message(req: Request) -> Response:
    try:
        credentials = MicrosoftAppCredentials(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
        client = ConnectorClient(credentials, 'https://smba.trafficmanager.net/fr/')
        teams_client = TeamsConnectorClient(credentials, 'https://smba.trafficmanager.net/fr/')
        teams_channels = teams_client.teams.get_teams_channels('19:[email protected]')
        general_channel = next(channel for channel in teams_channels.conversations if channel.name is None)
        conversation_parameters = ConversationParameters(
            is_group=True,
            channel_data={"channel": {"id": general_channel.id}},
            activity=MessageFactory.content_url('https://picsum.photos/200/300', 'image/png'),
        )
        client.conversations.create_conversation(conversation_parameters)
        return Response(status=HTTPStatus.OK)
    except Exception:
        traceback.print_exc()
示例#16
0
    def _get_or_create_connector_client(
            self, service_url: str,
            credentials: AppCredentials) -> ConnectorClient:
        if not credentials:
            credentials = MicrosoftAppCredentials.empty()

        # Get ConnectorClient from cache or create.
        client_key = BotFrameworkAdapter.key_for_connector_client(
            service_url, credentials.microsoft_app_id, credentials.oauth_scope)
        client = self._connector_client_cache.get(client_key)
        if not client:
            client = ConnectorClient(credentials, base_url=service_url)
            client.config.add_user_agent(USER_AGENT)
            self._connector_client_cache[client_key] = client

        return client
示例#17
0
    async def test_channel_msa_header_invalid_service_url_should_not_be_trusted(
            self):
        activity = Activity(service_url='https://webchat.botframework.com/')
        header = 'Bearer ' + await MicrosoftAppCredentials(
            '2cd87869-38a0-4182-9251-d056e8f0ac24',
            '2.30Vs3VQLKt974F').get_access_token()
        credentials = SimpleCredentialProvider(
            '7f74513e-6f96-4dbc-be9d-9a81fea22b88', '')

        with pytest.raises(Exception) as excinfo:
            await JwtTokenValidation.authenticate_request(
                activity, header, credentials)
        assert 'Unauthorized' in str(excinfo.value)

        assert not MicrosoftAppCredentials.is_trusted_service(
            'https://webchat.botframework.com/')
示例#18
0
    def __handle_initial_activity(
            self,
            activity):  # Initialization- Welcome msg, hotel info and pics

        Bot.init = False
        self.send_response(200)
        self.end_headers()
        credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
        connector = ConnectorClient(credentials, base_url=activity.service_url)

        Bot.Name = activity.text
        locs = Bot.show_location()
        st = wlc + Bot.Name + ". \nPlease choose which city you prefer."
        reply = Bot.__create_reply_activity(activity, st, locs)
        connector.conversations.send_to_conversation(reply.conversation.id,
                                                     reply)
示例#19
0
    def __init__(self, config: DefaultConfig):
        super(MainDialog, self).__init__(MainDialog.__name__)

        self.connection_name = config.CONNECTION_NAME
        self.add_dialog(
            WaterfallDialog(WaterfallDialog.__name__,
                            [self.sign_in_step, self.show_token_response]))
        self.add_dialog(
            OAuthPrompt(
                OAuthPrompt.__name__,
                OAuthPromptSettings(
                    connection_name=self.connection_name,
                    text="Sign In to AAD",
                    title="Sign In",
                    oauth_app_credentials=MicrosoftAppCredentials(
                        app_id=config.APP_ID, password=config.APP_PASSWORD))))
示例#20
0
    def __handle_conversation_update_activity(self, activity):
        self.send_response(202)
        self.end_headers()
        if len(activity.members_added):
            if activity.members_added[0].id != activity.recipient.id:
                credentials = MicrosoftAppCredentials(
                    MICROSOFT_CLIENT.get_microsoft_app_id(),
                    MICROSOFT_CLIENT.get_microsoft_app_password())

                response = MICROSOFT_CLIENT.get_new_user_message()
                reply = BotRequestHandler.__create_reply_activity(
                    activity, response)

                connector = ConnectorClient(credentials,
                                            base_url=reply.service_url)
                connector.conversations.send_to_conversation(
                    reply.conversation.id, reply)
    def __init__(  # pylint: disable=super-init-not-called
        self,
        inspection_state: InspectionState,
        user_state: UserState = None,
        conversation_state: ConversationState = None,
        credentials: MicrosoftAppCredentials = None,
    ):

        self.inspection_state = inspection_state
        self.inspection_state_accessor = inspection_state.create_property(
            "InspectionSessionByStatus")
        self.user_state = user_state
        self.conversation_state = conversation_state
        self.credentials = MicrosoftAppCredentials(
            credentials.microsoft_app_id if credentials else "",
            credentials.microsoft_app_password if credentials else "",
        )
示例#22
0
    def _create_streaming_connector_client(
            self, activity: Activity,
            request_handler: StreamingRequestHandler) -> ConnectorClient:
        empty_credentials = (MicrosoftAppCredentials.empty()
                             if self._channel_provider
                             and self._channel_provider.is_government() else
                             MicrosoftGovernmentAppCredentials.empty())
        streaming_driver = StreamingHttpDriver(request_handler)
        config = BotFrameworkConnectorConfiguration(
            empty_credentials,
            activity.service_url,
            pipeline_type=AsyncBfPipeline,
            driver=streaming_driver,
        )
        streaming_driver.config = config
        connector_client = ConnectorClient(None, custom_configuration=config)

        return connector_client
示例#23
0
 def __handle_conversation_update_activity(self, activity):
     """
     Handle any conversation update (triggers when bot is added)
     :param activity:
     :return:
     """
     self.send_response(202)
     self.end_headers()
     if activity.members_added[0].id != activity.recipient.id:
         # if any member is added
         credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)
         # reply with Welcome Message
         reply = ChatbotHandler.__create_reply_activity(
             activity, WELCOME_MSG)
         connector = ConnectorClient(credentials,
                                     base_url=reply.service_url)
         connector.conversations.send_to_conversation(
             reply.conversation.id, reply)
示例#24
0
    async def test_get_user_token_returns_token_with_magice_code(self):
        adapter = TestAdapter()
        connection_name = "myConnection"
        channel_id = "directline"
        user_id = "testUser"
        token = "abc123"
        magic_code = "888999"
        activity = Activity(channel_id=channel_id,
                            from_property=ChannelAccount(id=user_id))

        turn_context = TurnContext(adapter, activity)

        adapter.add_user_token(connection_name, channel_id, user_id, token,
                               magic_code)

        # First no magic_code
        token_response = await adapter.get_user_token(turn_context,
                                                      connection_name)
        assert not token_response

        # Can be retrieved with magic code
        token_response = await adapter.get_user_token(turn_context,
                                                      connection_name,
                                                      magic_code)
        assert token_response
        assert token == token_response.token
        assert connection_name == token_response.connection_name

        # Then can be retrieved without magic code
        token_response = await adapter.get_user_token(turn_context,
                                                      connection_name)
        assert token_response
        assert token == token_response.token
        assert connection_name == token_response.connection_name

        # Then can be retrieved using customized AppCredentials
        oauth_app_credentials = MicrosoftAppCredentials(None, None)
        token_response = await adapter.get_user_token(
            turn_context,
            connection_name,
            oauth_app_credentials=oauth_app_credentials)
        assert token_response
        assert token == token_response.token
        assert connection_name == token_response.connection_name
示例#25
0
    async def __build_credentials(self,
                                  app_id: str,
                                  oauth_scope: str = None) -> AppCredentials:
        app_password = await self._credential_provider.get_app_password(app_id)

        if self._channel_provider.is_government():
            return MicrosoftGovernmentAppCredentials(
                app_id,
                app_password,
                self.settings.channel_auth_tenant,
                scope=oauth_scope,
            )

        return MicrosoftAppCredentials(
            app_id,
            app_password,
            self.settings.channel_auth_tenant,
            oauth_scope=oauth_scope,
        )
    def __handle_message_activity(self, activity):
        """
        Handle the messages.  STATE used to collect APPID and APPKEY up front.  All other messsages sent to
        LUIS for parsing.  APPID and APPKEY specify the LUIS service called via REST. For example:
          https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/((APPID))?subscription-key=((APPKEY))
                &verbose=true&timezoneOffset=0&q=((TEXT-FOR-LUIS-TO-PARSE
        """
        BotRequestHandler.STATE+=1   ## POORMAN'S STATE TRACKING
        self.send_response(200)
        self.end_headers()
        credentials = MicrosoftAppCredentials(APPID, APPPASSWORD)
        connector = ConnectorClient(credentials, base_url=activity.service_url)
        LUIStext = ''

        ## FIRST, GET APPID
        if self.STATE==1:
            if activity.text:
                BotRequestHandler.LUISAPPID=activity.text
            reply = BotRequestHandler.__create_reply_activity(activity, "You entered application ID: %s\nNow, please input your subscription key (default: %s):" % (activity.text,self.LUISAPPKEY))

        ## SECOND, GET APPKEY
        elif self.STATE==2:
            if activity.text:
                BotRequestHandler.LUISAPPKEY=activity.text
            reply = BotRequestHandler.__create_reply_activity(activity, "Great! You entered application key: %s\nNow, enter some text for the LUIS model to render:" % activity.text)

        ## THIRD AND ONWARDS: SEND TEXT TO LUIS AND REPORT LUIS RESPONSE TO THE USER
        else:
            try:
                CLIENT = LUISClient(self.LUISAPPID, self.LUISAPPKEY, True)
                res = CLIENT.predict(activity.text)
                while res.get_dialog() is not None and not res.get_dialog().is_finished():
                    TEXT = input('%s\n'%res.get_dialog().get_prompt())
                    res = CLIENT.reply(TEXT, res)
                LUIStext=self.__handle_LUIS_response(res)
                reply = BotRequestHandler.__create_reply_activity(activity, 'LUIS says: %s' % LUIStext)
            except Exception as exc:
                LUIStext=exc
                print("Error: %s" % exc)
                reply = BotRequestHandler.__create_reply_activity(activity, 'About %s, LUIS complains: %s' % (activity.text,LUIStext))

        connector.conversations.send_to_conversation(reply.conversation.id, reply)
示例#27
0
    def __init__(self, settings: BotFrameworkAdapterSettings):
        """
        Initializes a new instance of the :class:`BotFrameworkAdapter` class.

        :param settings: The settings to initialize the adapter
        :type settings: :class:`BotFrameworkAdapterSettings`
        """
        super(BotFrameworkAdapter, self).__init__()
        self.settings = settings or BotFrameworkAdapterSettings("", "")
        self.settings.channel_service = self.settings.channel_service or os.environ.get(
            AuthenticationConstants.CHANNEL_SERVICE
        )

        self.settings.open_id_metadata = (
            self.settings.open_id_metadata
            or os.environ.get(AuthenticationConstants.BOT_OPEN_ID_METADATA_KEY)
        )
        self._credentials = MicrosoftAppCredentials(
            self.settings.app_id,
            self.settings.app_password,
            self.settings.channel_auth_tenant,
        )
        self._credential_provider = SimpleCredentialProvider(
            self.settings.app_id, self.settings.app_password
        )
        self._is_emulating_oauth_cards = False

        if self.settings.open_id_metadata:
            ChannelValidation.open_id_metadata_endpoint = self.settings.open_id_metadata
            GovernmentChannelValidation.OPEN_ID_METADATA_ENDPOINT = (
                self.settings.open_id_metadata
            )

        if JwtTokenValidation.is_government(self.settings.channel_service):
            self._credentials.oauth_endpoint = (
                GovernmentConstants.TO_CHANNEL_FROM_BOT_LOGIN_URL
            )
            self._credentials.oauth_scope = (
                GovernmentConstants.TO_CHANNEL_FROM_BOT_OAUTH_SCOPE
            )

        self._connector_client_cache: Dict[str, ConnectorClient] = {}
示例#28
0
    def __handle_message_activity(self, activity: Activity):
        self.send_response(200)
        self.end_headers()
        credentials = MicrosoftAppCredentials(APP_ID, APP_PASSWORD)

        connector = ConnectorClient(credentials, base_url=activity.service_url)
        print('User says %s' % activity.text)

        activity.text = filterUserMention(
            activity.text)  # def : group chat fix
        resp_text = chatbot_core.df_query(
            activity.text)  #process query to dialog flow

        if resp_text is None:
            resp_text = 'There is no response from the Bot.'

        reply = ChatbotHandler.__create_reply_activity(activity, resp_text)
        # reply = BotRequestHandler.__create_reply_activity(activity, 'You said: %s' % activity.text)
        connector.conversations.send_to_conversation(reply.conversation.id,
                                                     reply)
        print(activity)
示例#29
0
    async def create(
            self,
            service_url: str,
            audience: str  # pylint: disable=unused-argument
    ) -> ConnectorClient:
        if not self._service_url:
            self._service_url = service_url
        elif service_url != self._service_url:
            raise RuntimeError(
                "This is a streaming scenario, all connectors from this factory must all be for the same url."
            )

        # TODO: investigate if Driver and pipeline should be moved here
        streaming_driver = StreamingHttpDriver(self._request_handler)
        config = BotFrameworkConnectorConfiguration(
            MicrosoftAppCredentials.empty(),
            service_url,
            pipeline_type=AsyncBfPipeline,
            driver=streaming_driver,
        )
        streaming_driver.config = config
        connector_client = ConnectorClient(None, custom_configuration=config)

        return connector_client
示例#30
0
    async def __get_app_credentials(self, app_id: str,
                                    oauth_scope: str) -> AppCredentials:
        if not app_id:
            return MicrosoftAppCredentials.empty()

        # get from the cache if it's there
        cache_key = BotFrameworkAdapter.key_for_app_credentials(
            app_id, oauth_scope)
        app_credentials = self._app_credential_map.get(cache_key)
        if app_credentials:
            return app_credentials

        # If app credentials were provided, use them as they are the preferred choice moving forward
        if self._credentials:
            self._app_credential_map[cache_key] = self._credentials
            return self._credentials

        # Credentials not found in cache, build them
        app_credentials = await self.__build_credentials(app_id, oauth_scope)

        # Cache the credentials for later use
        self._app_credential_map[cache_key] = app_credentials

        return app_credentials