The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ProfileController.cs 19KB

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