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

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