Beispiel #1
0
        public async virtual Task MessageReceivedAsync(IDialogContext context, IAwaitable <IMessageActivity> argument)
        {
            var msg = await(argument);
            ConversationReference conversationReference;
            VSTSAcessToken        facebookToken = new VSTSAcessToken();
            string magicNumber = string.Empty;
            string token       = string.Empty;

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

                if (string.Equals(msg.Text, magicNumber))
                {
                    conversationReference.User.Properties["IsValidated"] = true;

                    context.UserData.SetValue("persistedCookieVSTS", conversationReference);

                    token = conversationReference.User.Properties["AccessToken"].ToString();

                    // Dialog is resumed by the OAuth callback and access token
                    // is encoded in the message.Text
                    var valid = Convert.ToBoolean(conversationReference.User.Properties["IsValidated"]);

                    if (valid)
                    {
                        var name = conversationReference.User.Properties["UserName"].ToString();
                        context.UserData.SetValue("name", name);
                        await context.PostAsync(Strings.VSTSLoginSuccessPrompt);

                        await context.PostAsync(Strings.VSTSlogoutPrompt);

                        context.UserData.SetValue(VSTSAuthTokenKey, token);
                        context.Done(token);
                    }
                }
                else
                {
                    //When entered number is not valid
                    await context.PostAsync(Strings.AuthMagicNumberNotMacthed);
                    await LogIn(context);
                }
            }
            else
            {
                await LogIn(context);
            }
        }
        /// <summary>
        /// Execute the VSTS Api call
        /// </summary>
        /// <param name="postData"></param>
        /// <param name="IsCallback"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static String PerformTokenRequest(String postData, bool IsCallback, out VSTSAcessToken token)
        {
            var error           = String.Empty;
            var strResponseData = String.Empty;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(
                ConfigurationManager.AppSettings["TokenUrl"]
                );

            webRequest.Method        = "POST";
            webRequest.ContentLength = postData.Length;
            webRequest.ContentType   = "application/x-www-form-urlencoded";

            using (StreamWriter swRequestWriter = new StreamWriter(webRequest.GetRequestStream()))
            {
                swRequestWriter.Write(postData);
            }

            try
            {
                HttpWebResponse hwrWebResponse = (HttpWebResponse)webRequest.GetResponse();

                if (hwrWebResponse.StatusCode == HttpStatusCode.OK)
                {
                    using (StreamReader srResponseReader = new StreamReader(hwrWebResponse.GetResponseStream()))
                    {
                        strResponseData = srResponseReader.ReadToEnd();
                    }

                    token = JsonConvert.DeserializeObject <VSTSAcessToken>(strResponseData);
                    return(null);
                }
            }
            catch (WebException wex)
            {
                error = Strings.VSTSApiRequestError + wex.Message;
            }
            catch (Exception ex)
            {
                error = Strings.VSTSApiIssue + ex.Message;
            }

            token = new VSTSAcessToken();
            return(error);
        }
        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)));
                }
            }
        }
Beispiel #4
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);
            }
        }