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

View File

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

View File

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

View File

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

View File

@ -10,8 +10,6 @@ namespace Teknik.Areas.Contact.ViewModels
{ {
public class ContactViewModel : ViewModelBase public class ContactViewModel : ViewModelBase
{ {
private TeknikEntities db = new TeknikEntities();
[Required] [Required]
[Display(Name = "Name")] [Display(Name = "Name")]
public string Name { get; set; } public string Name { get; set; }
@ -27,27 +25,5 @@ namespace Teknik.Areas.Contact.ViewModels
[Required] [Required]
[Display(Name = "Message")] [Display(Name = "Message")]
public string Message { get; set; } 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] [TeknikAuthorize]
public class PasteController : DefaultController public class PasteController : DefaultController
{ {
private TeknikEntities db = new TeknikEntities();
[TrackPageView] [TrackPageView]
[AllowAnonymous] [AllowAnonymous]
public ActionResult Index() public ActionResult Index()
@ -37,6 +35,7 @@ namespace Teknik.Areas.Paste.Controllers
[AllowAnonymous] [AllowAnonymous]
public ActionResult ViewPaste(string type, string url, string password) public ActionResult ViewPaste(string type, string url, string password)
{ {
TeknikEntities db = new TeknikEntities();
Models.Paste paste = db.Pastes.Where(p => p.Url == url).FirstOrDefault(); Models.Paste paste = db.Pastes.Where(p => p.Url == url).FirstOrDefault();
if (paste != null) if (paste != null)
{ {
@ -156,7 +155,9 @@ namespace Teknik.Areas.Paste.Controllers
{ {
try 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") 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 })); return Redirect(Url.SubRouteUrl("p", "Paste.View", new { type = "Full", url = paste.Url }));
} }
}
catch (Exception ex) catch (Exception ex)
{ {
return Redirect(Url.SubRouteUrl("error", "Error.500", new { 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( BundleTable.Bundles.Add(new CdnScriptBundle("~/bundles/highlight", config.CdnHost).Include(
"~/Scripts/Highlight/highlight.pack.js")); "~/Scripts/Highlight/highlight.pack.js"));
// Register Style Bundles // 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", "~/Content/Highlight/github-gist.css",
"~/Areas/Paste/Content/Paste.css")); "~/Areas/Paste/Content/Paste.css"));
} }

View File

@ -11,9 +11,8 @@ namespace Teknik.Areas.Paste
{ {
public static class PasteHelper 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(); Config config = Config.Load();
Models.Paste paste = db.Pastes.Create(); Models.Paste paste = db.Pastes.Create();
paste.DatePosted = DateTime.Now; paste.DatePosted = DateTime.Now;

View File

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

View File

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

View File

@ -17,8 +17,6 @@ namespace Teknik.Areas.Shortener.Controllers
[TeknikAuthorize] [TeknikAuthorize]
public class ShortenerController : DefaultController public class ShortenerController : DefaultController
{ {
private TeknikEntities db = new TeknikEntities();
[TrackPageView] [TrackPageView]
[AllowAnonymous] [AllowAnonymous]
public ActionResult Index() public ActionResult Index()
@ -30,6 +28,8 @@ namespace Teknik.Areas.Shortener.Controllers
[AllowAnonymous] [AllowAnonymous]
public ActionResult RedirectToUrl(string url) public ActionResult RedirectToUrl(string url)
{
using (TeknikEntities db = new TeknikEntities())
{ {
ShortenedUrl shortUrl = db.ShortenedUrls.Where(s => s.ShortUrl == url).FirstOrDefault(); ShortenedUrl shortUrl = db.ShortenedUrls.Where(s => s.ShortUrl == url).FirstOrDefault();
if (shortUrl != null) if (shortUrl != null)
@ -41,6 +41,7 @@ namespace Teknik.Areas.Shortener.Controllers
} }
return Redirect(Url.SubRouteUrl("error", "Error.Http404")); return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
} }
}
[HttpPost] [HttpPost]
[AllowAnonymous] [AllowAnonymous]
@ -48,7 +49,9 @@ namespace Teknik.Areas.Shortener.Controllers
{ {
if (url.IsValidUrl()) 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) 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 { result = new { shortUrl = shortUrl, originalUrl = url } });
} }
}
return Json(new { error = "Must be a valid 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 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 // Generate the shortened url
string shortUrl = StringHelper.RandomString(length); string shortUrl = StringHelper.RandomString(length);
while (db.ShortenedUrls.Where(s => s.ShortUrl == shortUrl).FirstOrDefault() != null) while (db.ShortenedUrls.Where(s => s.ShortUrl == shortUrl).FirstOrDefault() != null)

View File

@ -19,8 +19,6 @@ namespace Teknik.Areas.Status.Controllers
[TeknikAuthorize] [TeknikAuthorize]
public class StatusController : DefaultController public class StatusController : DefaultController
{ {
private TeknikEntities db = new TeknikEntities();
[TrackPageView] [TrackPageView]
[AllowAnonymous] [AllowAnonymous]
public ActionResult Index() public ActionResult Index()
@ -30,6 +28,8 @@ namespace Teknik.Areas.Status.Controllers
StatusViewModel model = new StatusViewModel(); StatusViewModel model = new StatusViewModel();
using (TeknikEntities db = new TeknikEntities())
{
// Load initial status info // Load initial status info
#region Statistics #region Statistics
Upload.Models.Upload upload = db.Uploads.OrderByDescending(u => u.UploadId).FirstOrDefault(); Upload.Models.Upload upload = db.Uploads.OrderByDescending(u => u.UploadId).FirstOrDefault();
@ -53,7 +53,7 @@ namespace Teknik.Areas.Status.Controllers
#region Transactions #region Transactions
DateTime curTime = DateTime.Now; DateTime curTime = DateTime.Now;
var billSums = db.Transactions.OfType<Bill>().GroupBy(b => new { b.Currency, b.DateSent.Month, b.DateSent.Year}).Select(b => new { month = b.Key.Month, year = b.Key.Year, currency = b.Key.Currency, total = b.Sum(c => c.Amount) }).ToList(); var billSums = db.Transactions.OfType<Bill>().GroupBy(b => new { b.Currency, b.DateSent.Month, b.DateSent.Year }).Select(b => new { month = b.Key.Month, year = b.Key.Year, currency = b.Key.Currency, total = b.Sum(c => c.Amount) }).ToList();
foreach (var sum in billSums) foreach (var sum in billSums)
{ {
decimal exchangeRate = CurrencyHelper.GetExchangeRate(sum.currency); decimal exchangeRate = CurrencyHelper.GetExchangeRate(sum.currency);
@ -157,7 +157,7 @@ namespace Teknik.Areas.Status.Controllers
} }
} }
#endregion #endregion
}
return View(model); return View(model);
} }

View File

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

View File

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

View File

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

View File

@ -7,6 +7,9 @@
@Styles.Render("~/Content/vault") @Styles.Render("~/Content/vault")
<script type="text/javascript"> <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")'; var deleteVaultURL = '@Url.SubRouteUrl(Model.CurrentSub, "Vault.DeleteVault")';
</script> </script>

View File

@ -143,9 +143,12 @@ namespace Teknik
} }
protected void Application_Error(object sender, EventArgs e) protected void Application_Error(object sender, EventArgs e)
{
Exception exception = null;
try
{ {
// Get the last exception // Get the last exception
Exception exception = Server.GetLastError(); exception = Server.GetLastError();
// Clear the response // Clear the response
Response.Clear(); Response.Clear();
@ -221,5 +224,19 @@ namespace Teknik
new HttpContextWrapper(Context), routeData)); 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 the password is supplied, verify the password
if (!string.IsNullOrEmpty(password)) if (!string.IsNullOrEmpty(password))
{ {
TeknikEntities db = new TeknikEntities(); using (TeknikEntities db = new TeknikEntities())
{
User user = UserHelper.GetUser(db, username); User user = UserHelper.GetUser(db, username);
if (user != null) if (user != null)
{ {
@ -80,6 +81,7 @@ namespace Teknik.Hubs
success = false; success = false;
} }
} }
}
if (success) if (success)
{ {

View File

@ -234,6 +234,18 @@ function getReadableBandwidthString(bandwidth) {
return Math.max(bandwidth, 0.1).toFixed(1) + byteUnits[i]; 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) { function moveUp(item) {
var prev = item.prev(); var prev = item.prev();
if (prev.length == 0) if (prev.length == 0)

View File

@ -11,8 +11,6 @@ namespace Teknik.Security
{ {
public class TeknikPrincipal : ITeknikPrincipal public class TeknikPrincipal : ITeknikPrincipal
{ {
TeknikEntities entities = new TeknikEntities();
private IIdentity _Identity; private IIdentity _Identity;
public IIdentity Identity public IIdentity Identity
{ {
@ -29,7 +27,8 @@ namespace Teknik.Security
{ {
if (m_Info == null && Identity != null && Identity.IsAuthenticated) 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; return m_Info;
} }

View File

@ -40,7 +40,7 @@
<forms domain=".teknik.io" protection="All" enableCrossAppRedirects="true" name="TeknikAuth" /> <forms domain=".teknik.io" protection="All" enableCrossAppRedirects="true" name="TeknikAuth" />
</authentication> </authentication>
<compilation debug="true" targetFramework="4.6.2" /> <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" /> <pages buffer="true" enableViewState="false" />
</system.web> </system.web>
<system.webServer> <system.webServer>
@ -123,7 +123,7 @@
<customHeaders> <customHeaders>
<add name="Access-Control-Allow-Credentials" value="true" /> <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-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" /> <add name="strict-transport-security" value="max-age=31536000; includeSubdomains" />
</customHeaders> </customHeaders>
</httpProtocol> </httpProtocol>

View File

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

View File

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

View File

@ -49,28 +49,20 @@ namespace Teknik.Utilities
} }
while (processedBytes > 0 && bytesRemaining > 0); 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) catch (Exception ex)
{ {
// Don't bother
throw ex; throw ex;
} }
finally finally
{ {
// dispose of file stream // dispose of file stream
if (stream != null)
{
stream.Dispose(); stream.Dispose();
} }
} }
}
public static void DecryptStreamToOutput(HttpResponseBase response, bool flush, Stream stream, int length, byte[] key, byte[] iv, string mode, string padding, int chunkSize) public static void DecryptStreamToOutput(HttpResponseBase response, bool flush, Stream stream, int length, byte[] key, byte[] iv, string mode, string padding, int chunkSize)
{ {