The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PasteController.cs 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Teknik.Areas.Paste.ViewModels;
  6. using Teknik.Areas.Users.Utility;
  7. using Teknik.Controllers;
  8. using Teknik.Filters;
  9. using Teknik.Utilities;
  10. using Teknik.Models;
  11. using Teknik.Attributes;
  12. using Teknik.Utilities.Cryptography;
  13. using Microsoft.Extensions.Logging;
  14. using Teknik.Configuration;
  15. using Teknik.Data;
  16. using Microsoft.AspNetCore.Authorization;
  17. using Microsoft.AspNetCore.Mvc;
  18. using Microsoft.EntityFrameworkCore;
  19. using Microsoft.AspNetCore.Http;
  20. using Teknik.Logging;
  21. using System.IO;
  22. using System.Threading.Tasks;
  23. namespace Teknik.Areas.Paste.Controllers
  24. {
  25. [Authorize]
  26. [Area("Paste")]
  27. public class PasteController : DefaultController
  28. {
  29. public PasteController(ILogger<Logger> logger, Config config, TeknikEntities dbContext) : base(logger, config, dbContext) { }
  30. [AllowAnonymous]
  31. public IActionResult Index()
  32. {
  33. ViewBag.Title = "Paste - " + _config.Title;
  34. ViewBag.Description = "Paste your code or text easily and securely. Set an expiration, set a password, or leave it open for the world to see.";
  35. PasteCreateViewModel model = new PasteCreateViewModel();
  36. return View(model);
  37. }
  38. [AllowAnonymous]
  39. public async Task<IActionResult> ViewPaste(string type, string url, string password)
  40. {
  41. Models.Paste paste = _dbContext.Pastes.Where(p => p.Url == url).FirstOrDefault();
  42. if (paste != null)
  43. {
  44. ViewBag.Title = ((string.IsNullOrEmpty(paste.Title)) ? string.Empty : paste.Title + " - ") + _config.Title + " Paste";
  45. ViewBag.Description = "Paste your code or text easily and securely. Set an expiration, set a password, or leave it open for the world to see.";
  46. // Increment Views
  47. paste.Views += 1;
  48. _dbContext.Entry(paste).State = EntityState.Modified;
  49. _dbContext.SaveChanges();
  50. // Check Expiration
  51. if (PasteHelper.CheckExpiration(paste))
  52. {
  53. _dbContext.Pastes.Remove(paste);
  54. _dbContext.SaveChanges();
  55. return new StatusCodeResult(StatusCodes.Status404NotFound);
  56. }
  57. PasteViewModel model = new PasteViewModel();
  58. model.Url = url;
  59. model.Title = paste.Title;
  60. model.Syntax = paste.Syntax;
  61. model.DatePosted = paste.DatePosted;
  62. if (User.Identity.IsAuthenticated && type.ToLower() == "full")
  63. {
  64. Users.Models.User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  65. if (user != null)
  66. {
  67. model.Vaults = user.Vaults.ToList();
  68. }
  69. }
  70. byte[] ivBytes = Encoding.Unicode.GetBytes(paste.IV);
  71. byte[] keyBytes = AesCounterManaged.CreateKey(paste.Key, ivBytes, paste.KeySize);
  72. // The paste has a password set
  73. if (!string.IsNullOrEmpty(paste.HashedPassword))
  74. {
  75. string hash = string.Empty;
  76. if (!string.IsNullOrEmpty(password))
  77. {
  78. hash = PasteHelper.HashPassword(paste.Key, password);
  79. keyBytes = AesCounterManaged.CreateKey(password, ivBytes, paste.KeySize);
  80. }
  81. if (string.IsNullOrEmpty(password) || hash != paste.HashedPassword)
  82. {
  83. PasswordViewModel passModel = new PasswordViewModel();
  84. passModel.Url = url;
  85. passModel.Type = type;
  86. if (!string.IsNullOrEmpty(password) && hash != paste.HashedPassword)
  87. {
  88. passModel.Error = true;
  89. passModel.ErrorMessage = "Invalid Password";
  90. }
  91. // Redirect them to the password request page
  92. return View("~/Areas/Paste/Views/Paste/PasswordNeeded.cshtml", passModel);
  93. }
  94. }
  95. // Read in the file
  96. string subDir = paste.FileName[0].ToString();
  97. string filePath = Path.Combine(_config.PasteConfig.PasteDirectory, subDir, paste.FileName);
  98. if (!System.IO.File.Exists(filePath))
  99. {
  100. return new StatusCodeResult(StatusCodes.Status404NotFound);
  101. }
  102. using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
  103. using (AesCounterStream cs = new AesCounterStream(fs, false, keyBytes, ivBytes))
  104. using (StreamReader sr = new StreamReader(cs, Encoding.Unicode))
  105. {
  106. model.Content = await sr.ReadToEndAsync();
  107. }
  108. switch (type.ToLower())
  109. {
  110. case "full":
  111. return View("~/Areas/Paste/Views/Paste/Full.cshtml", model);
  112. case "simple":
  113. return View("~/Areas/Paste/Views/Paste/Simple.cshtml", model);
  114. case "raw":
  115. return Content(model.Content, "text/plain");
  116. case "download":
  117. //Create File
  118. var cd = new System.Net.Mime.ContentDisposition
  119. {
  120. FileName = url + ".txt",
  121. Inline = true
  122. };
  123. Response.Headers.Add("Content-Disposition", cd.ToString());
  124. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
  125. return new BufferedFileStreamResult("application/octet-stream", async (response) => await ResponseHelper.StreamToOutput(response, true, new AesCounterStream(fs, false, keyBytes, ivBytes), (int)fs.Length, _config.PasteConfig.ChunkSize), false);
  126. default:
  127. return View("~/Areas/Paste/Views/Paste/Full.cshtml", model);
  128. }
  129. }
  130. return new StatusCodeResult(StatusCodes.Status404NotFound);
  131. }
  132. [HttpPost]
  133. [AllowAnonymous]
  134. [DisableRequestSizeLimit]
  135. public IActionResult Paste([Bind("Content, Title, Syntax, ExpireLength, ExpireUnit, Password")]PasteCreateViewModel model)
  136. {
  137. if (ModelState.IsValid)
  138. {
  139. if (_config.PasteConfig.Enabled)
  140. {
  141. try
  142. {
  143. Models.Paste paste = PasteHelper.CreatePaste(_config, _dbContext, model.Content, model.Title, model.Syntax, model.ExpireUnit, model.ExpireLength ?? 1, model.Password);
  144. if (model.ExpireUnit == "view")
  145. {
  146. paste.Views = -1;
  147. }
  148. if (User.Identity.IsAuthenticated)
  149. {
  150. Users.Models.User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  151. if (user != null)
  152. {
  153. paste.UserId = user.UserId;
  154. }
  155. }
  156. _dbContext.Pastes.Add(paste);
  157. _dbContext.SaveChanges();
  158. return Redirect(Url.SubRouteUrl("p", "Paste.View", new { type = "Full", url = paste.Url }));
  159. }
  160. catch (Exception ex)
  161. {
  162. return Redirect(Url.SubRouteUrl("error", "Error.500", new { exception = ex }));
  163. }
  164. }
  165. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  166. }
  167. return View("~/Areas/Paste/Views/Paste/Index.cshtml", model);
  168. }
  169. [HttpPost]
  170. public IActionResult Delete(string id)
  171. {
  172. Models.Paste foundPaste = _dbContext.Pastes.Where(p => p.Url == id).FirstOrDefault();
  173. if (foundPaste != null)
  174. {
  175. if (foundPaste.User.Username == User.Identity.Name)
  176. {
  177. string filePath = foundPaste.FileName;
  178. // Delete from the DB
  179. _dbContext.Pastes.Remove(foundPaste);
  180. _dbContext.SaveChanges();
  181. // Delete the File
  182. if (System.IO.File.Exists(filePath))
  183. {
  184. System.IO.File.Delete(filePath);
  185. }
  186. return Json(new { result = true });
  187. }
  188. return Json(new { error = new { message = "You do not have permission to edit this Paste" } });
  189. }
  190. return Json(new { error = new { message = "This Paste does not exist" } });
  191. }
  192. }
  193. }