public Handler(DataContext context, ITusUploadUtils tusUploadUtils, IActivityLogger logger) { _logger = logger; _tusUploadUtils = tusUploadUtils; _context = context; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHttpContextAccessor httpContextAccessor, ILogger <Startup> logger, ITusUploadUtils tusUploadUtils, IOptions <FtpServerSettings> config) { if (env.IsDevelopment()) { app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/api", StringComparison.InvariantCultureIgnoreCase), appBuilder => { // Custom API Error handler appBuilder.UseMiddleware <APIErrorHandlingMiddleware>(); } ); app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/api", StringComparison.InvariantCultureIgnoreCase), appBuilder => { // Default mvc error handler appBuilder.UseDeveloperExceptionPage(); } ); } else { app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/api", StringComparison.InvariantCultureIgnoreCase), appBuilder => { // Custom API Error handler appBuilder.UseMiddleware <APIErrorHandlingMiddleware>(); } ); app.UseWhen(ctx => !ctx.Request.Path.StartsWithSegments("/api", StringComparison.InvariantCultureIgnoreCase), appBuilder => { // Default mvc error handler appBuilder.UseExceptionHandler("/Home/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(); app.UseStaticFiles(); app.UseRouting(); app.UseCors("CorsPolicy"); app.UseAuthentication(); app.UseAuthorization(); // To use FTPServer as the storage you must use TusDiskStore instead of CustomTusDiskStore // if you want to use localhost as the storage without config param var uploadLocation = UploadLocationEnum.LocalHost; app.UseTus(httpContext => new DefaultTusConfiguration { // Use TusDiskStore instead of CustomTusDiskStore if you want to use localhost as the storage without config param Store = new TusDiskStore(tusUploadUtils.GetStorePath("uploads", uploadLocation), true, new TusDiskBufferSize(1024 * 1024 * 5, 1024 * 1024 * 5)), // On what url should we listen for uploads? UrlPath = "/api/v1/attachments/add-private-media", Events = new Events { OnAuthorizeAsync = eventContext => { var refreshToken = httpContextAccessor.HttpContext.Request.Cookies["refreshToken"]; if (refreshToken == null) { eventContext.FailRequest(HttpStatusCode.Unauthorized); return(Task.CompletedTask); } // Do other verification on the user; claims, roles, etc. In this case, check the username. // if (eventContext.HttpContext.User.Identity.Name != "test") // { // eventContext.FailRequest(HttpStatusCode.Forbidden, "'test' is the only allowed user"); // return Task.CompletedTask; // } // Verify different things depending on the intent of the request. // E.g.: // Does the file about to be written belong to this user? // Is the current user allowed to create new files or have they reached their quota? // etc etc switch (eventContext.Intent) { case IntentType.CreateFile: break; case IntentType.ConcatenateFiles: break; case IntentType.WriteFile: break; case IntentType.DeleteFile: break; case IntentType.GetFileInfo: break; case IntentType.GetOptions: break; default: break; } return(Task.CompletedTask); }, OnBeforeCreateAsync = async ctx => { var storePath = tusUploadUtils.GetStorePath("uploads", uploadLocation); // If localhost is the storage if (uploadLocation == UploadLocationEnum.LocalHost) { // Create temp directory if it does not exist... Directory.CreateDirectory(storePath); } // If FTP server is the storage if (uploadLocation == UploadLocationEnum.FtpServer) { // create an FTP client FtpClient client = new FtpClient(config.Value.ServerUri, config.Value.ServerPort, config.Value.ServerUsername, config.Value.ServerPassword); // Connecting to the server await client.ConnectAsync(); // check if a folder doesn't exist if (!await client.DirectoryExistsAsync(storePath)) { await client.CreateDirectoryAsync(storePath); } } if (!ctx.Metadata.ContainsKey("name")) { ctx.FailRequest("name metadata must be specified. "); } if (!ctx.Metadata.ContainsKey("type")) { ctx.FailRequest("filetype metadata must be specified. "); } if (!await tusUploadUtils.IsFileTypeAllowed(ctx.Metadata["type"].GetString(Encoding.UTF8), SiteTypeEnum.Blog)) { ctx.FailRequest("Filetype is not allowed!"); } }, OnFileCompleteAsync = async eventContext => { ITusFile file = await eventContext.GetFileAsync(); var refreshToken = httpContextAccessor.HttpContext.Request.Cookies["refreshToken"]; // Saving file information into database await tusUploadUtils.SaveTusFileInfoAsync(file, SiteTypeEnum.Blog, refreshToken, uploadLocation, UploadLinkAccessibilityEnum.Private, eventContext.CancellationToken); // If FTP server is the storage if (uploadLocation == UploadLocationEnum.FtpServer) { // create an FTP client FtpClient client = new FtpClient(config.Value.ServerUri, config.Value.ServerPort, config.Value.ServerUsername, config.Value.ServerPassword); // Connecting to the server await client.DisconnectAsync(); } }, } }); app.UseTus(httpContext => new DefaultTusConfiguration { // Use TusDiskStore instead of CustomTusDiskStore if you want to use localhost as the storage without config param Store = new TusDiskStore( tusUploadUtils.GetStorePath("uploads", uploadLocation, UploadLinkAccessibilityEnum.Private), true, new TusDiskBufferSize(1024 * 1024 * 5, 1024 * 1024 * 5)), // On what url should we listen for uploads? UrlPath = "/api/v1/attachments/add-public-media", Events = new Events { OnAuthorizeAsync = eventContext => { var refreshToken = httpContextAccessor.HttpContext.Request.Cookies["refreshToken"]; if (refreshToken == null) { eventContext.FailRequest(HttpStatusCode.Unauthorized); return(Task.CompletedTask); } // Do other verification on the user; claims, roles, etc. In this case, check the username. // if (eventContext.HttpContext.User.Identity.Name != "test") // { // eventContext.FailRequest(HttpStatusCode.Forbidden, "'test' is the only allowed user"); // return Task.CompletedTask; // } // Verify different things depending on the intent of the request. // E.g.: // Does the file about to be written belong to this user? // Is the current user allowed to create new files or have they reached their quota? // etc etc switch (eventContext.Intent) { case IntentType.CreateFile: break; case IntentType.ConcatenateFiles: break; case IntentType.WriteFile: break; case IntentType.DeleteFile: break; case IntentType.GetFileInfo: break; case IntentType.GetOptions: break; default: break; } return(Task.CompletedTask); }, OnBeforeCreateAsync = async ctx => { var storePath = tusUploadUtils.GetStorePath( "uploads", uploadLocation, UploadLinkAccessibilityEnum.Private); // If localhost is the storage if (uploadLocation == UploadLocationEnum.LocalHost) { // Create temp directory if it does not exist... Directory.CreateDirectory(storePath); } // If FTP server is the storage if (uploadLocation == UploadLocationEnum.FtpServer) { // create an FTP client FtpClient client = new FtpClient(config.Value.ServerUri, config.Value.ServerPort, config.Value.ServerUsername, config.Value.ServerPassword); // Connecting to the server await client.ConnectAsync(); // check if a folder doesn't exist if (!await client.DirectoryExistsAsync(storePath)) { await client.CreateDirectoryAsync(storePath); } } if (!ctx.Metadata.ContainsKey("name")) { ctx.FailRequest("name metadata must be specified. "); } if (!ctx.Metadata.ContainsKey("type")) { ctx.FailRequest("filetype metadata must be specified. "); } if (!await tusUploadUtils.IsFileTypeAllowed(ctx.Metadata["type"].GetString(Encoding.UTF8), SiteTypeEnum.Blog)) { ctx.FailRequest("Filetype is not allowed!"); } }, OnFileCompleteAsync = async eventContext => { ITusFile file = await eventContext.GetFileAsync(); var refreshToken = httpContextAccessor.HttpContext.Request.Cookies["refreshToken"]; // Saving file information into database await tusUploadUtils.SaveTusFileInfoAsync(file, SiteTypeEnum.Blog, refreshToken, uploadLocation, UploadLinkAccessibilityEnum.Public, eventContext.CancellationToken); // If FTP server is the storage if (uploadLocation == UploadLocationEnum.FtpServer) { // create an FTP client FtpClient client = new FtpClient(config.Value.ServerUri, config.Value.ServerPort, config.Value.ServerUsername, config.Value.ServerPassword); // Connecting to the server await client.DisconnectAsync(); } }, } }); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }