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 18KB

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