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

ProfileController.cs 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Entity;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Web;
  7. using System.Web.Mvc;
  8. using System.Web.Security;
  9. using Teknik.Areas.Blog.Models;
  10. using Teknik.Areas.Error.Controllers;
  11. using Teknik.Areas.Error.ViewModels;
  12. using Teknik.Areas.Profile.Models;
  13. using Teknik.Areas.Profile.ViewModels;
  14. using Teknik.Controllers;
  15. using Teknik.Helpers;
  16. using Teknik.Models;
  17. using Teknik.ViewModels;
  18. using System.Windows;
  19. using System.Net;
  20. namespace Teknik.Areas.Profile.Controllers
  21. {
  22. public class ProfileController : DefaultController
  23. {
  24. private TeknikEntities db = new TeknikEntities();
  25. // GET: Profile/Profile
  26. [AllowAnonymous]
  27. public ActionResult Index(string username)
  28. {
  29. if (string.IsNullOrEmpty(username))
  30. {
  31. username = User.Identity.Name;
  32. }
  33. ProfileViewModel model = new ProfileViewModel();
  34. ViewBag.Title = "User Does Not Exist - " + Config.Title;
  35. ViewBag.Message = "The User does not exist";
  36. User user = db.Users.Where(u => u.Username == username).FirstOrDefault();
  37. if (user != null)
  38. {
  39. ViewBag.Title = username + "'s Profile - " + Config.Title;
  40. ViewBag.Message = "Viewing " + username + "'s Profile";
  41. model.UserID = user.UserId;
  42. model.Username = user.Username;
  43. model.Email = string.Format("{0}@{1}", user.Username, Config.EmailConfig.Domain);
  44. model.JoinDate = user.JoinDate;
  45. model.LastSeen = user.LastSeen;
  46. model.UserSettings = user.UserSettings;
  47. model.BlogSettings = user.BlogSettings;
  48. model.UploadSettings = user.UploadSettings;
  49. model.Uploads = db.Uploads.Where(u => u.UserId == user.UserId).OrderByDescending(u => u.DateUploaded).ToList();
  50. model.Pastes = db.Pastes.Where(u => u.UserId == user.UserId).OrderByDescending(u => u.DatePosted).ToList();
  51. return View(model);
  52. }
  53. model.Error = true;
  54. return View(model);
  55. }
  56. // GET: Profile/Profile
  57. [AllowAnonymous]
  58. public ActionResult Settings()
  59. {
  60. if (User.Identity.IsAuthenticated)
  61. {
  62. string username = User.Identity.Name;
  63. SettingsViewModel model = new SettingsViewModel();
  64. ViewBag.Title = "User Does Not Exist - " + Config.Title;
  65. ViewBag.Message = "The User does not exist";
  66. User user = db.Users.Where(u => u.Username == username).FirstOrDefault();
  67. if (user != null)
  68. {
  69. ViewBag.Title = "Settings - " + Config.Title;
  70. ViewBag.Message = "Your " + Config.Title + " Settings";
  71. model.UserID = user.UserId;
  72. model.Username = user.Username;
  73. model.UserSettings = user.UserSettings;
  74. model.BlogSettings = user.BlogSettings;
  75. model.UploadSettings = user.UploadSettings;
  76. return View(model);
  77. }
  78. model.Error = true;
  79. return View(model);
  80. }
  81. return Redirect(Url.SubRouteUrl("error", "Error.Http403"));
  82. }
  83. [HttpGet]
  84. [AllowAnonymous]
  85. // GET: Profile
  86. public ActionResult Login(string ReturnUrl)
  87. {
  88. LoginViewModel model = new LoginViewModel();
  89. model.ReturnUrl = ReturnUrl;
  90. return View("/Areas/Profile/Views/Profile/ViewLogin.cshtml", model);
  91. }
  92. [HttpPost]
  93. [AllowAnonymous]
  94. [ValidateAntiForgeryToken]
  95. public ActionResult Login(LoginViewModel model)
  96. {
  97. if (ModelState.IsValid)
  98. {
  99. string username = model.Username;
  100. string password = SHA384.Hash(model.Username, model.Password);
  101. bool userValid = db.Users.Any(b => b.Username == username && b.HashedPassword == password);
  102. if (userValid)
  103. {
  104. FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
  105. if (string.IsNullOrEmpty(model.ReturnUrl))
  106. {
  107. return Json(new { result = "true" });
  108. }
  109. else
  110. {
  111. return Redirect(model.ReturnUrl);
  112. }
  113. }
  114. }
  115. return Json(new { error = "Invalid User name or Password." });
  116. }
  117. public ActionResult Logout()
  118. {
  119. FormsAuthentication.SignOut();
  120. return Redirect(Url.SubRouteUrl("www", "Home.Index"));
  121. }
  122. [HttpGet]
  123. [AllowAnonymous]
  124. // GET: Profile
  125. public ActionResult Register(string ReturnUrl)
  126. {
  127. RegisterViewModel model = new RegisterViewModel();
  128. model.ReturnUrl = ReturnUrl;
  129. return View("/Areas/Profile/Views/Profile/ViewRegistration.cshtml", model);
  130. }
  131. [HttpPost]
  132. [AllowAnonymous]
  133. [ValidateAntiForgeryToken]
  134. public ActionResult Register(RegisterViewModel model)
  135. {
  136. if (ModelState.IsValid)
  137. {
  138. if (Config.UserConfig.RegistrationEnabled)
  139. {
  140. var foundUser = db.Users.Where(b => b.Username == model.Username).FirstOrDefault();
  141. if (foundUser != null)
  142. {
  143. return Json(new { error = "That username already exists." });
  144. }
  145. if (model.Password != model.ConfirmPassword)
  146. {
  147. return Json(new { error = "Passwords must match." });
  148. }
  149. try
  150. {
  151. string email = string.Format("{0}@{1}", model.Username, Config.EmailConfig.Domain);
  152. // If Email Server is enabled
  153. if (Config.EmailConfig.Enabled)
  154. {
  155. // Connect to hmailserver COM
  156. var app = new hMailServer.Application();
  157. app.Connect();
  158. app.Authenticate(Config.EmailConfig.Username, Config.EmailConfig.Password);
  159. var domain = app.Domains.ItemByName[Config.EmailConfig.Domain];
  160. try
  161. {
  162. var account = domain.Accounts.ItemByAddress[email];
  163. return Json(new { error = "That email already exists." });
  164. }
  165. catch { }
  166. // If we got an exception, then the email doesnt exist and we continue on!
  167. var newAccount = domain.Accounts.Add();
  168. newAccount.Address = email;
  169. newAccount.Password = model.Password;
  170. newAccount.Active = true;
  171. newAccount.MaxSize = Config.EmailConfig.MaxSize;
  172. newAccount.Save();
  173. }
  174. // If Git is enabled
  175. if (Config.GitConfig.Enabled)
  176. {
  177. // Add gogs user
  178. using (var client = new WebClient())
  179. {
  180. var obj = new { source_id = 1, username = model.Username, email = email, password = model.Password };
  181. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  182. Uri baseUri = new Uri(Config.GitConfig.Host);
  183. string result = client.UploadString(new Uri(baseUri, "admin/users").ToString(), "POST", Newtonsoft.Json.JsonConvert.SerializeObject(obj));
  184. }
  185. }
  186. // Add User
  187. User newUser = db.Users.Create();
  188. newUser.JoinDate = DateTime.Now;
  189. newUser.Username = model.Username;
  190. newUser.HashedPassword = SHA384.Hash(model.Username, model.Password);
  191. newUser.UserSettings = new UserSettings();
  192. newUser.BlogSettings = new BlogSettings();
  193. newUser.UploadSettings = new UploadSettings();
  194. db.Users.Add(newUser);
  195. db.SaveChanges();
  196. // Generate blog for the user
  197. var newBlog = db.Blogs.Create();
  198. newBlog.UserId = db.Users.Where(u => u.Username == model.Username).Select(u => u.UserId).First();
  199. db.Blogs.Add(newBlog);
  200. db.SaveChanges();
  201. }
  202. catch (Exception ex)
  203. {
  204. return Json(new { error = "Unable to create the user." });
  205. }
  206. return Login(new LoginViewModel { Username = model.Username, Password = model.Password, RememberMe = false, ReturnUrl = model.ReturnUrl });
  207. }
  208. return Json(new { error = "User Registration is Disabled" });
  209. }
  210. return Json(new { error = "You must include all fields." });
  211. }
  212. [HttpPost]
  213. [ValidateAntiForgeryToken]
  214. public ActionResult Edit(string curPass, string newPass, string newPassConfirm, string website, string quote, string about, string blogTitle, string blogDesc, bool saveKey, bool serverSideEncrypt)
  215. {
  216. if (ModelState.IsValid)
  217. {
  218. User user = db.Users.Where(u => u.Username == User.Identity.Name).First();
  219. if (user != null)
  220. {
  221. string email = string.Format("{0}@{1}", User.Identity.Name, Config.EmailConfig.Domain);
  222. // Changing Password?
  223. if (!string.IsNullOrEmpty(curPass) && (!string.IsNullOrEmpty(newPass) || !string.IsNullOrEmpty(newPassConfirm)))
  224. {
  225. // Old Password Valid?
  226. if (SHA384.Hash(User.Identity.Name, curPass) != user.HashedPassword)
  227. {
  228. return Json(new { error = "Invalid Original Password." });
  229. }
  230. // The New Password Match?
  231. if (newPass != newPassConfirm)
  232. {
  233. return Json(new { error = "New Password Must Match." });
  234. }
  235. user.HashedPassword = SHA384.Hash(User.Identity.Name, newPass);
  236. // Update Email Pass
  237. if (Config.EmailConfig.Enabled)
  238. {
  239. var app = new hMailServer.Application();
  240. app.Connect();
  241. app.Authenticate(Config.EmailConfig.Username, Config.EmailConfig.Password);
  242. var domain = app.Domains.ItemByName[Config.EmailConfig.Domain];
  243. var account = domain.Accounts.ItemByAddress[email];
  244. account.Password = newPass;
  245. account.Save();
  246. }
  247. // Update Git Pass
  248. if (Config.GitConfig.Enabled)
  249. {
  250. using (var client = new WebClient())
  251. {
  252. var obj = new { source_id = 1, email = email, password = newPass };
  253. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  254. Uri baseUri = new Uri(Config.GitConfig.Host);
  255. string result = client.UploadString(new Uri(baseUri, "admin/users/" + User.Identity.Name).ToString(), "PATCH", Newtonsoft.Json.JsonConvert.SerializeObject(obj));
  256. }
  257. }
  258. }
  259. user.UserSettings.Website = website;
  260. user.UserSettings.Quote = quote;
  261. user.UserSettings.About = about;
  262. user.BlogSettings.Title = blogTitle;
  263. user.BlogSettings.Description = blogDesc;
  264. user.UploadSettings.SaveKey = saveKey;
  265. user.UploadSettings.ServerSideEncrypt = serverSideEncrypt;
  266. db.Entry(user).State = EntityState.Modified;
  267. db.SaveChanges();
  268. return Json(new { result = true });
  269. }
  270. return Json(new { error = "User does not exist" });
  271. }
  272. return Json(new { error = "Invalid Parameters" });
  273. }
  274. [HttpPost]
  275. [ValidateAntiForgeryToken]
  276. public ActionResult Delete()
  277. {
  278. if (ModelState.IsValid)
  279. {
  280. // Delete Email
  281. var app = new hMailServer.Application();
  282. app.Connect();
  283. app.Authenticate(Config.EmailConfig.Username, Config.EmailConfig.Password);
  284. var domain = app.Domains.ItemByName[Config.EmailConfig.Domain];
  285. var account = domain.Accounts.ItemByAddress[string.Format("{0}@{1}", User.Identity.Name, Config.EmailConfig.Domain)];
  286. account.Delete();
  287. // Delete Git
  288. if (Config.GitConfig.Enabled)
  289. {
  290. Uri baseUri = new Uri(Config.GitConfig.Host);
  291. WebRequest request = WebRequest.Create(new Uri(baseUri, "admin/users/" + User.Identity.Name).ToString());
  292. request.Method = "DELETE";
  293. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  294. }
  295. // Update uploads
  296. List<Upload.Models.Upload> uploads = db.Uploads.Include("User").Where(u => u.User.Username == User.Identity.Name).ToList();
  297. if (uploads != null)
  298. {
  299. foreach (Upload.Models.Upload upload in uploads)
  300. {
  301. upload.UserId = null;
  302. db.Entry(upload).State = EntityState.Modified;
  303. }
  304. }
  305. // Update pastes
  306. List<Paste.Models.Paste> pastes = db.Pastes.Include("User").Where(u => u.User.Username == User.Identity.Name).ToList();
  307. if (pastes != null)
  308. {
  309. foreach (Paste.Models.Paste paste in pastes)
  310. {
  311. paste.UserId = null;
  312. db.Entry(paste).State = EntityState.Modified;
  313. }
  314. }
  315. // Delete Blogs
  316. Blog.Models.Blog blog = db.Blogs.Include("BlogPosts").Include("BlogPosts.Comments").Include("User").Where(u => u.User.Username == User.Identity.Name).FirstOrDefault();
  317. if (blog != null)
  318. {
  319. db.Blogs.Remove(blog);
  320. }
  321. // Delete post comments
  322. List<BlogPostComment> postComments = db.BlogComments.Include("User").Where(u => u.User.Username == User.Identity.Name).ToList();
  323. if (postComments != null)
  324. {
  325. foreach (BlogPostComment postComment in postComments)
  326. {
  327. db.BlogComments.Remove(postComment);
  328. }
  329. }
  330. // Delete post comments
  331. List<Podcast.Models.PodcastComment> podComments = db.PodcastComments.Include("User").Where(u => u.User.Username == User.Identity.Name).ToList();
  332. if (podComments != null)
  333. {
  334. foreach (Podcast.Models.PodcastComment podComment in podComments)
  335. {
  336. db.PodcastComments.Remove(podComment);
  337. }
  338. }
  339. // Delete User
  340. User user = db.Users.Where(u => u.Username == User.Identity.Name).FirstOrDefault();
  341. if (user != null)
  342. {
  343. user.UserSettings = db.UserSettings.Find(user.UserId);
  344. user.BlogSettings = db.BlogSettings.Find(user.UserId);
  345. user.UploadSettings = db.UploadSettings.Find(user.UserId);
  346. db.Users.Remove(user);
  347. db.SaveChanges();
  348. FormsAuthentication.SignOut();
  349. return Json(new { result = true });
  350. }
  351. }
  352. return Json(new { error = "Unable to delete user" });
  353. }
  354. }
  355. }