Пример #1
0
        // 每次请求都会触发,一个页面会触发多次
        protected override void RequestStartup(TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines, NancyContext context)
        {
            base.RequestStartup(container, pipelines, context);

            var formsAuthConfiguration = new FormsAuthenticationConfiguration()
            {
                RedirectUrl = "~/account/logon",
                UserMapper  = container.Resolve <IUserMapper>(),
            };

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);

            // Enabling sessions in Nancy
            CookieBasedSessions.Enable(pipelines);

            //放RequestStartup这里是每次请求时判断session,为了避免session过期,所以不放在ApplicationStartup
            pipelines.BeforeRequest += (ctx) => {
                var uid  = ctx.Request.Session["TempUserId"];
                var user = ctx.CurrentUser;
                if (user == null && uid == null)
                {
                    ctx.Request.Session["TempUserId"] = "temp-" + Guid.NewGuid().ToString();
                }
                return(null);
            };
        }
Пример #2
0
 protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
 {
     base.ApplicationStartup(container, pipelines);
     //是否启用错误显示
     StaticConfiguration.DisableErrorTraces = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["disableError"]);
     CookieBasedSessions.Enable(pipelines);
 }
Пример #3
0
        //=============================================================================================/
        /// <summary>
        /// アプリケーションパイプラインの設定
        /// Session を有効にし、全てのリクエスト処理の前にユーザー情報の保存をする
        /// </summary>
        /// <param name="container"></param>
        /// <param name="pipelines"></param>
        //=============================================================================================/
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);
            CookieBasedSessions.Enable(pipelines);

            //pipelines.BeforeRequest += setUserSession;
        }
Пример #4
0
        // The bootstrapper enables you to reconfigure the composition of the framework,
        // by overriding the various methods and properties.
        // For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper
        // Nancy.Bootstrappers.Autofac

        ////https://github.com/nancyfx/nancy.bootstrappers.autofac
        ////http://stackoverflow.com/questions/17325840/registering-startup-class-in-nancy-using-autofac-bootstrapper

        protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines)
        {
            StaticConfiguration.DisableErrorTraces = false;
            // No registrations should be performed in here, however you may
            // resolve things that are needed during application startup.
            CookieBasedSessions.Enable(pipelines, Nancy.Cryptography.CryptographyConfiguration.Default);
        }
Пример #5
0
            protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
            {
                base.ApplicationStartup(container, pipelines);
                CookieBasedSessions.Enable(pipelines);

                pipelines.OnError += (context, exception) =>
                {
                    if (exception is NameNotFoundException)
                    {
                        return new Response
                               {
                                   StatusCode  = HttpStatusCode.NotFound,
                                   ContentType = "text/html",
                                   Contents    = (stream) =>
                                   {
                                       var errorMessage = Encoding.UTF8.GetBytes(exception.Message);
                                       stream.Write(errorMessage, 0, errorMessage.Length);
                                   }
                               }
                    }
                    ;
                    return(HttpStatusCode.InternalServerError);
                };
            }
        }
Пример #6
0
 protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
 {
     //enable the cookie
     CookieBasedSessions.Enable(pipelines);
     //Prevent errors on Linux
     StaticConfiguration.DisableErrorTraces = false;
 }
Пример #7
0
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            CookieBasedSessions.Enable(pipelines, CryptographyConfiguration.Default);

            StaticConfiguration.DisableErrorTraces = false;

            base.ApplicationStartup(container, pipelines);

            var settings = new SettingsServiceV2 <PlexRequestSettings>(new SettingsJsonRepository(new DbConfiguration(new SqliteFactory()), new MemoryCacheProvider()));
            var baseUrl  = settings.GetSettings().BaseUrl;
            var redirect = string.IsNullOrEmpty(baseUrl) ? "~/login" : $"~/{baseUrl}/login";

            // Enable forms auth
            var formsAuthConfiguration = new FormsAuthenticationConfiguration
            {
                RedirectUrl = redirect,
                UserMapper  = container.Resolve <IUserMapper>()
            };

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            ServicePointManager.ServerCertificateValidationCallback +=
                (sender, certificate, chain, sslPolicyErrors) => true;
        }
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            // Add an error handler to catch our entity not found exceptions
            pipelines.OnError += (context, exception) =>
            {
                // If we've raised an EntityNotFound exception in our data layer
                if (exception is EntityNotFoundException)
                {
                    return new Response()
                           {
                               StatusCode  = HttpStatusCode.NotFound,
                               ContentType = "text/html",
                               Contents    = (stream) =>
                               {
                                   var errorMessage = Encoding.UTF8.GetBytes("A Data Entity with the requested ID was not found in the database.");
                                   stream.Write(errorMessage, 0, errorMessage.Length);
                               }
                           }
                }
                ;

                // If none of the above handles our exception, then pass it on as a 500
                throw exception;
            };
            // End error handler

            CookieBasedSessions.Enable(pipelines);
        }
    }
Пример #9
0
        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
        {
            var formsAuthConfiguration =
                new FormsAuthenticationConfiguration()
            {
                RedirectUrl = "~/login",
                UserMapper  = container.Resolve <IUserMapper>(),
            };


            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
            CookieBasedSessions.Enable(pipelines);

            pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx =>
            {
                if (Helper.Settings.Instance.Client.CanConnect)
                {
                    return(null);
                }
                else
                {
                    if (String.Compare(ctx.Request.Path, "/notavailable", true) == 0)
                    {
                        return(null);
                    }
                    return(new RedirectResponse("/notavailable"));
                }
            });

            base.RequestStartup(container, pipelines, context);
        }
Пример #10
0
        protected override void ApplicationStartup(IKernel container, IPipelines pipelines)
        {
            Debug.WriteLine("Bootstrapper.ApplicationStartup");
            ConfigureContainer(container);

            JsonSettings.MaxJsonLength = int.MaxValue;

            CookieBasedSessions.Enable(pipelines, CryptographyConfiguration.Default);
            StaticConfiguration.DisableErrorTraces = false;

            base.ApplicationStartup(container, pipelines);


            var settings = new SettingsServiceV2 <PlexRequestSettings>(new SettingsJsonRepository(new DbConfiguration(new SqliteFactory()), new MemoryCacheProvider()));
            var baseUrl  = settings.GetSettings().BaseUrl;
            var redirect = string.IsNullOrEmpty(baseUrl) ? "~/login" : $"~/{baseUrl}/login";

            // Enable forms auth
            var config = new CustomAuthenticationConfiguration
            {
                RedirectUrl         = redirect,
                PlexUserRepository  = container.Get <IPlexUserRepository>(),
                LocalUserRepository = container.Get <IUserRepository>()
            };

            CustomAuthenticationProvider.Enable(pipelines, config);

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            ServicePointManager.ServerCertificateValidationCallback +=
                (sender, certificate, chain, sslPolicyErrors) => true;

            ServicePointManager.Expect100Continue = false;
        }
Пример #11
0
        // The bootstrapper enables you to reconfigure the composition of the framework,
        // by overriding the various methods and properties.
        // For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper

        protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            StaticConfiguration.DisableErrorTraces = false;
            CookieBasedSessions.Enable(pipelines);
        }
Пример #12
0
        public void Should_add_response_cookie_if_it_has_changed()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline  = new AfterPipeline();
            var hooks          = A.Fake <IApplicationPipelines>();

            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);
            CookieBasedSessions.Enable(hooks, encryptionProvider, hmacProvider, "this passphrase", "this is a salt", "hmac passphrase").WithFormatter(new Fakes.FakeSessionObjectFormatter());
            var request = CreateRequest("encryptedkey1=value1");

            A.CallTo(() => this.encryptionProvider.Decrypt("encryptedkey1=value1", A <string> .Ignored, A <byte[]> .Ignored)).Returns("key1=value1;");
            var response     = A.Fake <Response>();
            var nancyContext = new NancyContext()
            {
                Request = request, Response = response
            };

            beforePipeline.Invoke(nancyContext);
            request.Session["Testing"] = "Test";

            afterPipeline.Invoke(nancyContext);

            response.Cookies.Count.ShouldEqual(1);
        }
Пример #13
0
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            pipelines.AfterRequest += ctx =>
            {
                if (ctx.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    ctx.Response = new RedirectResponse("/Error/NotFound?returnUrl=" + Uri.EscapeDataString(ctx.Request.Path));
                }
            };
            container.Register <IUserMapper, UserMapper>();//Forms 认证
            var formsAuthConfiguration = new FormsAuthenticationConfiguration()
            {
                RedirectUrl = "~/Login",
                UserMapper  = container.Resolve <IUserMapper>(),
            };

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);

            //启用Session
            CookieBasedSessions.Enable(pipelines);

            pipelines.OnError += Error;
        }
Пример #14
0
        protected override void ApplicationStartup(TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            CookieBasedSessions.Enable(pipelines);

            Conventions.ViewLocationConventions.Add((viewName, model, context) => string.Concat("views/", viewName));

            Conventions.StaticContentsConventions.Add(
                StaticContentConventionBuilder.AddDirectory("assets", @"assets")
                );

            container.Register <IFlexUserStore, FlexMembershipUserStore <User, Role> >();
            container.Register(typeof(IDocumentStore), InitDocStore());
            container.Register(typeof(IDocumentSession), (c, overloads) =>
                               c.Resolve <IDocumentStore>().OpenSession());

            var cryptographyConfiguration = new CryptographyConfiguration(
                new RijndaelEncryptionProvider(new PassphraseKeyGenerator(Configuration.EncryptionKey, new byte[] { 8, 2, 10, 4, 68, 120, 7, 14 })),
                new DefaultHmacProvider(new PassphraseKeyGenerator(Configuration.HmacKey, new byte[] { 1, 20, 73, 49, 25, 106, 78, 86 })));

            var authenticationConfiguration =
                new FormsAuthenticationConfiguration()
            {
                CryptographyConfiguration = cryptographyConfiguration,
                RedirectUrl = "/login",
                UserMapper  = container.Resolve <IUserMapper>(),
            };

            FormsAuthentication.Enable(pipelines, authenticationConfiguration);

            FlexMembershipProvider.RegisterClient(
                new GoogleOpenIdClient(),
                "Google", new Dictionary <string, object>());
        }
Пример #15
0
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            StaticConfiguration.EnableHeadRouting = true;

            pipelines.AfterRequest += ctx =>
            {
                if (SystemConfig.ApiCros)
                {
                    ctx.Response.Headers["Access-Control-Allow-Origin"]  = "*";
                    ctx.Response.Headers["Access-Control-Allow-Headers"] = "Content-Type";
                    ctx.Response.Headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS";
                }
                if (ctx.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    ctx.Response = new RedirectResponse("/Error/NotFound?returnUrl=" + Uri.EscapeDataString(ctx.Request.Path));
                }
            };
            container.Register <IUserMapper, UserMapper>();//Forms 认证
            var formsAuthConfiguration = new FormsAuthenticationConfiguration()
            {
                RedirectUrl = "~/Login",
                UserMapper  = container.Resolve <IUserMapper>(),
            };

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);

            //启用Session
            CookieBasedSessions.Enable(pipelines);

            pipelines.OnError += Error;
        }
Пример #16
0
        public void Should_add_response_cookie_if_it_has_changed()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline  = new AfterPipeline();
            var hooks          = A.Fake <IPipelines>();

            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);
            CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(this.fakeObjectSerializer);
            var request = CreateRequest("encryptedkey1=value1");

            A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;");
            var response     = A.Fake <Response>();
            var nancyContext = new NancyContext()
            {
                Request = request, Response = response
            };

            beforePipeline.Invoke(nancyContext, new CancellationToken());
            request.Session["Testing"] = "Test";

            afterPipeline.Invoke(nancyContext, new CancellationToken());

            response.Cookies.Count.ShouldEqual(1);
        }
 protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
 {
     base.ApplicationStartup(container, pipelines);
     this.Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("Scripts"));
     CookieBasedSessions.Enable(pipelines);
     RouteTable.Routes.MapHubs();
 }
Пример #18
0
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            pipelines.AfterRequest += ctx =>
            {
                ctx.Response.Headers.Add("Access-Control-Allow-Origin", Config.CloudUrl);
                ctx.Response.Headers.Add("Access-Control-Allow-Methods", "GET,PUT,OPTIONS");
                ctx.Response.Headers.Add("Access-Control-Allow-Headers", "Accept, Origin, Content-type, Keep-Alive, Cache-Control");
                ctx.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
            };

            pipelines.OnError += (ctx, ex) =>
            {
                Debug.LogException(ex);
                return(HttpStatusCode.InternalServerError);
            };

            var cryptographyConfiguration = new CryptographyConfiguration(
                new NoEncryptionProvider(),
                new DefaultHmacProvider(new PassphraseKeyGenerator("passphrase", Config.salt)));

            var formsAuthConfiguration = new FormsAuthenticationConfiguration()
            {
                CryptographyConfiguration = cryptographyConfiguration,
                DisableRedirect           = true,
                UserMapper = container.Resolve <IUserMapper>(),
            };

            FormsAuthentication.FormsAuthenticationCookieName = "sim";

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);

            CookieBasedSessions.Enable(pipelines, cryptographyConfiguration);
        }
Пример #19
0
 protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
 {
     base.ApplicationStartup(container, pipelines);
     StaticConfiguration.Caching.EnableRuntimeViewUpdates = true;
     StaticConfiguration.DisableErrorTraces = false;
     CookieBasedSessions.Enable(pipelines);
 }
Пример #20
0
        protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            try
            {
                XDocument xDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/Config/settings.xml"));

                /* Load CloudPanel Settings */
                var settings = from s in xDoc.Elements("Settings")
                               select s;

                foreach (var s in settings)
                {
                    Settings.HostingOU     = s.Element("HostingOU").Value;
                    Settings.PrimaryDC     = s.Element("DomainController").Value;
                    Settings.Username      = s.Element("Username").Value;
                    Settings.Password      = s.Element("Password").Value;
                    Settings.SuperAdmins   = s.Element("SuperAdmins").Value;
                    Settings.BillingAdmins = s.Element("BillingAdmins").Value;
                }

                /* Load Exchange Settings */
                var exchange = from s in xDoc.Elements("Exchange")
                               select s;

                foreach (var s in exchange)
                {
                    Settings.ExchangeServer   = s.Element("Server").Value;
                    Settings.ExchangePFServer = s.Element("PFServer").Value;

                    int defaultVersion = 2013;
                    int.TryParse(s.Element("Version").Value, out defaultVersion);
                    Settings.Version = defaultVersion;

                    bool defaultBool = true;
                    bool.TryParse(s.Element("SSL").Value, out defaultBool);
                    Settings.ExchangeSSL = defaultBool;

                    Settings.ExchangeConnection = s.Element("Connection").Value;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }


            CookieBasedSessions.Enable(pipelines);

            base.ApplicationStartup(container, pipelines);

            /*var authenticationConfiguration =
             *  new FormsAuthenticationConfiguration
             *  {
             *      RedirectUrl = "~/login",
             *      UserMapper = container.Resolve<IUserMapper>(),
             *  };
             *
             * FormsAuthentication.Enable(pipelines, authenticationConfiguration);*/
        }
        public static void Enable(IPipelines pipelines, AuthenticationConfig config)
        {
            _config = config;
            _users  = new Dictionary <string, Auth0User>();

            pipelines.BeforeRequest.AddItemToStartOfPipeline(LoadCurrentUser);
            CookieBasedSessions.Enable(pipelines);
        }
Пример #22
0
        public BrowserFixture()
        {
            var bootstrapper =
                new ConfigurableBootstrapper(config => config.Modules(typeof(EchoModule)));

            CookieBasedSessions.Enable(bootstrapper);

            this.browser = new Browser(bootstrapper);
        }
Пример #23
0
        protected override void ApplicationStartup(Autofac.ILifetimeScope container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            CookieBasedSessions.Enable(pipelines);
            base.ApplicationStartup(container, pipelines);

            GlobalHost.DependencyResolver = new AutofacDependencyResolver(container);
            RouteTable.Routes.MapHubs();
            PublishrBootstrapper.Init();
        }
Пример #24
0
 protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
 {
     base.ApplicationStartup(container, pipelines);
     CookieBasedSessions.Enable(pipelines);
     //指定视图所在目录
     this.Conventions.ViewLocationConventions.Add((viewName, model, context) =>
     {
         return(string.Concat("Viewer/", viewName));
     });
 }
Пример #25
0
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            Console.WriteLine("App startup");
            base.ApplicationStartup(container, pipelines);
            CryptographyConfiguration defaultCc = CryptographyConfiguration.Default;

            var customEncryptionProvider       = new RijndaelEncryptionProvider(new CustomKeyGenerator());
            CryptographyConfiguration customCc = new CryptographyConfiguration(customEncryptionProvider, defaultCc.HmacProvider);

            CookieBasedSessions.Enable(pipelines, defaultCc);
        }
Пример #26
0
        protected override void ApplicationStartup(IKernel container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            Csrf.Enable(pipelines);

            CookieBasedSessions.Enable(pipelines);

            pipelines.BeforeRequest.AddItemToStartOfPipeline(FlowPrincipal);
            pipelines.BeforeRequest.AddItemToStartOfPipeline(SetCulture);
        }
Пример #27
0
        protected override void ApplicationStartup(StructureMap.IContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);

            StaticConfiguration.DisableCaches      = true;
            StaticConfiguration.DisableErrorTraces = false;

            this.Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("Scripts"));

            CookieBasedSessions.Enable(pipelines);
        }
Пример #28
0
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);
            //need to replace default CryptographyConfiguration for the form authentication
            //because defaut KeyGenerator generate on each app startup new keys and cookies invalidate after that
            this._cryptographyConfiguration = new CryptographyConfiguration(
                new RijndaelEncryptionProvider(new PassphraseKeyGenerator("SuperSecretPass", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })),
                new DefaultHmacProvider(new PassphraseKeyGenerator("UberSuperSecure1", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 })));

            CookieBasedSessions.Enable(pipelines);
        }
Пример #29
0
 protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
 {
     CookieBasedSessions.Enable(pipelines);
     pipelines.AfterRequest.AddItemToEndOfPipeline((ctx) =>
     {
         ctx.Response.WithHeader("Access-Control-Allow-Origin", "http://localhost:3000")
         .WithHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS")
         .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type, Credentials")
         .WithHeader("Access-Control-Expose-Headers", "Accept, Origin, Content-type, Credentials")
         .WithHeader("Access-Control-Allow-Credentials", "true");
     });
 }
Пример #30
0
        protected override void RequestStartup(ILifetimeScope container, IPipelines pipelines, NancyContext context)
        {
            base.RequestStartup(container, pipelines, context);
            var formsAuthConfiguration = new FormsAuthenticationConfiguration()
            {
                RedirectUrl = "~/login",
                UserMapper  = container.Resolve <IUserMapper>(),
            };

            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);
            CookieBasedSessions.Enable(pipelines);
        }