|
| 1 | +using Microsoft.AspNetCore.Mvc; |
| 2 | +using Microsoft.Extensions.Logging; |
| 3 | +using SecureFileSharingApp.Helpers; |
| 4 | +using SecureFileSharingApp.Models; |
| 5 | +using System; |
| 6 | +using System.IO; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using SecureFileSharingApp.Services; |
| 9 | +using Microsoft.AspNetCore.Hosting; |
| 10 | +using System.Net.Sockets; |
| 11 | +using System.Net; |
| 12 | + |
| 13 | + |
| 14 | +namespace SecureFileSharingApp.Controllers |
| 15 | +{ |
| 16 | + [ApiController] |
| 17 | + [Route("api/[controller]")] |
| 18 | + public class FileController : ControllerBase |
| 19 | + { |
| 20 | + private readonly ILogger<FileController> _logger; |
| 21 | + private readonly IWebHostEnvironment _env; |
| 22 | + private readonly IConfiguration _configuration; |
| 23 | + private readonly MailService _mailService; // Inject MailService |
| 24 | + private static readonly string[] allowedExtensions = { ".pdf", ".docx", ".xlsx", ".csv", ".txt" }; |
| 25 | + |
| 26 | + public FileController(ILogger<FileController> logger, |
| 27 | + IWebHostEnvironment env, |
| 28 | + IConfiguration configuration, |
| 29 | + MailService mailService) // Add MailService to constructor |
| 30 | + { |
| 31 | + _logger = logger; |
| 32 | + _env = env; |
| 33 | + _configuration = configuration; |
| 34 | + _mailService = mailService; // Assign MailService instance |
| 35 | + } |
| 36 | + |
| 37 | + [HttpPost("upload")] |
| 38 | + public async Task<IActionResult> UploadFile([FromForm] FileUploadRequest request, [FromForm] string folder = "default") |
| 39 | + { |
| 40 | + var file = request.File; |
| 41 | + |
| 42 | + if (file == null || file.Length == 0) |
| 43 | + return BadRequest("No file selected."); |
| 44 | + |
| 45 | + var extension = Path.GetExtension(file.FileName).ToLowerInvariant(); |
| 46 | + if (!allowedExtensions.Contains(extension)) |
| 47 | + return BadRequest("Unsupported file type."); |
| 48 | + |
| 49 | + var rootPath = Path.Combine(_env.ContentRootPath, "EncryptedFiles", folder); |
| 50 | + Directory.CreateDirectory(rootPath); |
| 51 | + |
| 52 | + // File versioning |
| 53 | + string fileName = Path.GetFileNameWithoutExtension(file.FileName); |
| 54 | + string ext = Path.GetExtension(file.FileName); |
| 55 | + string fullPath = Path.Combine(rootPath, file.FileName); |
| 56 | + int version = 1; |
| 57 | + |
| 58 | + while (System.IO.File.Exists(fullPath)) |
| 59 | + { |
| 60 | + fullPath = Path.Combine(rootPath, $"{fileName}_v{version}{ext}"); |
| 61 | + version++; |
| 62 | + } |
| 63 | + |
| 64 | + try |
| 65 | + { |
| 66 | + using (var stream = file.OpenReadStream()) |
| 67 | + { |
| 68 | + await FileEncryptionHelper.EncryptAndSaveFileAsync(stream, fullPath); |
| 69 | + } |
| 70 | + |
| 71 | + // Antivirus scan (if needed) |
| 72 | + //var isClean = await ScanWithClamAV(fullPath); |
| 73 | + //if (!isClean) |
| 74 | + //{ |
| 75 | + // System.IO.File.Delete(fullPath); |
| 76 | + // return BadRequest("File contains a virus."); |
| 77 | + //} |
| 78 | + |
| 79 | + // Use MailService to send email |
| 80 | + //await _mailService.SendEmailAsync("File Uploaded", |
| 81 | + //$"File '{Path.GetFileName(fullPath)}' was uploaded to folder '{folder}'."); |
| 82 | + |
| 83 | + _logger.LogInformation("File uploaded: {FileName}", file.FileName); |
| 84 | + return Ok("File uploaded, encrypted, and scanned successfully."); |
| 85 | + } |
| 86 | + catch (Exception ex) |
| 87 | + { |
| 88 | + _logger.LogError(ex, "Upload failed for file: {FileName}", file.FileName); |
| 89 | + return StatusCode(500, "File upload failed."); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + [HttpGet("download")] |
| 94 | + public async Task<IActionResult> DownloadFile([FromQuery] string fileName, [FromQuery] string folder = "default") |
| 95 | + { |
| 96 | + string filePath = Path.Combine(_env.ContentRootPath, "EncryptedFiles", folder, fileName); |
| 97 | + |
| 98 | + if (!System.IO.File.Exists(filePath)) |
| 99 | + { |
| 100 | + _logger.LogWarning("File not found: {FileName}", fileName); |
| 101 | + return NotFound("File not found."); |
| 102 | + } |
| 103 | + |
| 104 | + try |
| 105 | + { |
| 106 | + var memoryStream = new MemoryStream(); |
| 107 | + await FileEncryptionHelper.DecryptFileAsync(filePath, memoryStream); |
| 108 | + memoryStream.Position = 0; |
| 109 | + |
| 110 | + // Use MailService to send email on download |
| 111 | + //await _mailService.SendEmailAsync("File Downloaded", |
| 112 | + // $"File '{fileName}' was downloaded from folder '{folder}'."); |
| 113 | + |
| 114 | + _logger.LogInformation("File downloaded: {FileName}", fileName); |
| 115 | + return File(memoryStream, "application/octet-stream", fileName); |
| 116 | + } |
| 117 | + catch (Exception ex) |
| 118 | + { |
| 119 | + _logger.LogError(ex, "Download failed for file: {FileName}", fileName); |
| 120 | + return StatusCode(500, "File download failed."); |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + // Optional antivirus scan (if needed) |
| 125 | + private async Task<bool> ScanWithClamAV(string filePath) |
| 126 | + { |
| 127 | + try |
| 128 | + { |
| 129 | + using (var client = new TcpClient("localhost", 3310)) |
| 130 | + using (var stream = client.GetStream()) |
| 131 | + { |
| 132 | + var writer = new StreamWriter(stream); |
| 133 | + var reader = new StreamReader(stream); |
| 134 | + writer.AutoFlush = true; |
| 135 | + |
| 136 | + await writer.WriteLineAsync("zINSTREAM"); |
| 137 | + |
| 138 | + using var fileStream = System.IO.File.OpenRead(filePath); |
| 139 | + var buffer = new byte[2048]; |
| 140 | + int bytesRead; |
| 141 | + |
| 142 | + while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0) |
| 143 | + { |
| 144 | + var size = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(bytesRead)); |
| 145 | + await stream.WriteAsync(size); |
| 146 | + await stream.WriteAsync(buffer, 0, bytesRead); |
| 147 | + } |
| 148 | + |
| 149 | + await stream.WriteAsync(BitConverter.GetBytes(0)); |
| 150 | + var response = await reader.ReadLineAsync(); |
| 151 | + |
| 152 | + return response != null && response.Contains("OK"); |
| 153 | + } |
| 154 | + } |
| 155 | + catch (Exception ex) |
| 156 | + { |
| 157 | + _logger.LogError(ex, "ClamAV scan error."); |
| 158 | + return false; |
| 159 | + } |
| 160 | + } |
| 161 | + } |
| 162 | +} |
0 commit comments