1
0
mirror of https://git.teknik.io/Teknikode/Teknik.git synced 2023-08-02 14:16:22 +02:00

- Moved TeknikEntities from global field to disposed local instances.

- Added additional logging/handling of errors.
- Added processed/total bytes for uploads, downloads, and encryption/decryption.
- Fixed paste CSS bundle using a script handler.
- Fixed bad js when viewing a vault
This commit is contained in:
Uncled1023 2017-04-08 21:01:31 -07:00
parent 1058b040a4
commit e163e0ca8c
27 changed files with 1590 additions and 1419 deletions

View File

@ -47,10 +47,10 @@ namespace ServerMaint
if (Directory.Exists(configPath))
{
Config config = Config.Load(configPath);
TeknikEntities db = new TeknikEntities();
Output(string.Format("[{0}] Started Server Maintenance Process.", DateTime.Now));
using (TeknikEntities db = new TeknikEntities())
{
// Scan all the uploads for viruses, and remove the bad ones
if (options.ScanUploads && config.UploadConfig.VirusScanEnable)
{
@ -98,6 +98,7 @@ namespace ServerMaint
{
GenerateCleaningList(config, db, options.CleaningFile, options.DaysBeforeDeletion);
}
}
Output(string.Format("[{0}] Finished Server Maintenance Process.", DateTime.Now));
return 0;

View File

@ -16,8 +16,6 @@ namespace Teknik.Areas.API.Controllers
[TeknikAuthorize]
public class APIController : DefaultController
{
private TeknikEntities db = new TeknikEntities();
[AllowAnonymous]
public ActionResult Index()
{

View File

@ -24,8 +24,6 @@ namespace Teknik.Areas.API.Controllers
[TeknikAuthorize(AuthType.Basic)]
public class APIv1Controller : DefaultController
{
private TeknikEntities db = new TeknikEntities();
[AllowAnonymous]
public ActionResult Index()
{
@ -81,6 +79,8 @@ namespace Teknik.Areas.API.Controllers
if (model.blockSize <= 0)
model.blockSize = Config.UploadConfig.BlockSize;
using (TeknikEntities db = new TeknikEntities())
{
// Save the file data
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);
@ -125,6 +125,7 @@ namespace Teknik.Areas.API.Controllers
}
return Json(new { error = new { message = "Unable to save file" } });
}
}
else
{
return Json(new { error = new { message = "File Too Large" } });
@ -149,7 +150,9 @@ namespace Teknik.Areas.API.Controllers
{
if (model != null && model.code != null)
{
Paste.Models.Paste paste = PasteHelper.CreatePaste(model.code, model.title, model.syntax, model.expireUnit, model.expireLength, model.password, model.hide);
using (TeknikEntities db = new TeknikEntities())
{
Paste.Models.Paste paste = PasteHelper.CreatePaste(db, model.code, model.title, model.syntax, model.expireUnit, model.expireLength, model.password, model.hide);
// Associate this with the user if they are logged in
if (User.Identity.IsAuthenticated)
@ -177,6 +180,7 @@ namespace Teknik.Areas.API.Controllers
}
});
}
}
return Json(new { error = new { message = "Invalid Paste Request" } });
}
catch (Exception ex)
@ -194,7 +198,9 @@ namespace Teknik.Areas.API.Controllers
{
if (model.url.IsValidUrl())
{
ShortenedUrl newUrl = Shortener.Shortener.ShortenUrl(model.url, Config.ShortenerConfig.UrlLength);
using (TeknikEntities db = new TeknikEntities())
{
ShortenedUrl newUrl = Shortener.Shortener.ShortenUrl(db, model.url, Config.ShortenerConfig.UrlLength);
// Associate this with the user if they are logged in
if (User.Identity.IsAuthenticated)
@ -224,6 +230,7 @@ namespace Teknik.Areas.API.Controllers
}
});
}
}
return Json(new { error = new { message = "Must be a valid Url" } });
}
catch (Exception ex)

View File

@ -17,8 +17,6 @@ namespace Teknik.Areas.Contact.Controllers
[TeknikAuthorize]
public class ContactController : DefaultController
{
private TeknikEntities db = new TeknikEntities();
// GET: Contact/Contact
[TrackPageView]
[AllowAnonymous]
@ -39,6 +37,8 @@ namespace Teknik.Areas.Contact.Controllers
if (Config.ContactConfig.Enabled)
{
try
{
using (TeknikEntities db = new TeknikEntities())
{
// Insert the message into the DB
Models.Contact newContact = db.Contact.Create();
@ -49,6 +49,7 @@ namespace Teknik.Areas.Contact.Controllers
newContact.DateAdded = DateTime.Now;
db.Contact.Add(newContact);
db.SaveChanges();
}
// Let's also email the message to support
SmtpClient client = new SmtpClient();

View File

@ -10,8 +10,6 @@ namespace Teknik.Areas.Contact.ViewModels
{
public class ContactViewModel : ViewModelBase
{
private TeknikEntities db = new TeknikEntities();
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
@ -27,27 +25,5 @@ namespace Teknik.Areas.Contact.ViewModels
[Required]
[Display(Name = "Message")]
public string Message { get; set; }
public bool Insert()
{
bool success = true;
try
{
Models.Contact newContact = db.Contact.Create();
newContact.Name = Name;
newContact.Email = Email;
newContact.Subject = Subject;
newContact.Message = Message;
newContact.DateAdded = DateTime.Now;
db.Contact.Add(newContact);
db.SaveChanges();
}
catch (Exception ex)
{
success = false;
}
return success;
}
}
}

View File

@ -21,8 +21,6 @@ namespace Teknik.Areas.Paste.Controllers
[TeknikAuthorize]
public class PasteController : DefaultController
{
private TeknikEntities db = new TeknikEntities();
[TrackPageView]
[AllowAnonymous]
public ActionResult Index()
@ -37,6 +35,7 @@ namespace Teknik.Areas.Paste.Controllers
[AllowAnonymous]
public ActionResult ViewPaste(string type, string url, string password)
{
TeknikEntities db = new TeknikEntities();
Models.Paste paste = db.Pastes.Where(p => p.Url == url).FirstOrDefault();
if (paste != null)
{
@ -156,7 +155,9 @@ namespace Teknik.Areas.Paste.Controllers
{
try
{
Models.Paste paste = PasteHelper.CreatePaste(model.Content, model.Title, model.Syntax, model.ExpireUnit, model.ExpireLength ?? 1, model.Password, model.Hide);
using (TeknikEntities db = new TeknikEntities())
{
Models.Paste paste = PasteHelper.CreatePaste(db, model.Content, model.Title, model.Syntax, model.ExpireUnit, model.ExpireLength ?? 1, model.Password, model.Hide);
if (model.ExpireUnit == "view")
{
@ -177,6 +178,7 @@ namespace Teknik.Areas.Paste.Controllers
return Redirect(Url.SubRouteUrl("p", "Paste.View", new { type = "Full", url = paste.Url }));
}
}
catch (Exception ex)
{
return Redirect(Url.SubRouteUrl("error", "Error.500", new { exception = ex }));

View File

@ -86,7 +86,7 @@ namespace Teknik.Areas.Paste
BundleTable.Bundles.Add(new CdnScriptBundle("~/bundles/highlight", config.CdnHost).Include(
"~/Scripts/Highlight/highlight.pack.js"));
// Register Style Bundles
BundleTable.Bundles.Add(new CdnScriptBundle("~/Content/paste", config.CdnHost).Include(
BundleTable.Bundles.Add(new CdnStyleBundle("~/Content/paste", config.CdnHost).Include(
"~/Content/Highlight/github-gist.css",
"~/Areas/Paste/Content/Paste.css"));
}

View File

@ -11,9 +11,8 @@ namespace Teknik.Areas.Paste
{
public static class PasteHelper
{
public static Models.Paste CreatePaste(string content, string title = "", string syntax = "text", string expireUnit = "never", int expireLength = 1, string password = "", bool hide = false)
public static Models.Paste CreatePaste(TeknikEntities db, string content, string title = "", string syntax = "text", string expireUnit = "never", int expireLength = 1, string password = "", bool hide = false)
{
TeknikEntities db = new TeknikEntities();
Config config = Config.Load();
Models.Paste paste = db.Pastes.Create();
paste.DatePosted = DateTime.Now;

View File

@ -19,8 +19,6 @@ namespace Teknik.Areas.Podcast.Controllers
[TeknikAuthorize]
public class PodcastController : DefaultController
{
private TeknikEntities db = new TeknikEntities();
[TrackPageView]
[AllowAnonymous]
public ActionResult Index()
@ -33,6 +31,8 @@ namespace Teknik.Areas.Podcast.Controllers
ViewBag.Title = Config.PodcastConfig.Title + " - " + Config.Title;
ViewBag.Description = Config.PodcastConfig.Description;
bool editor = User.IsInRole("Podcast");
using (TeknikEntities db = new TeknikEntities())
{
var foundPodcasts = db.Podcasts.Where(p => (p.Published || editor)).FirstOrDefault();
if (foundPodcasts != null)
{
@ -43,6 +43,7 @@ namespace Teknik.Areas.Podcast.Controllers
model.Error = true;
model.ErrorMessage = "No Podcasts Available";
}
}
return View("~/Areas/Podcast/Views/Podcast/Main.cshtml", model);
}
@ -63,6 +64,8 @@ namespace Teknik.Areas.Podcast.Controllers
PodcastViewModel model = new PodcastViewModel();
// find the podcast specified
bool editor = User.IsInRole("Podcast");
using (TeknikEntities db = new TeknikEntities())
{
var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.Episode == episode)).FirstOrDefault();
if (foundPodcast != null)
{
@ -71,6 +74,7 @@ namespace Teknik.Areas.Podcast.Controllers
ViewBag.Title = model.Title + " - Teknikast - " + Config.Title;
return View("~/Areas/Podcast/Views/Podcast/ViewPodcast.cshtml", model);
}
}
model.Error = true;
model.ErrorMessage = "No Podcasts Available";
return View("~/Areas/Podcast/Views/Podcast/ViewPodcast.cshtml", model);
@ -78,6 +82,8 @@ namespace Teknik.Areas.Podcast.Controllers
[AllowAnonymous]
public ActionResult Download(int episode, string fileName)
{
using (TeknikEntities db = new TeknikEntities())
{
// find the podcast specified
var foundPodcast = db.Podcasts.Where(p => (p.Published && p.Episode == episode)).FirstOrDefault();
@ -107,10 +113,13 @@ namespace Teknik.Areas.Podcast.Controllers
}
return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
}
}
[HttpPost]
[AllowAnonymous]
public ActionResult GetPodcasts(int startPodcastID, int count)
{
using (TeknikEntities db = new TeknikEntities())
{
bool editor = User.IsInRole("Podcast");
var podcasts = db.Podcasts.Where(p => p.Published || editor).OrderByDescending(p => p.DatePosted).Skip(startPodcastID).Take(count).ToList();
@ -124,10 +133,13 @@ namespace Teknik.Areas.Podcast.Controllers
}
return PartialView("~/Areas/Podcast/Views/Podcast/Podcasts.cshtml", podcastViews);
}
}
[HttpPost]
[AllowAnonymous]
public ActionResult GetPodcastEpisode(int podcastId)
{
using (TeknikEntities db = new TeknikEntities())
{
bool editor = User.IsInRole("Podcast");
var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
@ -137,10 +149,13 @@ namespace Teknik.Areas.Podcast.Controllers
}
return Json(new { error = "No podcast found" });
}
}
[HttpPost]
[AllowAnonymous]
public ActionResult GetPodcastTitle(int podcastId)
{
using (TeknikEntities db = new TeknikEntities())
{
bool editor = User.IsInRole("Podcast");
var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
@ -150,10 +165,13 @@ namespace Teknik.Areas.Podcast.Controllers
}
return Json(new { error = "No podcast found" });
}
}
[HttpPost]
[AllowAnonymous]
public ActionResult GetPodcastDescription(int podcastId)
{
using (TeknikEntities db = new TeknikEntities())
{
bool editor = User.IsInRole("Podcast");
var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
@ -163,10 +181,13 @@ namespace Teknik.Areas.Podcast.Controllers
}
return Json(new { error = "No podcast found" });
}
}
[HttpPost]
[AllowAnonymous]
public ActionResult GetPodcastFiles(int podcastId)
{
using (TeknikEntities db = new TeknikEntities())
{
bool editor = User.IsInRole("Podcast");
var foundPodcast = db.Podcasts.Where(p => ((p.Published || editor) && p.PodcastId == podcastId)).FirstOrDefault();
@ -186,6 +207,7 @@ namespace Teknik.Areas.Podcast.Controllers
}
return Json(new { error = "No podcast found" });
}
}
[HttpPost]
public ActionResult CreatePodcast(int episode, string title, string description)
@ -193,6 +215,8 @@ namespace Teknik.Areas.Podcast.Controllers
if (ModelState.IsValid)
{
if (User.IsInRole("Podcast"))
{
using (TeknikEntities db = new TeknikEntities())
{
// Grab the next episode number
Models.Podcast lastPod = db.Podcasts.Where(p => p.Episode == episode).FirstOrDefault();
@ -214,6 +238,7 @@ namespace Teknik.Areas.Podcast.Controllers
}
return Json(new { error = "That episode already exists" });
}
}
return Json(new { error = "You don't have permission to create a podcast" });
}
return Json(new { error = "No podcast created" });
@ -225,6 +250,8 @@ namespace Teknik.Areas.Podcast.Controllers
if (ModelState.IsValid)
{
if (User.IsInRole("Podcast"))
{
using (TeknikEntities db = new TeknikEntities())
{
Models.Podcast podcast = db.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault();
if (podcast != null)
@ -270,6 +297,7 @@ namespace Teknik.Areas.Podcast.Controllers
}
return Json(new { error = "No podcast found" });
}
}
return Json(new { error = "You don't have permission to edit this podcast" });
}
return Json(new { error = "Invalid Inputs" });
@ -281,6 +309,8 @@ namespace Teknik.Areas.Podcast.Controllers
if (ModelState.IsValid)
{
if (User.IsInRole("Podcast"))
{
using (TeknikEntities db = new TeknikEntities())
{
Models.Podcast podcast = db.Podcasts.Find(podcastId);
if (podcast != null)
@ -294,6 +324,7 @@ namespace Teknik.Areas.Podcast.Controllers
}
return Json(new { error = "No podcast found" });
}
}
return Json(new { error = "You don't have permission to publish this podcast" });
}
return Json(new { error = "Invalid Inputs" });
@ -305,6 +336,8 @@ namespace Teknik.Areas.Podcast.Controllers
if (ModelState.IsValid)
{
if (User.IsInRole("Podcast"))
{
using (TeknikEntities db = new TeknikEntities())
{
Models.Podcast podcast = db.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault();
if (podcast != null)
@ -319,6 +352,7 @@ namespace Teknik.Areas.Podcast.Controllers
}
return Json(new { error = "No podcast found" });
}
}
return Json(new { error = "You don't have permission to delete this podcast" });
}
return Json(new { error = "Invalid Inputs" });
@ -329,6 +363,8 @@ namespace Teknik.Areas.Podcast.Controllers
[HttpPost]
[AllowAnonymous]
public ActionResult GetComments(int podcastId, int startCommentID, int count)
{
using (TeknikEntities db = new TeknikEntities())
{
var comments = db.PodcastComments.Where(p => (p.PodcastId == podcastId)).OrderByDescending(p => p.DatePosted).Skip(startCommentID).Take(count).ToList();
List<CommentViewModel> commentViews = new List<CommentViewModel>();
@ -341,10 +377,13 @@ namespace Teknik.Areas.Podcast.Controllers
}
return PartialView("~/Areas/Podcast/Views/Podcast/Comments.cshtml", commentViews);
}
}
[HttpPost]
[AllowAnonymous]
public ActionResult GetCommentArticle(int commentID)
{
using (TeknikEntities db = new TeknikEntities())
{
PodcastComment comment = db.PodcastComments.Where(p => (p.PodcastCommentId == commentID)).FirstOrDefault();
if (comment != null)
@ -353,11 +392,14 @@ namespace Teknik.Areas.Podcast.Controllers
}
return Json(new { error = "No article found" });
}
}
[HttpPost]
public ActionResult CreateComment(int podcastId, string article)
{
if (ModelState.IsValid)
{
using (TeknikEntities db = new TeknikEntities())
{
if (db.Podcasts.Where(p => p.PodcastId == podcastId).FirstOrDefault() != null)
{
@ -374,6 +416,7 @@ namespace Teknik.Areas.Podcast.Controllers
}
return Json(new { error = "That podcast does not exist" });
}
}
return Json(new { error = "Invalid Parameters" });
}
@ -381,6 +424,8 @@ namespace Teknik.Areas.Podcast.Controllers
public ActionResult EditComment(int commentID, string article)
{
if (ModelState.IsValid)
{
using (TeknikEntities db = new TeknikEntities())
{
PodcastComment comment = db.PodcastComments.Where(c => c.PodcastCommentId == commentID).FirstOrDefault();
if (comment != null)
@ -397,6 +442,7 @@ namespace Teknik.Areas.Podcast.Controllers
}
return Json(new { error = "No comment found" });
}
}
return Json(new { error = "Invalid Parameters" });
}
@ -404,6 +450,8 @@ namespace Teknik.Areas.Podcast.Controllers
public ActionResult DeleteComment(int commentID)
{
if (ModelState.IsValid)
{
using (TeknikEntities db = new TeknikEntities())
{
PodcastComment comment = db.PodcastComments.Where(c => c.PodcastCommentId == commentID).FirstOrDefault();
if (comment != null)
@ -418,6 +466,7 @@ namespace Teknik.Areas.Podcast.Controllers
}
return Json(new { error = "No comment found" });
}
}
return Json(new { error = "Invalid Parameters" });
}
#endregion

View File

@ -19,8 +19,6 @@ namespace Teknik.Areas.RSS.Controllers
[TeknikAuthorize(AuthType.Basic)]
public class RSSController : DefaultController
{
private TeknikEntities db = new TeknikEntities();
[AllowAnonymous]
public ActionResult Index()
{
@ -32,6 +30,8 @@ namespace Teknik.Areas.RSS.Controllers
[TrackDownload]
[AllowAnonymous]
public ActionResult Blog(string username)
{
using (TeknikEntities db = new TeknikEntities())
{
// If empty, grab the main blog
List<BlogPost> posts = new List<BlogPost>();
@ -98,10 +98,13 @@ namespace Teknik.Areas.RSS.Controllers
return new RssResult(badFeed);
}
}
[TrackDownload]
[AllowAnonymous]
public ActionResult Podcast()
{
using (TeknikEntities db = new TeknikEntities())
{
List<SyndicationItem> items = new List<SyndicationItem>();
List<Podcast.Models.Podcast> podcasts = db.Podcasts.Where(p => p.Published).OrderByDescending(p => p.Episode).ToList();
@ -132,3 +135,4 @@ namespace Teknik.Areas.RSS.Controllers
}
}
}
}

View File

@ -17,8 +17,6 @@ namespace Teknik.Areas.Shortener.Controllers
[TeknikAuthorize]
public class ShortenerController : DefaultController
{
private TeknikEntities db = new TeknikEntities();
[TrackPageView]
[AllowAnonymous]
public ActionResult Index()
@ -30,6 +28,8 @@ namespace Teknik.Areas.Shortener.Controllers
[AllowAnonymous]
public ActionResult RedirectToUrl(string url)
{
using (TeknikEntities db = new TeknikEntities())
{
ShortenedUrl shortUrl = db.ShortenedUrls.Where(s => s.ShortUrl == url).FirstOrDefault();
if (shortUrl != null)
@ -41,6 +41,7 @@ namespace Teknik.Areas.Shortener.Controllers
}
return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
}
}
[HttpPost]
[AllowAnonymous]
@ -48,7 +49,9 @@ namespace Teknik.Areas.Shortener.Controllers
{
if (url.IsValidUrl())
{
ShortenedUrl newUrl = Shortener.ShortenUrl(url, Config.ShortenerConfig.UrlLength);
using (TeknikEntities db = new TeknikEntities())
{
ShortenedUrl newUrl = Shortener.ShortenUrl(db, url, Config.ShortenerConfig.UrlLength);
if (User.Identity.IsAuthenticated)
{
@ -70,6 +73,7 @@ namespace Teknik.Areas.Shortener.Controllers
return Json(new { result = new { shortUrl = shortUrl, originalUrl = url } });
}
}
return Json(new { error = "Must be a valid Url" });
}

View File

@ -11,10 +11,8 @@ namespace Teknik.Areas.Shortener
{
public static class Shortener
{
public static ShortenedUrl ShortenUrl(string url, int length)
public static ShortenedUrl ShortenUrl(TeknikEntities db, string url, int length)
{
TeknikEntities db = new TeknikEntities();
// Generate the shortened url
string shortUrl = StringHelper.RandomString(length);
while (db.ShortenedUrls.Where(s => s.ShortUrl == shortUrl).FirstOrDefault() != null)

View File

@ -19,8 +19,6 @@ namespace Teknik.Areas.Status.Controllers
[TeknikAuthorize]
public class StatusController : DefaultController
{
private TeknikEntities db = new TeknikEntities();
[TrackPageView]
[AllowAnonymous]
public ActionResult Index()
@ -30,6 +28,8 @@ namespace Teknik.Areas.Status.Controllers
StatusViewModel model = new StatusViewModel();
using (TeknikEntities db = new TeknikEntities())
{
// Load initial status info
#region Statistics
Upload.Models.Upload upload = db.Uploads.OrderByDescending(u => u.UploadId).FirstOrDefault();
@ -157,7 +157,7 @@ namespace Teknik.Areas.Status.Controllers
}
}
#endregion
}
return View(model);
}

View File

@ -26,8 +26,6 @@ namespace Teknik.Areas.Upload.Controllers
[TeknikAuthorize]
public class UploadController : DefaultController
{
private TeknikEntities db = new TeknikEntities();
// GET: Upload/Upload
[HttpGet]
[TrackPageView]
@ -37,6 +35,8 @@ namespace Teknik.Areas.Upload.Controllers
ViewBag.Title = "Teknik Upload - End to End Encryption";
UploadViewModel model = new UploadViewModel();
model.CurrentSub = Subdomain;
using (TeknikEntities db = new TeknikEntities())
{
Users.Models.User user = UserHelper.GetUser(db, User.Identity.Name);
if (user != null)
{
@ -47,6 +47,7 @@ namespace Teknik.Areas.Upload.Controllers
{
model.Encrypt = false;
}
}
return View(model);
}
@ -83,6 +84,8 @@ namespace Teknik.Areas.Upload.Controllers
}
}
using (TeknikEntities db = new TeknikEntities())
{
Models.Upload upload = Uploader.SaveFile(db, Config, data.InputStream, fileType, contentLength, encrypt, fileExt, iv, null, keySize, blockSize);
if (upload != null)
{
@ -100,6 +103,7 @@ namespace Teknik.Areas.Upload.Controllers
}
return Json(new { error = new { message = "Unable to upload file" } });
}
}
else
{
return Json(new { error = new { message = "File Too Large" } });
@ -122,6 +126,8 @@ namespace Teknik.Areas.Upload.Controllers
if (Config.UploadConfig.DownloadEnabled)
{
ViewBag.Title = "Teknik Download - " + file;
using (TeknikEntities db = new TeknikEntities())
{
Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
if (upload != null)
{
@ -188,6 +194,8 @@ namespace Teknik.Areas.Upload.Controllers
// Read in the file
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
try
{
// If the IV is set, and Key is set, then decrypt it while sending
if (!string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
{
@ -210,11 +218,17 @@ namespace Teknik.Areas.Upload.Controllers
false);
}
}
catch (Exception ex)
{
Logging.Logger.WriteEntry(Logging.LogLevel.Warning, "Error in Download", ex);
}
}
}
}
}
return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
}
}
return Redirect(Url.SubRouteUrl("error", "Error.Http403"));
}
@ -223,6 +237,8 @@ namespace Teknik.Areas.Upload.Controllers
public FileResult DownloadData(string file)
{
if (Config.UploadConfig.DownloadEnabled)
{
using (TeknikEntities db = new TeknikEntities())
{
Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
if (upload != null)
@ -238,6 +254,7 @@ namespace Teknik.Areas.Upload.Controllers
Redirect(Url.SubRouteUrl("error", "Error.Http404"));
return null;
}
}
Redirect(Url.SubRouteUrl("error", "Error.Http403"));
return null;
}
@ -245,6 +262,8 @@ namespace Teknik.Areas.Upload.Controllers
[HttpGet]
[AllowAnonymous]
public ActionResult Delete(string file, string key)
{
using (TeknikEntities db = new TeknikEntities())
{
ViewBag.Title = "File Delete - " + file + " - " + Config.Title;
Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
@ -274,9 +293,12 @@ namespace Teknik.Areas.Upload.Controllers
}
return RedirectToRoute("Error.Http404");
}
}
[HttpPost]
public ActionResult GenerateDeleteKey(string file)
{
using (TeknikEntities db = new TeknikEntities())
{
Models.Upload upload = db.Uploads.Where(up => up.Url == file).FirstOrDefault();
if (upload != null)
@ -295,3 +317,4 @@ namespace Teknik.Areas.Upload.Controllers
}
}
}
}

View File

@ -46,7 +46,7 @@ function processDownload(key) {
lastTime = curTime;
lastData = e.data.processed;
var percentComplete = Math.round(e.data.processed * 100 / e.data.total);
setProgress(percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Decrypting [' + getReadableBandwidthString(speed * 8) + ']');
setProgress(percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Decrypting [' + getReadableFileSizeString(e.data.processed) + ' / ' + getReadableFileSizeString(e.data.total) + ' @ ' + getReadableBandwidthString(speed * 8) + ']');
}
break;
case 'finish':
@ -92,7 +92,7 @@ function processDownload(key) {
lastTime = curTime;
lastData = e.loaded;
var percentComplete = Math.round(e.loaded * 100 / e.total);
setProgress(percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Downloading File [' + getReadableBandwidthString(speed * 8) + ']');
setProgress(percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Downloading File [' + getReadableFileSizeString(e.loaded) + ' / ' + getReadableFileSizeString(e.total) + ' @ ' + getReadableBandwidthString(speed * 8) + ']');
}
};

View File

@ -217,7 +217,7 @@ function encryptFile(file, callback) {
lastTime = curTime;
lastData = e.data.processed;
var percentComplete = Math.round(e.data.processed * 100 / e.data.total);
setProgress(fileID, percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Encrypting [' + getReadableBandwidthString(speed * 8) + ']');
setProgress(fileID, percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Encrypting [' + getReadableFileSizeString(e.data.processed) + ' / ' + getReadableFileSizeString(e.data.total) + ' @ ' + getReadableBandwidthString(speed * 8) + ']');
}
break;
case 'finish':
@ -306,7 +306,7 @@ function uploadProgress(fileID, lastTime, lastData, evt) {
setProgress(fileID, 100, 'progress-bar-success progress-bar-striped active', '', 'Processing Upload');
}
else {
setProgress(fileID, percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Uploading to Server [' + getReadableBandwidthString(speed * 8) + ']');
setProgress(fileID, percentComplete, 'progress-bar-success progress-bar-striped active', percentComplete + '%', 'Uploading to Server [' + getReadableFileSizeString(evt.loaded) + ' / ' + getReadableFileSizeString(evt.total) + ' @ ' + getReadableBandwidthString(speed * 8) + ']');
}
}
}

View File

@ -23,7 +23,6 @@ namespace Teknik.Areas.Users.Controllers
public class UserController : DefaultController
{
private static readonly UsedCodesManager usedCodesManager = new UsedCodesManager();
private TeknikEntities db = new TeknikEntities();
[TrackPageView]
[AllowAnonymous]
@ -51,6 +50,8 @@ namespace Teknik.Areas.Users.Controllers
ViewBag.Description = "The User does not exist";
try
{
using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, username);
@ -86,6 +87,7 @@ namespace Teknik.Areas.Users.Controllers
model.Error = true;
model.ErrorMessage = "The user does not exist";
}
}
catch (Exception ex)
{
model.Error = true;
@ -103,6 +105,8 @@ namespace Teknik.Areas.Users.Controllers
ViewBag.Title = "User Does Not Exist - " + Config.Title;
ViewBag.Description = "The User does not exist";
using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, username);
if (user != null)
@ -133,6 +137,7 @@ namespace Teknik.Areas.Users.Controllers
return View(model);
}
}
model.Error = true;
return View(model);
}
@ -145,6 +150,8 @@ namespace Teknik.Areas.Users.Controllers
ViewBag.Title = username + "'s Public Key - " + Config.Title;
ViewBag.Description = "The PGP public key for " + username;
using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, username);
if (user != null)
{
@ -153,6 +160,7 @@ namespace Teknik.Areas.Users.Controllers
return Content(user.SecuritySettings.PGPSignature, "text/plain");
}
}
}
return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
}
@ -174,6 +182,8 @@ namespace Teknik.Areas.Users.Controllers
if (ModelState.IsValid)
{
string username = model.Username;
using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, username);
if (user != null)
{
@ -247,6 +257,7 @@ namespace Teknik.Areas.Users.Controllers
}
}
}
}
model.Error = true;
model.ErrorMessage = "Invalid Username or Password.";
@ -289,6 +300,8 @@ namespace Teknik.Areas.Users.Controllers
if (ModelState.IsValid)
{
if (Config.UserConfig.RegistrationEnabled)
{
using (TeknikEntities db = new TeknikEntities())
{
if (!model.Error && !UserHelper.ValidUsername(Config, model.Username))
{
@ -352,6 +365,7 @@ namespace Teknik.Areas.Users.Controllers
}
}
}
}
if (!model.Error)
{
model.Error = true;
@ -368,6 +382,8 @@ namespace Teknik.Areas.Users.Controllers
if (ModelState.IsValid)
{
try
{
using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, User.Identity.Name);
if (user != null)
@ -479,6 +495,7 @@ namespace Teknik.Areas.Users.Controllers
}
return Json(new { error = "User does not exist" });
}
}
catch (Exception ex)
{
return Json(new { error = ex.GetFullMessage(true) });
@ -494,6 +511,8 @@ namespace Teknik.Areas.Users.Controllers
if (ModelState.IsValid)
{
try
{
using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, User.Identity.Name);
if (user != null)
@ -504,6 +523,7 @@ namespace Teknik.Areas.Users.Controllers
return Json(new { result = true });
}
}
}
catch (Exception ex)
{
return Json(new { error = ex.GetFullMessage(true) });
@ -518,7 +538,15 @@ namespace Teknik.Areas.Users.Controllers
bool verified = true;
if (string.IsNullOrEmpty(code))
verified &= false;
// Is there a code?
if (verified)
{
using (TeknikEntities db = new TeknikEntities())
{
verified &= UserHelper.VerifyRecoveryEmail(db, Config, User.Identity.Name, code);
}
}
RecoveryEmailVerificationViewModel model = new RecoveryEmailVerificationViewModel();
model.Success = verified;
@ -533,6 +561,8 @@ namespace Teknik.Areas.Users.Controllers
if (ModelState.IsValid)
{
try
{
using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, User.Identity.Name);
if (user != null)
@ -552,6 +582,7 @@ namespace Teknik.Areas.Users.Controllers
}
}
}
}
catch (Exception ex)
{
return Json(new { error = ex.GetFullMessage(true) });
@ -578,6 +609,8 @@ namespace Teknik.Areas.Users.Controllers
if (ModelState.IsValid)
{
try
{
using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, username);
if (user != null)
@ -594,6 +627,7 @@ namespace Teknik.Areas.Users.Controllers
}
return Json(new { error = "The username is not valid" });
}
}
catch (Exception ex)
{
return Json(new { error = ex.GetFullMessage(true) });
@ -609,6 +643,12 @@ namespace Teknik.Areas.Users.Controllers
bool verified = true;
if (string.IsNullOrEmpty(code))
verified &= false;
// Is there a code?
if (verified)
{
using (TeknikEntities db = new TeknikEntities())
{
verified &= UserHelper.VerifyResetPassword(db, Config, username, code);
if (verified)
@ -618,6 +658,8 @@ namespace Teknik.Areas.Users.Controllers
Session["AuthenticatedUser"] = user;
Session["AuthCode"] = code;
}
}
}
ResetPasswordVerificationViewModel model = new ResetPasswordVerificationViewModel();
model.Success = verified;
@ -649,8 +691,11 @@ namespace Teknik.Areas.Users.Controllers
return Json(new { error = "Passwords must match" });
}
using (TeknikEntities db = new TeknikEntities())
{
User newUser = UserHelper.GetUser(db, user.Username);
UserHelper.EditAccount(db, Config, newUser, true, password);
}
return Json(new { result = true });
}
@ -712,6 +757,8 @@ namespace Teknik.Areas.Users.Controllers
HttpCookie trustedDeviceCookie = UserHelper.CreateTrustedDeviceCookie(user.Username, Request.Url.Host.GetDomain(), Request.IsLocal);
Response.Cookies.Add(trustedDeviceCookie);
using (TeknikEntities db = new TeknikEntities())
{
TrustedDevice device = new TrustedDevice();
device.UserId = user.UserId;
device.Name = (string.IsNullOrEmpty(deviceName)) ? "Unknown" : deviceName;
@ -722,6 +769,7 @@ namespace Teknik.Areas.Users.Controllers
db.TrustedDevices.Add(device);
db.SaveChanges();
}
}
if (string.IsNullOrEmpty(returnUrl))
returnUrl = Request.UrlReferrer.AbsoluteUri.ToString();
@ -737,6 +785,8 @@ namespace Teknik.Areas.Users.Controllers
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult VerifyAuthenticatorCode(string code)
{
using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, User.Identity.Name);
if (user != null)
@ -758,6 +808,7 @@ namespace Teknik.Areas.Users.Controllers
}
return Json(new { error = "User does not exist" });
}
}
[HttpGet]
public ActionResult GenerateAuthQrCode(string key)
@ -776,6 +827,8 @@ namespace Teknik.Areas.Users.Controllers
public ActionResult ClearTrustedDevices()
{
try
{
using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, User.Identity.Name);
if (user != null)
@ -801,6 +854,7 @@ namespace Teknik.Areas.Users.Controllers
}
return Json(new { error = "User does not exist" });
}
}
catch (Exception ex)
{
return Json(new { error = ex.GetFullMessage(true) });
@ -812,6 +866,8 @@ namespace Teknik.Areas.Users.Controllers
public ActionResult GenerateToken(string name)
{
try
{
using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, User.Identity.Name);
if (user != null)
@ -839,6 +895,7 @@ namespace Teknik.Areas.Users.Controllers
}
return Json(new { error = "User does not exist" });
}
}
catch (Exception ex)
{
return Json(new { error = ex.GetFullMessage(true) });
@ -850,6 +907,8 @@ namespace Teknik.Areas.Users.Controllers
public ActionResult RevokeAllTokens()
{
try
{
using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, User.Identity.Name);
if (user != null)
@ -870,6 +929,7 @@ namespace Teknik.Areas.Users.Controllers
}
return Json(new { error = "User does not exist" });
}
}
catch (Exception ex)
{
return Json(new { error = ex.GetFullMessage(true) });
@ -881,6 +941,8 @@ namespace Teknik.Areas.Users.Controllers
public ActionResult EditTokenName(int tokenId, string name)
{
try
{
using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, User.Identity.Name);
if (user != null)
@ -898,6 +960,7 @@ namespace Teknik.Areas.Users.Controllers
}
return Json(new { error = "User does not exist" });
}
}
catch (Exception ex)
{
return Json(new { error = ex.GetFullMessage(true) });
@ -909,6 +972,8 @@ namespace Teknik.Areas.Users.Controllers
public ActionResult DeleteToken(int tokenId)
{
try
{
using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, User.Identity.Name);
if (user != null)
@ -927,6 +992,7 @@ namespace Teknik.Areas.Users.Controllers
}
return Json(new { error = "User does not exist" });
}
}
catch (Exception ex)
{
return Json(new { error = ex.GetFullMessage(true) });

View File

@ -20,10 +20,10 @@ namespace Teknik.Areas.Vault.Controllers
[TeknikAuthorize]
public class VaultController : DefaultController
{
private TeknikEntities db = new TeknikEntities();
[AllowAnonymous]
public ActionResult ViewVault(string id)
{
using (TeknikEntities db = new TeknikEntities())
{
Models.Vault foundVault = db.Vaults.Where(v => v.Url == id).FirstOrDefault();
if (foundVault != null)
@ -59,7 +59,7 @@ namespace Teknik.Areas.Vault.Controllers
db.SaveChanges();
UploadItemViewModel uploadModel = new UploadItemViewModel();
upload.VaultItemId = item.VaultItemId;
uploadModel.VaultItemId = item.VaultItemId;
uploadModel.Title = item.Title;
uploadModel.Description = item.Description;
uploadModel.DateAdded = item.DateAdded;
@ -97,6 +97,7 @@ namespace Teknik.Areas.Vault.Controllers
}
return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
}
}
[HttpGet]
[AllowAnonymous]
@ -147,6 +148,8 @@ namespace Teknik.Areas.Vault.Controllers
[HttpGet]
public ActionResult EditVault(string url, string type, string items)
{
using (TeknikEntities db = new TeknikEntities())
{
ViewBag.Title = "Edit Vault";
Vault.Models.Vault foundVault = db.Vaults.Where(v => v.Url == url).FirstOrDefault();
@ -228,6 +231,7 @@ namespace Teknik.Areas.Vault.Controllers
}
return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
}
}
[HttpPost]
[AllowAnonymous]
@ -237,6 +241,8 @@ namespace Teknik.Areas.Vault.Controllers
if (model != null)
{
if (!string.IsNullOrEmpty(model.title))
{
using (TeknikEntities db = new TeknikEntities())
{
Vault.Models.Vault newVault = db.Vaults.Create();
// Create a new ID
@ -299,6 +305,7 @@ namespace Teknik.Areas.Vault.Controllers
db.SaveChanges();
return Json(new { result = new { url = Url.SubRouteUrl("v", "Vault.ViewVault", new { id = url }) } });
}
}
return Json(new { error = new { message = "You must supply a Title" } });
}
return Json(new { error = new { message = "Invalid Parameters" } });
@ -309,6 +316,8 @@ namespace Teknik.Areas.Vault.Controllers
public ActionResult EditVault(ModifyVaultViewModel model)
{
if (model != null)
{
using (TeknikEntities db = new TeknikEntities())
{
Vault.Models.Vault foundVault = db.Vaults.Where(v => v.VaultId == model.vaultId).FirstOrDefault();
if (foundVault != null)
@ -375,11 +384,14 @@ namespace Teknik.Areas.Vault.Controllers
}
return Json(new { error = new { message = "That Vault does not exist" } });
}
}
return Json(new { error = new { message = "Invalid Parameters" } });
}
[HttpPost]
public ActionResult DeleteVault(string url)
{
using (TeknikEntities db = new TeknikEntities())
{
Vault.Models.Vault foundVault = db.Vaults.Where(v => v.Url == url).FirstOrDefault();
if (foundVault != null)
@ -395,6 +407,7 @@ namespace Teknik.Areas.Vault.Controllers
}
return Json(new { error = new { message = "That Vault does not exist" } });
}
}
[HttpPost]
[AllowAnonymous]
@ -415,6 +428,8 @@ namespace Teknik.Areas.Vault.Controllers
{
bool valid = false;
if (!string.IsNullOrEmpty(type) && !string.IsNullOrEmpty(url))
{
using (TeknikEntities db = new TeknikEntities())
{
switch (type.ToLower())
{
@ -434,6 +449,7 @@ namespace Teknik.Areas.Vault.Controllers
break;
}
}
}
return valid;
}
}

View File

@ -7,6 +7,9 @@
@Styles.Render("~/Content/vault")
<script type="text/javascript">
var helpURL = '@Url.SubRouteUrl("help", "Help.Markdown")';
var validateItemURL = '@Url.SubRouteUrl(Model.CurrentSub, "Vault.Action", new { action = "ValidateItem" })';
var modifyVaultURL = '@Url.SubRouteUrl(Model.CurrentSub, "Vault.Action", new { action = "EditVault" })';
var deleteVaultURL = '@Url.SubRouteUrl(Model.CurrentSub, "Vault.DeleteVault")';
</script>

View File

@ -143,9 +143,12 @@ namespace Teknik
}
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = null;
try
{
// Get the last exception
Exception exception = Server.GetLastError();
exception = Server.GetLastError();
// Clear the response
Response.Clear();
@ -221,5 +224,19 @@ namespace Teknik
new HttpContextWrapper(Context), routeData));
}
}
catch (Exception ex)
{
// Unable to display error, so try to log it
try
{
Logging.Logger.WriteEntry(Logging.LogLevel.Warning, "Error in Application_Error", ex);
if (exception != null)
{
Logging.Logger.WriteEntry(Logging.LogLevel.Error, "Exception Thrown", exception);
}
}
catch(Exception) { }
}
}
}
}

View File

@ -68,7 +68,8 @@ namespace Teknik.Hubs
// If the password is supplied, verify the password
if (!string.IsNullOrEmpty(password))
{
TeknikEntities db = new TeknikEntities();
using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, username);
if (user != null)
{
@ -80,6 +81,7 @@ namespace Teknik.Hubs
success = false;
}
}
}
if (success)
{

View File

@ -234,6 +234,18 @@ function getReadableBandwidthString(bandwidth) {
return Math.max(bandwidth, 0.1).toFixed(1) + byteUnits[i];
}
function getReadableFileSizeString(fileSizeInBytes) {
var i = -1;
var byteUnits = [' KB', ' MB', ' GB', ' TB', 'PB', 'EB', 'ZB', 'YB'];
do {
fileSizeInBytes = fileSizeInBytes / 1024;
i++;
} while (fileSizeInBytes > 1024);
return Math.max(fileSizeInBytes, 0.1).toFixed(1) + byteUnits[i];
};
function moveUp(item) {
var prev = item.prev();
if (prev.length == 0)

View File

@ -11,8 +11,6 @@ namespace Teknik.Security
{
public class TeknikPrincipal : ITeknikPrincipal
{
TeknikEntities entities = new TeknikEntities();
private IIdentity _Identity;
public IIdentity Identity
{
@ -29,7 +27,8 @@ namespace Teknik.Security
{
if (m_Info == null && Identity != null && Identity.IsAuthenticated)
{
m_Info = UserHelper.GetUser(entities, Identity.Name);
TeknikEntities db = new TeknikEntities();
m_Info = UserHelper.GetUser(db, Identity.Name);
}
return m_Info;
}

View File

@ -40,7 +40,7 @@
<forms domain=".teknik.io" protection="All" enableCrossAppRedirects="true" name="TeknikAuth" />
</authentication>
<compilation debug="true" targetFramework="4.6.2" />
<httpRuntime targetFramework="4.6.2" maxRequestLength="1048576" executionTimeout="3600" relaxedUrlToFileSystemMapping="true" />
<httpRuntime targetFramework="4.6.2" maxRequestLength="5242880" executionTimeout="3600" relaxedUrlToFileSystemMapping="true" />
<pages buffer="true" enableViewState="false" />
</system.web>
<system.webServer>
@ -123,7 +123,7 @@
<customHeaders>
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Authorization, Accept, Origin, Content-Type, X-Requested-With" />
<add name="Access-Control-Allow-Headers" value="Authorization, Accept, Origin, Content-Type, X-Requested-With, Connection, Transfer-Encoding" />
<add name="strict-transport-security" value="max-age=31536000; includeSubdomains" />
</customHeaders>
</httpProtocol>

View File

@ -39,8 +39,8 @@ namespace TeknikStreaming
private void LoadStreams()
{
TeknikEntities db = new TeknikEntities();
using (TeknikEntities db = new TeknikEntities())
{
List<User> users = db.Users.ToList();
if (users != null)
{
@ -53,3 +53,4 @@ namespace TeknikStreaming
}
}
}
}

View File

@ -43,6 +43,7 @@ namespace Teknik.Utilities
protected override void WriteFile(System.Web.HttpResponseBase response)
{
response.Buffer = bufferOutput;
response.BufferOutput = bufferOutput;
responseDelegate(response);
}
}

View File

@ -49,28 +49,20 @@ namespace Teknik.Utilities
}
while (processedBytes > 0 && bytesRemaining > 0);
}
catch (HttpException httpEx)
{
// If we lost connection, that's fine
if (httpEx.ErrorCode == -2147023667)
{
// do nothing
}
else
{
//throw httpEx;
}
}
catch (Exception ex)
{
// Don't bother
throw ex;
}
finally
{
// dispose of file stream
if (stream != null)
{
stream.Dispose();
}
}
}
public static void DecryptStreamToOutput(HttpResponseBase response, bool flush, Stream stream, int length, byte[] key, byte[] iv, string mode, string padding, int chunkSize)
{