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.

APIv1Controller.cs 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Entity;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Web;
  7. using System.Web.Mvc;
  8. using Teknik.Areas.Upload;
  9. using Teknik.Areas.Paste;
  10. using Teknik.Controllers;
  11. using Teknik.Utilities;
  12. using Teknik.Models;
  13. using System.Text;
  14. using Teknik.Areas.Shortener.Models;
  15. using nClam;
  16. using Teknik.Filters;
  17. using Teknik.Areas.API.Models;
  18. using Teknik.Areas.Users.Models;
  19. using Teknik.Areas.Users.Utility;
  20. using Teknik.Attributes;
  21. namespace Teknik.Areas.API.Controllers
  22. {
  23. [TeknikAuthorize(AuthType.Basic)]
  24. public class APIv1Controller : DefaultController
  25. {
  26. private TeknikEntities db = new TeknikEntities();
  27. [AllowAnonymous]
  28. public ActionResult Index()
  29. {
  30. return Redirect(Url.SubRouteUrl("help", "Help.API"));
  31. }
  32. [HttpPost]
  33. [AllowAnonymous]
  34. [TrackPageView]
  35. public ActionResult Upload(APIv1UploadModel model)
  36. {
  37. try
  38. {
  39. if (model.file != null)
  40. {
  41. if (model.file.ContentLength <= Config.UploadConfig.MaxUploadSize)
  42. {
  43. // convert file to bytes
  44. byte[] fileData = null;
  45. string fileExt = Path.GetExtension(model.file.FileName);
  46. int contentLength = model.file.ContentLength;
  47. using (var binaryReader = new BinaryReader(model.file.InputStream))
  48. {
  49. fileData = binaryReader.ReadBytes(model.file.ContentLength);
  50. }
  51. // Scan the file to detect a virus
  52. if (Config.UploadConfig.VirusScanEnable)
  53. {
  54. byte[] scanData = fileData;
  55. // If it was encrypted client side, decrypt it
  56. if (!model.encrypt && model.key != null)
  57. {
  58. // If the IV is set, and Key is set, then decrypt it
  59. if (!string.IsNullOrEmpty(model.key) && !string.IsNullOrEmpty(model.iv))
  60. {
  61. // Decrypt the data
  62. scanData = AES.Decrypt(scanData, model.key, model.iv);
  63. }
  64. }
  65. ClamClient clam = new ClamClient(Config.UploadConfig.ClamServer, Config.UploadConfig.ClamPort);
  66. clam.MaxStreamSize = Config.UploadConfig.MaxUploadSize;
  67. ClamScanResult scanResult = clam.SendAndScanFile(scanData);
  68. switch (scanResult.Result)
  69. {
  70. case ClamScanResults.Clean:
  71. break;
  72. case ClamScanResults.VirusDetected:
  73. return Json(new { error = new { message = string.Format("Virus Detected: {0}. As per our <a href=\"{1}\">Terms of Service</a>, Viruses are not permited.", scanResult.InfectedFiles.First().VirusName, Url.SubRouteUrl("tos", "TOS.Index")) } });
  74. case ClamScanResults.Error:
  75. break;
  76. case ClamScanResults.Unknown:
  77. break;
  78. }
  79. }
  80. // Need to grab the contentType if it's empty
  81. if (string.IsNullOrEmpty(model.contentType))
  82. {
  83. model.contentType = (string.IsNullOrEmpty(model.file.ContentType)) ? "application/octet-stream" : model.file.ContentType;
  84. }
  85. // Initialize the key size and block size if empty
  86. if (model.keySize <= 0)
  87. model.keySize = Config.UploadConfig.KeySize;
  88. if (model.blockSize <= 0)
  89. model.blockSize = Config.UploadConfig.BlockSize;
  90. byte[] data = null;
  91. // If they want us to encrypt the file first, do that here
  92. if (model.encrypt)
  93. {
  94. // Generate key and iv if empty
  95. if (string.IsNullOrEmpty(model.key))
  96. {
  97. model.key = StringHelper.RandomString(model.keySize / 8);
  98. }
  99. if (string.IsNullOrEmpty(model.iv))
  100. {
  101. model.iv = StringHelper.RandomString(model.blockSize / 8);
  102. }
  103. data = AES.Encrypt(fileData, model.key, model.iv);
  104. if (data == null || data.Length <= 0)
  105. {
  106. return Json(new { error = new { message = "Unable to encrypt file" } });
  107. }
  108. }
  109. // Save the file data
  110. Upload.Models.Upload upload = Uploader.SaveFile(db, Config, (model.encrypt) ? data : fileData, model.contentType, contentLength, fileExt, model.iv, (model.saveKey) ? model.key : null, model.keySize, model.blockSize);
  111. if (upload != null)
  112. {
  113. // Associate this with the user if they provided an auth key
  114. if (User.Identity.IsAuthenticated)
  115. {
  116. User foundUser = UserHelper.GetUser(db, User.Identity.Name);
  117. if (foundUser != null)
  118. {
  119. upload.UserId = foundUser.UserId;
  120. db.Entry(upload).State = EntityState.Modified;
  121. db.SaveChanges();
  122. }
  123. }
  124. // Generate delete key if asked to
  125. if (model.genDeletionKey)
  126. {
  127. string delKey = StringHelper.RandomString(Config.UploadConfig.DeleteKeyLength);
  128. upload.DeleteKey = delKey;
  129. db.Entry(upload).State = EntityState.Modified;
  130. db.SaveChanges();
  131. }
  132. // Pull all the information together
  133. string fullUrl = Url.SubRouteUrl("upload", "Upload.Download", new { file = upload.Url });
  134. var returnData = new
  135. {
  136. url = (model.saveKey || string.IsNullOrEmpty(model.key)) ? fullUrl : fullUrl + "#" + model.key,
  137. fileName = upload.Url,
  138. contentType = model.contentType,
  139. contentLength = contentLength,
  140. key = model.key,
  141. keySize = model.keySize,
  142. iv = model.iv,
  143. blockSize = model.blockSize,
  144. deletionKey = upload.DeleteKey
  145. };
  146. return Json(new { result = returnData });
  147. }
  148. return Json(new { error = new { message = "Unable to save file" } });
  149. }
  150. else
  151. {
  152. return Json(new { error = new { message = "File Too Large" } });
  153. }
  154. }
  155. return Json(new { error = new { message = "Invalid Upload Request" } });
  156. }
  157. catch(Exception ex)
  158. {
  159. return Json(new { error = new { message = "Exception: " + ex.Message } });
  160. }
  161. }
  162. [HttpPost]
  163. [AllowAnonymous]
  164. [TrackPageView]
  165. public ActionResult Paste(APIv1PasteModel model)
  166. {
  167. try
  168. {
  169. if (model != null && model.code != null)
  170. {
  171. Paste.Models.Paste paste = PasteHelper.CreatePaste(model.code, model.title, model.syntax, model.expireUnit, model.expireLength, model.password, model.hide);
  172. // Associate this with the user if they are logged in
  173. if (User.Identity.IsAuthenticated)
  174. {
  175. User foundUser = UserHelper.GetUser(db, User.Identity.Name);
  176. if (foundUser != null)
  177. {
  178. paste.UserId = foundUser.UserId;
  179. }
  180. }
  181. db.Pastes.Add(paste);
  182. db.SaveChanges();
  183. return Json(new
  184. {
  185. result = new
  186. {
  187. id = paste.Url,
  188. url = Url.SubRouteUrl("paste", "Paste.View", new { type = "Full", url = paste.Url, password = model.password }),
  189. title = paste.Title,
  190. syntax = paste.Syntax,
  191. expiration = paste.ExpireDate,
  192. password = model.password
  193. }
  194. });
  195. }
  196. return Json(new { error = new { message = "Invalid Paste Request" } });
  197. }
  198. catch (Exception ex)
  199. {
  200. return Json(new { error = new { message = "Exception: " + ex.Message } });
  201. }
  202. }
  203. [HttpPost]
  204. [AllowAnonymous]
  205. [TrackPageView]
  206. public ActionResult Shorten(APIv1ShortenModel model)
  207. {
  208. try
  209. {
  210. if (model.url.IsValidUrl())
  211. {
  212. ShortenedUrl newUrl = Shortener.Shortener.ShortenUrl(model.url, Config.ShortenerConfig.UrlLength);
  213. // Associate this with the user if they are logged in
  214. if (User.Identity.IsAuthenticated)
  215. {
  216. User foundUser = UserHelper.GetUser(db, User.Identity.Name);
  217. if (foundUser != null)
  218. {
  219. newUrl.UserId = foundUser.UserId;
  220. }
  221. }
  222. db.ShortenedUrls.Add(newUrl);
  223. db.SaveChanges();
  224. string shortUrl = string.Format("{0}://{1}/{2}", HttpContext.Request.Url.Scheme, Config.ShortenerConfig.ShortenerHost, newUrl.ShortUrl);
  225. if (Config.DevEnvironment)
  226. {
  227. shortUrl = Url.SubRouteUrl("shortened", "Shortener.View", new { url = newUrl.ShortUrl });
  228. }
  229. return Json(new
  230. {
  231. result = new
  232. {
  233. shortUrl = shortUrl,
  234. originalUrl = model.url
  235. }
  236. });
  237. }
  238. return Json(new { error = new { message = "Must be a valid Url" } });
  239. }
  240. catch (Exception ex)
  241. {
  242. return Json(new { error = new { message = "Exception: " + ex.Message } });
  243. }
  244. }
  245. }
  246. }