Exemple #1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var path = Path.Combine(env.ContentRootPath); 
            var provider = new PhysicalFileProvider(path);
            provider.Watch("*.*");

            // Set up custom content types -associating file extension to MIME type
            var contentTypeProvider = new FileExtensionContentTypeProvider();
            // Add new mappings
            contentTypeProvider.Mappings[".hdr"] = "application/octet-stream";
            contentTypeProvider.Mappings[".babylon"] = "application/json";
            contentTypeProvider.Mappings[".fx"] = "text/plain";
            contentTypeProvider.Mappings[".map"] = "text/plain";

            var options = new StaticFileOptions()
            {
                RequestPath = "",
                FileProvider = provider,
                ContentTypeProvider = contentTypeProvider
            };
            app.UseStaticFiles(options);
        }
        public static IConfigurationBuilder AddYamlFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException("InvalidFilePath", nameof(path));
            }

            if (provider == null && Path.IsPathRooted(path))
            {
                provider = new PhysicalFileProvider(Path.GetDirectoryName(path));
                path = Path.GetFileName(path);
            }
            var source = new YamlConfigurationSource
            {
                FileProvider = provider,
                Path = path,
                Optional = optional,
                ReloadOnChange = reloadOnChange
            };
            builder.Add(source);
            return builder;
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            //use session
            app.UseSession();

            app.UseFileServer();

            var provider = new PhysicalFileProvider(
                Path.Combine(_contentRootPath, "node_modules")
            );
            var _fileServerOptions = new FileServerOptions();
            _fileServerOptions.RequestPath = "/node_modules";
            _fileServerOptions.StaticFileOptions.FileProvider = provider;
            _fileServerOptions.EnableDirectoryBrowsing = true;
            app.UseFileServer(_fileServerOptions);

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //    app.UseDatabaseErrorPage();
            //    app.UseBrowserLink();
            //}
            //else
            //{
            //    app.UseExceptionHandler("/Home/Error");
            //}
            app.UseStatusCodePagesWithRedirects("~/Home/StatusCodePage");

            app.UseExceptionHandler("/Home/Error");
            app.UseStaticFiles();

            app.UseIdentity();

            // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
            app.UseFacebookAuthentication(new FacebookOptions()
            {
                AppId = Configuration["Authentication:Facebook:AppId"],
                AppSecret = Configuration["Authentication:Facebook:AppSecret"]
            });
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                      name: "areaAdmin",
                      template: "{area:exists}/{controller}/{action}/{id?}",
                      defaults: new {controller="Home", action = "Index" }
                      );

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            //SampleData.InitializeDatabaseAsync(app.ApplicationServices).Wait();
        }
        public static IApplicationBuilder UseNodeModules(this IApplicationBuilder app, IHostingEnvironment env)
        {
            var path = Path.Combine(env.ContentRootPath, "node_modules");
            var provider = new PhysicalFileProvider(path);

            var options = new StaticFileOptions();
            options.RequestPath = "/node_modules";
            options.FileProvider = provider;
            app.UseStaticFiles(options);
            return app;
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var physicalFileSystem = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"));
            var options = new FileServerOptions
            {
                EnableDefaultFiles = true,
                FileProvider = physicalFileSystem
            };
            options.StaticFileOptions.FileProvider = physicalFileSystem;
            options.StaticFileOptions.ServeUnknownFileTypes = false;
            options.DefaultFilesOptions.DefaultFileNames = new[] { "index.html" };
            app.UseFileServer(options);
        }
Exemple #6
0
 internal static void AddSingleton <T>(PhysicalFileProvider physicalFileProvider)
 {
     throw new NotImplementedException();
 }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            // this will serve up wwwroot
            app.UseFileServer();

            // this will serve up node_modules
            var provider = new PhysicalFileProvider(
                Path.Combine(_contentRootPath, "node_modules")
            );
            var _fileServerOptions = new FileServerOptions();
            _fileServerOptions.RequestPath = "/node_modules";
            _fileServerOptions.StaticFileOptions.FileProvider = provider;
            _fileServerOptions.EnableDirectoryBrowsing = true;
            app.UseFileServer(_fileServerOptions);

            AutoMapperConfiguration.Configure();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true
            });

            // Custom authentication middleware
            //app.UseMiddleware<AuthMiddleware>();

            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                    // Uncomment the following line to add a route for porting Web API 2 controllers.
                    //routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
                });

            DbInitializer.Initialize(app.ApplicationServices, _applicationPath);
        }
Exemple #8
0
 public StaticWebAssetsFileProvider(string pathPrefix, string contentRoot)
 {
     BasePath      = NormalizePath(pathPrefix);
     InnerProvider = new PhysicalFileProvider(contentRoot);
 }
 public RoxyFilemanProvider(string root)
 {
     _physicalFileProvider = new PhysicalFileProvider(root);
 }
Exemple #10
0
        /// <summary>
        /// Installs WordPress middleware.
        /// </summary>
        /// <param name="app">The application builder.</param>
        /// <param name="path">Physical location of wordpress folder. Can be absolute or relative to the current directory.</param>
        public static IApplicationBuilder UseWordPress(this IApplicationBuilder app, string path = null)
        {
            // wordpress root path:
            if (path == null)
            {
                // bin/wordpress
                path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "/wordpress";

                if (Directory.Exists(path) == false)
                {
                    // cwd/wordpress
                    path = Path.GetDirectoryName(Directory.GetCurrentDirectory()) + "/wordpress";

                    if (Directory.Exists(path) == false)
                    {
                        // cwd/../wordpress
                        path = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory())) + "/wordpress";
                    }
                }
            }

            var root      = System.IO.Path.GetFullPath(path);
            var fprovider = new PhysicalFileProvider(root);

            // log exceptions:
            app.UseDiagnostic();

            // load options
            var options = new WordPressConfig()
                          .LoadFromSettings(app.ApplicationServices)    // appsettings.json
                          .LoadFromEnvironment(app.ApplicationServices) // environment variables (known cloud hosts)
                          .LoadFromOptions(app.ApplicationServices)     // IConfigureOptions<WordPressConfig> service
                          .LoadDefaults();                              //

            // list of plugins:
            var plugins = new WpPluginContainer(options.PluginContainer);

            // response caching:
            if (options.EnableResponseCaching)
            {
                // var cachepolicy = new WpResponseCachingPolicyProvider();
                // var cachekey = app.ApplicationServices.GetService<WpResponseCachingKeyProvider>();

                var cachepolicy = new WpResponseCachePolicy();
                plugins.Add(cachepolicy);

                // app.UseMiddleware<ResponseCachingMiddleware>(cachepolicy, cachekey);
                app.UseMiddleware <WpResponseCacheMiddleware>(new MemoryCache(new MemoryCacheOptions {
                }), cachepolicy);
            }

            // if (options.LegacyPluginAssemblies != null)
            // {
            //     options.LegacyPluginAssemblies.ForEach(name => Context.AddScriptReference(Assembly.Load(new AssemblyName(name))));
            // }

            var wploader = new WpLoader(plugins:
                                        CompositionHelpers.GetPlugins(options.CompositionContainers.CreateContainer(), app.ApplicationServices)
                                        .Concat(plugins.GetPlugins(app.ApplicationServices)));

            // url rewriting:
            app.UseRewriter(new RewriteOptions().Add(context => ShortUrlRule(context, fprovider)));

            // update globals used by WordPress:
            WpStandard.DB_HOST     = options.DbHost;
            WpStandard.DB_NAME     = options.DbName;
            WpStandard.DB_PASSWORD = options.DbPassword;
            WpStandard.DB_USER     = options.DbUser;

            //
            var env = app.ApplicationServices.GetService <IHostingEnvironment>();

            WpStandard.WP_DEBUG = options.Debug || env.IsDevelopment();

            // handling php files:
            var startup = new Action <Context>(ctx =>
            {
                Apply(ctx, options, wploader);
            });

            // app.UsePhp(
            //     prefix: default, // NOTE: maybe we can handle only index.php and wp-admin/*.php ?
            //     configureContext: startup,
            //     rootPath: root);

            app.UsePhp(new PhpRequestOptions()
            {
                ScriptAssembliesName = options.LegacyPluginAssemblies?.ToArray(),
                BeforeRequest        = startup,
                RootPath             = root,
            });

            // static files
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = fprovider
            });

            // fire wp-cron.php asynchronously
            WpCronScheduler.StartScheduler(startup, TimeSpan.FromSeconds(60), root);

            //
            return(app);
        }
        public async Task <ActionResult> Setup(SetupApiViewModel model)
        {
            if (!IsDefaultShell())
            {
                return(this.ChallengeOrForbid("Api"));
            }

            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants))
            {
                return(this.ChallengeOrForbid("Api"));
            }

            if (!String.IsNullOrEmpty(model.UserName) && model.UserName.Any(c => !_identityOptions.User.AllowedUserNameCharacters.Contains(c)))
            {
                ModelState.AddModelError(nameof(model.UserName), S["User name '{0}' is invalid, can only contain letters or digits.", model.UserName]);
            }

            // Only add additional error if attribute validation has passed.
            if (!String.IsNullOrEmpty(model.Email) && !_emailAddressValidator.Validate(model.Email))
            {
                ModelState.AddModelError(nameof(model.Email), S["The email is invalid."]);
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            if (!_shellHost.TryGetSettings(model.Name, out var shellSettings))
            {
                ModelState.AddModelError(nameof(SetupApiViewModel.Name), S["Tenant not found: '{0}'", model.Name]);
            }

            if (shellSettings.State == TenantState.Running)
            {
                return(StatusCode(201));
            }

            if (shellSettings.State != TenantState.Uninitialized)
            {
                return(BadRequest(S["The tenant can't be setup."]));
            }

            var databaseProvider = shellSettings["DatabaseProvider"];

            if (String.IsNullOrEmpty(databaseProvider))
            {
                databaseProvider = model.DatabaseProvider;
            }

            var selectedProvider = _databaseProviders.FirstOrDefault(x => String.Equals(x.Value, databaseProvider, StringComparison.OrdinalIgnoreCase));

            if (selectedProvider == null)
            {
                return(BadRequest(S["The database provider is not defined."]));
            }

            var tablePrefix = shellSettings["TablePrefix"];

            if (String.IsNullOrEmpty(tablePrefix))
            {
                tablePrefix = model.TablePrefix;
            }

            var connectionString = shellSettings["connectionString"];

            if (String.IsNullOrEmpty(connectionString))
            {
                connectionString = model.ConnectionString;
            }

            if (selectedProvider.HasConnectionString && String.IsNullOrEmpty(connectionString))
            {
                return(BadRequest(S["The connection string is required for this database provider."]));
            }

            var recipeName = shellSettings["RecipeName"];

            if (String.IsNullOrEmpty(recipeName))
            {
                recipeName = model.RecipeName;
            }

            RecipeDescriptor recipeDescriptor = null;

            if (String.IsNullOrEmpty(recipeName))
            {
                if (model.Recipe == null)
                {
                    return(BadRequest(S["Either 'Recipe' or 'RecipeName' is required."]));
                }

                var tempFilename = Path.GetTempFileName();

                using (var fs = System.IO.File.Create(tempFilename))
                {
                    await model.Recipe.CopyToAsync(fs);
                }

                var fileProvider = new PhysicalFileProvider(Path.GetDirectoryName(tempFilename));

                recipeDescriptor = new RecipeDescriptor
                {
                    FileProvider   = fileProvider,
                    BasePath       = "",
                    RecipeFileInfo = fileProvider.GetFileInfo(Path.GetFileName(tempFilename))
                };
            }
            else
            {
                var setupRecipes = await _setupService.GetSetupRecipesAsync();

                recipeDescriptor = setupRecipes.FirstOrDefault(x => String.Equals(x.Name, recipeName, StringComparison.OrdinalIgnoreCase));

                if (recipeDescriptor == null)
                {
                    return(BadRequest(S["Recipe '{0}' not found.", recipeName]));
                }
            }

            var setupContext = new SetupContext
            {
                ShellSettings   = shellSettings,
                EnabledFeatures = null, // default list,
                Errors          = new Dictionary <string, string>(),
                Recipe          = recipeDescriptor,
                Properties      = new Dictionary <string, object>
                {
                    { SetupConstants.SiteName, model.SiteName },
                    { SetupConstants.AdminUsername, model.UserName },
                    { SetupConstants.AdminEmail, model.Email },
                    { SetupConstants.AdminPassword, model.Password },
                    { SetupConstants.SiteTimeZone, model.SiteTimeZone },
                    { SetupConstants.DatabaseProvider, selectedProvider.Value },
                    { SetupConstants.DatabaseConnectionString, connectionString },
                    { SetupConstants.DatabaseTablePrefix, tablePrefix },
                }
            };

            var executionId = await _setupService.SetupAsync(setupContext);

            // Check if a component in the Setup failed
            if (setupContext.Errors.Any())
            {
                foreach (var error in setupContext.Errors)
                {
                    ModelState.AddModelError(error.Key, error.Value);
                }

                return(StatusCode(500, ModelState));
            }

            return(Ok(executionId));
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            //FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();
            //provider.Mappings[".image"] = "image/png";
            //provider.Mappings.Remove(".mp4");

            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),
            //    //RequestPath = new PathString("/imgs"),
            //    //ContentTypeProvider = provider,
            //    ContentTypeProvider = new MyContentTypeProvider(),
            //    DefaultContentType = "image/png",
            //    HttpsCompression = HttpsCompressionMode.Compress,
            //    ServeUnknownFileTypes = true,
            //    OnPrepareResponse = (response) =>
            //    {
            //        response.Context.Response.Headers[HeaderNames.CacheControl] = $"public,max-age=31536000";
            //        response.Context.Response.Headers[HeaderNames.Pragma] = $"public,max-age=31536000";
            //        response.Context.Response.Headers[HeaderNames.Expires] = DateTime.UtcNow.AddYears(1).ToString("R");

            //        if (response.Context.Request.Path.StartsWithSegments("/imgs"))
            //        {
            //            if (response.Context.User.Identity.IsAuthenticated)
            //            {
            //                if (response.Context.User.IsInRole("Admin"))
            //                {
            //                    return;
            //                }
            //                else
            //                {
            //                    response.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            //                    throw new UnauthorizedAccessException();
            //                }
            //            }
            //            else
            //            {
            //                response.Context.Response.Redirect("/Identity/Account/Login");
            //            }
            //        }
            //    }
            //});

            //UseDefaultFiles must be called before UseStaticFiles to serve the default file.
            //default.htm default.html index.htm index.html
            //app.UseDefaultFiles();
            // Serve my app-specific default file, if present.
            //DefaultFilesOptions options = new DefaultFilesOptions();
            //options.DefaultFileNames.Clear();
            //options.DefaultFileNames.Add("mydefault.html");
            //app.UseDefaultFiles(options);

            //app.UseStaticFiles(); // For the wwwroot folder
            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),
            //    RequestPath = "/StaticFiles"
            //});

            //app.UseStaticFiles(); // For the wwwroot folder
            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles", "imgs")),
            //    RequestPath = "/MyImages"
            //});
            //app.UseDirectoryBrowser(new DirectoryBrowserOptions
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles", "imgs")),
            //    RequestPath = "/MyImages"
            //});

            //UseFileServer combines the functionality of UseStaticFiles, UseDefaultFiles, and UseDirectoryBrowser.
            //app.UseFileServer();
            //The following code builds upon the parameterless overload by enabling directory browsing:
            //app.UseFileServer(enableDirectoryBrowsing: true);

            //Using the file hierarchy and preceding code, URLs resolve as follows:
            //URI                                               Response
            //http://<server_address>/StaticFiles/imgs/1.png	MyStaticFiles/images/imgs/1.png
            //http://<server_address>/StaticFiles	            MyStaticFiles/default.html
            //app.UseStaticFiles(); // For the wwwroot folder
            //app.UseFileServer(new FileServerOptions
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),
            //    RequestPath = "/MyStaticFiles",
            //UseDirectoryBrowser and UseStaticFiles can leak secrets. Disabling directory browsing in production is highly recommended.
            //Carefully review which directories are enabled via UseStaticFiles or UseDirectoryBrowser.
            //The entire directory and its sub-directories become publicly accessible.
            //Store files suitable for serving to the public in a dedicated directory,
            //such as <content_root>/wwwroot.Separate these files from MVC views, Razor Pages(2.x only), configuration files, etc.
            //    EnableDirectoryBrowsing = false,
            //});

            //https://www.iana.org/assignments/media-types/media-types.xhtml    See MIME content types.
            // Set up custom content types - associating file extension to MIME type
            var provider = new FileExtensionContentTypeProvider();

            // Add new mappings
            provider.Mappings[".myapp"] = "application/x-msdownload";
            provider.Mappings[".htm3"]  = "text/html";
            provider.Mappings[".image"] = "image/png";
            // Replace an existing mapping
            provider.Mappings[".rtf"] = "application/x-msdownload";
            // Remove MP4 videos.
            provider.Mappings.Remove(".mp4");
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider        = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "imgs")),
                RequestPath         = "/MyImages",
                ContentTypeProvider = provider,
                //Warning == Enabling ServeUnknownFileTypes is a security risk.It's disabled by default, and its use is discouraged.
                //FileExtensionContentTypeProvider provides a safer alternative to serving files with non-standard extensions.
                ServeUnknownFileTypes         = true,
                DefaultContentType            = "image/png",
                HttpsCompression              = HttpsCompressionMode.Compress,
                RedirectToAppendTrailingSlash = true,
                OnPrepareResponse             = (sfrc) =>
                {
                    if (sfrc.File.Exists && !sfrc.File.IsDirectory)
                    {
                        var name       = sfrc.File.Name;
                        var lastModify = sfrc.File.LastModified;
                        var length     = sfrc.File.Length;
                        var pp         = sfrc.File.PhysicalPath;
                        if (name.Contains("1") || length > 273519)
                        {
                            sfrc.Context.Response.Redirect("/Identity/Account/Login");
                        }
                    }

                    var startsWithSegmentsImages = sfrc.Context.Request.Path.StartsWithSegments("/MyImages");
                    var isAuthenticated          = sfrc.Context.User.Identity.IsAuthenticated;
                    var isInRoleAdmin            = sfrc.Context.User.IsInRole("Admin");
                    if (startsWithSegmentsImages)
                    {
                        if (isAuthenticated)
                        {
                            if (isInRoleAdmin)
                            {
                                return;
                            }
                            else
                            {
                                sfrc.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                                throw new UnauthorizedAccessException();
                            }
                        }
                        else
                        {
                            sfrc.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                            sfrc.Context.Response.Redirect("/Identity/Account/Login");
                        }
                    }

                    var cachePeriod = env.IsDevelopment() ? "600" : "604800";
                    // Requires the following import:
                    // using Microsoft.AspNetCore.Http;
                    sfrc.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}");

                    if (!sfrc.Context.Request.Cookies.ContainsKey(".AspNetCore.Identity.Application"))
                    {
                        sfrc.Context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    }


                    var headers     = sfrc.Context.Response.Headers;
                    var contentType = headers["Content-Type"];
                    if (contentType != "application/x-gzip" && !sfrc.File.Name.EndsWith(".gz"))
                    {
                        return;
                    }
                    var fileNameToTry    = sfrc.File.Name.Substring(0, sfrc.File.Name.Length - 3);
                    var mimeTypeProvider = new FileExtensionContentTypeProvider();
                    if (mimeTypeProvider.TryGetContentType(fileNameToTry, out var mimeType))
                    {
                        headers.Add("Content-Encoding", "gzip");
                        headers["Content-Type"] = mimeType;
                    }
                }
            });
Exemple #13
0
 //construtor usado para quando FORMOS UTILIZAR ARQUIVOS, COMO NO CASO DO EMAIL
 public LivrosAplicacao(LyfrDBContext context, PhysicalFileProvider provedorDiretoriosArquivos)
 {
     _context = context;
     _provedorDiretoriosArquivos = provedorDiretoriosArquivos;
 }
Exemple #14
0
 public TestFileProvider(IHostingEnvironment env)
 {
     _physicalFileProvider = new PhysicalFileProvider(env.ContentRootPath);
 }
        public async Task <ActionResult> Setup(SetupApiViewModel model)
        {
            if (!IsDefaultShell())
            {
                return(Unauthorized());
            }

            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageTenants))
            {
                return(Unauthorized());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            if (!_shellHost.TryGetSettings(model.Name, out var shellSettings))
            {
                ModelState.AddModelError(nameof(SetupApiViewModel.Name), S["Tenant not found: '{0}'", model.Name]);
            }

            if (shellSettings.State == TenantState.Running)
            {
                return(StatusCode(201));
            }

            if (shellSettings.State != TenantState.Uninitialized)
            {
                return(BadRequest(S["The tenant can't be setup."]));
            }

            var selectedProvider = _databaseProviders.FirstOrDefault(x => String.Equals(x.Value, model.DatabaseProvider, StringComparison.OrdinalIgnoreCase));

            if (selectedProvider == null)
            {
                return(BadRequest(S["The database provider is not defined."]));
            }

            var tablePrefix = shellSettings.TablePrefix;

            if (String.IsNullOrEmpty(tablePrefix))
            {
                tablePrefix = model.TablePrefix;
            }

            var connectionString = shellSettings.ConnectionString;

            if (String.IsNullOrEmpty(connectionString))
            {
                connectionString = model.ConnectionString;
            }

            if (selectedProvider.HasConnectionString && String.IsNullOrEmpty(connectionString))
            {
                return(BadRequest(S["The connection string is required for this database provider."]));
            }

            var recipeName = shellSettings.RecipeName;

            if (String.IsNullOrEmpty(recipeName))
            {
                recipeName = model.RecipeName;
            }

            RecipeDescriptor recipeDescriptor = null;

            if (String.IsNullOrEmpty(recipeName))
            {
                if (model.Recipe == null)
                {
                    return(BadRequest(S["Either 'Recipe' or 'RecipeName' is required."]));
                }

                var tempFilename = Path.GetTempFileName();

                using (var fs = System.IO.File.Create(tempFilename))
                {
                    await model.Recipe.CopyToAsync(fs);
                }

                var fileProvider = new PhysicalFileProvider(Path.GetDirectoryName(tempFilename));

                recipeDescriptor = new RecipeDescriptor
                {
                    FileProvider   = fileProvider,
                    BasePath       = "",
                    RecipeFileInfo = fileProvider.GetFileInfo(Path.GetFileName(tempFilename))
                };
            }
            else
            {
                var setupRecipes = await _setupService.GetSetupRecipesAsync();

                recipeDescriptor = setupRecipes.FirstOrDefault(x => String.Equals(x.Name, recipeName, StringComparison.OrdinalIgnoreCase));

                if (recipeDescriptor == null)
                {
                    return(BadRequest(S["Recipe '{0}' not found.", recipeName]));
                }
            }

            var setupContext = new SetupContext
            {
                ShellSettings            = shellSettings,
                SiteName                 = model.SiteName,
                EnabledFeatures          = null, // default list,
                AdminUsername            = model.UserName,
                AdminEmail               = model.Email,
                AdminPassword            = model.Password,
                Errors                   = new Dictionary <string, string>(),
                Recipe                   = recipeDescriptor,
                SiteTimeZone             = model.SiteTimeZone,
                DatabaseProvider         = selectedProvider.Name,
                DatabaseConnectionString = connectionString,
                DatabaseTablePrefix      = tablePrefix
            };

            var executionId = await _setupService.SetupAsync(setupContext);

            // Check if a component in the Setup failed
            if (setupContext.Errors.Any())
            {
                foreach (var error in setupContext.Errors)
                {
                    ModelState.AddModelError(error.Key, error.Value);
                }

                return(StatusCode(500, ModelState));
            }

            return(Ok(executionId));
        }
Exemple #16
0
 public HostingEnvironment(PhysicalFileProvider outputFileProvider, string mode)
 {
     EnvironmentName     = mode;
     ApplicationName     = typeof(BundleBuilder).Assembly.GetName().Name;
     WebRootFileProvider = outputFileProvider;
 }
Exemple #17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostEnvironment env, CodePasteService codePasteService)
        {
            var options = new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            };

            app.UseForwardedHeaders(options);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();
            app.UseResponseCompression();

            //Static redirect for invite link
            app.Map("/invite", builder =>
            {
                builder.Run(handler =>
                {
                    //TODO: Maybe un-hardcode this?
                    //handler.Response.StatusCode = StatusCodes

                    handler.Response.Redirect("https://aka.ms/csharp-discord");
                    return(Task.CompletedTask);
                });
            });

            // Serve up log files for maintainers only
            app.MapWhen(x => x.Request.Path.Value.StartsWith(_logFilesRequestPath), builder =>
            {
                var fileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "logs"));
                builder
                .UseMiddleware <LogFilesAuthorizationMiddleware>()
                .UseDirectoryBrowser(new DirectoryBrowserOptions()
                {
                    FileProvider = fileProvider,
                    RequestPath  = _logFilesRequestPath
                })
                .UseStaticFiles(new StaticFileOptions()
                {
                    FileProvider          = fileProvider,
                    RequestPath           = _logFilesRequestPath,
                    ServeUnknownFileTypes = true
                });
            });

            //Map to static files when not hitting the API
            app.MapWhen(x => !x.Request.Path.Value.StartsWith("/api"), builder =>
            {
                //Tiny middleware to redirect invalid requests to index.html,
                //this ensures that our frontend routing works on fresh requests
                builder.Use(async(context, next) =>
                {
                    await next();
                    if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
                    {
                        context.Request.Path = "/index.html";
                        await next();
                    }
                })
                .UseDefaultFiles()
                .UseStaticFiles();
            });

            //Defer to MVC for anything that doesn't match (and ostensibly
            //starts with /api)
            app.UseMvcWithDefaultRoute();
        }
        public IActionResult Create(Guid TaskId, IFormFile file, AssignmentViewModel assignment)
        {
            string uniqueFileName = "";

            assignment.Description = HtmlEncoder.Default.Encode(assignment.Description);
            IPAddress remoteIpAddress = Request.HttpContext.Connection.RemoteIpAddress;

            string loggedInUser = User.Identity.Name;
            var    student      = _studentsService.GetStudent(loggedInUser);

            if (Path.GetExtension(file.FileName) == ".pdf")
            {
                byte[] whitelist = new byte[] { 37, 80, 68, 70 };

                if (file != null)
                {
                    MemoryStream userFile = new MemoryStream();

                    using (var f = file.OpenReadStream())
                    {
                        //Reading a number of bytes at the same type(4) and not skipping any(0)
                        byte[] buffer = new byte[4];
                        f.Read(buffer, 0, 4);

                        for (int i = 0; i < whitelist.Length; i++)
                        {
                            if (whitelist[i] != buffer[i])
                            {
                                ModelState.AddModelError("file", "File is not valid nor accepted");
                                return(View());
                            }
                        }
                        f.Position = 0;

                        uniqueFileName  = Guid.NewGuid() + Path.GetExtension(file.FileName);
                        assignment.Path = uniqueFileName;
                        string absolutePath = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "ValueableFiles")).Root + uniqueFileName;


                        f.CopyTo(userFile);
                        var encryptedFile = Encryption.HybridEnryption(userFile, student.PublicKey);

                        try
                        {
                            System.IO.File.WriteAllBytes(absolutePath, encryptedFile.ToArray());
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "Error while saving the file try again later");
                            return(View("Error", new ErrorViewModel()
                            {
                                Message = "Error while saving the file try again later"
                            }));
                        }

                        assignment.Signature = Encryption.SignData(encryptedFile);
                    }

                    assignment.StudentId = student.Id;
                    assignment.TaskId    = TaskId;
                    _assignmentsService.AddAssignment(assignment);
                    _logger.LogInformation(loggedInUser, "User Uploaded a file successfully", remoteIpAddress);
                    return(Redirect("/Home/Index"));
                }
                TempData["error"] = "File is null";
                return(RedirectToAction("Create"));
            }
            TempData["error"] = "Only pdf files";
            return(RedirectToAction("Create"));
        }
Exemple #19
0
        public static IMvcBuilder ConfigureRazorViewToStringRenderer(this IServiceCollection services, string executingAssembly = null)
        {
            var applicationEnvironment = PlatformServices.Default.Application;

            string        applicationName;
            string        path;
            IFileProvider fileProvider;

            if (!string.IsNullOrEmpty(executingAssembly))
            {
                applicationName = Path.GetFileNameWithoutExtension(executingAssembly);
                path            = Path.GetDirectoryName(executingAssembly);
            }
            else
            {
                applicationName = Assembly.GetExecutingAssembly().GetName().Name;
                path            = Directory.GetCurrentDirectory();
            }

            fileProvider = new PhysicalFileProvider(path);

            var environment = new HostingEnvironment
            {
                ContentRootFileProvider = fileProvider,
                ContentRootPath         = path,
                ApplicationName         = applicationName
            };

            services.AddSingleton <IHostEnvironment>(environment);

            services.Configure <MvcRazorRuntimeCompilationOptions>(options =>
            {
                options.FileProviders.Clear();
                options.FileProviders.Add(fileProvider);
            });

            var viewAssemblies = Directory.GetFiles(path, "*.Views.dll").Select(x => Path.GetFileName(x));

            services.AddLogging();

            //var serviceBuilder = services.BuildServiceProvider();
            //var logger = serviceBuilder.GetService<ILogger<RazorViewToStringRenderer>>();

            //logger.LogInformation("RazorViewToStringRenderer is using the following config: {applicationName} - {path}", applicationName, path);
            //logger.LogInformation("RazorViewToStringRenderer is registering the following dlls: {viewAssemblies}", viewAssemblies);

            var diagnosticListener = new DiagnosticListener("Microsoft.AspNetCore");

            services.AddSingleton <DiagnosticSource>(diagnosticListener);
            services.AddSingleton(diagnosticListener);

            services.AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>();
            services.AddSingleton(applicationEnvironment);
            var mvcBuilder = services.AddMvc()
                             .AddViewLocalization()
                             .AddDataAnnotationsLocalization();

            foreach (var viewAssembly in viewAssemblies)
            {
                mvcBuilder.PartManager.ApplicationParts.Add(new CompiledRazorAssemblyPart(Assembly.LoadFile($"{path}\\{viewAssembly}")));
            }
            services.AddScoped <IRazorViewToStringRenderer, RazorViewToStringRenderer>();

            return(mvcBuilder);
        }
Exemple #20
0
        // Policy based authorization, requests must meet the policy criteria to be get access to the resources.
        private static void MapImperativeFiles(IAuthorizationService authorizationService, IApplicationBuilder branch, PhysicalFileProvider files)
        {
            branch.Use(async(context, next) =>
            {
                var fileInfo = files.GetFileInfo(context.Request.Path);
                AuthorizationResult result = null;
                if (fileInfo.Exists)
                {
                    result = await authorizationService.AuthorizeAsync(context.User, fileInfo, "files");
                }
                else
                {
                    // https://github.com/aspnet/Home/issues/2537
                    var dir = files.GetDirectoryContents(context.Request.Path);
                    if (dir.Exists)
                    {
                        result = await authorizationService.AuthorizeAsync(context.User, dir, "files");
                    }
                    else
                    {
                        context.Response.StatusCode = StatusCodes.Status404NotFound;
                        return;
                    }
                }

                if (!result.Succeeded)
                {
                    if (!context.User.Identity.IsAuthenticated)
                    {
                        await context.ChallengeAsync(new AuthenticationProperties()
                        {
                            // https://github.com/aspnet/Security/issues/1730
                            // Return here after authenticating
                            RedirectUri = context.Request.PathBase + context.Request.Path + context.Request.QueryString
                        });
                        return;
                    }
                    // Authenticated but not authorized
                    await context.ForbidAsync();
                    return;
                }

                await next();
            });
            branch.UseFileServer(new FileServerOptions()
            {
                EnableDirectoryBrowsing = true,
                FileProvider            = files
            });
        }
Exemple #21
0
 public FileManagerController(IWebHostEnvironment hostingEnvironment)
 {
     this.basePath  = hostingEnvironment.ContentRootPath;
     this.operation = new PhysicalFileProvider();
     this.operation.RootFolder(this.basePath + "\\wwwroot\\Files"); // Data\\Files denotes in which files and folders are available.
 }
Exemple #22
0
        private readonly static string _embeddedResourceProjectName = "Blazor.Host"; // Note: Not the same as _hostAssembly.Name

        public static IApplicationBuilder UseBlazorUI(this IApplicationBuilder app, string rootPath)
        {
            var staticFilesRoot = Path.GetFullPath(Path.Combine(rootPath, "wwwroot"));
            var fileProvider    = new PhysicalFileProvider(staticFilesRoot);

            var contentTypeProvider = new FileExtensionContentTypeProvider();

            contentTypeProvider.Mappings.Add(".dll", "application/octet-stream");
            contentTypeProvider.Mappings.Add(".exe", "application/octet-stream");
            contentTypeProvider.Mappings.Add(".wasm", "application/octet-stream");

            app.UseDefaultFiles(new DefaultFilesOptions
            {
                FileProvider = fileProvider,
                // RequestPath = requestPath, // TODO: Allow mounting in subdir of URL space
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = fileProvider,
                // RequestPath = requestPath, // TODO: Allow mounting in subdir of URL space
                ContentTypeProvider = contentTypeProvider
            });

            app.UseRazorCompilation(rootPath);

            // For requests under /_framework, serve embedded resources
            app.Map("/_framework", frameworkBuilder =>
            {
                frameworkBuilder.Run(async context =>
                {
                    var pathValue      = context.Request.Path.Value; // e.g., "/browser.js"
                    var resourceName   = pathValue.Replace('/', '.');
                    var resourceStream = _hostAssembly.GetManifestResourceStream($"{_embeddedResourceProjectName}.wwwroot._framework{resourceName}");
                    if (resourceStream != null)
                    {
                        if (contentTypeProvider.TryGetContentType(pathValue, out var contentType))
                        {
                            context.Response.ContentType = contentType;
                        }
                        context.Response.ContentLength = resourceStream.Length;
                        await resourceStream.CopyToAsync(context.Response.Body);
                    }
                    else
                    {
                        context.Response.StatusCode = 404;
                    }
                });
            });

            // For requests under /_bin, serve assemblies from the client app's bin dir
            var clientBinDir = Path.GetFullPath(Path.Combine(rootPath, "bin", "Debug", "netcoreapp1.0"));

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider        = new PhysicalFileProvider(clientBinDir),
                RequestPath         = new PathString("/_bin"),
                ContentTypeProvider = contentTypeProvider
            });

            app.UseLiveReloading();

            // SPA fallback routing - for requests that don't match physical files, and don't appear
            // to be attempts to fetch static files, map them all to /index.html
            app.Use(async(context, next) =>
            {
                var requestPath = context.Request.Path;
                if (!IsStaticFileRequest(requestPath.Value))
                {
                    // TODO: There's probably a better way to return this file using the static files middleware
                    context.Response.ContentType = "text/html";
                    await context.Response.SendFileAsync(Path.Combine(rootPath, "wwwroot", "index.html"));
                }
                else
                {
                    await next();
                }
            });

            return(app);
        }
Exemple #23
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAuthorizationService authorizationService)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();

            //FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();
            //provider.Mappings[".image"] = "image/png";
            //provider.Mappings.Remove(".mp4");

            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),
            //    //RequestPath = new PathString("/imgs"),
            //    //ContentTypeProvider = provider,
            //    ContentTypeProvider = new MyContentTypeProvider(),
            //    DefaultContentType = "image/png",
            //    HttpsCompression = HttpsCompressionMode.Compress,
            //    ServeUnknownFileTypes = true,
            //    OnPrepareResponse = (response) =>
            //    {
            //        response.Context.Response.Headers[HeaderNames.CacheControl] = $"public,max-age=31536000";
            //        response.Context.Response.Headers[HeaderNames.Pragma] = $"public,max-age=31536000";
            //        response.Context.Response.Headers[HeaderNames.Expires] = DateTime.UtcNow.AddYears(1).ToString("R");

            //        if (response.Context.Request.Path.StartsWithSegments("/imgs"))
            //        {
            //            if (response.Context.User.Identity.IsAuthenticated)
            //            {
            //                if (response.Context.User.IsInRole("Admin"))
            //                {
            //                    return;
            //                }
            //                else
            //                {
            //                    response.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            //                    throw new UnauthorizedAccessException();
            //                }
            //            }
            //            else
            //            {
            //                response.Context.Response.Redirect("/Identity/Account/Login");
            //            }
            //        }
            //    }
            //});

            //UseDefaultFiles must be called before UseStaticFiles to serve the default file.
            //default.htm default.html index.htm index.html
            //app.UseDefaultFiles();
            // Serve my app-specific default file, if present.
            //DefaultFilesOptions options = new DefaultFilesOptions();
            //options.DefaultFileNames.Clear();
            //options.DefaultFileNames.Add("mydefault.html");
            //app.UseDefaultFiles(options);

            //app.UseStaticFiles(); // For the wwwroot folder
            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),
            //    RequestPath = "/StaticFiles"
            //});

            //app.UseStaticFiles(); // For the wwwroot folder
            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles", "imgs")),
            //    RequestPath = "/MyImages"
            //});
            //app.UseDirectoryBrowser(new DirectoryBrowserOptions
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles", "imgs")),
            //    RequestPath = "/MyImages"
            //});

            //UseFileServer combines the functionality of UseStaticFiles, UseDefaultFiles, and UseDirectoryBrowser.
            //app.UseFileServer();
            //The following code builds upon the parameterless overload by enabling directory browsing:
            //app.UseFileServer(enableDirectoryBrowsing: true);

            //Using the file hierarchy and preceding code, URLs resolve as follows:
            //URI                                               Response
            //http://<server_address>/StaticFiles/imgs/1.png	MyStaticFiles/images/imgs/1.png
            //http://<server_address>/StaticFiles	            MyStaticFiles/default.html
            //app.UseStaticFiles(); // For the wwwroot folder
            //app.UseFileServer(new FileServerOptions
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),
            //    RequestPath = "/MyStaticFiles",
            //UseDirectoryBrowser and UseStaticFiles can leak secrets. Disabling directory browsing in production is highly recommended.
            //Carefully review which directories are enabled via UseStaticFiles or UseDirectoryBrowser.
            //The entire directory and its sub-directories become publicly accessible.
            //Store files suitable for serving to the public in a dedicated directory,
            //such as <content_root>/wwwroot.Separate these files from MVC views, Razor Pages(2.x only), configuration files, etc.
            //    EnableDirectoryBrowsing = false,
            //});

            //https://www.iana.org/assignments/media-types/media-types.xhtml    See MIME content types.
            // Set up custom content types - associating file extension to MIME type
            var provider = new FileExtensionContentTypeProvider();

            // Add new mappings
            provider.Mappings[".myapp"] = "application/x-msdownload";
            provider.Mappings[".htm3"]  = "text/html";
            provider.Mappings[".image"] = "image/png";
            // Replace an existing mapping
            provider.Mappings[".rtf"] = "application/x-msdownload";
            // Remove MP4 videos.
            provider.Mappings.Remove(".mp4");
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider        = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "imgs")),
                RequestPath         = "/MyImages",
                ContentTypeProvider = provider,
                //Warning == Enabling ServeUnknownFileTypes is a security risk.It's disabled by default, and its use is discouraged.
                //FileExtensionContentTypeProvider provides a safer alternative to serving files with non-standard extensions.
                ServeUnknownFileTypes         = true,
                DefaultContentType            = "image/png",
                HttpsCompression              = HttpsCompressionMode.Compress,
                RedirectToAppendTrailingSlash = true,
                OnPrepareResponse             = (sfrc) =>
                {
                    if (sfrc.File.Exists && !sfrc.File.IsDirectory)
                    {
                        var name       = sfrc.File.Name;
                        var lastModify = sfrc.File.LastModified;
                        var length     = sfrc.File.Length;
                        var pp         = sfrc.File.PhysicalPath;
                        if (name.Contains("1") || length > 273519)
                        {
                            sfrc.Context.Response.Redirect("/Identity/Account/Login");
                        }
                    }

                    var startsWithSegmentsImages = sfrc.Context.Request.Path.StartsWithSegments("/MyImages");
                    var isAuthenticated          = sfrc.Context.User.Identity.IsAuthenticated;
                    var isInRoleAdmin            = sfrc.Context.User.IsInRole("Admin");
                    if (startsWithSegmentsImages)
                    {
                        if (isAuthenticated)
                        {
                            if (isInRoleAdmin)
                            {
                                return;
                            }
                            else
                            {
                                sfrc.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                                throw new UnauthorizedAccessException();
                            }
                        }
                        else
                        {
                            sfrc.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                            sfrc.Context.Response.Redirect("/Identity/Account/Login");
                        }
                    }

                    //var cachePeriod = env.IsDevelopment() ? "600" : "604800";
                    //// Requires the following import:
                    //// using Microsoft.AspNetCore.Http;
                    //sfrc.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}");
                    //sfrc.Context.Response.Headers["Cache-Control"] = "private, max-age=43200";
                    //sfrc.Context.Response.Headers["Expires"] = DateTime.UtcNow.AddHours(12).ToString("R");
                    //const int durationInSeconds = 60 * 60 * 24;
                    //sfrc.Context.Response.Headers[HeaderNames.CacheControl] = "public,max-age=" + durationInSeconds;
                    //sfrc.Context.Response.Headers.Append("Access-Control-Allow-Origin", "*");
                    //sfrc.Context.Response.Headers.Append("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");


                    if (!sfrc.Context.Request.Cookies.ContainsKey(".AspNetCore.Identity.Application"))
                    {
                        sfrc.Context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    }


                    //var headers = sfrc.Context.Response.Headers;
                    //var contentType = headers["Content-Type"];
                    //if (contentType != "application/x-gzip" && !sfrc.File.Name.EndsWith(".gz"))
                    //{
                    //    return;
                    //}
                    //var fileNameToTry = sfrc.File.Name.Substring(0, sfrc.File.Name.Length - 3);
                    //var mimeTypeProvider = new FileExtensionContentTypeProvider();
                    //if (mimeTypeProvider.TryGetContentType(fileNameToTry, out var mimeType))
                    //{
                    //    headers.Add("Content-Encoding", "gzip");
                    //    headers["Content-Type"] = mimeType;
                    //}
                }
            });
            app.UseDirectoryBrowser(new DirectoryBrowserOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "imgs")),
                RequestPath  = "/MyImages",
                RedirectToAppendTrailingSlash = true,
            });

            //Static File Middleware understands almost 400 known file content types
            //If no middleware handles the request, a 404 Not Found response is returned.
            //The following code enables serving unknown types and renders the unknown file as an image:
            //app.UseStaticFiles(new StaticFileOptions
            //{
            //    ServeUnknownFileTypes = true,
            //    DefaultContentType = "image/png"
            //});

            //Complete the following steps in IIS Manager to remove the IIS static file handler at the server or website level:
            //Navigate to the Modules feature.
            //Select StaticFileModule in the list.
            //Click Remove in the Actions sidebar.

            using (ServerManager serverManager = new ServerManager())
            {
                Configuration config = serverManager.GetWebConfiguration("Contoso");

                // var directoryBrowseSection = config.GetSection("system.webServer/directoryBrowse");

                //enabled Optional Boolean attribute.
                //Specifies whether directory browsing is enabled (true) or disabled (false) on the Web server.
                //The default value is false.

                //directoryBrowseSection["enabled"] = true;

                //showFlags Optional flags attribute.
                //The showFlags attribute can have one or more of the following possible values.
                //If you specify more than one value, separate the values with a comma (,).
                //The default values are Date, Time, Size, Extension.
                //Value       Description
                //Date        Includes the last modified date for a file or directory in a directory listing.
                //Extension   Includes a file name extension for a file in a directory listing.
                //LongDate    Includes the last modified date in extended format for a file in a directory listing.
                //None        Specifies that only the file or directory names are returned in a directory listing.
                //Size        Includes the file size for a file in a directory listing.
                //Time        Includes the last modified time for a file or directory in a directory listing.

                //directoryBrowseSection["showFlags"] = @"Date, Time, Size, Extension, LongDate";

                //serverManager.CommitChanges();
            }

            //◘◘◘◘◘◘◘◘

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();


            app.Run(async context =>
            {
                if (context.User?.Identities == null)
                {
                    await context.Response.WriteAsync("No user identities");
                }

                foreach (var id in context.User.Identities)
                {
                    var sb = new StringBuilder();

                    sb.AppendLine("Identity");
                    sb.AppendLine($"  Name: {id.Name}");
                    sb.AppendLine($"  Label: {id.Label}");
                    sb.AppendLine($"  AuthType: {id.AuthenticationType}");
                    sb.AppendLine($"  Authenticated?: {id.IsAuthenticated}");
                    var claims = string.Join(", ", id.Claims.Select(c => c.Value));
                    sb.AppendLine($"  Claims: {claims}");

                    await context.Response.WriteAsync(sb.ToString());
                }
            });


            var files = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "PrivateFiles"));

            app.Map("/MapAuthenticatedFiles", branch =>
            {
                MapAuthenticatedFiles(branch, files);
            });

            app.Map("/MapImperativeFiles", branch =>
            {
                MapImperativeFiles(authorizationService, branch, files);
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
                endpoints.MapRazorPages();
            });
        }
Exemple #24
0
        private static void RegisterModulesDependencies(IServiceCollection services, LeafModulesOptions options)
        {
            // TODO: 어셈블리에서 디펜던시를 판단해서 등록하는 코드를 분리할 것
            var fileProvider = new PhysicalFileProvider(options.BasePath);

            var dllFiles = fileProvider.GetDirectoryContents("");

            if (!dllFiles.Exists)
            {
                return;
            }

            foreach (var dllFile in dllFiles
                     .Where(f => !f.IsDirectory && f.Exists &&
                            Path.GetExtension(f.Name).Equals(@".dll", StringComparison.OrdinalIgnoreCase)))
            {
                // TODO: try catch 처리
                var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(dllFile.PhysicalPath);

                var classes =
                    from type in assembly.GetTypes()
                    let attribute = type.GetCustomAttribute(typeof(DependencyServiceAttribute), true)
                                    where attribute != null
                                    select new { Type = type, Attribute = (DependencyServiceAttribute)attribute };

                foreach (var serviceClass in classes)
                {
                    if (serviceClass.Attribute.ImplemenType != null)
                    {
                        // TODO: ImplementType을 지정한 인터페이스를 구현한 클래스가 아닐 경우 예외를 발생시킬지 결정 - 예외 발생 시 시스템 스타트 오류 처리 필요
                        if (!serviceClass.Attribute.ImplemenType.IsAssignableFrom(serviceClass.Type))
                        {
                            continue;
                        }

                        // TODO: 지정한 인터페이스 형식으로 등록된 클래스가 있을 경우의 처리

                        if (serviceClass.Attribute.Singleton)
                        {
                            services.AddSingleton(serviceClass.Attribute.ImplemenType, serviceClass.Type);
                        }
                        else
                        {
                            services.AddTransient(serviceClass.Attribute.ImplemenType, serviceClass.Type);
                        }
                    }
                    else
                    {
                        if (serviceClass.Attribute.Singleton)
                        {
                            services.AddSingleton(serviceClass.Type);
                        }
                        else
                        {
                            services.AddTransient(serviceClass.Type);
                        }
                    }
                }
            }

            // TODO: Dll 파일의 변경이 있을 때 어플리케이션을 셧다운 - 재시작은 운영체제에 일임 (systemd 나 supervisord 이용)
            // https://www.blakepell.com/asp-net-core-ability-to-restart-your-site-programatically-updated-for-2-0
            // https://www.blakepell.com/asp-net-core-ability-to-restart-your-site-programmatically

            var token = fileProvider.Watch("**/*.dll");

            token.RegisterChangeCallback(state => { options.Shutdown?.Invoke(); }, null);
        }
 public PhysicalFileProviderAdapter(string path)
 {
     _prodider = new PhysicalFileProvider(path);
 }
Exemple #26
0
            public static void Middleware(IApplicationBuilder app)
            {
                if (EnvironmentHelper.IsProduction())
                {
                    app.UseResponseCaching();
                }

                // Root Path and GZip
                app.UseStaticFiles(new StaticFileOptions
                {
                    OnPrepareResponse = (context) =>
                    {
                        var headers          = context.Context.Response.GetTypedHeaders();
                        headers.CacheControl = new CacheControlHeaderValue
                        {
                            MaxAge = Core.SystemConfigs.MvcPath.MaxAgeResponseHeader
                        };
                    }
                });

                // Path and GZip for Statics Content
                string currentDirectory = Directory.GetCurrentDirectory();

                foreach (var staticsContent in Core.SystemConfigs.MvcPath.StaticsContents)
                {
                    string fileProviderPath = string.IsNullOrWhiteSpace(staticsContent.Area)
                        ? Path.Combine(currentDirectory, staticsContent.FolderRelativePath)
                        : Path.Combine(currentDirectory, Core.SystemConfigs.MvcPath.AreasRootFolderName,
                                       staticsContent.Area,
                                       staticsContent.FolderRelativePath);

                    if (!Directory.Exists(fileProviderPath))
                    {
                        // Skip if Directory is not exists
                        continue;
                    }

                    PhysicalFileProvider fileProvider = new PhysicalFileProvider(fileProviderPath);

                    PathString requestPath = new PathString(staticsContent.HttpRequestPath);

                    app.UseStaticFiles(new StaticFileOptions
                    {
                        FileProvider      = fileProvider,
                        RequestPath       = requestPath,
                        OnPrepareResponse = (context) =>
                        {
                            var headers          = context.Context.Response.GetTypedHeaders();
                            headers.CacheControl = new CacheControlHeaderValue
                            {
                                MaxAge = staticsContent.MaxAgeResponseHeader
                            };
                        }
                    });
                }

                // Config Global Route
                app.UseMvc(routes =>
                {
                    routes.MapRoute("areaRoute", "{area:exists}/{controller=Home}/{action=Index}");

                    routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
                });
            }
Exemple #27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = OpenIdConnectDefaults.AuthenticationScheme;
            }).AddOpenIdConnect(options =>
            {
                options.Authority            = $"{Configuration.GetSection("AzureAd").GetSection("Instance").Value}{Configuration.GetSection("AzureAd").GetSection("TenantId").Value}"; //+ this.TenantName; //358d0f13-4eda-45ea-886e-a6dcc6a70ae2
                options.ClientId             = Configuration.GetSection("AzureAd").GetSection("ClientId").Value;
                options.ClientSecret         = Configuration.GetSection("AzureAd").GetSection("ClientSecret").Value;
                options.ResponseType         = OpenIdConnectResponseType.Code;
                options.ResponseMode         = OpenIdConnectResponseMode.FormPost;
                options.CallbackPath         = "/security/signin-callback";
                options.SignedOutRedirectUri = "/home/";
                options.TokenValidationParameters.ValidateIssuer = false;
                options.SaveTokens       = true;
                options.Resource         = Configuration.GetSection("configurations").GetSection("RESOURCE_URL").Value;
                options.UseTokenLifetime = true;
            }).AddCookie();

            IFileProvider physicalProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory());

            services.AddSingleton <IFileProvider>(physicalProvider);

            //services.Configure<CookiePolicyOptions>(options =>
            //{
            //    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            //    options.CheckConsentNeeded = context => false;
            //    options.MinimumSameSitePolicy = SameSiteMode.None;
            //});

            //services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            //  .AddAzureAD(options => Configuration.Bind("AzureAd", options)).AddCookie(OpenIdConnectDefaults.AuthenticationScheme);
            //services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            //{
            //    options.Authority = options.Authority;//+ "/v2.0/"
            //    options.Resource = Configuration.GetSection("configurations").GetSection("RESOURCE_URL").Value;
            //    options.TokenValidationParameters.ValidateIssuer = false;
            //    options.ResponseType = OpenIdConnectResponseType.Code;
            //    options.SaveTokens = true;
            //});
            ////    services.AddMvc(options =>
            ////{
            ////    var policy = new AuthorizationPolicyBuilder()
            ////        .RequireAuthenticatedUser()
            ////        .Build();
            ////    options.Filters.Add(new AuthorizeFilter(policy));
            ////}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDistributedMemoryCache();
            services.AddMvc();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(60);
            });

            services.AddSingleton <DiagnozeService>();
            services.AddSingleton <UserSessionService>();
            services.AddSingleton <LogAnalyticsService>();
            services.AddSingleton <CommonService>();
            services.AddSingleton <RoleAssignmentService>();
        }
        public override List <dynamic> SwapData_In(int nStepSwaps = 1)
        {
            Console.WriteLine("DataSwap IOFiles::");
            Console.WriteLine("\t" + _dirSwap);

            int            result = 0, nums = 0;
            List <string>  errs     = new List <string>();
            List <dynamic> lstDatas = new List <dynamic>();

            nStepSwaps = nStepSwaps <= 0 ? int.MaxValue : nStepSwaps;

            var provider = new PhysicalFileProvider(_dirSwap);
            var contents = provider.GetDirectoryContents(string.Empty);

            Console.WriteLine("\tSwap IOFiles(" + contents.Count() + ")");
            foreach (var item in contents)
            {
                if (item.IsDirectory)
                {
                    continue;
                }
                if (_delayedTime > 0)  //解析时间并校检
                {
                    if ((DateTime.Now - item.LastModified.LocalDateTime).TotalSeconds > _delayedTime)
                    {
                        this.SwapData_BackUp(item.PhysicalPath, _dirSwap_back);
                        continue;
                    }
                }
                string strExtension = System.IO.Path.GetExtension(item.Name);
                if (strExtension != ".json" && strExtension != ".geojson")
                {
                    continue;
                }
                if (item.Name.Substring(0, _tagName.Length) != _tagName)
                {
                    continue;
                }
                if (this.checkNeedAck(item.Name))
                {
                    continue;
                }

                using (System.IO.StreamReader file = System.IO.File.OpenText(item.PhysicalPath))
                {
                    Console.WriteLine("\tnew file swap:: " + item.PhysicalPath);
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        //循环解析文件json数据
                        JObject jsonFile = (JObject)JToken.ReadFrom(reader);
                        if (jsonFile["datas"] != null)
                        {
                            JArray jsonDatas = (JArray)jsonFile["datas"];

                            List <dynamic> lstData = new List <dynamic>();
                            foreach (var jsonData in jsonDatas)
                            {
                                var res = this.CreateData_ClassObj(jsonData);
                                lstData.Add(res);
                            }
                            var data = new { path = file, fileData = lstData };
                            lstDatas.Add(new { tagAck = item.Name, filePath = item.PhysicalPath, dataInfo = jsonFile });
                        }
                        else
                        {
                            var data = new { path = file, fileData = jsonFile };
                            lstDatas.Add(new { tagAck = item.Name, filePath = item.PhysicalPath, dataInfo = jsonFile });
                        }
                    }

                    //记录Ackinfo
                    if (_useAck)
                    {
                        var ackInfo = new DataSwap_AckInfo(item.PhysicalPath, DateTime.Now);
                        _ackInfos[item.Name] = ackInfo;
                    }
                    else
                    {
                        this.SwapData_BackUp(item.PhysicalPath, _dirSwap_back);         // 备份文件
                    }
                    nums++;
                    if (nums >= nStepSwaps)
                    {
                        break;
                    }
                }
            }

            Console.WriteLine("DataSwap IOFiles End." + "\tMargin Swap IOFiles(" + (contents.Count()) + ")\n");
            return(lstDatas);
        }
Exemple #29
0
        public IActionResult IlanEdit(EditIlanModel ilanmodel, List <IFormFile> files)
        {
            if (!ModelState.IsValid)
            {
                var ilan = _ilanService.GetIlanDetail(ilanmodel.IlanId);
                ilanmodel.IlanResimleri = ilan.IlanResimleri;
                ViewBag.Markalar        = _markaService.GetMarkalar();
                ViewBag.Iller           = _ilService.GetIller();
                return(View(ilanmodel));
            }
            var entity = _ilanService.GetById(ilanmodel.IlanId);

            if (entity == null)
            {
                return(NotFound());
            }
            entity.ilanBasligi      = ilanmodel.ilanBasligi;
            entity.ilanDetay        = ilanmodel.ilanDetay;
            entity.ilId             = Convert.ToInt32(ilanmodel.ilId);
            entity.seri             = ilanmodel.seri;
            entity.model            = ilanmodel.model;
            entity.yil              = ilanmodel.yil;
            entity.yakitTipi        = ilanmodel.yakitTipi;
            entity.vitesTipi        = ilanmodel.vitesTipi;
            entity.kilometre        = ilanmodel.kilometre;
            entity.kasaTipi         = ilanmodel.kasaTipi;
            entity.motorGücü        = ilanmodel.motorGücü;
            entity.motorHacmi       = ilanmodel.motorHacmi;
            entity.azamiSurati      = ilanmodel.azamiSurati;
            entity.hizlanma         = ilanmodel.hizlanma;
            entity.cekisTipi        = ilanmodel.cekisTipi;
            entity.sehirIciTuketim  = ilanmodel.sehirIciTuketim;
            entity.sehirDisiTuketim = ilanmodel.sehirDisiTuketim;
            entity.renk             = ilanmodel.renk;
            entity.kimden           = ilanmodel.kimden;
            entity.takas            = ilanmodel.takas;
            entity.durum            = ilanmodel.durum;
            entity.fiyat            = ilanmodel.fiyat;
            entity.markaId          = Convert.ToInt32(ilanmodel.markaId);
            entity.anasayfa         = ilanmodel.anasayfa;
            _ilanService.Update(entity);

            if (files != null)
            {
                foreach (var file in files)
                {
                    if (file.Length > 0)
                    {
                        var fileName         = Path.GetFileName(file.FileName);
                        var myUniqueFileName = Convert.ToString(Guid.NewGuid());
                        var fileExtension    = Path.GetExtension(fileName);
                        var newFileName      = String.Concat(myUniqueFileName, fileExtension);
                        var resim            = new Resim()
                        {
                            url    = newFileName,
                            IlanId = ilanmodel.IlanId,
                        };
                        _ilanResimService.Create(resim);

                        var filepath =
                            new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Images")).Root + $@"\{newFileName}";
                        using (FileStream fs = System.IO.File.Create(filepath))
                        {
                            file.CopyTo(fs);
                            fs.Flush();
                        }
                    }
                }
            }

            return(Redirect("/admin/ilan/list"));
        }
Exemple #30
0
        public override void Configure(BundleCollectionConfigurer bundles)
        {
            var fileProvider = new PhysicalFileProvider(Path.GetDirectoryName(ConfigFilePath));

            bundles.LoadFromConfigFile(Path.GetFileName(ConfigFilePath), fileProvider);
        }
 public RoxyFilemanProvider(string root, ExclusionFilters filters)
 {
     _physicalFileProvider = new PhysicalFileProvider(root, filters);
 }
Exemple #32
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext <NittanDBcontext>(options =>
                                                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


            services.AddSingleton <IFileProvider>(new PhysicalFileProvider(
                                                      Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")));

            services.AddDistributedMemoryCache();

            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                options.IdleTimeout     = TimeSpan.FromDays(1);
                options.Cookie.HttpOnly = true;
            });

            services.AddDistributedMemoryCache();


            services.ConfigureApplicationCookie(options =>
            {
                options.ExpireTimeSpan = TimeSpan.FromDays(1);
            });

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath           = new PathString("/Login/Logout");
                options.LogoutPath          = new PathString("/Login/Logout");
                options.AccessDeniedPath    = new PathString("/Login/Logout");
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                options.Cookie.Expiration   = TimeSpan.FromDays(1);
                options.ExpireTimeSpan      = TimeSpan.FromDays(1);
                options.Events = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = LastChangedValidator.ValidateAsync
                };
            });

            services.AddCors(options =>
            {
                options.AddPolicy("AnyOrigin", builder =>
                {
                    builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod();
                });
            });


            services.AddTransient <MenuMasterService, MenuMasterService>();

            services.AddTransient <InterFaceDBcontext, InterFaceDBcontext>();


            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddScoped <SessionTimeoutAttribute>();

            services.AddHttpContextAccessor();

            services.AddTransient <IUserRepository, UserRepository>();

            services.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN");


            // Add framework services.
            services
            .AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

            IFileProvider physicalProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory());

            services.AddSingleton <IFileProvider>(physicalProvider);

            services.AddTransient <IEmailService, EmailService>();
        }
Exemple #33
0
 public FileManagerController(IHostingEnvironment hostingEnvironment)
 {
     this.basePath  = hostingEnvironment.ContentRootPath;
     this.operation = new PhysicalFileProvider();
     this.operation.RootFolder(this.basePath + "\\" + this.root);
 }
        public static void Main(string[] args)
        {
            {
                #region Snippet_1
                IFileSystem fs = new PhysicalFileProvider(@"C:\Users").ToFileSystem();
                #endregion Snippet_1
            }
            {
                #region Snippet_2
                IFileProvider fp = new PhysicalFileProvider(@"C:\");
                IFileSystem   fs = fp.ToFileSystem(
                    canBrowse: true,
                    canObserve: true,
                    canOpen: true);
                #endregion Snippet_2

                foreach (var line in fs.VisitTree(depth: 2))
                {
                    Console.WriteLine(line);
                }
            }
            {
                #region Snippet_3
                IFileProvider         fp         = new PhysicalFileProvider(@"C:\Users");
                IFileSystemDisposable filesystem = fp.ToFileSystem().AddDisposable(fp);
                #endregion Snippet_3
            }
            {
                #region Snippet_4
                IFileSystemDisposable filesystem = new PhysicalFileProvider(@"C:\Users")
                                                   .ToFileSystem()
                                                   .AddDisposeAction(fs => fs.FileProviderDisposable?.Dispose());
                #endregion Snippet_4
            }
            {
                #region Snippet_5
                using (var fs = new PhysicalFileProvider(@"C:\Users")
                                .ToFileSystem()
                                .AddDisposeAction(f => f.FileProviderDisposable?.Dispose()))
                {
                    fs.Browse("");

                    // Post pone dispose at end of using()
                    IDisposable belateDisposeHandle = fs.BelateDispose();
                    // Start concurrent work
                    Task.Run(() =>
                    {
                        // Do work
                        Thread.Sleep(100);
                        fs.GetEntry("");

                        // Release the belate dispose handle
                        // FileSystem is actually disposed here
                        // provided that the using block has exited
                        // in the main thread.
                        belateDisposeHandle.Dispose();
                    });

                    // using() exists here and starts the dispose fs
                }
                #endregion Snippet_5
            }

            {
                #region Snippet_6
                IFileSystem fs = new PhysicalFileProvider(@"C:\Users").ToFileSystem();
                foreach (var line in fs.VisitTree(depth: 2))
                {
                    Console.WriteLine(line);
                }
                #endregion Snippet_6
            }

            {
                #region Snippet_7
                IFileSystem        fs       = new PhysicalFileProvider(@"C:\Users").ToFileSystem();
                IObserver <IEvent> observer = new Observer();
                using (IDisposable handle = fs.Observe("**", observer))
                {
                }
                #endregion Snippet_7
            }
        }
Exemple #35
0
        public IFileInfo GetFileInfo(string path)
        {
            var physicalFileProvider = new PhysicalFileProvider(Path.GetDirectoryName(path));

            return(physicalFileProvider.GetFileInfo(Path.GetFileName(path)));
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            Core.MakeFilesFolder();
            Core.MakeSpeciesFolder();
            services.AddSingleton <IFileProvider>(new PhysicalFileProvider(Core.FilesFolderPath));
            services.AddMvc();
            services.AddSession();

            // configure strongly typed settings objects
            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get <AppSettings>();
            var key         = Encoding.ASCII.GetBytes(appSettings.Secret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy(RolePolicy.PoliticaRoleAdministrador,
                                  policy => policy.RequireRole(Role.Admin));

                options.AddPolicy(RolePolicy.PoliticaRoleInvitado,
                                  policy => policy.RequireRole(Role.Invitado));

                options.AddPolicy(RolePolicy.PoliticaRoleTodos,
                                  policy => policy.RequireRole(Role.Invitado, Role.Admin));

                options.AddPolicy(RolePolicy.PoliticaRoleAdminDev,
                                  policy => policy.RequireRole(Role.Admin, Role.Desarrollador));
            });

            // configure DI for application services
            services.AddScoped <IAuthService, AuthService>();
            services.AddScoped <IUserRepository, UserRepository>();

            IFileProvider physicalProvider = new PhysicalFileProvider(Core.getServerDirectory());

            services.AddSingleton <IFileProvider>(physicalProvider);
            services.Configure <Settings>(
                options =>
            {
                options.iConfigurationRoot = Configuration;
            });
            services.AddTransient <IIncidentRepository, IncidentRepository>();
            services.AddTransient <IAlertRepository, AlertRepository>();
            services.AddTransient <IImageRepository, ImageRepository>();
            services.AddTransient <IAudioRepository, AudioRepository>();
            services.AddTransient <IStationRepository, StationRepository>();
            services.AddTransient <ILabelRepository, LabelRepository>();
            services.AddTransient <ISensorRepository, SensorRepository>();
            services.AddTransient <IDataRepository, DataRepository>();
            services.AddTransient <IInfoSensoresRepository, InfoSensoresRepository>();
            services.AddTransient <IUserRepository, UserRepository>();
            services.AddTransient <IAnimalRepository, AnimalRepository>();

            services.AddSingleton <AuthService>();
            //services.AddSingleton<UserRepository>();

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                                  builder =>
                {
                    builder.AllowAnyOrigin();
                });
            });
        }