microsoft/teams.net

Public

mirrored fromhttps://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
next/oauth-card-null-ref-bug

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

core/samples/PABot/Dialogs/MainDialog.cs

158lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4using Microsoft.Bot.Builder;
5using Microsoft.Bot.Builder.Dialogs;
6using Microsoft.Bot.Schema;
7using Microsoft.Graph.Models;
8
9namespace PABot.Dialogs
10{
11 /// <summary>
12 /// Main dialog that handles the authentication and user interactions.
13 /// </summary>
14 public class MainDialog : LogoutDialog
15 {
16 protected readonly ILogger _logger;
17
18 /// <summary>
19 /// Initializes a new instance of the <see cref="MainDialog"/> class.
20 /// </summary>
21 /// <param name="configuration">The configuration.</param>
22 /// <param name="logger">The logger.</param>
23 public MainDialog(IConfiguration configuration, ILogger<MainDialog> logger)
24 : base(nameof(MainDialog), configuration["ConnectionName"] ?? "graph")
25 {
26 _logger = logger;
27
28 AddDialog(new OAuthPrompt(
29 nameof(OAuthPrompt),
30 new OAuthPromptSettings
31 {
32 ConnectionName = ConnectionName,
33 Text = "Please Sign In",
34 Title = "Sign In",
35 Timeout = 300000, // User has 5 minutes to login (1000 * 60 * 5)
36 EndOnInvalidMessage = true
37 }));
38
39 AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));
40
41 AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
42 {
43 PromptStepAsync,
44 LoginStepAsync,
45 DisplayTokenPhase1Async,
46 DisplayTokenPhase2Async,
47 }));
48
49 // The initial child Dialog to run.
50 InitialDialogId = nameof(WaterfallDialog);
51 }
52
53 /// <summary>
54 /// Prompts the user to sign in.
55 /// </summary>
56 /// <param name="stepContext">The waterfall step context.</param>
57 /// <param name="cancellationToken">The cancellation token.</param>
58 /// <returns>A task representing the asynchronous operation.</returns>
59 private async Task<DialogTurnResult> PromptStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
60 {
61 _logger.LogInformation("PromptStepAsync() called.");
62 return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), null, cancellationToken);
63 }
64
65 /// <summary>
66 /// Handles the login step.
67 /// </summary>
68 /// <param name="stepContext">The waterfall step context.</param>
69 /// <param name="cancellationToken">The cancellation token.</param>
70 /// <returns>A task representing the asynchronous operation.</returns>
71 private async Task<DialogTurnResult> LoginStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
72 {
73 TokenResponse tokenResponse = (TokenResponse)stepContext.Result;
74 if (tokenResponse?.Token != null)
75 {
76 try
77 {
78 SimpleGraphClient client = new(tokenResponse.Token);
79 User me = await client.GetMeAsync();
80 string title = !string.IsNullOrEmpty(me.JobTitle) ? me.JobTitle : "Unknown";
81
82 await stepContext.Context.SendActivityAsync($"You're logged in as {me.DisplayName} ({me.UserPrincipalName}); your job title is: {title}");
83
84 string photo = await client.GetPhotoAsync();
85
86 if (!string.IsNullOrEmpty(photo))
87 {
88 CardImage cardImage = new(photo);
89 ThumbnailCard card = new(images: new List<CardImage> { cardImage });
90 IMessageActivity reply = MessageFactory.Attachment(card.ToAttachment());
91
92 await stepContext.Context.SendActivityAsync(reply, cancellationToken);
93 }
94 else
95 {
96 await stepContext.Context.SendActivityAsync(MessageFactory.Text("Sorry! User doesn't have a profile picture to display."), cancellationToken);
97 }
98
99 return await stepContext.PromptAsync(
100 nameof(ConfirmPrompt),
101 new PromptOptions { Prompt = MessageFactory.Text("Would you like to view your token?") },
102 cancellationToken);
103 }
104 catch (Exception ex)
105 {
106 _logger.LogError(ex, "Error occurred while processing your request.");
107 }
108 }
109 else
110 {
111 _logger.LogInformation("Response token is null or empty.");
112 }
113
114 await stepContext.Context.SendActivityAsync(MessageFactory.Text("Login was not successful, please try again."), cancellationToken);
115 return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
116 }
117
118 /// <summary>
119 /// Displays the token if the user confirms.
120 /// </summary>
121 /// <param name="stepContext">The waterfall step context.</param>
122 /// <param name="cancellationToken">The cancellation token.</param>
123 /// <returns>A task representing the asynchronous operation.</returns>
124 private async Task<DialogTurnResult> DisplayTokenPhase1Async(WaterfallStepContext stepContext, CancellationToken cancellationToken)
125 {
126 _logger.LogInformation("DisplayTokenPhase1Async() method called.");
127
128 await stepContext.Context.SendActivityAsync(MessageFactory.Text("Thank you."), cancellationToken);
129
130 bool result = (bool)stepContext.Result;
131 if (result)
132 {
133 return await stepContext.BeginDialogAsync(nameof(OAuthPrompt), cancellationToken: cancellationToken);
134 }
135
136 return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
137 }
138
139 /// <summary>
140 /// Displays the token to the user.
141 /// </summary>
142 /// <param name="stepContext">The waterfall step context.</param>
143 /// <param name="cancellationToken">The cancellation token.</param>
144 /// <returns>A task representing the asynchronous operation.</returns>
145 private async Task<DialogTurnResult> DisplayTokenPhase2Async(WaterfallStepContext stepContext, CancellationToken cancellationToken)
146 {
147 _logger.LogInformation("DisplayTokenPhase2Async() method called.");
148
149 TokenResponse tokenResponse = (TokenResponse)stepContext.Result;
150 if (tokenResponse != null)
151 {
152 await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Here is your token: {tokenResponse.Token}"), cancellationToken);
153 }
154
155 return await stepContext.EndDialogAsync(cancellationToken: cancellationToken);
156 }
157 }
158}
159