Exemplo n.º 1
0
        public void SigninStateVerificationQueryInitsWithNoArgs()
        {
            var verificationQuery = new SigninStateVerificationQuery();

            Assert.NotNull(verificationQuery);
            Assert.IsType <SigninStateVerificationQuery>(verificationQuery);
        }
        /// <summary>
        /// Handles state verification query for signin auth flow.
        /// </summary>
        /// <param name="activity">Incoming request from Bot Framework.</param>
        /// <param name="connectorClient">Connector client instance for posting to Bot Framework.</param>
        /// <returns>Task tracking operation.</returns>
        private static async Task <HttpResponseMessage> HandleStateVerificationQuery(Activity activity, ConnectorClient connectorClient)
        {
            SigninStateVerificationQuery stateVerifyQuery = activity.GetSigninStateVerificationQueryData();
            var state = stateVerifyQuery.State;

            // Decrypt state string to get code and original userId
            var botSecret      = ConfigurationManager.AppSettings[MicrosoftAppCredentials.MicrosoftAppPasswordKey];
            var decryptedState = CipherHelper.Decrypt(state, botSecret);
            var stateObj       = JsonConvert.DeserializeObject <JObject>(decryptedState);
            var code           = stateObj.GetValue("accessCode").Value <string>();
            var userId         = stateObj.GetValue("userId").Value <string>();

            // Verify userId
            var trustableUserId = activity.From.Id;

            if (userId != trustableUserId)
            {
                // Remove invalid user's cached credential (if any)
                userIdFacebookTokenCache.Remove(userId);

                // Issue a unauthorized message to clients
                Activity replyError = activity.CreateReply();
                replyError.Text = "Unauthorized: User ID verification failed. Please try again.";
                await connectorClient.Conversations.ReplyToActivityWithRetriesAsync(replyError);

                return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }
            else
            {
                // Prepare FB OAuth request
                var fbAppId            = ConfigurationManager.AppSettings["SigninFbClientId"];
                var fbOAuthRedirectUrl = ConfigurationManager.AppSettings["SigninBaseUrl"] + "/auth/callback";
                var fbAppSecret        = ConfigurationManager.AppSettings["SigninFbClientSecret"];
                var fbOAuthTokenUrl    = "/v2.10/oauth/access_token";
                var fbOAuthTokenParams = $"?client_id={fbAppId}&redirect_uri={fbOAuthRedirectUrl}&client_secret={fbAppSecret}&code={code}";

                // Use access code to exchange FB token
                HttpResponseMessage fbResponse = await FBGraphHttpClient.Instance.GetAsync(fbOAuthTokenUrl + fbOAuthTokenParams);

                var tokenObj = await fbResponse.Content.ReadAsAsync <JObject>();

                var token = tokenObj.GetValue("access_token").Value <string>();

                // Update cache
                userIdFacebookTokenCache[userId] = token;

                // Send a thumbnail card with user's FB profile
                var card = await CreateFBProfileCard(token);

                Activity replyActivity = activity.CreateReply();
                replyActivity.Attachments.Add(card);
                await connectorClient.Conversations.ReplyToActivityWithRetriesAsync(replyActivity);

                return(new HttpResponseMessage(HttpStatusCode.OK));
            }
        }
Exemplo n.º 3
0
        public void SigninStateVerificationQueryInits()
        {
            var state = "OK";

            var verificationQuery = new SigninStateVerificationQuery(state);

            Assert.NotNull(verificationQuery);
            Assert.IsType <SigninStateVerificationQuery>(verificationQuery);
            Assert.Equal(state, verificationQuery.State);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Every conversation turn for our Echo Bot will call this method.
        /// There are no dialogs used, since it's "single turn" processing, meaning a single
        /// request and response.
        /// </summary>
        /// <param name="turnContext">A <see cref="ITurnContext"/> containing all the data needed
        /// for processing this conversation turn. </param>
        /// <param name="cancellationToken">(Optional) A <see cref="CancellationToken"/> that can be used by other objects
        /// or threads to receive notice of cancellation.</param>
        /// <returns>A <see cref="Task"/> that represents the work queued to execute.</returns>
        /// <seealso cref="BotStateSet"/>
        /// <seealso cref="ConversationState"/>
        /// <seealso cref="IMiddleware"/>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
        {
            DialogContext dc           = null;
            ITeamsContext teamsContext = turnContext.TurnState.Get <ITeamsContext>();

            var asdd = turnContext.Activity.ChannelData;

            if (teamsContext != null)
            {
                // Now fetch the Team ID, Channel ID, and Tenant ID off of the incoming activity
                var incomingTeamId    = teamsContext.Team.Id;
                var incomingChannelid = teamsContext.Channel.Id;
                var incomingTenantId  = teamsContext.Tenant.Id;

                SigninStateVerificationQuery asd = teamsContext.GetSigninStateVerificationQueryData();

                // Make an operation call to fetch the list of channels in the team, and print count of channels.
                var channels = await teamsContext.Operations.FetchChannelListAsync(incomingTeamId, cancellationToken : cancellationToken);

                await turnContext.SendActivityAsync($"You have {channels.Conversations.Count} channels in this team");

                // Make an operation call to fetch details of the team where the activity was posted, and print it.
                var teamInfo = await teamsContext.Operations.FetchTeamDetailsAsync(incomingTeamId);

                await turnContext.SendActivityAsync($"Name of this team is {teamInfo.Name} and group-id is {teamInfo.AadGroupId}");
            }



            if (turnContext.Activity.Type == ActivityTypes.Message)
            {
                dc = await _dialogs.CreateContextAsync(turnContext, cancellationToken);

                // Get the state properties from the turn context.
                Usuario userProfile =
                    await _accessors.UserProfile.GetAsync(turnContext, () => new Usuario());

                if (userProfile.EsperaRespuestaQNA || turnContext.Activity.Text.ToLower() == "ayuda")
                {
                    var recognizerResult = await botServices.LuisServices["DispatchPepe"].RecognizeAsync(turnContext, cancellationToken);
                    var topIntent        = recognizerResult?.GetTopScoringIntent();
                    await DispatchToTopIntentAsync(turnContext, dc, topIntent, cancellationToken);
                }
                // Continue any current dialog.
                DialogTurnResult dialogTurnResult = await dc.ContinueDialogAsync();



                if (dialogTurnResult.Status == DialogTurnStatus.Empty)
                //if (dialogTurnResult.Result is null)
                {
                    // Get the intent recognition result
                    var recognizerResult = await botServices.LuisServices["DispatchPepe"].RecognizeAsync(turnContext, cancellationToken);
                    var topIntent        = recognizerResult?.GetTopScoringIntent();

                    if (topIntent == null)
                    {
                        await turnContext.SendActivityAsync("Unable to get the top intent.");
                    }
                    else
                    {
                        await DispatchToTopIntentAsync(turnContext, dc, topIntent, cancellationToken);
                    }
                }
                else if (dialogTurnResult.Status == DialogTurnStatus.Complete)
                {
                    await dc.BeginDialogAsync("SendWelcomeMessage", cancellationToken);
                }
                //COMBINAR CON ESTO
                //
                //await ProcessInputAsync(turnContext, cancellationToken);
            }
            else if (turnContext.Activity.Type == ActivityTypes.Invoke || turnContext.Activity.Type == ActivityTypes.Event)
            {
                // This handles the Microsoft Teams Invoke Activity sent when magic code is not used.
                // See: https://docs.microsoft.com/en-us/microsoftteams/platform/concepts/authentication/auth-oauth-card#getting-started-with-oauthcard-in-teams
                // Manifest Schema Here: https://docs.microsoft.com/en-us/microsoftteams/platform/resources/schema/manifest-schema
                // It also handles the Event Activity sent from The Emulator when the magic code is not used.
                // See: https://blog.botframework.com/2018/08/28/testing-authentication-to-your-bot-using-the-bot-framework-emulator/

                // Sanity check the activity type and channel Id.
                if (turnContext.Activity.Type == ActivityTypes.Invoke && turnContext.Activity.ChannelId != "msteams")
                {
                    throw new InvalidOperationException("The Invoke type is only valid onthe MSTeams channel.");
                }

                dc = await _dialogs.CreateContextAsync(turnContext, cancellationToken);

                await dc.ContinueDialogAsync(cancellationToken);

                if (!turnContext.Responded)
                {
                    await dc.BeginDialogAsync(OutlookDialogID);
                }
            }
            else if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate)
            {
                // Send a welcome message to the user and tell them what actions they may perform to use this bot
                if (turnContext.Activity.MembersAdded != null)
                {
                    dc = await _dialogs.CreateContextAsync(turnContext, cancellationToken);

                    //await dc.BeginDialogAsync("SendWelcomeMessageAsync");
                    var reply = turnContext.Activity.CreateReply();
                    reply.Type = ActivityTypes.Typing;
                    await dc.Context.SendActivityAsync(reply);

                    if (turnContext.Activity.MembersAdded != null)
                    {
                        foreach (var member in turnContext.Activity.MembersAdded)
                        {
                            if (member.Id != turnContext.Activity.Recipient.Id)
                            {
                                this.nuevaConversacion = true;
                                //await SendWelcomeMessageAsync(turnContext, cancellationToken, true);
                                await dc.BeginDialogAsync("SendWelcomeMessage");
                            }
                        }
                    }
                }
            }
            else if (turnContext.Activity.Type == ActivityTypes.DeleteUserData)
            {
                string idChannel   = turnContext.Activity.ChannelId;
                string idChannelx  = turnContext.Activity.Conversation.AadObjectId;
                string idChannelxd = turnContext.Activity.MembersAdded.First().Id;
                await _accessors.UserState.DeleteAsync(turnContext, cancellationToken);

                await _accessors.ConversationState.DeleteAsync(turnContext, cancellationToken);

                //context.Reset();
                //context.ConversationData.Clear();
                //context.UserData.Clear();
                //context.PrivateConversationData.Clear();
                //await context.FlushAsync(CancellationToken.None);
            }
            else if (turnContext.Activity.Type == ActivityTypes.Typing)
            {
            }
            else if (turnContext.Activity.Type == ActivityTypes.Handoff)
            {
            }
            else if (turnContext.Activity.Type == ActivityTypes.Trace)
            {
            }
            else if (turnContext.Activity.Type == ActivityTypes.Suggestion)
            {
            }

            //else if (turnContext.Activity.Type == ActivityTypes.)
            //{

            //}
            // Save the new turn count into the conversation state.
            await _accessors.UserState.SaveChangesAsync(turnContext, false, cancellationToken);

            await _accessors.ConversationState.SaveChangesAsync(turnContext, false, cancellationToken);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Handles the signin state verification action asynchronously.
 /// </summary>
 /// <param name="turnContext">The turn context.</param>
 /// <param name="query">The signin state verification action.</param>
 /// <returns>Task tracking operation.</returns>
 public virtual Task <InvokeResponse> HandleSigninStateVerificationActionAsync(ITurnContext turnContext, SigninStateVerificationQuery query)
 {
     return(Task.FromResult <InvokeResponse>(null));
 }
Exemplo n.º 6
0
        public async Task <InvokeResponse> HandleSigninVerifyStateAsync(ITurnContext <IInvokeActivity> turnContext, SigninStateVerificationQuery query, CancellationToken cancellationToken)
        {
            var connectionName = _appSettings.OAuthConnectionName;
            var token          = await((IUserTokenProvider)turnContext.Adapter).GetUserTokenAsync(
                turnContext,
                connectionName,
                query.State,
                cancellationToken);

            if (token != null && !string.IsNullOrEmpty(token.Token))
            {
                await turnContext.SendActivityAsync("You have signed in successfully. Please type command one more time.", cancellationToken : cancellationToken);
            }

            return(new InvokeResponse {
                Status = (int)HttpStatusCode.OK
            });
        }
Exemplo n.º 7
0
 protected override Task <InvokeResponse> OnSigninVerifyStateAsync(ITurnContext <IInvokeActivity> turnContext, SigninStateVerificationQuery query, CancellationToken cancellationToken)
 => _invokeActivityHandler.HandleSigninVerifyStateAsync(turnContext, query, cancellationToken);
 protected virtual Task <InvokeResponse> OnSigninVerifyStateAsync(ITurnContext <IInvokeActivity> turnContext, SigninStateVerificationQuery query, CancellationToken cancellationToken)
 {
     return(Task.FromResult <InvokeResponse>(null));
 }