Esempio n. 1
0
        public async Task CreateCaptchaCode()
        {
            var captcha = CaptchaUtils.Create();
            await captcha.CheckCodeImg.WriteToFileAsync(FileUtils.Combine(SystemUtils.GetMapPath("/TestSource/ImageTest"), "Captcha.png"));

            Console.WriteLine("验证码字符串:" + captcha.CheckCodeString);
        }
Esempio n. 2
0
        /// <summary>
        ///     Creates a new captcha with the specified arguments.
        /// </summary>
        /// <param name="htmlHelper">
        ///     The specified <see cref="HtmlHelper" />.
        /// </param>
        /// <param name="length">The specified length of characters.</param>
        /// <param name="parameters">The specified parameters, if any.</param>
        /// <returns>
        ///     An instance of <see cref="ICaptcha" />.
        /// </returns>
        public static ICaptcha Captcha(this HtmlHelper htmlHelper, int length, params ParameterModel[] parameters)
        {
            List <ParameterModel> list = CaptchaUtils.GetParameters(parameters);

            list.Add(new ParameterModel(DefaultCaptchaManager.LengthAttribute, length));
            return(CaptchaUtils.GenerateCaptcha(htmlHelper, list));
        }
Esempio n. 3
0
        /// <summary>
        ///     Determines whether the captcha is valid, and write error message if need.
        /// </summary>
        /// <param name="controllerBase">
        ///     The specified <see cref="ControllerBase" />.
        /// </param>
        /// <param name="errorText">The specified error message.</param>
        /// <param name="parameters">The specified parameters, if any.</param>
        /// <returns>
        ///     <c>True</c> if the captcha is valid; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsCaptchaValid(this ControllerBase controllerBase, string errorText,
                                          params ParameterModel[] parameters)
        {
            List <ParameterModel> list = CaptchaUtils.GetParameters(parameters);

            list.Add(new ParameterModel(DefaultCaptchaManager.ErrorAttribute, errorText));
            return(CaptchaUtils.ValidateCaptcha(controllerBase, list));
        }
Esempio n. 4
0
        public FileResult Get([FromRoute] string value)
        {
            var info = TranslateUtils.JsonDeserialize <CaptchaUtils.Captcha>(_settingsManager.Decrypt(value));

            var bytes = CaptchaUtils.GetCaptcha(info.Value);

            return(File(bytes, "image/png"));
        }
Esempio n. 5
0
        public FileResult CaptchaGet([FromQuery] string token)
        {
            var captcha = TranslateUtils.JsonDeserialize <CaptchaUtils.Captcha>(_settingsManager.Decrypt(token));

            var bytes = CaptchaUtils.GetCaptcha(captcha.Value);

            return(File(bytes, "image/png"));
        }
Esempio n. 6
0
        /// <summary>
        ///     Creates a new math captcha values with the specified arguments.
        /// </summary>
        /// <param name="controller">
        ///     The specified <see cref="ControllerBase" />.
        /// </param>
        /// <param name="parameters">The specified parameters, if any.</param>
        /// <returns>
        ///     An instance of <see cref="IUpdateInfoModel" />.
        /// </returns>
        public static IUpdateInfoModel GenerateMathCaptchaValue(this ControllerBase controller, params ParameterModel[] parameters)
        {
            List <ParameterModel> list = CaptchaUtils.GetParameters(parameters);

            list.Add(new ParameterModel(DefaultCaptchaManager.MathCaptchaAttribute, true));
            var container = new CombinedParameterContainer(new ParameterModelContainer(list), new RequestParameterContainer(controller.ControllerContext.HttpContext.Request));

            return(controller.GetCaptchaManager().GenerateNew(controller, container));
        }
 /// <summary>
 ///     Called by the ASP.NET MVC framework before the action method executes.
 /// </summary>
 /// <param name="filterContext">The filter context.</param>
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     CaptchaUtils.ValidateCaptcha(filterContext.Controller, new[]
     {
         new ParameterModel(
             DefaultCaptchaManager.ErrorAttribute,
             GetErrorMessage())
     });
 }
Esempio n. 8
0
        /// <summary>
        ///     Creates a new math captcha with the specified arguments.
        /// </summary>
        /// <param name="htmlHelper">
        ///     The specified <see cref="HtmlHelper" />.
        /// </param>
        /// <param name="refreshText">The specified refresh button text.</param>
        /// <param name="inputText">The specified input text.</param>
        /// <param name="parameters">The specified parameters, if any.</param>
        /// <returns>
        ///     An instance of <see cref="ICaptcha" />.
        /// </returns>
        public static ICaptcha MathCaptcha(this HtmlHelper htmlHelper, string refreshText, string inputText,
                                           params ParameterModel[] parameters)
        {
            List <ParameterModel> list = CaptchaUtils.GetParameters(parameters);

            list.Add(new ParameterModel(DefaultCaptchaManager.InputTextAttribute, inputText));
            list.Add(new ParameterModel(DefaultCaptchaManager.RefreshTextAttribute, refreshText));
            list.Add(new ParameterModel(DefaultCaptchaManager.MathCaptchaAttribute, true));
            return(CaptchaUtils.GenerateCaptcha(htmlHelper, list));
        }
Esempio n. 9
0
        /// <summary>
        ///     Refreshes a captcha.
        /// </summary>
        /// <returns>
        ///     An instance of <see cref="ActionResult" />.
        /// </returns>
        public virtual ActionResult Refresh()
        {
            var parameterContainer = new RequestParameterContainer(Request);

            if (Request.IsAjaxRequest())
            {
                IUpdateInfoModel updateInfoModel =
                    CaptchaUtils.CaptchaManagerFactory(parameterContainer).Update(parameterContainer);
                return(CaptchaUtils.BuilderProviderFactory(parameterContainer).RefreshCaptcha(updateInfoModel));
            }
            return(Redirect(Request.UrlReferrer.AbsolutePath));
        }
Esempio n. 10
0
        /// <summary>
        ///     Makes the captcha "intelligent".
        /// </summary>
        /// <param name="captcha">
        ///     The specified <see cref="ICaptcha" />.
        /// </param>
        /// <param name="parameters">The specified parameters, if any.</param>
        /// <returns>
        ///     An instance of <see cref="ICaptcha" />.
        /// </returns>
        public static ICaptcha AsIntelligent(this ICaptcha captcha, params ParameterModel[] parameters)
        {
            List <ParameterModel> list = CaptchaUtils.GetParameters(parameters);
            var container      = new CombinedParameterContainer(new ParameterModelContainer(list), captcha.BuildInfo.ParameterContainer);
            var captchaManager = CaptchaUtils.CaptchaManagerFactory(container);

            if (captchaManager.IntelligencePolicy == null)
            {
                throw new NullReferenceException("The IntelligencePolicy property is null.");
            }
            return(captchaManager.IntelligencePolicy.MakeIntelligent(captchaManager, captcha, container));
        }
Esempio n. 11
0
        /// <summary>
        ///     Creates a new captcha with the specified arguments.
        /// </summary>
        /// <param name="htmlHelper">
        ///     The specified <see cref="HtmlHelper" />.
        /// </param>
        /// <param name="refreshText">The specified refresh button text.</param>
        /// <param name="inputText">The specified input text.</param>
        /// <param name="length">The specified length of characters.</param>
        /// <param name="requiredMessageText">The specified required message text.</param>
        /// <param name="addValidationSpan">
        ///     If <c>true</c> add a span for validation; otherwise <c>false</c>.
        /// </param>
        /// <param name="parameters">The specified parameters, if any.</param>
        /// <returns>
        ///     An instance of <see cref="ICaptcha" />.
        /// </returns>
        public static ICaptcha Captcha(this HtmlHelper htmlHelper, string refreshText, string inputText,
                                       int length, string requiredMessageText, bool addValidationSpan = false,
                                       params ParameterModel[] parameters)
        {
            List <ParameterModel> list = CaptchaUtils.GetParameters(parameters);

            list.Add(new ParameterModel(DefaultCaptchaManager.InputTextAttribute, inputText));
            list.Add(new ParameterModel(DefaultCaptchaManager.RefreshTextAttribute, refreshText));
            list.Add(new ParameterModel(DefaultCaptchaManager.LengthAttribute, length));
            list.Add(new ParameterModel(DefaultCaptchaManager.IsRequiredAttribute, true));
            list.Add(new ParameterModel(DefaultCaptchaManager.RequiredMessageAttribute, requiredMessageText));
            list.Add(new ParameterModel(DefaultCaptchaManager.IsNeedValidationSpanAttribute, addValidationSpan));
            return(CaptchaUtils.GenerateCaptcha(htmlHelper, list));
        }
Esempio n. 12
0
        /// <summary>
        ///     Creates a new math captcha with the specified partial view.
        /// </summary>
        /// <param name="htmlHelper">
        ///     The specified <see cref="HtmlHelper" />.
        /// </param>
        /// <param name="partialViewName">The name of the partial view to render.</param>
        /// <param name="viewData">The view data dictionary for the partial view.</param>
        /// <param name="parameters">The specified parameters, if any.</param>
        /// <returns>
        ///     An instance of <see cref="ICaptcha" />.
        /// </returns>
        public static ICaptcha MathCaptcha(this HtmlHelper htmlHelper, [AspMvcPartialView] string partialViewName,
                                           ViewDataDictionary viewData = null, params ParameterModel[] parameters)
        {
            Validate.ArgumentNotNullOrEmpty(partialViewName, "partialViewName");
            List <ParameterModel> list = CaptchaUtils.GetParameters(parameters);

            list.Add(new ParameterModel(DefaultCaptchaManager.MathCaptchaAttribute, true));
            list.Add(new ParameterModel(DefaultCaptchaManager.PartialViewNameAttribute, partialViewName));
            if (viewData != null)
            {
                list.Add(new ParameterModel(DefaultCaptchaManager.PartialViewDataAttribute, viewData));
            }
            return(CaptchaUtils.GenerateCaptcha(htmlHelper, list));
        }
Esempio n. 13
0
        public StringResult New()
        {
            var captcha = new CaptchaUtils.Captcha
            {
                Value    = CaptchaUtils.GetCode(),
                ExpireAt = DateTime.Now.AddMinutes(10)
            };
            var json = TranslateUtils.JsonSerialize(captcha);

            return(new StringResult
            {
                Value = _settingsManager.Encrypt(json)
            });
        }
Esempio n. 14
0
        /// <summary>
        ///     Generates a new captcha image.
        /// </summary>
        public virtual void Generate()
        {
            var parameterContainer = new RequestParameterContainer(Request);

            try
            {
                if (Request.UrlReferrer.AbsolutePath == Request.Url.AbsolutePath)
                {
                    throw new InvalidOperationException();
                }

                IDrawingModel drawingModel =
                    CaptchaUtils.CaptchaManagerFactory(parameterContainer).GetDrawingModel(parameterContainer);
                CaptchaUtils.BuilderProviderFactory(parameterContainer).WriteCaptchaImage(Response, drawingModel);
            }
            catch (Exception)
            {
                CaptchaUtils.BuilderProviderFactory(parameterContainer).WriteErrorImage(Response);
            }
        }
Esempio n. 15
0
        public IActionResult GenerateCaptcha()
        {
            HttpContext.Session.SetString(nameof(ClientLoginModel.Captcha), CaptchaUtils.GenerateCaptcha(200, 60, out var images).ToLowerInvariant());

            return(File(images, "image/png"));
        }
Esempio n. 16
0
        private static void Main(string[] args)
        {
            var log = new SynkServer.Core.Logger();

            var settings = ServerSettings.Parse(args);

            var server = new HTTPServer(log, settings);
            var site   = new Site(server, "public");

            var keys  = new Dictionary <string, KeyPair>();
            var lines = File.ReadAllLines(rootPath + "keys.txt");

            log.Info("Loadking keys...");
            foreach (var line in lines)
            {
                var temp = line.Split(',');
                var mail = temp[0];
                var key  = temp[1];
                keys[mail] = new KeyPair(key.HexToBytes());
            }
            log.Info($"Loaded {keys.Count} keys!");

            log.Info("Initializing mailboxes...");

            var custom_mailboxes  = new ConcurrentDictionary <string, Mailbox>();
            var default_mailboxes = new ConcurrentDictionary <string, Mailbox>();

            foreach (var entry in keys)
            {
                var mailbox = new Mailbox(entry.Value);
                default_mailboxes[entry.Key] = mailbox;

                if (string.IsNullOrEmpty(mailbox.name))
                {
                    log.Info("Registering mail: " + entry.Key);
                    mailbox.RegisterName(entry.Key);
                }
            }

            if (File.Exists(rootPath + whitelistFileName))
            {
                var xml  = File.ReadAllText(rootPath + whitelistFileName);
                var root = XMLReader.ReadFromString(xml);

                try
                {
                    root = root["users"];

                    foreach (var node in root.Children)
                    {
                        if (node.Name.Equals("whitelistuser"))
                        {
                            var user = node.ToObject <WhitelistUser>();
                            if (user != null)
                            {
                                whitelist.Add(user);
                                whitelistEmailMap[user.email]   = user;
                                whitelistWalletMap[user.wallet] = user;
                            }
                        }
                    }
                }
                catch
                {
                    Console.WriteLine("Error loading whitelist!");
                }
            }

            Console.WriteLine("Initializing server...");

            var cache = new FileCache(log, rootPath);

            Console.CancelKeyPress += delegate {
                Console.WriteLine("Closing service.");
                server.Stop();
                Environment.Exit(0);
            };

            var templateEngine = new TemplateEngine("views");

            site.Get("/", (request) =>
            {
                return(HTTPResponse.FromString(File.ReadAllText(rootPath + "home.html")));
            });

            site.Get("/terms", (request) =>
            {
                return(File.ReadAllBytes(rootPath + "terms.html"));
            });

            site.Get("/demo", (request) =>
            {
                var currentMailbox = request.session.Get <Mailbox>("current", default_mailboxes.Values.FirstOrDefault());
                var context        = new Dictionary <string, object>();

                var mailboxList = default_mailboxes.Values.ToList();

                var customMailbox = request.session.Get <Mailbox>("custom");
                if (customMailbox != null)
                {
                    mailboxList.Add(customMailbox);
                }

                context["mailboxes"] = mailboxList;

                context["currentMailbox"] = currentMailbox.name;
                context["currentAddress"] = currentMailbox.address;

                var mails = new List <MailEntry>();

                lock (currentMailbox)
                {
                    foreach (Mail entry in currentMailbox.messages)
                    {
                        var mail = new MailEntry()
                        {
                            from    = entry.fromAddress.Split('@')[0],
                            subject = entry.subject,
                            body    = entry.body,
                            date    = "12:10 AM"
                        };

                        mails.Insert(0, mail);
                    }
                }

                context["mails"] = mails.ToArray();
                context["empty"] = mails.Count == 0;

                var flash = request.session.Get <string>("flash");
                if (flash != null)
                {
                    context["flash"] = flash;
                    request.session.Remove("flash");
                }

                return(templateEngine.Render(site, context, new string[] { "demo" }));
            });

            site.Get("/demo/inbox/{id}", (request) =>
            {
                var id = request.args["id"];
                if (default_mailboxes.ContainsKey(id))
                {
                    var mailbox = default_mailboxes[id];
                    request.session.Set("current", mailbox);
                }
                else
                if (custom_mailboxes.ContainsKey(id))
                {
                    var mailbox = custom_mailboxes[id];
                    request.session.Set("current", mailbox);
                }
                return(HTTPResponse.Redirect("/demo"));
            });

            site.Post("/demo/custom", (request) =>
            {
                var emailStr = request.args["email"];

                var privateStr = request.args["private"];
                var privateKey = privateStr.HexToBytes();

                if (privateKey.Length == 32)
                {
                    var customKeys = new KeyPair(privateKey);
                    var mailbox    = new Mailbox(customKeys);

                    if (string.IsNullOrEmpty(mailbox.name))
                    {
                        mailbox.RegisterName(emailStr);
                    }
                    else
                    if (mailbox.name != emailStr)
                    {
                        request.session.Set("flash", "Wrong mail for this address");
                        return(HTTPResponse.Redirect("/demo"));
                    }

                    request.session.Set("current", mailbox);
                    request.session.Set("custom", mailbox);

                    if (!custom_mailboxes.ContainsKey(emailStr))
                    {
                        custom_mailboxes[emailStr] = mailbox;
                        lock (mailbox)
                        {
                            mailbox.SyncMessages();
                        }
                    }
                }

                return(HTTPResponse.Redirect("/demo"));
            });

            site.Post("/demo/send", (request) =>
            {
                var to      = request.args["to"];
                var subject = request.args["subject"];
                var body    = request.args["body"];

                var script = NeoAPI.GenerateScript(Protocol.scriptHash, "getAddressFromMailbox", new object[] { to });
                var invoke = NeoAPI.TestInvokeScript(Protocol.net, script);

                var temp = (byte[])invoke.result;
                if (temp != null && temp.Length > 0)
                {
                    var currentMailbox = request.session.Get <Mailbox>("current");

                    if (currentMailbox == null || string.IsNullOrEmpty(currentMailbox.name))
                    {
                        request.session.Set("flash", "Invalid mailbox selected");
                    }
                    else
                    {
                        var msg = Mail.Create(currentMailbox, to, subject, body);

                        try
                        {
                            if (currentMailbox.SendMessage(msg))
                            {
                                request.session.Set("flash", "Your message was sent to " + to);
                            }
                        }

                        catch (Exception e)
                        {
                            request.session.Set("flash", e.Message);
                        }
                    }
                }
                else
                {
                    request.session.Set("flash", to + " is not a valid Phantasma mailbox address");
                }

                return(HTTPResponse.Redirect("/demo"));
            });


            site.Post("/signup", (request) =>
            {
                var fullName = request.GetVariable("whitelist_name");
                var email    = request.GetVariable("whitelist_email");
                var wallet   = request.GetVariable("whitelist_wallet");
                var country  = request.GetVariable("whitelist_country");

                var captcha   = request.GetVariable("whitelist_captcha");
                var signature = request.GetVariable("whitelist_signature");

                string error = null;

                if (string.IsNullOrEmpty(fullName) || fullName.Length <= 5)
                {
                    error = "Full name is invalid";
                }
                else
                if (string.IsNullOrEmpty(email) || !email.Contains("@") || !email.Contains("."))
                {
                    error = "Email is invalid";
                }
                else
                if (string.IsNullOrEmpty(wallet) || !wallet.ToLower().StartsWith("a") || !WalletHelper.IsValidWallet(wallet))
                {
                    error = "Wallet does not seems to be a valid NEO address";
                }
                else
                if (string.IsNullOrEmpty(country))
                {
                    error = "Country is invalid";
                }
                else
                if (string.IsNullOrEmpty(captcha) || !CaptchaUtils.VerifyCatcha(captcha, signature))
                {
                    error = "Captcha is invalid";
                }
                else
                if (PhantasmaSite.whitelistEmailMap.ContainsKey(email))
                {
                    error = "Email already registered";
                }
                else
                if (PhantasmaSite.whitelistWalletMap.ContainsKey(wallet))
                {
                    error = "Wallet already registered";
                }

                var root = DataNode.CreateObject("signup");
                root.AddField("result", error != null ? "fail" : "success");

                if (error != null)
                {
                    root.AddField("error", error);
                }
                else
                {
                    var user     = new WhitelistUser();
                    user.name    = fullName;
                    user.email   = email;
                    user.wallet  = wallet;
                    user.country = country;

                    PhantasmaSite.AddToWhitelist(user);
                }

                var json = JSONWriter.WriteToString(root);
                return(Encoding.UTF8.GetBytes(json));
            });

            site.Get("captcha/", (request) =>
            {
                var content = File.ReadAllText(rootPath + "captcha.html");

                string sign;
                string pic;
                CaptchaUtils.GenerateCaptcha(rootPath + "captcha.fnt", out sign, out pic);

                content = content.Replace("$SIGNATURE", sign).Replace("$CAPTCHA", pic);

                return(Encoding.UTF8.GetBytes(content));
            });

            #region EMAIL SYNC THREAD
            log.Info("Running email thread");

            var emailThread = new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;

                do
                {
                    foreach (var mailbox in default_mailboxes.Values)
                    {
                        try
                        {
                            lock (mailbox)
                            {
                                mailbox.SyncMessages();
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }

                    foreach (var mailbox in custom_mailboxes.Values)
                    {
                        try
                        {
                            lock (mailbox)
                            {
                                mailbox.SyncMessages();
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }

                    var delay = (int)(TimeSpan.FromSeconds(5).TotalMilliseconds);
                    Thread.Sleep(delay);
                } while (true);
            });

            emailThread.Start();
            #endregion

            server.Run();
        }
Esempio n. 17
0
 /// <summary>
 /// Gets the <see cref="ICaptchaBuilderProvider"/> using the specified <see cref="ControllerBase"/>.
 /// </summary>
 /// <param name="controllerBase">The specified <see cref="ControllerBase"/>.</param>
 /// <returns>An instance of <see cref="ICaptchaBuilderProvider"/>.</returns>
 public static ICaptchaBuilderProvider GetCaptchaBuilderProvider(this ControllerBase controllerBase)
 {
     return(CaptchaUtils.BuilderProviderFactory(
                new RequestParameterContainer(controllerBase.ControllerContext.HttpContext.Request)));
 }