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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

import aiounittest
from botbuilder.dialogs.prompts import OAuthPromptSettings
from botbuilder.schema import (
    Activity,
    ActivityTypes,
    ChannelAccount,
    ConversationAccount,
    InputHints,
    SignInConstants,
    TokenResponse,
)

from botbuilder.core import CardFactory, ConversationState, MemoryStorage, TurnContext
from botbuilder.core.adapters import TestAdapter
from botbuilder.dialogs import DialogSet, DialogTurnStatus, PromptOptions
from botbuilder.dialogs.prompts import OAuthPrompt


def create_reply(activity):
    return Activity(
        type=ActivityTypes.message,
        from_property=ChannelAccount(
            id=activity.recipient.id, name=activity.recipient.name
        ),
        recipient=ChannelAccount(
            id=activity.from_property.id, name=activity.from_property.name
        ),
        reply_to_id=activity.id,
        service_url=activity.service_url,
        channel_id=activity.channel_id,
        conversation=ConversationAccount(
            is_group=activity.conversation.is_group,
            id=activity.conversation.id,
            name=activity.conversation.name,
        ),
    )


class OAuthPromptTests(aiounittest.AsyncTestCase):
    async def test_should_call_oauth_prompt(self):
        connection_name = "myConnection"
        token = "abc123"

        async def callback_handler(turn_context: TurnContext):
            dialog_context = await dialogs.create_context(turn_context)

            results = await dialog_context.continue_dialog()
            if results.status == DialogTurnStatus.Empty:
                await dialog_context.prompt("prompt", PromptOptions())
            elif results.status == DialogTurnStatus.Complete:
                if results.result.token:
                    await turn_context.send_activity("Logged in.")
                else:
                    await turn_context.send_activity("Failed")

            await convo_state.save_changes(turn_context)

        # Initialize TestAdapter.
        adapter = TestAdapter(callback_handler)

        # Create ConversationState with MemoryStorage and register the state as middleware.
        convo_state = ConversationState(MemoryStorage())

        # Create a DialogState property, DialogSet and AttachmentPrompt.
        dialog_state = convo_state.create_property("dialogState")
        dialogs = DialogSet(dialog_state)
        dialogs.add(
            OAuthPrompt(
                "prompt", OAuthPromptSettings(connection_name, "Login", None, 300000)
            )
        )

        async def inspector(
            activity: Activity, description: str = None
        ):  # pylint: disable=unused-argument
            self.assertTrue(len(activity.attachments) == 1)
            self.assertTrue(
                activity.attachments[0].content_type
                == CardFactory.content_types.oauth_card
            )

            # send a mock EventActivity back to the bot with the token
            adapter.add_user_token(
                connection_name, activity.channel_id, activity.recipient.id, token
            )

            event_activity = create_reply(activity)
            event_activity.type = ActivityTypes.event
            event_activity.from_property, event_activity.recipient = (
                event_activity.recipient,
                event_activity.from_property,
            )
            event_activity.name = "tokens/response"
            event_activity.value = TokenResponse(
                connection_name=connection_name, token=token
            )

            context = TurnContext(adapter, event_activity)
            await callback_handler(context)

        step1 = await adapter.send("Hello")
        step2 = await step1.assert_reply(inspector)
        await step2.assert_reply("Logged in.")

    async def test_should_call_oauth_prompt_with_code(self):
        connection_name = "myConnection"
        token = "abc123"
        magic_code = "888999"

        async def exec_test(turn_context: TurnContext):
            dialog_context = await dialogs.create_context(turn_context)

            results = await dialog_context.continue_dialog()
            if results.status == DialogTurnStatus.Empty:
                await dialog_context.prompt("prompt", PromptOptions())
            elif results.status == DialogTurnStatus.Complete:
                if results.result.token:
                    await turn_context.send_activity("Logged in.")

                else:
                    await turn_context.send_activity("Failed")

            await convo_state.save_changes(turn_context)

        # Initialize TestAdapter.
        adapter = TestAdapter(exec_test)

        # Create ConversationState with MemoryStorage and register the state as middleware.
        convo_state = ConversationState(MemoryStorage())

        # Create a DialogState property, DialogSet and AttachmentPrompt.
        dialog_state = convo_state.create_property("dialog_state")
        dialogs = DialogSet(dialog_state)
        dialogs.add(
            OAuthPrompt(
                "prompt", OAuthPromptSettings(connection_name, "Login", None, 300000)
            )
        )

        def inspector(
            activity: Activity, description: str = None
        ):  # pylint: disable=unused-argument
            assert len(activity.attachments) == 1
            assert (
                activity.attachments[0].content_type
                == CardFactory.content_types.oauth_card
            )

            # send a mock EventActivity back to the bot with the token
            adapter.add_user_token(
                connection_name,
                activity.channel_id,
                activity.recipient.id,
                token,
                magic_code,
            )

        step1 = await adapter.send("Hello")
        step2 = await step1.assert_reply(inspector)
        step3 = await step2.send(magic_code)
        await step3.assert_reply("Logged in.")

    async def test_oauth_prompt_doesnt_detect_code_in_begin_dialog(self):
        connection_name = "myConnection"
        token = "abc123"
        magic_code = "888999"

        async def exec_test(turn_context: TurnContext):
            # Add a magic code to the adapter preemptively so that we can test if the message that triggers
            # BeginDialogAsync uses magic code detection
            adapter.add_user_token(
                connection_name,
                turn_context.activity.channel_id,
                turn_context.activity.from_property.id,
                token,
                magic_code,
            )

            dialog_context = await dialogs.create_context(turn_context)

            results = await dialog_context.continue_dialog()
            if results.status == DialogTurnStatus.Empty:
                # If magicCode is detected when prompting, this will end the dialog and return the token in tokenResult
                token_result = await dialog_context.prompt("prompt", PromptOptions())
                if isinstance(token_result.result, TokenResponse):
                    self.assertTrue(False)  # pylint: disable=redundant-unittest-assert

            await convo_state.save_changes(turn_context)

        # Initialize TestAdapter.
        adapter = TestAdapter(exec_test)

        # Create ConversationState with MemoryStorage and register the state as middleware.
        convo_state = ConversationState(MemoryStorage())

        # Create a DialogState property, DialogSet and AttachmentPrompt.
        dialog_state = convo_state.create_property("dialog_state")
        dialogs = DialogSet(dialog_state)
        dialogs.add(
            OAuthPrompt(
                "prompt", OAuthPromptSettings(connection_name, "Login", None, 300000)
            )
        )

        def inspector(
            activity: Activity, description: str = None
        ):  # pylint: disable=unused-argument
            assert len(activity.attachments) == 1
            assert (
                activity.attachments[0].content_type
                == CardFactory.content_types.oauth_card
            )

        step1 = await adapter.send(magic_code)
        await step1.assert_reply(inspector)

    async def test_should_add_accepting_input_hint_oauth_prompt(self):
        connection_name = "myConnection"
        called = False

        async def callback_handler(turn_context: TurnContext):
            nonlocal called
            dialog_context = await dialogs.create_context(turn_context)

            await dialog_context.continue_dialog()
            await dialog_context.prompt(
                "prompt", PromptOptions(prompt=Activity(), retry_prompt=Activity())
            )

            self.assertTrue(
                dialog_context.active_dialog.state["options"].prompt.input_hint
                == InputHints.accepting_input
            )
            self.assertTrue(
                dialog_context.active_dialog.state["options"].retry_prompt.input_hint
                == InputHints.accepting_input
            )

            await convo_state.save_changes(turn_context)
            called = True

        # Initialize TestAdapter.
        adapter = TestAdapter(callback_handler)

        # Create ConversationState with MemoryStorage and register the state as middleware.
        convo_state = ConversationState(MemoryStorage())

        # Create a DialogState property, DialogSet and AttachmentPrompt.
        dialog_state = convo_state.create_property("dialogState")
        dialogs = DialogSet(dialog_state)
        dialogs.add(
            OAuthPrompt(
                "prompt", OAuthPromptSettings(connection_name, "Login", None, 300000)
            )
        )

        await adapter.send("Hello")
        self.assertTrue(called)

    async def test_should_end_oauth_prompt_on_invalid_message_when_end_on_invalid_message(
        self,
    ):
        connection_name = "myConnection"
        token = "abc123"
        magic_code = "888999"

        async def exec_test(turn_context: TurnContext):
            dialog_context = await dialogs.create_context(turn_context)

            results = await dialog_context.continue_dialog()

            if results.status == DialogTurnStatus.Empty:
                await dialog_context.prompt("prompt", PromptOptions())
            elif results.status == DialogTurnStatus.Complete:
                if results.result and results.result.token:
                    await turn_context.send_activity("Failed")

                else:
                    await turn_context.send_activity("Ended")

            await convo_state.save_changes(turn_context)

        # Initialize TestAdapter.
        adapter = TestAdapter(exec_test)

        # Create ConversationState with MemoryStorage and register the state as middleware.
        convo_state = ConversationState(MemoryStorage())

        # Create a DialogState property, DialogSet and AttachmentPrompt.
        dialog_state = convo_state.create_property("dialog_state")
        dialogs = DialogSet(dialog_state)
        dialogs.add(
            OAuthPrompt(
                "prompt",
                OAuthPromptSettings(connection_name, "Login", None, 300000, None, True),
            )
        )

        def inspector(
            activity: Activity, description: str = None
        ):  # pylint: disable=unused-argument
            assert len(activity.attachments) == 1
            assert (
                activity.attachments[0].content_type
                == CardFactory.content_types.oauth_card
            )

            # send a mock EventActivity back to the bot with the token
            adapter.add_user_token(
                connection_name,
                activity.channel_id,
                activity.recipient.id,
                token,
                magic_code,
            )

        step1 = await adapter.send("Hello")
        step2 = await step1.assert_reply(inspector)
        step3 = await step2.send("test invalid message")
        await step3.assert_reply("Ended")

    async def test_should_timeout_oauth_prompt_with_message_activity(
        self,
    ):
        activity = Activity(type=ActivityTypes.message, text="any")
        await self.run_timeout_test(activity)

    async def test_should_timeout_oauth_prompt_with_token_response_event_activity(
        self,
    ):
        activity = Activity(
            type=ActivityTypes.event, name=SignInConstants.token_response_event_name
        )
        await self.run_timeout_test(activity)

    async def test_should_timeout_oauth_prompt_with_verify_state_operation_activity(
        self,
    ):
        activity = Activity(
            type=ActivityTypes.invoke, name=SignInConstants.verify_state_operation_name
        )
        await self.run_timeout_test(activity)

    async def test_should_not_timeout_oauth_prompt_with_custom_event_activity(
        self,
    ):
        activity = Activity(type=ActivityTypes.event, name="custom event name")
        await self.run_timeout_test(activity, False, "Ended", "Failed")

    async def run_timeout_test(
        self,
        activity: Activity,
        should_succeed: bool = True,
        token_response: str = "Failed",
        no_token_resonse="Ended",
    ):
        connection_name = "myConnection"
        token = "abc123"
        magic_code = "888999"

        async def exec_test(turn_context: TurnContext):
            dialog_context = await dialogs.create_context(turn_context)

            results = await dialog_context.continue_dialog()

            if results.status == DialogTurnStatus.Empty:
                await dialog_context.prompt("prompt", PromptOptions())
            elif results.status == DialogTurnStatus.Complete or (
                results.status == DialogTurnStatus.Waiting and not should_succeed
            ):
                if results.result and results.result.token:
                    await turn_context.send_activity(token_response)

                else:
                    await turn_context.send_activity(no_token_resonse)

            await convo_state.save_changes(turn_context)

        # Initialize TestAdapter.
        adapter = TestAdapter(exec_test)

        # Create ConversationState with MemoryStorage and register the state as middleware.
        convo_state = ConversationState(MemoryStorage())

        # Create a DialogState property, DialogSet and AttachmentPrompt.
        dialog_state = convo_state.create_property("dialog_state")
        dialogs = DialogSet(dialog_state)
        dialogs.add(
            OAuthPrompt(
                "prompt",
                OAuthPromptSettings(connection_name, "Login", None, 1),
            )
        )

        def inspector(
            activity: Activity, description: str = None
        ):  # pylint: disable=unused-argument
            assert len(activity.attachments) == 1
            assert (
                activity.attachments[0].content_type
                == CardFactory.content_types.oauth_card
            )

            # send a mock EventActivity back to the bot with the token
            adapter.add_user_token(
                connection_name,
                activity.channel_id,
                activity.recipient.id,
                token,
                magic_code,
            )

        step1 = await adapter.send("Hello")
        step2 = await step1.assert_reply(inspector)
        step3 = await step2.send(activity)
        await step3.assert_reply(no_token_resonse)