예제 #1
0
        public static CaptchaModel GetCaptchaModel(string name)
        {
            var model = new CaptchaModel();

            if (name != "")
            {
                model.ID = name;
            }
            else
            {
                model.ID = "captcha";
            }

            // This Captcha code was extracted from:
            // http://www.stefanprodan.eu/2012/01/user-friendly-captcha-for-asp-net-mvc/

            var rand = new Random((int)DateTime.Now.Ticks);

            // Generate new question
            int a       = rand.Next(0, 9);
            int b       = rand.Next(0, 9);
            int c       = rand.Next(0, 9);
            int d       = rand.Next(0, 9);
            int e       = rand.Next(0, 9);
            var captcha = string.Format("{0}  {1}  {2}  {3}  {4}", a, b, c, d, e);

            using (var mem = new MemoryStream())
                using (var bmp = new Bitmap(130, 30))
                    using (var gfx = Graphics.FromImage(bmp))
                    {
                        gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                        gfx.SmoothingMode     = SmoothingMode.AntiAlias;
                        gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height));

                        // Add noise
                        int i, r, x, y;
                        Pen pen = new Pen(Color.Yellow);
                        for (i = 1; i < 10; i++)
                        {
                            pen.Color = Color.FromArgb((rand.Next(0, 255)), (rand.Next(0, 255)), (rand.Next(0, 255)));

                            r = rand.Next(0, (130 / 3));
                            x = rand.Next(0, 130);
                            y = rand.Next(0, 30);

                            gfx.DrawEllipse(pen, x - r, y - r, r, r);
                        }

                        // Add question
                        gfx.DrawString(captcha, new Font("Tahoma", 16), Brushes.Gray, 2, 3);

                        // Render as Png
                        bmp.Save(mem, ImageFormat.Png);

                        model.Image          = Convert.ToBase64String(mem.GetBuffer());
                        model.EncryptedValue = CustomEncrypt.Encrypt(captcha.Replace(" ", ""));
                    }

            return(model);
        }
예제 #2
0
        /// <summary>
        /// 自定义生成验证码数据,调用方生成验证码
        /// </summary>
        /// <param name="purpose">验证类型,区分大小写</param>
        /// <param name="target">验证对象,target可以是邮件/手机等 都可以,区分大小写</param>
        /// <param name="lifeTimeSeconds">验证码有效时间,单位秒</param>
        /// <param name="maxErrorCount">最大错误次数</param>
        /// <param name="captcha">自行生成验证码并传入</param>
        /// <param name="securityStamp">target当前的安全标识,比如用户修改了密码等安全标识验证码需要失效</param>
        /// <returns></returns>
        public async Task <string> Build(string purpose, string target, int lifeTimeSeconds, int maxErrorCount, string captcha,
                                         string?securityStamp = null)
        {
            if (purpose is null)
            {
                throw new ArgumentNullException(nameof(purpose));
            }
            if (target is null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (lifeTimeSeconds <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(lifeTimeSeconds));
            }
            if (maxErrorCount < 0 || maxErrorCount > 99)
            {
                throw new ArgumentOutOfRangeException(nameof(maxErrorCount));
            }
            if (string.IsNullOrWhiteSpace(captcha))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(captcha));
            }

            var key   = GetKey(purpose, target, securityStamp);
            var model = new CaptchaModel();

            model._errorCounter = maxErrorCount;
            model._captcha      = captcha;
            MemoryCache.Set(key, model, TimeSpan.FromSeconds(lifeTimeSeconds));
            return(await Task.FromResult(captcha));
        }
예제 #3
0
        public String getToken()
        {
            // 產生一個 5 個字元的亂碼字串
            var pwd     = new Password(5).IncludeNumeric();
            var Captcha = pwd.Next();

            // 封裝字符和過期時間
            CaptchaModel captchaModel = new CaptchaModel();

            captchaModel.Code = Captcha;

            //設定過期時間為一分鐘
            captchaModel.Exp = DateTime.Now.AddMinutes(1);

            //轉換json字串
            string jsonString = JsonSerializer.Serialize(captchaModel);

            System.Console.WriteLine(jsonString);

            //AES加密
            string token = StringEncrypt.aesEncryptBase64(jsonString, CryptoKey);

            //取代特殊符號回傳

            return(base64url_encode(token));
        }
예제 #4
0
 public ActionResult Index(CaptchaModel objCaptchaModel)
 {
     if (IsValidCaptcha(objCaptchaModel))
     {
         return(RedirectToAction("Success"));
     }
     ViewBag.ErrorMessage = "Incorrect Captcha, Please try again";
     return(View("Index"));
 }
예제 #5
0
        public ActionResult Captcha(CaptchaModel model)
        {
            if (!ModelState.IsValid)
            {
                //clear captcha field
                ModelState.SetModelValue("Captcha", new ValueProviderResult("", "", System.Globalization.CultureInfo.CurrentCulture));
                return(View(model));
            }

            //proceed to next step
            return(View(model)
                   .WithSuccessSnackbar("Yes!! This is the right captcha"));
        }
예제 #6
0
        public void Generate()
        {
            CaptchaModel model = Captcha.Generate();

            CorrectX = model.X;
            //pb2.Size = new Size(model.Slide.Width, model.Slide.Height);
            //pb1.Size = new Size(model.Background.Width, model.Background.Height);
            pb2.Image = model.Slide;
            pb1.Image = model.Background;
            Bitmap bitmap = (Bitmap)model.Background;
            Color  color  = bitmap.GetPixel(bitmap.Width - lblRefresh.Width, lblRefresh.Height);

            lblRefresh.ForeColor = Captcha.AntiColor(color);
        }
예제 #7
0
        /// <summary>
        /// Help method for verify
        /// </summary>
        /// <param name="captcha"></param>
        /// <returns></returns>
        internal static bool IsVerify(CaptchaModel captcha)
        {
            try {
                var encryptorModel = GetEncryptorModel();
                if (encryptorModel == null)
                {
                    return(false);
                }

                var textDecrypt = GetEncryption().Decrypt(captcha.CaptchaDeText, encryptorModel.Password, encryptorModel.Salt);
                return(textDecrypt == captcha.CaptchaInputText);
            } catch {
                return(false);
            }
        }
예제 #8
0
        /// <summary>
        /// Method to check whether the captcha is valid or not
        /// </summary>
        /// <param name="objCaptchaModel"></param>
        /// <returns></returns>
        public bool IsValidCaptcha(CaptchaModel objCaptchaModel)
        {
            bool check = false;

            try
            {
                if (!String.IsNullOrEmpty(objCaptchaModel.Text) && Session[Cons.CaptchaSessionKey].ToString() == objCaptchaModel.Text)
                {
                    check = true;
                }
            }
            catch (Exception ex)
            {
                //log exception
                throw;
            }
            return(check);
        }
 public ServiceResponse GeneratingCaptchaCookie(CaptchaModel jobj)
 {
     result = new ServiceResponse();
     try
     {
         if (ModelState.IsValid)
         {
             result.StatusCode = (int)HttpStatusCode.OK;
             GenerateCaptchaCookie(jobj.Location);
             result.Response = true;
         }
     }
     catch
     {
         result.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
         result.Response = 0;
     }
     return result;
 }
 public ServiceResponse GeneratingCaptchaCookie(CaptchaModel jobj)
 {
     result = new ServiceResponse();
     try
     {
         if (ModelState.IsValid)
         {
             result.StatusCode = (int)HttpStatusCode.OK;
             GenerateCaptchaCookie(jobj.Location);
             result.Response = true;
         }
     }
     catch
     {
         result.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
         result.Response   = 0;
     }
     return(result);
 }
예제 #11
0
        public ActionResult Index(CaptchaModel captchaModel)
        {
            if (ModelState.IsValid)
            {
                if (Session["captcha"] != null && captchaModel.Captcha == Session["captcha"].ToString())
                {
                    ModelState.AddModelError("", "Doğrulama kodunu doğru girdiniz.");
                }
                else
                {
                    ModelState.AddModelError("", "Doğrulama kodunu yanlış girdiniz.");
                }
            }
            else
            {
                ModelState.AddModelError("", "Lütfen doğrulama kodunu boş bırakmayınız.");
            }

            return(View(captchaModel));
        }
예제 #12
0
        /// <summary>
        /// Check for proper input captcha
        /// </summary>
        /// <param name="controllerBase"></param>
        /// <param name="textError">text for error</param>
        /// <returns></returns>
        public static bool IsCaptchaVerify(this ControllerBase controllerBase, string textError)
        {
            try {
                var captchaModel = new CaptchaModel {
                    CaptchaDeText =
                        controllerBase.ValueProvider.GetValue("CaptchaDeText").AttemptedValue,
                    CaptchaInputText =
                        controllerBase.ValueProvider.GetValue("CaptchaInputText").AttemptedValue
                };

                controllerBase.ViewData.ModelState.Remove("CaptchaDeText");
                controllerBase.ViewData.ModelState.Remove("CaptchaInputText");
                var isVerify = IsVerify(captchaModel);
                if (!isVerify)
                {
                    controllerBase.ViewData.ModelState.AddModelError("CaptchaInputText", textError);
                }

                return(isVerify);
            } catch (Exception) {
                throw new NullReferenceException("Form not contain CaptchaModel");
            }
        }
예제 #13
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                ControllerBase controllerBase = filterContext.Controller;
                var            captchaModel   = new CaptchaModel
                {
                    CaptchaDeText =
                        controllerBase.ValueProvider.GetValue("CaptchaDeText").AttemptedValue,
                    CaptchaInputText =
                        controllerBase.ValueProvider.GetValue("CaptchaInputText").AttemptedValue
                };
                if (!CaptchaHelper.IsVerify(captchaModel))
                {
                    controllerBase.ViewData.ModelState.AddModelError("CaptchaInputText", _textError);
                }
            }
            catch (Exception)
            {
                throw new NullReferenceException("Form not contain CaptchaModel");
            }

            base.OnActionExecuting(filterContext);
        }
예제 #14
0
 public LoginModel()
 {
     Captcha = new CaptchaModel();
 }
예제 #15
0
파일: Captcha.cs 프로젝트: yukselis/wiieasy
 public Captcha(CaptchaModel Model)
 {
     this.CaptchaModel = Model;
 }
예제 #16
0
파일: Captcha.cs 프로젝트: yukselis/wiieasy
 public Captcha()
 {
     this.CaptchaModel = new CaptchaModel();
 }
예제 #17
0
 public CaptchaController(HumanCaptchaContext _context, IExceptionManager _exceptionManager)
 {
     this.model = new CaptchaModel(_context, _exceptionManager);
     //default length
     this.size = 6;
 }
예제 #18
0
 public LocalPasswordModel()
 {
     Captcha = new CaptchaModel();
 }
예제 #19
0
 public static bool Verify(CaptchaModel model)
 {
     return(IsVerify(model));
 }
 /// <summary>
 /// Default constructer
 /// </summary>
 public BaseViewModel()
 {
     Errors  = new List <string>();
     Captcha = new CaptchaModel();
 }
예제 #21
0
 public ForgotPasswordModel()
 {
     Captcha = new CaptchaModel();
 }
예제 #22
0
        public ActionResult Register(User model)
        {
            if (model.UserId == 0)
            {
                ViewBag.result = 1;
                return(RedirectToAction("Register"));
            }
            else if (model.Email != null && model.BirthYear != null && model.TcNo != null && model.Password != null && model.FirstName != null && model.LastName != null && model.Phone != null)
            {
                CaptchaModel captchaModel;
                using (System.Net.WebClient webClient = new System.Net.WebClient())
                {
                    captchaModel = new CaptchaModel(System.Text.Encoding.Default.GetString(webClient.UploadValues("https://www.google.com/recaptcha/api/siteverify", new NameValueCollection()
                    {
                        ["secret"]   = "6Lch1uoUAAAAALTxp59SX0NAe9BZ9n8_yjT0VeFV",
                        ["response"] = Request.Form["g-recaptcha-response"],
                        ["remoteip"] = Request.ServerVariables["REMOTE_ADDR"]
                    })));
                }
                if (!captchaModel.success)
                {
                    TempData["Mesaj"] = new TempDataDictionary {
                        { "class", "alert-danger" }, { "Msg", "Güvenlik adımını tamamlayın" }
                    };
                }
                var year = model.BirthYear.Value.Date.Year;

                var result = tcControl.TCKimlikNoDogrula(Convert.ToInt64(model.TcNo), model.FirstName.ToUpper(), model.LastName.ToUpper(), year);

                if (result)
                {
                    if (model.UserId == 2)
                    {
                        CourierVM item = new DL.ViewModels.CourierVM {
                            AddressId = 1, TcNo = model.TcNo, Phone = model.Phone, FirstName = model.FirstName, Password = model.Password, LastName = model.LastName, Email = model.Email, BirthYear = model.BirthYear.Value.Date
                        };
                        DataContractJsonSerializer ser =
                            new DataContractJsonSerializer(typeof(CourierVM));
                        MemoryStream mem = new MemoryStream();
                        ser.WriteObject(mem, item);
                        string data =
                            Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
                        WebClient webClientt = new WebClient();
                        webClientt.Headers["Content-type"] = "application/json";
                        webClientt.Encoding = Encoding.UTF8;
                        var response = webClientt.UploadString("http://localhost:65132/QarocoService.svc/Courier/CourierAdd", "POST", data);
                        var resultx  = JsonConvert.DeserializeObject(response);
                        return(RedirectToAction("Login"));
                        // resultx doğru ise ekrana kayıt başarılı çıkar
                    }
                    else if (model.UserId == 1)
                    {
                        CustomerVM item = new DL.ViewModels.CustomerVM {
                            AddressId = 1, TcNo = model.TcNo, Phone = model.Phone, FirstName = model.FirstName, Password = model.Password, LastName = model.LastName, Email = model.Email, BirthYear = model.BirthYear.Value.Date
                        };
                        DataContractJsonSerializer ser =
                            new DataContractJsonSerializer(typeof(CustomerVM));
                        MemoryStream mem = new MemoryStream();
                        ser.WriteObject(mem, item);
                        string data =
                            Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
                        WebClient webClientt = new WebClient();
                        webClientt.Headers["Content-type"] = "application/json";
                        webClientt.Encoding = Encoding.UTF8;
                        var response = webClientt.UploadString("http://localhost:65132/QarocoService.svc/Customer/CustomerAdd", "POST", data);
                        var resultx  = JsonConvert.DeserializeObject(response);
                        return(RedirectToAction("Login"));
                        // resultx doğru ise ekrana kayıt başarılı çıkar
                    }
                    else
                    {
                        ViewBag.result = 1;
                        return(RedirectToAction("Register"));
                    }
                }
                else
                {
                    ViewBag.result = 0;
                    return(RedirectToAction("Register"));
                }
            }
            else
            {
                ViewBag.result = 1;
                return(RedirectToAction("Register"));
            }
        }
예제 #23
0
        public ActionResult Login(User model)
        {
            if (model.Email != null && model.Password != null)
            {
                CaptchaModel captchaModel;
                using (System.Net.WebClient webClient = new System.Net.WebClient())
                {
                    captchaModel = new CaptchaModel(System.Text.Encoding.Default.GetString(webClient.UploadValues("https://www.google.com/recaptcha/api/siteverify", new NameValueCollection()
                    {
                        ["secret"]   = "6Lch1uoUAAAAALTxp59SX0NAe9BZ9n8_yjT0VeFV",
                        ["response"] = Request.Form["g-recaptcha-response"],
                        ["remoteip"] = Request.ServerVariables["REMOTE_ADDR"]
                    })));
                }
                if (!captchaModel.success)
                {
                    TempData["Mesaj"] = new TempDataDictionary {
                        { "class", "alert-danger" }, { "Msg", "Güvenlik adımını tamamlayın" }
                    };
                }
                /* Burda Başlar Post eder */
                DataContractJsonSerializer ser =
                    new DataContractJsonSerializer(typeof(User));

                MemoryStream mem = new MemoryStream();
                ser.WriteObject(mem, model);
                string data =
                    Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
                WebClient webClientt = new WebClient();
                webClientt.Headers["Content-type"] = "application/json";
                webClientt.Encoding = Encoding.UTF8;
                var  response = webClientt.UploadString("http://localhost:65132/QarocoService.svc/UserLogin/User", "POST", data);
                User user     = JsonConvert.DeserializeObject <User>(response);
                /* Burda Biter */

                if (user != null)
                {
                    Session["LoginUser"] = user;

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    DataContractJsonSerializer serializer =
                        new DataContractJsonSerializer(typeof(string));

                    MemoryStream memoryStream = new MemoryStream();
                    serializer.WriteObject(memoryStream, model.Email);
                    string _data =
                        Encoding.UTF8.GetString(memoryStream.ToArray(), 0, (int)memoryStream.Length);
                    WebClient web = new WebClient();
                    web.Headers["Content-type"] = "application/json";
                    web.Encoding = Encoding.UTF8;
                    var  result = web.UploadString("http://localhost:65132/QarocoService.svc/User/UserLog", "POST", _data);
                    User _user  = JsonConvert.DeserializeObject <User>(result);

                    if (string.IsNullOrEmpty(ipAddress) && _user != null)
                    {
                        Log log = new Log();
                        ipAddress          = Request.ServerVariables["REMOTE_ADDR"];
                        log.LogEmail       = _user.Email;
                        log.LogDate        = DateTime.Now;
                        log.LogDescription = log.LogDate.Value.ToShortDateString() + " Tarihindeki giriş hatanız";
                        log.LogIp          = ipAddress;

                        DataContractJsonSerializer ser2 =
                            new DataContractJsonSerializer(typeof(Log));

                        MemoryStream memory = new MemoryStream();
                        ser2.WriteObject(memory, log);
                        string data2 =
                            Encoding.UTF8.GetString(memory.ToArray(), 0, (int)memory.Length);
                        WebClient _webClientt = new WebClient();
                        _webClientt.Headers["Content-type"] = "application/json";
                        _webClientt.Encoding = Encoding.UTF8;
                        var response2 = _webClientt.UploadString("http://localhost:65132/QarocoService.svc/Log/LogAdd", "POST", data2);
                        if (response2 == "true")
                        {
                            TempData["Mesaj"] = new TempDataDictionary {
                                { "class", "alert-danger" }, { "Msg", "Kullanıcı Adı veya şifre hatalı!" }
                            };
                            return(View());
                        }
                        else
                        {
                            return(View());
                        }
                    }
                    else
                    {
                        return(View());
                    }
                }
            }
            else
            {
                TempData["Mesaj"] = new TempDataDictionary {
                    { "class", "alert-danger" }, { "Msg", "Kullanıcı Adı veya şifre Girmediniz!" }
                };
                return(View());
            }
        }