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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. public ActionResult Login(LoginViewModel model)
  98. {
  99. if (ModelState.IsValid)
  100. {
  101. string username = model.Username;
  102. string password = SHA384.Hash(model.Username, model.Password);
  103. User user = db.Users.Where(b => b.Username == username).FirstOrDefault();
  104. if (user != null)
  105. {
  106. if (user.TransferAccount)
  107. {
  108. password = SHA256.Hash(model.Password, Config.Salt1, Config.Salt2);
  109. }
  110. bool userValid = db.Users.Any(b => b.Username == username && b.HashedPassword == password);
  111. if (userValid)
  112. {
  113. if (user.TransferAccount)
  114. {
  115. user.HashedPassword = SHA384.Hash(model.Username, model.Password);
  116. user.TransferAccount = false;
  117. db.Entry(user).State = EntityState.Modified;
  118. db.SaveChanges();
  119. }
  120. HttpCookie authcookie = FormsAuthentication.GetAuthCookie(model.Username, model.RememberMe);
  121. authcookie.Domain = string.Format(".{0}", Config.Host);
  122. authcookie.HttpOnly = true;
  123. authcookie.Secure = true;
  124. Response.AppendCookie(authcookie);
  125. if (string.IsNullOrEmpty(model.ReturnUrl))
  126. {
  127. return Json(new { result = "true" });
  128. }
  129. else
  130. {
  131. return Redirect(model.ReturnUrl);
  132. }
  133. }
  134. }
  135. }
  136. return Json(new { error = "Invalid Username or Password." });
  137. }
  138. public ActionResult Logout()
  139. {
  140. FormsAuthentication.SignOut();
  141. return Redirect(Url.SubRouteUrl("www", "Home.Index"));
  142. }
  143. [HttpGet]
  144. [AllowAnonymous]
  145. // GET: Profile
  146. public ActionResult Register(string ReturnUrl)
  147. {
  148. RegisterViewModel model = new RegisterViewModel();
  149. model.ReturnUrl = ReturnUrl;
  150. return View("/Areas/Profile/Views/Profile/ViewRegistration.cshtml", model);
  151. }
  152. [HttpPost]
  153. [AllowAnonymous]
  154. public ActionResult Register(RegisterViewModel model)
  155. {
  156. if (ModelState.IsValid)
  157. {
  158. if (Config.UserConfig.RegistrationEnabled)
  159. {
  160. var foundUser = db.Users.Where(b => b.Username == model.Username).FirstOrDefault();
  161. if (foundUser != null)
  162. {
  163. return Json(new { error = "That username already exists." });
  164. }
  165. if (model.Password != model.ConfirmPassword)
  166. {
  167. return Json(new { error = "Passwords must match." });
  168. }
  169. try
  170. {
  171. string email = string.Format("{0}@{1}", model.Username, Config.EmailConfig.Domain);
  172. // If Email Server is enabled
  173. if (Config.EmailConfig.Enabled)
  174. {
  175. // Connect to hmailserver COM
  176. var app = new hMailServer.Application();
  177. app.Connect();
  178. app.Authenticate(Config.EmailConfig.Username, Config.EmailConfig.Password);
  179. var domain = app.Domains.ItemByName[Config.EmailConfig.Domain];
  180. try
  181. {
  182. var account = domain.Accounts.ItemByAddress[email];
  183. return Json(new { error = "That email already exists." });
  184. }
  185. catch { }
  186. // If we got an exception, then the email doesnt exist and we continue on!
  187. var newAccount = domain.Accounts.Add();
  188. newAccount.Address = email;
  189. newAccount.Password = model.Password;
  190. newAccount.Active = true;
  191. newAccount.MaxSize = Config.EmailConfig.MaxSize;
  192. newAccount.Save();
  193. }
  194. // If Git is enabled
  195. if (Config.GitConfig.Enabled)
  196. {
  197. // Add gogs user
  198. using (var client = new WebClient())
  199. {
  200. var obj = new { username = model.Username, email = email, password = model.Password };
  201. string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  202. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  203. Uri baseUri = new Uri(Config.GitConfig.Host);
  204. Uri finalUri = new Uri(baseUri, "api/v1/admin/users?token=" + Config.GitConfig.AccessToken);
  205. string result = client.UploadString(finalUri, "POST", json);
  206. }
  207. }
  208. // Add User
  209. User newUser = db.Users.Create();
  210. newUser.JoinDate = DateTime.Now;
  211. newUser.Username = model.Username;
  212. newUser.HashedPassword = SHA384.Hash(model.Username, model.Password);
  213. newUser.UserSettings = new UserSettings();
  214. newUser.BlogSettings = new BlogSettings();
  215. newUser.UploadSettings = new UploadSettings();
  216. db.Users.Add(newUser);
  217. db.SaveChanges();
  218. // Generate blog for the user
  219. var newBlog = db.Blogs.Create();
  220. newBlog.UserId = newUser.UserId;
  221. db.Blogs.Add(newBlog);
  222. db.SaveChanges();
  223. }
  224. catch (Exception ex)
  225. {
  226. return Json(new { error = "Unable to create the user." });
  227. }
  228. return Login(new LoginViewModel { Username = model.Username, Password = model.Password, RememberMe = false, ReturnUrl = model.ReturnUrl });
  229. }
  230. return Json(new { error = "User Registration is Disabled" });
  231. }
  232. return Json(new { error = "You must include all fields." });
  233. }
  234. [HttpPost]
  235. public ActionResult Edit(string curPass, string newPass, string newPassConfirm, string website, string quote, string about, string blogTitle, string blogDesc, bool saveKey, bool serverSideEncrypt)
  236. {
  237. if (ModelState.IsValid)
  238. {
  239. User user = db.Users.Where(u => u.Username == User.Identity.Name).First();
  240. if (user != null)
  241. {
  242. string email = string.Format("{0}@{1}", User.Identity.Name, Config.EmailConfig.Domain);
  243. // Changing Password?
  244. if (!string.IsNullOrEmpty(curPass) && (!string.IsNullOrEmpty(newPass) || !string.IsNullOrEmpty(newPassConfirm)))
  245. {
  246. // Old Password Valid?
  247. if (SHA384.Hash(User.Identity.Name, curPass) != user.HashedPassword)
  248. {
  249. return Json(new { error = "Invalid Original Password." });
  250. }
  251. // The New Password Match?
  252. if (newPass != newPassConfirm)
  253. {
  254. return Json(new { error = "New Password Must Match." });
  255. }
  256. user.HashedPassword = SHA384.Hash(User.Identity.Name, newPass);
  257. // Update Email Pass
  258. if (Config.EmailConfig.Enabled)
  259. {
  260. var app = new hMailServer.Application();
  261. app.Connect();
  262. app.Authenticate(Config.EmailConfig.Username, Config.EmailConfig.Password);
  263. var domain = app.Domains.ItemByName[Config.EmailConfig.Domain];
  264. var account = domain.Accounts.ItemByAddress[email];
  265. account.Password = newPass;
  266. account.Save();
  267. }
  268. // Update Git Pass
  269. if (Config.GitConfig.Enabled)
  270. {
  271. using (var client = new WebClient())
  272. {
  273. var obj = new { source_id = 1, email = email, password = newPass };
  274. string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  275. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  276. Uri baseUri = new Uri(Config.GitConfig.Host);
  277. Uri finalUri = new Uri(baseUri, "api/v1/admin/users/" + User.Identity.Name + "?token=" + Config.GitConfig.AccessToken);
  278. string result = client.UploadString(finalUri, "PATCH", json);
  279. }
  280. }
  281. }
  282. user.UserSettings.Website = website;
  283. user.UserSettings.Quote = quote;
  284. user.UserSettings.About = about;
  285. user.BlogSettings.Title = blogTitle;
  286. user.BlogSettings.Description = blogDesc;
  287. user.UploadSettings.SaveKey = saveKey;
  288. user.UploadSettings.ServerSideEncrypt = serverSideEncrypt;
  289. db.Entry(user).State = EntityState.Modified;
  290. db.SaveChanges();
  291. return Json(new { result = true });
  292. }
  293. return Json(new { error = "User does not exist" });
  294. }
  295. return Json(new { error = "Invalid Parameters" });
  296. }
  297. [HttpPost]
  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. }