コード例 #1
0
        /// <summary>
        /// Login the user.
        /// </summary>
        /// <param name="context"> The Dialog context.</param>
        /// <returns> A task that represents the login action.</returns>
        private async Task LogIn(IDialogContext context, string workItemId)
        {
            string token;

            if (!context.UserData.TryGetValue(VSTSAuthTokenKey, out token))
            {
                var conversationReference = context.Activity.ToConversationReference();

                context.UserData.SetValue("persistedCookieVSTS", conversationReference);
                conversationReference.User.Properties.Add("workItemId", workItemId);

                // sending the sigin card with Facebook login url
                var reply        = context.MakeMessage();
                var vstsLoginUrl = VSTSHelpers.GenerateAuthorizeUrl(conversationReference);

                reply.Text = Strings.VSTSGetWorkItemLoginPrompt;

                //Login Card

                var loginCard = new HeroCard
                {
                    Title   = Strings.VSTSLoginCardTitle,
                    Buttons = new List <CardAction> {
                        new CardAction(ActionTypes.OpenUrl, Strings.VSTSLoginCardButtonCaption, value: vstsLoginUrl)
                    }
                };

                reply.Attachments.Add(loginCard.ToAttachment());

                await context.PostAsync(reply);

                context.Wait(MessageReceivedAsync);
            }
            else
            {
                await context.PostAsync(Strings.VSTSLoginSessionExistsPrompt);

                await context.PostAsync(Strings.VSTSlogoutPrompt);

                context.Done(token);
            }
        }
コード例 #2
0
        public async Task <HttpResponseMessage> OAuthCallbackVSTS(string code, string state, CancellationToken token)
        {
            ConversationReference conversationReferenceJSON = JsonConvert.DeserializeObject <ConversationReference>(state);

            //// Get the resumption cookie
            var address = new Address
                          (
                botId: conversationReferenceJSON.Bot.Id,
                channelId: conversationReferenceJSON.ChannelId,
                userId: conversationReferenceJSON.User.Id,
                conversationId: conversationReferenceJSON.Conversation.Id,
                serviceUrl: conversationReferenceJSON.ServiceUrl
                          );

            var conversationReference = address.ToConversationReference();

            string workItemId = string.Empty;

            if (conversationReferenceJSON.User.Properties["workItemId"] != null)
            {
                workItemId = conversationReferenceJSON.User.Properties["workItemId"].ToString();
                conversationReference.User.Properties.Add("workItemId", workItemId);
            }

            VSTSAcessToken accessToken = new VSTSAcessToken();
            String         error       = null;

            if (!String.IsNullOrEmpty(code))
            {
                error = VSTSHelpers.PerformTokenRequest(VSTSHelpers.GenerateRequestPostData(code), true, out accessToken);

                //Set the User Token, Magic Number and IsValidated Property to User Properties.
                if (String.IsNullOrEmpty(error))
                {
                    conversationReference.User.Properties.Add("AccessToken", accessToken.accessToken);
                    conversationReference.User.Properties.Add("RefreshToken", accessToken.refreshToken);
                    conversationReference.User.Properties.Add("MagicNumber", ConfigurationManager.AppSettings["VSTSMagicNumber"].ToString());
                    conversationReference.User.Properties.Add("IsValidated", false);
                    conversationReference.User.Properties.Add("UserName", conversationReferenceJSON.User.Name);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, new InvalidOperationException(Strings.VSTSCallbackAuthError)));
            }

            // Create the message that is send to conversation to resume the login flow
            var msg = conversationReference.GetPostToBotMessage();

            msg.Text = $"token:{accessToken.accessToken}";

            // Resume the conversation to SimpleFacebookAuthDialog
            using (var scope1 = DialogModule.BeginLifetimeScope(Conversation.Container, msg))
            {
                var dataBag = scope1.Resolve <IBotData>();
                await dataBag.LoadAsync(token);

                ConversationReference pending;
                var connector = new ConnectorClient(new Uri(conversationReference.ServiceUrl));

                if (dataBag.UserData.TryGetValue("persistedCookieVSTS", out pending))
                {
                    dataBag.UserData.SetValue("persistedCookieVSTS", conversationReference);

                    await dataBag.FlushAsync(token);

                    //Send message to Bot
                    IMessageActivity message = Activity.CreateMessageActivity();
                    message.From         = conversationReference.User;
                    message.Recipient    = conversationReference.User;
                    message.Conversation = new ConversationAccount(id: conversationReference.Conversation.Id);
                    message.Text         = Strings.OAuthCallbackUserPrompt;
                    await connector.Conversations.SendToConversationAsync((Activity)message);

                    return(Request.CreateResponse(Strings.OAuthCallbackMessage));
                }
                else
                {
                    // Callback is called with no pending message as a result the login flow cannot be resumed.
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, new InvalidOperationException(Strings.AuthCallbackResumeError)));
                }
            }
        }
コード例 #3
0
        public async virtual Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var msg = await(argument);

            ConversationReference conversationReference;
            VSTSAcessToken        vstsToken = new VSTSAcessToken();
            string magicNumber         = string.Empty;
            string token               = string.Empty;
            string refreshToken        = string.Empty;
            String error               = null;
            string requestedWorkItemId = string.Empty;
            bool   IsAuthenticated     = false;

            if (context.UserData.TryGetValue("persistedCookieVSTS", out conversationReference))
            {
                requestedWorkItemId = conversationReference.User.Properties["workItemId"].ToString();

                if (string.IsNullOrEmpty(requestedWorkItemId))
                {
                    requestedWorkItemId = msg.Text;
                    IsAuthenticated     = true;
                }
                else
                {
                    magicNumber = conversationReference.User.Properties["MagicNumber"].ToString();

                    if (string.Equals(msg.Text, magicNumber))
                    {
                        IsAuthenticated = true;
                    }
                    else
                    {
                        //When entered number is not valid
                        await context.PostAsync(Strings.AuthMagicNumberNotMacthed);
                        await LogIn(context, msg.Text);
                    }
                }

                if (IsAuthenticated)
                {
                    refreshToken = conversationReference.User.Properties["RefreshToken"].ToString();

                    //Get the refreshed token
                    error = VSTSHelpers.PerformTokenRequest(VSTSHelpers.GenerateRefreshPostData(refreshToken), true, out vstsToken);

                    if (String.IsNullOrEmpty(error))
                    {
                        conversationReference.User.Properties["AccessToken"]  = vstsToken.accessToken;
                        conversationReference.User.Properties["RefreshToken"] = vstsToken.refreshToken;
                    }

                    WorkItemEx workItem = await VSTSHelpers.GetWorkItem(vstsToken.accessToken, requestedWorkItemId);

                    if (workItem != null)
                    {
                        var workItemCardMessage = CreateWorkItemCard(context, workItem, requestedWorkItemId);
                        await context.PostAsync(workItemCardMessage);
                    }
                }
            }
            else
            {
                await LogIn(context, msg.Text);
            }
        }