Esempio n. 1
0
        public async Task <IActionResult> GetImageFile([FromQuery] int?width = null, [FromQuery] int?height = null)
        {
            CleanUpSessionRepository();

            if (width.HasValue)
            {
                _generator.ImageWidth = width.Value;
            }
            if (height.HasValue)
            {
                _generator.ImageHeight = height.Value;
            }

            CaptchaResult captchaResult = await _generator.GetCaptchaResult().ConfigureAwait(false);

            _repository.Add(new SimpleCaptchaResult
            {
                Id         = captchaResult.Id,
                Text       = captchaResult.Text,
                CreateDate = DateTime.Now
            });
            using (MemoryStream stream = new MemoryStream())
            {
                captchaResult.Image.Save(stream, ImageFormat.Png);
                return(File(stream.ToArray(), "image/png", captchaResult.Id.ToString()));
            }
        }
        public CaptchaResult GetCaptcha(int width, int height)
        {
            Guid   captchaToken;
            string captchaAnswer;
            string requestorIpAddress = String.Empty;

            if (HttpContext.Current != null)
            {
                requestorIpAddress = HttpContext.Current.Request.UserHostAddress;
            }

            DataAccess.Captcha.GetNewCaptchaAnswer(requestorIpAddress, out captchaToken, out captchaAnswer);

            Common.Utility.CaptchaImage captchaImage = new Common.Utility.CaptchaImage(captchaAnswer, width, height);

            MemoryStream memoryStream = new MemoryStream();

            captchaImage.Image.Save(memoryStream, ImageFormat.Jpeg);

            CaptchaResult returnValue = new CaptchaResult()
            {
                CaptchaImage = memoryStream.GetBuffer(),
                CaptchaToken = captchaToken
            };

            return(returnValue);
        }
Esempio n. 3
0
        public bool IsValidCaptcha()
        {
            //More on how this works at: https://theprogressiveviews.blogspot.com/2016/08/google-recaptcha-with-server-side.html

            string responce  = Request["g-recaptcha-response"];
            string secretKey = "6LcumlMUAAAAAOMAUWGdHMX972thSUuSkQe61tc0";
            var    request   = (HttpWebRequest)WebRequest.Create("https://www.google.com/recaptcha/api/siteverify?secret=+" + secretKey + "&response=" + responce);

            using (WebResponse wResponse = request.GetResponse())
            {
                using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream()))
                {
                    string jsonResponse     = readStream.ReadToEnd();
                    JavaScriptSerializer js = new JavaScriptSerializer();

                    CaptchaResult data = js.Deserialize <CaptchaResult>(jsonResponse);

                    if (Convert.ToBoolean(data.success))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
Esempio n. 4
0
        public async Task <bool> Verify(string secret, string token, string remoteIp)
        {
            HttpClient client = _clientFactory.CreateClient("hCaptcha");

            // Create post data
            List <KeyValuePair <string, string> > postData = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("secret", secret),
                new KeyValuePair <string, string>("response", token),
                new KeyValuePair <string, string>("remoteip", remoteIp)
            };

            // Request api
            HttpResponseMessage response = await client.PostAsync("/siteverify", new FormUrlEncodedContent(postData));

            response.EnsureSuccessStatusCode();

            Stream contentStream = await response.Content.ReadAsStreamAsync();

            try
            {
                CaptchaResult result = await JsonSerializer.DeserializeAsync <CaptchaResult>(contentStream, new JsonSerializerOptions { IgnoreNullValues = true, PropertyNameCaseInsensitive = true });

                return(result.Success);
            }
            catch (JsonException)
            {
                Console.WriteLine("Invalid JSON.");
            }

            return(false);
        }
Esempio n. 5
0
        public Boolean ReCaptcha(string captcha)
        {
            const string secret = "6LcbnlsbAAAAAGVC-me0TRpGpyYcb393Zw08DCsP";

            var restUrl = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, captcha);

            WebRequest      req  = WebRequest.Create(restUrl);
            HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

            JsonSerializer serializer = new JsonSerializer();

            CaptchaResult result = null;

            using (var reader = new StreamReader(resp.GetResponseStream()))
            {
                string resultObject = reader.ReadToEnd();
                result = JsonConvert.DeserializeObject <CaptchaResult>(resultObject);
            }
            if (result.Success)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public async Task <CaptchaResult> GenerateCaptchaAsync()
        {
            string captchaCode = await _captchaGenerator.GenerateCaptchaCodeAsync();

            CaptchaResult result = new CaptchaResult
            {
                CaptchaCode = captchaCode,
                Timestamp   = DateTime.UtcNow
            };

            string emailTo = await _emailReceiverSelector.SelectAsync();

            if (string.IsNullOrEmpty(emailTo))
            {
                result.Failed = true;
                return(result);
            }

            string subject = await _emailBodyGenerator.GenerateSubjectAsync(result);

            string body = await _emailBodyGenerator.GenerateBodyAsync(result);

            await _emailSender.SendAsync(emailTo, subject, body);

            await _captchaCodeStorage.SaveAsync(captchaCode);

            return(result);
        }
        public static bool IsValidCaptcha(string resp)
        {
            try
            {
                //6LdfpOUUAAAAACyQSQx1wiu4ajqCSrMMUUPTZQB_
                string acceeskey = ConfigurationManager.AppSettings["captchaserverkey"].ToString();
                var    req       = (HttpWebRequest)WebRequest.Create
                                       ("https://www.google.com/recaptcha/api/siteverify?secret=" + acceeskey + "&response=" + resp + "");
                //Google recaptcha Response
                using (WebResponse wResponse = req.GetResponse())
                {
                    using (StreamReader readStream = new StreamReader(wResponse.GetResponseStream()))
                    {
                        string jsonResponse     = readStream.ReadToEnd();
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        // Deserialize Json
                        CaptchaResult data = js.Deserialize <CaptchaResult>(jsonResponse);
                        if (Convert.ToBoolean(data.success))
                        {
                            return(true);
                        }
                        else
                        {
                            throw new Exception("Invalid Captcha Try Again..");
                        }
                    }
                }
            }

            catch (Exception e)
            {
                throw new Exception("Invalid Captcha Try Again..");
            }
        }
Esempio n. 8
0
        public async Task <CaptchaResult> GenerateCaptchaAsync()
        {
            string captchaCode = await _captchaCodeGenerator.GenerateCaptchaCodeAsync();

            await _captchaCodeStorage.SaveAsync(captchaCode);

            CaptchaResult result = new CaptchaResult
            {
                CaptchaCode = captchaCode,
                Timestamp   = DateTime.UtcNow
            };

            string phoneNumber = await _smsReceiverSelector.SelectAsync();

            string content = await _smsContentGenerator.GenerateAsync(result);

            if (string.IsNullOrEmpty(phoneNumber) || string.IsNullOrEmpty(content))
            {
                result.Failed = true;
                return(result);
            }
            await _smsSender.SendAsync(phoneNumber, content);

            return(result);
        }
Esempio n. 9
0
        //[NoBrowserCache]
        //[OutputCache(Location = OutputCacheLocation.None, NoStore = true, Duration = 0, VaryByParam = "None")]
        public async Task <ClientCaptchaResult> GetImage([FromQuery] int?width = null, [FromQuery] int?height = null)
        {
            CleanUpSessionRepository();

            if (width.HasValue)
            {
                _generator.ImageWidth = width.Value;
            }
            if (height.HasValue)
            {
                _generator.ImageHeight = height.Value;
            }

            CaptchaResult captchaResult = await _generator.GetCaptchaResult().ConfigureAwait(false);

            MemoryStream stream = new MemoryStream();

            captchaResult.Image.Save(stream, ImageFormat.Png);

            ClientCaptchaResult clientCaptchaResults =
                new ClientCaptchaResult
            {
                Id          = captchaResult.Id,
                ImageBase64 = Convert.ToBase64String(stream.ToArray())
            };

            _repository.Add(new SimpleCaptchaResult
            {
                Id         = captchaResult.Id,
                Text       = captchaResult.Text,
                CreateDate = DateTime.Now
            });

            return(clientCaptchaResults);
        }
Esempio n. 10
0
        public ActionResult Index(Admin admin)
        {
            string password     = admin.AdminPassword.Trim();
            string hashPassword = new CryptoHelper().ComputeSha256Hash(password);

            string key = "AAAAAAAAAAAA111111111111AAAAAAAAAAAA111111111111";
            string iv  = "AAAAAAAA11111111";

            string mail        = admin.AdminUserName.Trim();
            string cryptedMail = new CryptoHelper().Encrypt(mail, key, iv);

            var adminUser = adminManager.GetList().FirstOrDefault(x => x.AdminUserName == cryptedMail && x.AdminPassword == hashPassword);

            if (adminUser != null)
            {
                FormsAuthentication.SetAuthCookie(adminUser.AdminUserName, false);
                Session["AdminUserName"] = adminUser.AdminUserName;

                var captcha = Request.Form["g-recaptcha-response"];

                const string secret = "6LdmkncbAAAAAAJ3JiXuJQLAg9G-3quKomE2O6xo";


                var restUrl = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, captcha);

                WebRequest      req  = WebRequest.Create(restUrl);
                HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

                JsonSerializer serializer = new JsonSerializer();

                CaptchaResult result = null;

                using (var reader = new StreamReader(resp.GetResponseStream()))
                {
                    string resultObject = reader.ReadToEnd();
                    result = JsonConvert.DeserializeObject <CaptchaResult>(resultObject);
                }

                if (!result.Success)
                {
                    ModelState.AddModelError("", "captcha mesajınız hatalı");
                    if (result.ErrorCodes != null)
                    {
                        ModelState.AddModelError("", result.ErrorCodes[0]);
                    }
                }
                else
                {
                    ViewBag.MessageRobot = "Kayıt Başarılı.";
                    return(RedirectToAction("Index", "AdminCategory"));
                }

                return(RedirectToAction("Index"));
            }
            else
            {
                return(RedirectToAction("Index"));
            }
        }
Esempio n. 11
0
        public IActionResult GetCaptchaImage()
        {
            string        sCaptchaCode = CaptchaHelper.GenerateCaptchaCode();
            CaptchaResult result       = CaptchaHelper.GetImage(116, 36, sCaptchaCode);

            HttpContext.Session.SetString(CaptchaCodeSessionName, sCaptchaCode);
            return(new FileStreamResult(new MemoryStream(result.CaptchaByteData), "image/png"));
        }
Esempio n. 12
0
        public FileStreamResult Image()
        {
            CaptchaResult result = CaptchaImageGenerator.GetImage(200, 100, "HELLO");

            Stream s = new MemoryStream(result.CaptchaByteData);

            return(new FileStreamResult(s, "image/png"));
        }
            public CaptchaResult FetchCaptchaResult(string jsBody)
            {
                Task.Run(() =>
                {
                    _captchaResult = _captcha.SolveTextCaptcha(jsBody).Result;
                });

                return(_captchaResult);
            }
        private async Task <DialogTurnResult> confirmStep(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var    _activitySessionId = stepContext.Context.Activity.From.Id;
            var    userCaptcha        = stepContext.Context.Activity.Text;
            object stata = stepContext.ActiveDialog.State["stepIndex"];

            if (userCaptcha == captcha)
            {
                return(await stepContext.NextAsync(userCaptcha, cancellationToken));
            }
            else
            {
                var promptOptions = new PromptOptions
                {
                    Prompt = MessageFactory.Text("That's not right captcha"),
                };

                //await stepContext.PromptAsync(nameof(TextPrompt), promptOptions, cancellationToken);

                await stepContext.Context.SendActivityAsync(MessageFactory.Text("That's not right captcha"), cancellationToken);

                CaptchaResult result = new CaptchaResult();

                result = await APIRequest.GetCaptcha();

                captcha = result.CaptchaCode;
                string card             = "\\Cards\\artCaptcha.json";
                var    adaptiveCardJson = File.ReadAllText(Environment.CurrentDirectory + card);
                adaptiveCardJson = adaptiveCardJson.Replace("{str}", result.CaptchBase64Data);
                JObject json1 = JObject.Parse(adaptiveCardJson);
                var     adaptiveCardAttachment = new Attachment()
                {
                    ContentType = "application/vnd.microsoft.card.adaptive",
                    Content     = JsonConvert.DeserializeObject(json1.ToString()),
                };
                var cardResponse = MessageFactory.Attachment(adaptiveCardAttachment);
                await stepContext.Context.SendActivityAsync(cardResponse, cancellationToken);

                object stata1 = stepContext.ActiveDialog.State["stepIndex"];

                return(await stepContext.NextAsync(null, cancellationToken));

                //string card = "\\Cards\\artCaptcha.json";
                //var adaptiveCardJson = File.ReadAllText(Environment.CurrentDirectory + card);
                //adaptiveCardJson = adaptiveCardJson.Replace("{str}", result.CaptchBase64Data);
                //var adaptiveCardAttachment = new Attachment()
                //{
                //    ContentType = "application/vnd.microsoft.card.adaptive",
                //    Content = JsonConvert.DeserializeObject(adaptiveCardJson.ToString()),
                //};
                //if (!string.IsNullOrWhiteSpace(card))
                //{
                //    return await stepContext.PromptAsync(nameof(TextPrompt), new PromptOptions { Prompt = (Activity)MessageFactory.Attachment(adaptiveCardAttachment) }, cancellationToken);
                //}
                //return await stepContext.NextAsync(captcha, cancellationToken);
            }
        }
        public CaptchaResult FetchCaptchaResult(string jsTextarea)
        {
            Task.Run(() =>
            {
                _captchaResult = _captcha.SolveNormalCaptcha(jsTextarea).Result;
            });

            return(_captchaResult);
        }
Esempio n. 16
0
        public IActionResult GetCaptchaImage()
        {
            int           width       = 100;
            int           height      = 36;
            string        captchaCode = Captcha.GenerateCaptchaCode();
            CaptchaResult result      = Captcha.GenerateCaptchaImage(width, height, captchaCode);

            return(Json(new { Code = result.CaptchaCode, Data = result.CaptchBase64Data }));
        }
        public CaptchaResult GetCaptchaImage()
        {
            //int width = 100;
            //int height = 36;
            int           width       = 140;
            int           height      = 36;
            var           captchaCode = CustomCaptcha.GenerateCaptchaCode();
            CaptchaResult result      = CustomCaptcha.GenerateCaptchaImage(width, height, captchaCode);

            //HttpContext.Session.SetString("CaptchaCode", result.CaptchaCode);
            //Stream s = new MemoryStream(result.CaptchaByteData);
            //return new FileStreamResult(s, "image/png");
            return(result);
        }
Esempio n. 18
0
 private string SaveAsFile(CaptchaResult result)
 {
     using (Stream s = new MemoryStream(result.CaptchaByteData))
     {
         byte[] srcBuf = new Byte[s.Length];
         s.Read(srcBuf, 0, srcBuf.Length);
         s.Seek(0, SeekOrigin.Begin);
         using (FileStream fs = new FileStream($"d:/{result.CaptchaCode}.png", FileMode.Create, FileAccess.Write))
         {
             fs.Write(srcBuf, 0, srcBuf.Length);
             fs.Close();
         }
         return($"d:/{result.CaptchaCode}.png");
     }
 }
Esempio n. 19
0
        /// <summary>
        /// 验证输入的验证码是否和session中的一致
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JsonResult Validate(CaptchaResult request)
        {
            if (ModelState.IsValid)
            {
                // Validate Captcha Code
                if (!Captcha.ValidateCaptchaCode(request.CaptchaCode, HttpContext))
                {
                    // return error
                }

                // continue business logic
            }

            return(null);
        }
        public Task <string> GenerateBodyAsync(CaptchaResult captcha)
        {
            var body = new StringBuilder(300);

            body.Append("<!DOCTYPE html>");
            body.Append("<html><head>");
            body.Append(@"<meta http-equiv='Content-Type' content='text/html;charset = UTF-8'>");
            body.Append("<title>NCaptcha Code Email</title>");
            body.Append("</head>");
            body.Append("<body style='background:#fff;'>");
            body.Append("<h1>");
            body.Append("NCaptcha Code Email");
            body.Append("</h1>");
            body.Append($"<p>Your captcha Code is: <code>{captcha.CaptchaCode}</code></p>");
            body.Append("</body></html>");

            return(Task.FromResult(body.ToString()));
        }
Esempio n. 21
0
        public ActionResult Create([Bind(Include = "Id,Name,FirstName,Email,Message,Date")] ContactDM contactDM)
        {
            var captcha = Request.Form["g-recaptcha-response"]; const string secret = "6Lei-9sUAAAAAJmy7TqUVDe4hf0JvF6yYRn0dBrg";

            var restUrl = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, captcha);

            WebRequest      req  = WebRequest.Create(restUrl);
            HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

            JsonSerializer serializer = new JsonSerializer();

            CaptchaResult result = null;

            using (var reader = new StreamReader(resp.GetResponseStream()))
            {
                string resultObject = reader.ReadToEnd();
                result = JsonConvert.DeserializeObject <CaptchaResult>(resultObject);
            }
            if (!result.Success)
            {
                ModelState.AddModelError("", "captcha messagge error");
                if (result.ErrorCodes != null)
                {
                    ModelState.AddModelError("", result.ErrorCodes[0]);
                }
            }
            else
            {
                if (ModelState.IsValid)
                {
                    contactDM.Date = DateTime.Now;
                    db.Contacts.Add(contactDM);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }

            return(View(contactDM));
        }
Esempio n. 22
0
        public FileContentResult Captcha()
        {
            CaptchaOptions options = new CaptchaOptions
            {
                GaussianDeviation = 0.4,
                Height            = 35,
                Background        = NoiseLevel.Low,
                Line = NoiseLevel.Low
            };

            using (ICapatcha capatch = new FluentCaptcha())
            {
                capatch.Options = options;
                CaptchaResult captchaResult = capatch.DrawBackgroud().DrawLine().DrawText().Atomized().DrawBroder().DrawImage();
                using (captchaResult)
                {
                    MemoryStream ms = new MemoryStream();
                    captchaResult.Bitmap.Save(ms, ImageFormat.Gif);
                    Session["Captcha"] = captchaResult.Text;
                    return(File(ms.ToArray(), "image/gif"));
                }
            }
        }
Esempio n. 23
0
        /// <summary>
        /// 使用指定账号登录微博
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="proxy">设置代理(可选)</param>
        /// <returns>WebAccessBase:</returns>
        public void WeiboLogin(string userName, string password, string proxy = null)
        {
            try
            {
                UserName = userName;
                Password = password;
                Error    = "";
                if (!string.IsNullOrEmpty(proxy))
                {
                    Web.SetProxy(proxy, "", "");
                }

                Web.Encode = Encoding.GetEncoding("gb2312");
                //todo m.weibo.cn
                Web.Reffer = null;
                Web.GetHTML("http://m.weibo.cn");

                const string loginUrl = "https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F";

                Web.GetHTML(loginUrl);

                //编码用户名 @替换为%40 进行Base64编码
                string su    = userName.Replace("@", "%40");
                Byte[] bufin = Encoding.UTF8.GetBytes(su);
                su = Convert.ToBase64String(bufin, 0, bufin.Length);
                var callbackStr  = string.Format("jsonpcallback{0}", CommonExtension.GetTime());
                var perLoginUrl  = string.Format("https://login.sina.com.cn/sso/prelogin.php?checkpin=1&entry=mweibo&su={0}&callback={1}", su, callbackStr);
                var perLoginHtml = Web.GetHTML(perLoginUrl);
                if (string.IsNullOrEmpty(perLoginHtml))
                {
                    Error  = string.Format("账号:{0}密码{1}访问预处理页面失败", userName, password);
                    Result = "登录失败";
                    CNWeiboLoginLogger.Info(Error);
                    return;
                }

                CaptchaResult captchaResult = null;
                string        pcid          = "";
                string        door          = "";
                string        showpin       = "0";
                #region 打码
                if (perLoginHtml.Contains("\"showpin\":1"))
                {
                    showpin = "1";
                    var imageHtml = Web.GetHTML("https://passport.weibo.cn/captcha/image");
                    try
                    {
                        dynamic postResult = DynamicJson.Parse(imageHtml);
                        string  retcode    = postResult.retcode;
                        if (retcode != "20000000")
                        {
                            Error = string.Format("账号:{0}密码{1}获取验证码 错误代码:{2}错误信息:{3}",
                                                  userName, password,
                                                  postResult.retcode, postResult.msg);
                            Result = "获取验证码失败";
                            CNWeiboLoginLogger.Info(Error);
                            return;
                        }

                        pcid = postResult.data.pcid;
                        string imageStr = postResult.data.image;
                        imageStr = imageStr.Replace("data:image/png;base64,", "");
                        var imageByte = Convert.FromBase64String(imageStr);
                        try
                        {
                            captchaResult = _ruoKuaiClient.HandleCaptcha(imageByte, "3050", "27979", "052b72d9df844391b4cbb94b258fcb61");
                        }
                        catch (Exception ex)
                        {
                            Error  = ex.ToString();
                            Result = "调用打码失败";
                            CNWeiboLoginLogger.Error(Error, ex);
                            return;
                        }

                        if (captchaResult == null)
                        {
                            Error = Result = "调用打码后结果为空";
                            CNWeiboLoginLogger.Info(Error);
                            return;
                        }

                        if (!string.IsNullOrEmpty(captchaResult.Error))
                        {
                            Error = Result = captchaResult.Error;
                            CNWeiboLoginLogger.Info(Error);
                            return;
                        }
                        door = captchaResult.CaptchaStr;
                    }
                    catch (Exception ex)
                    {
                        Error  = ex.ToString();
                        Result = "执行打码失败";
                        CNWeiboLoginLogger.Error(Error, ex);
                        return;
                    }
                }
                #endregion 打码

                const string postUrl = "https://passport.weibo.cn/sso/login";
                //username=uwtsuy%40hyatt.altrality.com&password=TTDmtbgIYXY&savestate=1&ec=0&pagerefer=https%3A%2F%2Fpassport.weibo.cn%2Fsignin%2Fwelcome%3Fentry%3Dmweibo%26r%3Dhttp%253A%252F%252Fm.weibo.cn%252F%26&entry=mweibo&loginfrom=&client_id=&code=&hff=&hfp=
                string postData = string.Format(
                    "username={0}&password={1}&savestate=1{2}&ec=0&pagerefer=https%3A%2F%2Fpassport.weibo.cn%2Fsignin%2Fwelcome%3Fentry%3Dmweibo%26r%3Dhttp%253A%252F%252Fm.weibo.cn%252F%26&entry=mweibo&loginfrom=&client_id=&code=&hff=&hfp=",
                    userName.Replace("@", "%40"), password,
                    showpin == "1" ? string.Format("&pincode={0}&pcid={1}", door, pcid) : "");

                Web.Reffer = new Uri(loginUrl);
                var postHtml = Web.Post(postUrl, postData);
                if (string.IsNullOrEmpty(postHtml))
                {
                    Error  = string.Format("账号:{0}密码{1}登录提交失败", userName, password);
                    Result = "登录提交失败";
                    CNWeiboLoginLogger.Info(Error);
                    return;
                }

                #region 设置cookies
                try
                {
                    dynamic postResult = DynamicJson.Parse(postHtml);
                    string  retcode    = postResult.retcode;
                    if (retcode == "50011010")
                    {
                        Error = string.Format("账号:{0} 密码{1} 登录提交 账号有异常 错误代码:{2} 错误信息:{3}",
                                              userName, password, postResult.retcode, postResult.msg);
                        Result = "账号有异常";
                        CNWeiboLoginLogger.Info(Error);
                        return;
                    }

                    if (retcode == "50011002")
                    {
                        Error = string.Format("账号:{0} 密码{1} 登录提交 密码错误 错误代码:{2} 错误信息:{3}",
                                              userName, password, postResult.retcode, postResult.msg);
                        Result = "密码错误";
                        CNWeiboLoginLogger.Info(Error);
                        return;
                    }

                    if (captchaResult != null && retcode == "50011006")
                    {
                        try
                        {
                            _ruoKuaiClient.ReportError(captchaResult.Id);
                        }
                        catch (Exception exception)
                        {
                            Debug.WriteLine(exception);
                        }
                        Error = string.Format("账号:{0}密码{1}登录提交 错误代码:{2}错误信息:{3}",
                                              userName, password, postResult.retcode,
                                              postResult.msg);
                        Result = "打码错误";
                        CNWeiboLoginLogger.Info(Error);
                        return;
                    }

                    if (retcode != "20000000")
                    {
                        Error = string.Format("账号:{0}密码{1}登录提交 错误代码:{2}错误信息:{3}",
                                              userName, password, postResult.retcode,
                                              postResult.msg);
                        Result = postResult.msg;
                        CNWeiboLoginLogger.Info(Error);
                        return;
                    }

                    Uid = postResult.data.uid;
                    if (postResult.data.IsDefined("loginresulturl") && !string.IsNullOrEmpty(postResult.data["loginresulturl"]))
                    {
                        string loginresulturl = postResult.data["loginresulturl"] + "&savestate=1&url=http%3A%2F%2Fm.weibo.cn%2F";
                        Web.Reffer = new Uri(loginUrl);
                        var temp0 = Web.GetHTML(loginresulturl);
                        if (string.IsNullOrEmpty(temp0))
                        {
                            Error  = string.Format("账号{0} 密码{1} 设置weibo.cn的cookies失败", userName, password);
                            Result = "设置cookies失败";
                            CNWeiboLoginLogger.Info(Error);
                            return;
                        }
                        VerifyCnSecurityPage(userName, password);
                    }
                    else
                    {
                        string weibo_com = string.Format("https:{0}&savestate=1&callback=jsonpcallback{1}", postResult.data.crossdomainlist["weibo.com"], CommonExtension.GetTime());
                        Web.Reffer = new Uri(loginUrl);
                        var temp1 = Web.GetHTML(weibo_com);
                        if (string.IsNullOrEmpty(temp1))
                        {
                            Error  = string.Format("账号{0}密码{1}设置weibo.com的cookies失败", userName, password);
                            Result = "设置cookies失败";
                            CNWeiboLoginLogger.Info(Error);
                            return;
                        }
                        string sina_com_cn = string.Format("https:{0}&savestate=1&callback=jsonpcallback{1}", postResult.data.crossdomainlist["sina.com.cn"], CommonExtension.GetTime());
                        Web.Reffer = new Uri(loginUrl);
                        Web.GetHTML(sina_com_cn);
                        string weibo_cn = string.Format("https:{0}&savestate=1&callback=jsonpcallback{1}", postResult.data.crossdomainlist["weibo.cn"], CommonExtension.GetTime());
                        Web.Reffer = new Uri(loginUrl);
                        var temp2 = Web.GetHTML(weibo_cn);
                        if (string.IsNullOrEmpty(temp2))
                        {
                            Error  = string.Format("账号{0}密码{1}设置weibo.cn的cookies失败", userName, password);
                            Result = "设置cookies失败";
                            CNWeiboLoginLogger.Info(Error);
                            return;
                        }
                        VerifyCnSecurityPage(userName, password);
                    }
                }
                catch (Exception ex)
                {
                    Error  = string.Format("账号{0}密码{1}分析登录结果失败\r\n{2}", userName, password, postHtml);
                    Result = "分析登录结果失败";
                    CNWeiboLoginLogger.Error(Error, ex);
                }
                #endregion 设置cookies
            }
            catch (Exception ex)
            {
                Result = Error = "发生未处理异常";
                CNWeiboLoginLogger.Error(Error, ex);
            }
        }
 public Task <string> GenerateSubjectAsync(CaptchaResult captcha)
 {
     return(Task.FromResult("NCaptcha Code Email"));
 }
Esempio n. 25
0
        /// <summary>
        /// 使用指定账号登录微博[COM]
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="proxy">设置代理(可选)</param>
        /// <returns>WebAccessBase:Http操作对象(存储登录结果,可供后续程序使用)</returns>
        public void WeiboLogin(string userName, string password, string proxy = null)
        {
            try
            {
                UserName = userName;
                Password = password;
                if (!string.IsNullOrEmpty(proxy))
                {
                    Web.SetProxy(proxy, "", "");
                }

                Web.Encode = Encoding.GetEncoding("gb2312");
                //存储访问网页后获取的源码信息
                //访问weibo主页
                var html = Web.GetHTML("http://weibo.com");
                if (string.IsNullOrEmpty(html))
                {
                    Result = "GET新浪微博主页网络错误";
                    Error  = string.Format("{0} {1}", Result, Web.Error.Message);
                    ComWeiboLoginLogger.Error(Error, Web.Error);
                    return;
                }

                #region 获取登录时的校验信息

                //编码用户名 @替换为%40 进行Base64编码
                string su    = userName.Replace("@", "%40");
                Byte[] bufin = Encoding.UTF8.GetBytes(su);
                su = Convert.ToBase64String(bufin, 0, bufin.Length);
                //拼接地址
                string preLoginPageUrl = string.Format("http://login.sina.com.cn/sso/prelogin.php?entry=weibo&callback=sinaSSOController.preloginCallBack&su={0}&rsakt=mod&checkpin=1&client=ssologin.js(v1.4.15)&_={1}", su, CommonExtension.GetTime().ToString(CultureInfo.InvariantCulture));
                //获取校验信息
                html = Web.GetHTML(preLoginPageUrl);
                if (string.IsNullOrEmpty(html))
                {
                    Result = "GET新浪微博prelogin页面网络错误";
                    Error  = string.Format("{0} {1}", Result, Web.Error.Message);
                    ComWeiboLoginLogger.Error(Error, Web.Error);
                    return;
                }

                #endregion 获取登录时的校验信息

                #region 检查并提取校验信息

                string        retcode = "";
                string        servertime;
                string        nonce;
                string        rsakv;
                string        showpin;
                string        pcid;
                string        door          = "";
                CaptchaResult captchaResult = null;
                try
                {
                    Regex   rg_preloginCallBack   = new Regex(@"sinaSSOController.preloginCallBack\((?<json>.*?)\)");
                    var     json_preloginCallBack = rg_preloginCallBack.Match(html).Groups["json"].Value;
                    dynamic preInfo = DynamicJson.Parse(json_preloginCallBack);
                    retcode    = preInfo.retcode;
                    servertime = preInfo.servertime;
                    nonce      = preInfo.nonce;
                    rsakv      = preInfo.rsakv;
                    showpin    = preInfo.showpin;
                    pcid       = preInfo.pcid;
                }
                catch (Exception ex)
                {
                    Result = "解析prelogin结果出错";
                    Error  = string.Format("{0} {1}", Result, retcode);
                    ComWeiboLoginLogger.Error(Error, ex);
                    return;
                }

                #region 打码

                if (showpin == "1")
                {
                    string picurl = string.Format("http://login.sina.com.cn/cgi/pin.php?r={1}&s=0&p={0}", pcid, new Random(Guid.NewGuid().GetHashCode()).Next(10000000, 99999999));
                    Web.Reffer = new Uri("http://weibo.com/");
                    var imageByte = Web.GetImageByte(picurl);
                    try
                    {
                        //File.WriteAllBytes("pic.jpg", imageByte);
                        //captchaResult = CaptchaClient.Client.HandleCaptcha(imageByte);
                        captchaResult = _ruoKuaiClient.HandleCaptcha(imageByte, "3050", "27979", "052b72d9df844391b4cbb94b258fcb61");
                    }
                    catch (Exception ex)
                    {
                        Result = "调用打码失败";
                        Error  = string.Format("{0} {1}", Result, ex.Message);
                        ComWeiboLoginLogger.Error(Error, ex);
                        return;
                    }
                    if (captchaResult == null)
                    {
                        Error = Result = "调用打码后结果为空";
                        ComWeiboLoginLogger.Info(Error);
                        return;
                    }
                    if (!string.IsNullOrEmpty(captchaResult.Error))
                    {
                        Error = Result = captchaResult.Error;
                        ComWeiboLoginLogger.Info(Error);
                        return;
                    }
                    door = captchaResult.CaptchaStr;
                }

                #endregion 打码

                #endregion 检查并提取校验信息

                #region 生成登录信息

                string sp = "";
                for (int i = 0; i < 5; i++)
                {
                    try
                    {
                        sp = SinaPassword.GetPassword(password, servertime, nonce);
                        if (!string.IsNullOrEmpty(sp))
                        {
                            Result = "";
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        Error = Result = "计算密码密文出错" + ex;
                    }
                }
                if (string.IsNullOrEmpty(sp))
                {
                    Result = "计算密码密文失败";
                    ComWeiboLoginLogger.Error(Error);
                    return;
                }
                Error = "";
                int prelt = new Random(Guid.NewGuid().GetHashCode()).Next(50, 500);
                //entry=weibo&gateway=1&from=&savestate=0&useticket=1&pagerefer=&vsnf=1&su=enBtaW5keWUlNDBqb2xseS5mYW50YXN5YXBwbGUuY29t&service=miniblog&servertime=1370330588&nonce=GPDB7O&pwencode=rsa2&rsakv=1330428213&sp=51f8c7f774ff71f31e5b181df5adfadff257b4d3299ddae8f7e6c3b7656fd9604ac8796973ff314d934984b2fdd1df4636dc52a3d2ba6d575758da929c36df9761beb1820a9509a9cd35e9c467a206efab379b10803a98f626a28baec918cf35e7f1f10c463a86abdd45619a28c579088802172e30bc4ac8d4c93d24ebd7a60e&encoding=UTF-8&prelt=73&url=http%3A%2F%2Fweibo.com%2Fajaxlogin.php%3Fframelogin%3D1%26callback%3Dparent.sinaSSOController.feedBackUrlCallBack&returntype=META
                string postData = string.Format("entry=weibo&gateway=1&from=&savestate=0&useticket=1&pagerefer={6}&vsnf=1&su={0}&service=miniblog&servertime={1}&nonce={2}&pwencode=rsa2&rsakv={3}&sp={4}&sr=1440*900&encoding=UTF-8&prelt={5}&url=http%3A%2F%2Fweibo.com%2Fajaxlogin.php%3Fframelogin%3D1%26callback%3Dparent.sinaSSOController.feedBackUrlCallBack&returntype=META",
                                                su, servertime, nonce, rsakv, sp, prelt, showpin == "1" ? string.Format("&pcid={0}&door={1}", pcid, door) : "");

                #endregion 生成登录信息

                #region 登录新浪

                Web.Reffer = new Uri("http://weibo.com/");
                //登录的POST地址
                string loginPostUrl = "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)";
                html = Web.Post(loginPostUrl, postData);
                if (string.IsNullOrEmpty(html))
                {
                    Result = "POST新浪微博login页面网络错误";
                    Error  = string.Format("{0} {1}", Result, Web.Error.Message);
                    ComWeiboLoginLogger.Error(Error, Web.Error);
                    return;
                }
                if (html.Contains("retcode=101"))
                {
                    Error = Result = "密码错误";
                    ComWeiboLoginLogger.Info(Error);
                    return;
                }
                if (html.Contains("retcode=4040"))
                {
                    Error = Result = "登录次数过多";
                    ComWeiboLoginLogger.Info(Error);
                    return;
                }
                if (html.Contains("retcode=4057"))
                {
                    Error = Result = "账号有异常";
                    ComWeiboLoginLogger.Info(Error);
                    return;
                }
                if (html.Contains("retcode=4069"))
                {
                    Error = Result = "账号未激活";
                    ComWeiboLoginLogger.Info(Error);
                    return;
                }
                if (!html.Contains("retcode=0") && !html.Contains("retcode=4049"))
                {
                    Error  = string.Format("账号:{0}密码{1}登录提交失败\r\n{2}", userName, password, html);
                    Result = "登录失败";
                    ComWeiboLoginLogger.Info(Error);
                    return;
                }

                #endregion 登录新浪

                #region 获取并访问设置Cookies地址

                Regex  regex          = new Regex(@"location.replace\([""'](?<url>.*?)[""']\);");
                string weiboCookieUrl = regex.Match(html).Groups["url"].Value;
                if (string.IsNullOrEmpty(weiboCookieUrl))
                {
                    Error = Result = "登录结果中未匹配到ajax地址";
                    ComWeiboLoginLogger.Info(Error);
                    return;
                }
                string temp1 = Web.GetHTML(weiboCookieUrl);
                if (string.IsNullOrEmpty(temp1))
                {
                    Result = "GET新浪微博ajaxlogin页面网络错误";
                    Error  = string.Format("{0} {1}", Result, Web.Error.Message);
                    ComWeiboLoginLogger.Error(Error, Web.Error);
                    return;
                }
                dynamic loginResult;
                if (temp1.Contains("<title>Sina Visitor System</title>"))
                {
                    temp1       = "{\"result\":false,\"errno\":\"4049\",\"reason\":\"\"}";
                    loginResult = DynamicJson.Parse(temp1);
                }
                else
                {
                    temp1 = temp1.Replace("<html><head><script language='javascript'>parent.sinaSSOController.feedBackUrlCallBack({", "{").Replace("});</script></head><body></body></html>", "}");

                    try
                    {
                        loginResult = DynamicJson.Parse(temp1);
                    }
                    catch (Exception ex)
                    {
                        Result = "反序列化出错 temp1=[" + temp1 + "]";
                        Error  = string.Format("{0} {1}", Result, ex.Message);
                        ComWeiboLoginLogger.Error(Error, ex);
                        return;
                    }
                }

                string weiboUrl = "http://weibo.com/";
                if (loginResult.result)
                {
                    weiboUrl += loginResult.userinfo.userdomain;
                }
                else
                {
                    string errno = loginResult.errno;
                    switch (errno)
                    {
                    case "5":
                        Error = Result = "用户名错误";
                        return;

                    case "101":
                        Error = Result = "密码错误";
                        return;

                    case "2070":
                        try
                        {
                            if (captchaResult != null)
                            {
                                _ruoKuaiClient.ReportError(captchaResult.Id);
                            }
                        }
                        catch (Exception)
                        {
                            // ignored
                        }
                        Error = Result = "验证码错误";
                        return;

                    case "4040":
                        Error = Result = "登录次数过于频繁";
                        return;

                    case "4049":
                    {
                        #region 打码再登陆一次

                        string picurl = string.Format("http://login.sina.com.cn/cgi/pin.php?r={1}&s=0&p={0}", pcid,
                                                      new Random(Guid.NewGuid().GetHashCode()).Next(10000000, 99999999));
                        Web.Reffer = new Uri("http://weibo.com/");
                        var imageByte = Web.GetImageByte(picurl);
                        try
                        {
                            //File.WriteAllBytes("pic.jpg", imageByte);
                            //captchaResult = CaptchaClient.Client.HandleCaptcha(imageByte);
                            captchaResult = _ruoKuaiClient.HandleCaptcha(imageByte, "3050", "27979", "052b72d9df844391b4cbb94b258fcb61");
                        }
                        catch (Exception ex)
                        {
                            Result = "调用打码失败";
                            Error  = ex.Message;
                            return;
                        }
                        if (captchaResult == null)
                        {
                            Result = "调用打码后结果为空";
                            return;
                        }
                        if (!string.IsNullOrEmpty(captchaResult.Error))
                        {
                            Result = captchaResult.Error;
                            return;
                        }
                        door = captchaResult.CaptchaStr;

                        try
                        {
                            sp = SinaPassword.GetPassword(password, servertime, nonce);
                        }
                        catch (Exception ex)
                        {
                            Result = "计算密码密文出错";
                            Error  = ex.Message;
                            return;
                        }
                        if (string.IsNullOrEmpty(sp))
                        {
                            Result = "计算密码密文失败";
                            return;
                        }
                        prelt    = new Random(Guid.NewGuid().GetHashCode()).Next(50, 500);
                        postData =
                            string.Format(
                                "entry=weibo&gateway=1&from=&savestate=0&useticket=1&pagerefer={6}&vsnf=1&su={0}&service=miniblog&servertime={1}&nonce={2}&pwencode=rsa2&rsakv={3}&sp={4}&sr=1440*900&encoding=UTF-8&prelt={5}&url=http%3A%2F%2Fweibo.com%2Fajaxlogin.php%3Fframelogin%3D1%26callback%3Dparent.sinaSSOController.feedBackUrlCallBack&returntype=META",
                                su, servertime, nonce, rsakv, sp, prelt, string.Format("&pcid={0}&door={1}", pcid, door));

                        Web.Reffer = new Uri("http://weibo.com/");
                        //登录的POST地址
                        loginPostUrl = "http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)";
                        html         = Web.Post(loginPostUrl, postData);
                        if (string.IsNullOrEmpty(html))
                        {
                            Result = "POST新浪微博login页面网络错误";
                            Error  = Web.Error.Message;
                            return;
                        }

                        if (html.Contains("retcode=101"))
                        {
                            Result = "密码错误";
                            return;
                        }
                        if (html.Contains("retcode=4040"))
                        {
                            Result = "登录次数过多";
                            return;
                        }
                        if (html.Contains("retcode=4057"))
                        {
                            Result = "账号有异常";
                            return;
                        }
                        if (html.Contains("retcode=2070"))
                        {
                            try
                            {
                                _ruoKuaiClient.ReportError(captchaResult.Id);
                            }
                            catch (Exception)
                            {
                                // ignored
                            }
                            Result = "验证码错误";
                            return;
                        }
                        if (html.Contains("retcode=4069"))
                        {
                            Result = "账号未激活";
                            return;
                        }
                        if (!html.Contains("retcode=0"))
                        {
                            ComWeiboLoginLogger.Info("账号:{0}密码{1}登录提交失败\r\n{2}", userName, password, html);
                            Result = "登录失败2";
                            return;
                        }

                        regex          = new Regex(@"location.replace\([""'](?<url>.*?)[""']\);");
                        weiboCookieUrl = regex.Match(html).Groups["url"].Value;
                        if (string.IsNullOrEmpty(weiboCookieUrl))
                        {
                            Result = "登录结果中未匹配到ajax地址";
                            return;
                        }
                        temp1 = Web.GetHTML(weiboCookieUrl);
                        if (string.IsNullOrEmpty(temp1))
                        {
                            Result = "GET新浪微博ajaxlogin页面网络错误";
                            Error  = Web.Error.Message;
                            return;
                        }

                        temp1 =
                            temp1.Replace(
                                "<html><head><script language='javascript'>parent.sinaSSOController.feedBackUrlCallBack({",
                                "{").Replace("});</script></head><body></body></html>", "}");
                        loginResult = DynamicJson.Parse(temp1);
                        weiboUrl    = "http://weibo.com/";
                        if (loginResult.result)
                        {
                            weiboUrl += loginResult.userinfo.userdomain;
                        }
                        else
                        {
                            errno = loginResult.errno;
                            switch (errno)
                            {
                            case "5":
                                Result = "用户名错误";
                                return;

                            case "101":
                                Result = "密码错误";
                                return;

                            case "2070":
                                try
                                {
                                    _ruoKuaiClient.ReportError(captchaResult.Id);
                                }
                                catch (Exception)
                                {
                                    // ignored
                                }
                                Result = "验证码错误";
                                return;

                            case "4040":
                                Result = "登录次数过于频繁";
                                return;

                            case "4057":
                                Result = "账号有异常";
                                return;

                            default:
                                Result = loginResult.reason;
                                return;
                            }
                        }

                        #endregion 打码再登陆一次
                    }
                    break;

                    case "4057":
                        Error = Result = "账号有异常";
                        return;

                    case "4069":
                        Error = Result = "账号未激活";
                        return;

                    default:
                        Result = loginResult.reason;
                        return;
                    }
                }
                Web.GetHTML(weiboUrl);

                #endregion 获取并访问设置Cookies地址

                #region 访问微博设置页面判断账号状态

                html = Web.GetHTML("http://weibo.com/");
                if (!string.IsNullOrEmpty(html) && html.Contains("您当前使用的账号存在异常,请完成以下操作解除异常状态"))
                {
                    Error = Result = "无法收短信解封";
                    return;
                }
                if (!string.IsNullOrEmpty(html) && html.Contains("<title>微博帐号解冻"))
                {
                    Error = Result = "封号";
                    return;
                }
                if (!string.IsNullOrEmpty(html) && html.Contains("<title>404错误") && html.Contains("在线申诉"))
                {
                    Error = Result = "死号";
                    return;
                }
                html = Web.GetHTML("http://security.weibo.com/security/index");
                //判断账号状态
                if (!string.IsNullOrEmpty(html))
                {
                    if ((html.Contains("帐号安全系统检测到您的帐号存在高危风险")))
                    {
                        Error = Result = "锁定";
                        return;
                    }
                    if (html.Contains("修改密码"))
                    {
                        Result = GetUidFromHTML(html) ? "正常" : "获取UID失败";
                    }
                    else
                    {
                        //File.AppendAllText("SinaWeiboLoginUnknownError.txt", userName + "\t" + password + Environment.NewLine);
                        ComWeiboLoginLogger.Info("账号{0}登录后安全页面分析失败\r\n{1}", userName, html);
                        Error = Result = "未知失败";
                    }
                }
                else
                {
                    Error = Result = "GET新浪微博账号安全页面网络错误";
                }

                #endregion 访问微博设置页面判断账号状态
            }
            catch (Exception ex)
            {
                Error = Result = "发生未处理异常";
                ComWeiboLoginLogger.Error(Error, ex);
            }
        }
Esempio n. 26
0
 public void Test()
 {
     CaptchaResult result = CaptchaImageGenerator.GetImage(200, 100, "HELLO");
 }
        private async Task <DialogTurnResult> apiCallStep2(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var sessionModelsAccessors = UserState1.CreateProperty <SessionModel>(nameof(SessionModel));
            var sessionModels          = await sessionModelsAccessors.GetAsync(stepContext.Parent.Context, () => new SessionModel());

            //CaptchaResult result = new CaptchaResult();

            //result = await APIRequest.GetCaptcha();

            //string card = "\\Cards\\artCaptcha.json";
            //var adaptiveCardJson = File.ReadAllText(Environment.CurrentDirectory + card);
            //adaptiveCardJson = adaptiveCardJson.Replace("{str}", result.CaptchBase64Data);
            //JObject json = JObject.Parse(adaptiveCardJson);
            //var adaptiveCardAttachment = new Attachment()
            //{
            //    ContentType = "application/vnd.microsoft.card.adaptive",
            //    Content = JsonConvert.DeserializeObject(json.ToString()),
            //};
            //var cardResponse = MessageFactory.Attachment(adaptiveCardAttachment);
            //await stepContext.Context.SendActivityAsync(cardResponse, cancellationToken);
            //return await stepContext.EndDialogAsync();

            if ((string)stepContext.Result == "true")
            {
                var           _activitySessionId = stepContext.Context.Activity.From.Id;
                var           textReq            = stepContext.Context.Activity.Text;
                object        stata  = stepContext.ActiveDialog.State["stepIndex"];
                CaptchaResult result = new CaptchaResult();

                result = await APIRequest.GetCaptcha();

                captcha = result.CaptchaCode;
                string card             = "\\Cards\\artCaptcha.json";
                var    adaptiveCardJson = File.ReadAllText(Environment.CurrentDirectory + card);
                adaptiveCardJson = adaptiveCardJson.Replace("{str}", result.CaptchBase64Data);
                JObject json = JObject.Parse(adaptiveCardJson);
                var     adaptiveCardAttachment = new Attachment()
                {
                    ContentType = "application/vnd.microsoft.card.adaptive",
                    Content     = JsonConvert.DeserializeObject(json.ToString()),
                };
                var cardResponse = MessageFactory.Attachment(adaptiveCardAttachment);
                await stepContext.Context.SendActivityAsync(cardResponse, cancellationToken);

                object stata1 = stepContext.ActiveDialog.State["stepIndex"];

                return(await stepContext.NextAsync(captcha, cancellationToken));
            }
            else
            {
                var _activitySessionId = stepContext.Context.Activity.From.Id;
                var textReq            = stepContext.Context.Activity.Text;

                //var sessionModelsAccessors = UserState1.CreateProperty<SessionModel>(nameof(SessionModel));
                //var sessionModels = await sessionModelsAccessors.GetAsync(stepContext.Parent.Context, () => new SessionModel());

                string EmailId = sessionModels.EmailId;
                LoginUserID = sessionModels.UserID;
                var otpDetails = (ArtOTP)stepContext.Options;

                string response = string.Empty;

                string json = "{\"UserID\":\"{UserID}\",\"Password\":\"null\",\"Activity\":\"AccountUnlock\",\"sessionId\":\"{sessionId}\",\"sourceorigin\":\"1\",\"MobileNumber\":\"null\",\"QuestionAnswerModelList\":\"null\"}";
                json = json.Replace("{UserID}", LoginUserID).Replace("{sessionId}", stepContext.Context.Activity.From.Id);

                response = await APIRequest.ValidateUserID(json);

                object stata = stepContext.ActiveDialog.State["stepIndex"];

                if (response == "true")
                {
                    CaptchaResult result = new CaptchaResult();

                    result = await APIRequest.GetCaptcha();

                    captcha = result.CaptchaCode;
                    string card             = "\\Cards\\artCaptcha.json";
                    var    adaptiveCardJson = File.ReadAllText(Environment.CurrentDirectory + card);
                    adaptiveCardJson = adaptiveCardJson.Replace("{str}", result.CaptchBase64Data);
                    JObject json1 = JObject.Parse(adaptiveCardJson);
                    var     adaptiveCardAttachment = new Attachment()
                    {
                        ContentType = "application/vnd.microsoft.card.adaptive",
                        Content     = JsonConvert.DeserializeObject(json1.ToString()),
                    };
                    var cardResponse = MessageFactory.Attachment(adaptiveCardAttachment);
                    await stepContext.Context.SendActivityAsync(cardResponse, cancellationToken);

                    return(await stepContext.NextAsync(captcha, cancellationToken));
                }
                else if (response.Replace("\"", "") == "Invalid Userid. Please try with correct userid.")
                {
                    var promptOptions = new PromptOptions {
                        Prompt = MessageFactory.Text("Hmm… I didn't find an account with the email address: ${EmailId}.  Try again or ask to speak to a live agent")
                    };
                    return(await stepContext.PromptAsync(nameof(TextPrompt), promptOptions, cancellationToken));
                }
                else if (response.Replace("\"", "") == "User not enrolled in ART. Please do enroll before proceeding to Unlock/Reset.")
                {
                    var artUserNotEnrolled = CreateAdaptiveCardAttachment("CoreBot.Cards.artUserNotEnrolled.json");
                    var cardResponse       = MessageFactory.Attachment(artUserNotEnrolled);
                    await stepContext.Context.SendActivityAsync(cardResponse, cancellationToken);

                    return(await stepContext.EndDialogAsync(response, cancellationToken));
                }
                else if (response.Replace("\"", "") == "User account is not locked.")
                {
                    //artAccountNotLock
                    var artAccountNotLock = CreateAdaptiveCardAttachment("CoreBot.Cards.artAccountNotLock.json");
                    var cardResponse      = MessageFactory.Attachment(artAccountNotLock);
                    await stepContext.Context.SendActivityAsync(cardResponse, cancellationToken);

                    return(await stepContext.EndDialogAsync(response, cancellationToken));
                }
                else
                {
                    await stepContext.Context.SendActivityAsync(troubleText);

                    var artAccountNotLock = CreateAdaptiveCardAttachment("CoreBot.Cards.artTroubleAccount.json");
                    var cardResponse      = MessageFactory.Attachment(artAccountNotLock);
                    await stepContext.Context.SendActivityAsync(cardResponse, cancellationToken);

                    return(await stepContext.EndDialogAsync("false", cancellationToken));
                }
            }
        }
        public Task <string> GenerateAsync(CaptchaResult captcha)
        {
            string content = $"Hello, your captcha code is: {captcha.CaptchaCode}. [via. NCaptcha]";

            return(Task.FromResult(content));
        }
Esempio n. 29
0
    public CaptchaResult Captcha(String SPID, String phone, String type,String ExtendField)
    {
        CaptchaResult Result = new CaptchaResult();
        Result.Result = ErrorDefinition.IError_Result_UnknowError_Code;
        Result.ErrorDescription = "";
        Result.ExtendField = "";
        StringBuilder strLog = new StringBuilder();
        strLog.Append("====================================\r\n");
        strLog.Append("通过手机找回综合平台密码接口\r\n");
        strLog.AppendFormat("时间:{0}\r\n", DateTime.Now.ToString("u"));
        strLog.AppendFormat("参数,SPID:{0},phone:{1},ExtendField:{2}\r\n",SPID,phone,ExtendField);
        try
        {
            #region 数据合法性验证
            //数据合法性判断
            if (CommonUtility.IsEmpty(SPID))
            {
                Result.Result = ErrorDefinition.BT_IError_Result_InValidSPID_Code;
                Result.ErrorDescription = ErrorDefinition.BT_IError_Result_InValidSPID_Msg + "不能为空";
                return Result;
            }

            if (SPID.Length != ConstDefinition.Length_SPID)
            {
                Result.Result = ErrorDefinition.BT_IError_Result_InValidSPID_Code;
                Result.ErrorDescription = ErrorDefinition.BT_IError_Result_InValidSPID_Msg + "长度有误";
                return Result;
            }

            //IP是否允许访问
            Result.Result = CommonBizRules.CheckIPLimit(SPID, HttpContext.Current.Request.UserHostAddress, this.Context, out Result.ErrorDescription);
            if (Result.Result != 0)
            {
                return Result;
            }

            if (CommonUtility.IsEmpty(phone))
            {
                Result.Result = ErrorDefinition.BT_IError_Result_InValidSPID_Code;
                Result.ErrorDescription ="phone不能为空";
                return Result;
            }

            #endregion
            String jsonResult = String.Empty;
            string sign = String.Empty;
            String appId = UDBConstDefinition.DefaultInstance.UnifyPlatformAppId;
            String appSecret = UDBConstDefinition.DefaultInstance.UnifyPlatformAppSecret;
            String version = UDBConstDefinition.DefaultInstance.UnifyPlatformVersion;
            String clientType = UDBConstDefinition.DefaultInstance.UnifyPlatformClientType;
            String clientIp = HttpContext.Current.Request.UserHostAddress;
            String clientAgent = HttpContext.Current.Request.UserAgent;
            strLog.AppendFormat("获取综合平台接入参数:appId:{0},appSecret:{1},version:{2},clientType:{3},clientIp:{4},clientAgent:{5}\r\n", appId, appSecret, version, clientType, clientIp, clientAgent);

            string paras = String.Empty;
            string format = "json";
            string parameters = "mobile=" + phone + "&type=" + type + "&clientIp=" + clientIp + "&clientAgent=" + clientAgent;
            strLog.AppendFormat("parameters:={0}\r\n", parameters);
            paras = CryptographyUtil.XXTeaEncrypt(parameters, appSecret);
            strLog.AppendFormat("paras:={0}\r\n", paras);
            sign = CryptographyUtil.HMAC_SHA1(appId + clientType + format + version + paras, appSecret);
            strLog.AppendFormat("sign:={0}\r\n", sign);
            System.Collections.Specialized.NameValueCollection postData = new System.Collections.Specialized.NameValueCollection();
            postData.Add("appId", appId);
            postData.Add("version", version);
            postData.Add("clientType", clientType);
            postData.Add("paras", paras);
            postData.Add("sign", sign);
            postData.Add("format", format);

            System.Net.WebClient webclient = new System.Net.WebClient();
            webclient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可
            byte[] responseData = webclient.UploadValues(UDBConstDefinition.DefaultInstance.UnifyPlatformCaptchaUrl, "POST", postData);
            jsonResult = System.Text.Encoding.UTF8.GetString(responseData);
            strLog.AppendFormat("jsonResult:{0}\r\n", jsonResult);

            Dictionary<string, string> result_dic = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonResult);

            String result = String.Empty;
            String msg = String.Empty;
            result_dic.TryGetValue("msg", out msg);
            result_dic.TryGetValue("result", out result);

            Result.Result = Convert.ToInt64(result);
            Result.ErrorDescription = msg;

        }
        catch (Exception e)
        {
            Result.ErrorDescription += e.Message;
        }
        finally
        {
            strLog.Append("====================================\r\n");
            BTUCenterInterfaceLog.CenterForBizTourLog("Captcha", strLog);
        }
        return Result;
    }