The next generation of the Teknik Services. Written in ASP.NET. Fork for blog tags.
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.

UserController.cs 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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.Shortener.Models;
  10. using Teknik.Areas.Blog.Models;
  11. using Teknik.Areas.Error.Controllers;
  12. using Teknik.Areas.Error.ViewModels;
  13. using Teknik.Areas.Users.Models;
  14. using Teknik.Areas.Users.ViewModels;
  15. using Teknik.Controllers;
  16. using Teknik.Helpers;
  17. using Teknik.Models;
  18. using Teknik.ViewModels;
  19. using System.Windows;
  20. using System.Net;
  21. using Teknik.Areas.Users.Utility;
  22. using Teknik.Filters;
  23. namespace Teknik.Areas.Users.Controllers
  24. {
  25. public class UserController : DefaultController
  26. {
  27. private TeknikEntities db = new TeknikEntities();
  28. // GET: Profile/Profile
  29. [TrackPageView]
  30. [AllowAnonymous]
  31. public ActionResult Index(string username)
  32. {
  33. if (string.IsNullOrEmpty(username))
  34. {
  35. username = User.Identity.Name;
  36. }
  37. ProfileViewModel model = new ProfileViewModel();
  38. ViewBag.Title = "User Does Not Exist - " + Config.Title;
  39. ViewBag.Description = "The User does not exist";
  40. try
  41. {
  42. User user = UserHelper.GetUser(db, username);
  43. if (user != null)
  44. {
  45. ViewBag.Title = username + "'s Profile - " + Config.Title;
  46. ViewBag.Description = "Viewing " + username + "'s Profile";
  47. model.UserID = user.UserId;
  48. model.Username = user.Username;
  49. if (Config.EmailConfig.Enabled)
  50. {
  51. model.Email = string.Format("{0}@{1}", user.Username, Config.EmailConfig.Domain);
  52. }
  53. model.JoinDate = user.JoinDate;
  54. model.LastSeen = UserHelper.GetLastAccountActivity(db, Config, user);
  55. model.UserSettings = user.UserSettings;
  56. model.BlogSettings = user.BlogSettings;
  57. model.UploadSettings = user.UploadSettings;
  58. model.Uploads = db.Uploads.Where(u => u.UserId == user.UserId).OrderByDescending(u => u.DateUploaded).ToList();
  59. model.Pastes = db.Pastes.Where(u => u.UserId == user.UserId).OrderByDescending(u => u.DatePosted).ToList();
  60. model.ShortenedUrls = db.ShortenedUrls.Where(s => s.UserId == user.UserId).OrderByDescending(s => s.DateAdded).ToList();
  61. return View(model);
  62. }
  63. model.Error = true;
  64. model.ErrorMessage = "The user does not exist";
  65. }
  66. catch (Exception ex)
  67. {
  68. model.Error = true;
  69. model.ErrorMessage = ex.GetFullMessage(true);
  70. }
  71. return View(model);
  72. }
  73. [TrackPageView]
  74. [AllowAnonymous]
  75. public ActionResult Settings()
  76. {
  77. if (User.Identity.IsAuthenticated)
  78. {
  79. string username = User.Identity.Name;
  80. SettingsViewModel model = new SettingsViewModel();
  81. ViewBag.Title = "User Does Not Exist - " + Config.Title;
  82. ViewBag.Description = "The User does not exist";
  83. User user = UserHelper.GetUser(db, username);
  84. if (user != null)
  85. {
  86. ViewBag.Title = "Settings - " + Config.Title;
  87. ViewBag.Description = "Your " + Config.Title + " Settings";
  88. model.UserID = user.UserId;
  89. model.Username = user.Username;
  90. model.RecoveryEmail = user.RecoveryEmail;
  91. model.RecoveryVerified = user.RecoveryVerified;
  92. model.UserSettings = user.UserSettings;
  93. model.BlogSettings = user.BlogSettings;
  94. model.UploadSettings = user.UploadSettings;
  95. return View(model);
  96. }
  97. model.Error = true;
  98. return View(model);
  99. }
  100. return Redirect(Url.SubRouteUrl("error", "Error.Http403"));
  101. }
  102. [HttpGet]
  103. [TrackPageView]
  104. [AllowAnonymous]
  105. public ActionResult ViewRawPGP(string username)
  106. {
  107. ViewBag.Title = username + "'s Public Key - " + Config.Title;
  108. ViewBag.Description = "The PGP public key for " + username;
  109. User user = UserHelper.GetUser(db, username);
  110. if (user != null)
  111. {
  112. if (!string.IsNullOrEmpty(user.UserSettings.PGPSignature))
  113. {
  114. return Content(user.UserSettings.PGPSignature, "text/plain");
  115. }
  116. }
  117. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  118. }
  119. [HttpGet]
  120. [TrackPageView]
  121. [AllowAnonymous]
  122. public ActionResult Login(string ReturnUrl)
  123. {
  124. LoginViewModel model = new LoginViewModel();
  125. model.ReturnUrl = ReturnUrl;
  126. return View("/Areas/User/Views/User/ViewLogin.cshtml", model);
  127. }
  128. [HttpPost]
  129. [AllowAnonymous]
  130. public ActionResult Login([Bind(Prefix = "Login")]LoginViewModel model)
  131. {
  132. if (ModelState.IsValid)
  133. {
  134. string username = model.Username;
  135. User user = UserHelper.GetUser(db, username);
  136. if (user != null)
  137. {
  138. bool userValid = UserHelper.UserPasswordCorrect(db, Config, user, model.Password);
  139. if (userValid)
  140. {
  141. UserHelper.TransferUser(db, Config, user, model.Password);
  142. user.LastSeen = DateTime.Now;
  143. db.Entry(user).State = EntityState.Modified;
  144. db.SaveChanges();
  145. HttpCookie authcookie = UserHelper.CreateAuthCookie(model.Username, model.RememberMe, Request.Url.Host.GetDomain(), Request.IsLocal);
  146. Response.Cookies.Add(authcookie);
  147. if (string.IsNullOrEmpty(model.ReturnUrl))
  148. {
  149. return Json(new { result = "true" });
  150. }
  151. else
  152. {
  153. return Redirect(model.ReturnUrl);
  154. }
  155. }
  156. }
  157. }
  158. return Json(new { error = "Invalid Username or Password." });
  159. }
  160. public ActionResult Logout()
  161. {
  162. // Get cookie
  163. HttpCookie authCookie = Utility.UserHelper.CreateAuthCookie(User.Identity.Name, false, Request.Url.Host.GetDomain(), Request.IsLocal);
  164. // Signout
  165. FormsAuthentication.SignOut();
  166. Session.Abandon();
  167. // Destroy Cookies
  168. authCookie.Expires = DateTime.Now.AddYears(-1);
  169. Response.Cookies.Add(authCookie);
  170. return Redirect(Url.SubRouteUrl("www", "Home.Index"));
  171. }
  172. [HttpGet]
  173. [TrackPageView]
  174. [AllowAnonymous]
  175. public ActionResult Register(string ReturnUrl)
  176. {
  177. RegisterViewModel model = new RegisterViewModel();
  178. model.ReturnUrl = ReturnUrl;
  179. return View("/Areas/User/Views/User/ViewRegistration.cshtml", model);
  180. }
  181. [HttpPost]
  182. [AllowAnonymous]
  183. public ActionResult Register([Bind(Prefix="Register")]RegisterViewModel model)
  184. {
  185. if (ModelState.IsValid)
  186. {
  187. if (Config.UserConfig.RegistrationEnabled)
  188. {
  189. if (!UserHelper.ValidUsername(Config, model.Username))
  190. {
  191. return Json(new { error = "That username is not valid" });
  192. }
  193. if (!UserHelper.UsernameAvailable(db, Config, model.Username))
  194. {
  195. return Json(new { error = "That username is not available" });
  196. }
  197. if (model.Password != model.ConfirmPassword)
  198. {
  199. return Json(new { error = "Passwords must match" });
  200. }
  201. // PGP Key valid?
  202. if (!string.IsNullOrEmpty(model.PublicKey) && !PGP.IsPublicKey(model.PublicKey))
  203. {
  204. return Json(new { error = "Invalid PGP Public Key" });
  205. }
  206. try
  207. {
  208. User newUser = db.Users.Create();
  209. newUser.JoinDate = DateTime.Now;
  210. newUser.Username = model.Username;
  211. if (!string.IsNullOrEmpty(model.RecoveryEmail))
  212. newUser.RecoveryEmail = model.RecoveryEmail;
  213. newUser.UserSettings = new UserSettings();
  214. if (!string.IsNullOrEmpty(model.PublicKey))
  215. newUser.UserSettings.PGPSignature = model.PublicKey;
  216. newUser.BlogSettings = new BlogSettings();
  217. newUser.UploadSettings = new UploadSettings();
  218. UserHelper.AddAccount(db, Config, newUser, model.Password);
  219. // If they have a recovery email, let's send a verification
  220. if (!string.IsNullOrEmpty(model.RecoveryEmail))
  221. {
  222. string verifyCode = UserHelper.CreateRecoveryEmailVerification(db, Config, newUser);
  223. string resetUrl = Url.SubRouteUrl("user", "User.ResetPassword", new { Username = model.Username });
  224. string verifyUrl = Url.SubRouteUrl("user", "User.VerifyRecoveryEmail", new { Code = verifyCode });
  225. UserHelper.SendRecoveryEmailVerification(Config, model.Username, model.RecoveryEmail, resetUrl, verifyUrl);
  226. }
  227. }
  228. catch (Exception ex)
  229. {
  230. return Json(new { error = ex.GetFullMessage(true) });
  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 pgpPublicKey, string recoveryEmail, string website, string quote, string about, string blogTitle, string blogDesc, bool saveKey, bool serverSideEncrypt)
  240. {
  241. if (ModelState.IsValid)
  242. {
  243. try
  244. {
  245. User user = UserHelper.GetUser(db, User.Identity.Name);
  246. if (user != null)
  247. {
  248. bool changePass = false;
  249. string email = string.Format("{0}@{1}", User.Identity.Name, Config.EmailConfig.Domain);
  250. // Changing Password?
  251. if (!string.IsNullOrEmpty(curPass) && (!string.IsNullOrEmpty(newPass) || !string.IsNullOrEmpty(newPassConfirm)))
  252. {
  253. // Old Password Valid?
  254. if (!UserHelper.UserPasswordCorrect(db, Config, user, curPass))
  255. {
  256. return Json(new { error = "Invalid Original Password." });
  257. }
  258. // The New Password Match?
  259. if (newPass != newPassConfirm)
  260. {
  261. return Json(new { error = "New Password Must Match." });
  262. }
  263. changePass = true;
  264. }
  265. // PGP Key valid?
  266. if (!string.IsNullOrEmpty(pgpPublicKey) && !PGP.IsPublicKey(pgpPublicKey))
  267. {
  268. return Json(new { error = "Invalid PGP Public Key" });
  269. }
  270. user.UserSettings.PGPSignature = pgpPublicKey;
  271. bool newRecovery = false;
  272. if (recoveryEmail != user.RecoveryEmail)
  273. {
  274. newRecovery = true;
  275. user.RecoveryEmail = recoveryEmail;
  276. user.RecoveryVerified = false;
  277. }
  278. user.UserSettings.Website = website;
  279. user.UserSettings.Quote = quote;
  280. user.UserSettings.About = about;
  281. user.BlogSettings.Title = blogTitle;
  282. user.BlogSettings.Description = blogDesc;
  283. user.UploadSettings.SaveKey = saveKey;
  284. user.UploadSettings.ServerSideEncrypt = serverSideEncrypt;
  285. UserHelper.EditAccount(db, Config, user, changePass, newPass);
  286. // If they have a recovery email, let's send a verification
  287. if (!string.IsNullOrEmpty(recoveryEmail) && newRecovery)
  288. {
  289. string verifyCode = UserHelper.CreateRecoveryEmailVerification(db, Config, user);
  290. string resetUrl = Url.SubRouteUrl("user", "User.ResetPassword", new { Username = user.Username });
  291. string verifyUrl = Url.SubRouteUrl("user", "User.VerifyRecoveryEmail", new { Code = verifyCode });
  292. UserHelper.SendRecoveryEmailVerification(Config, user.Username, user.RecoveryEmail, resetUrl, verifyUrl);
  293. }
  294. return Json(new { result = true });
  295. }
  296. return Json(new { error = "User does not exist" });
  297. }
  298. catch (Exception ex)
  299. {
  300. return Json(new { error = ex.GetFullMessage(true) });
  301. }
  302. }
  303. return Json(new { error = "Invalid Parameters" });
  304. }
  305. [HttpPost]
  306. public ActionResult Delete()
  307. {
  308. if (ModelState.IsValid)
  309. {
  310. try
  311. {
  312. User user = UserHelper.GetUser(db, User.Identity.Name);
  313. if (user != null)
  314. {
  315. UserHelper.DeleteAccount(db, Config, user);
  316. // Sign Out
  317. Logout();
  318. return Json(new { result = true });
  319. }
  320. }
  321. catch (Exception ex)
  322. {
  323. return Json(new { error = ex.GetFullMessage(true) });
  324. }
  325. }
  326. return Json(new { error = "Unable to delete user" });
  327. }
  328. [HttpGet]
  329. public ActionResult VerifyRecoveryEmail(string code)
  330. {
  331. bool verified = true;
  332. if (string.IsNullOrEmpty(code))
  333. verified &= false;
  334. verified &= UserHelper.VerifyRecoveryEmail(db, Config, User.Identity.Name, code);
  335. RecoveryEmailVerificationViewModel model = new RecoveryEmailVerificationViewModel();
  336. model.Success = verified;
  337. return View("/Areas/User/Views/User/ViewRecoveryEmailVerification.cshtml", model);
  338. }
  339. [HttpPost]
  340. public ActionResult ResendVerifyRecoveryEmail()
  341. {
  342. if (ModelState.IsValid)
  343. {
  344. try
  345. {
  346. User user = UserHelper.GetUser(db, User.Identity.Name);
  347. if (user != null)
  348. {
  349. // If they have a recovery email, let's send a verification
  350. if (!string.IsNullOrEmpty(user.RecoveryEmail))
  351. {
  352. if (!user.RecoveryVerified)
  353. {
  354. string verifyCode = UserHelper.CreateRecoveryEmailVerification(db, Config, user);
  355. string resetUrl = Url.SubRouteUrl("user", "User.ResetPassword", new { Username = user.Username });
  356. string verifyUrl = Url.SubRouteUrl("user", "User.VerifyRecoveryEmail", new { Code = verifyCode });
  357. UserHelper.SendRecoveryEmailVerification(Config, user.Username, user.RecoveryEmail, resetUrl, verifyUrl);
  358. return Json(new { result = true });
  359. }
  360. return Json(new { error = "The recovery email is already verified" });
  361. }
  362. }
  363. }
  364. catch (Exception ex)
  365. {
  366. return Json(new { error = ex.GetFullMessage(true) });
  367. }
  368. }
  369. return Json(new { error = "Unable to resend verification" });
  370. }
  371. [HttpGet]
  372. [AllowAnonymous]
  373. public ActionResult ResetPassword(string username)
  374. {
  375. ResetPasswordViewModel model = new ResetPasswordViewModel();
  376. model.Username = username;
  377. return View("/Areas/User/Views/User/ResetPassword.cshtml", model);
  378. }
  379. [HttpPost]
  380. [AllowAnonymous]
  381. public ActionResult SendResetPasswordVerification(string username)
  382. {
  383. if (ModelState.IsValid)
  384. {
  385. try
  386. {
  387. User user = UserHelper.GetUser(db, username);
  388. if (user != null)
  389. {
  390. // If they have a recovery email, let's send a verification
  391. if (!string.IsNullOrEmpty(user.RecoveryEmail) && user.RecoveryVerified)
  392. {
  393. string verifyCode = UserHelper.CreateResetPasswordVerification(db, Config, user);
  394. string resetUrl = Url.SubRouteUrl("user", "User.VerifyResetPassword", new { Username = user.Username, Code = verifyCode });
  395. UserHelper.SendResetPasswordVerification(Config, user.Username, user.RecoveryEmail, resetUrl);
  396. return Json(new { result = true });
  397. }
  398. return Json(new { error = "The username doesn't have a recovery email specified" });
  399. }
  400. return Json(new { error = "The username is not valid" });
  401. }
  402. catch (Exception ex)
  403. {
  404. return Json(new { error = ex.GetFullMessage(true) });
  405. }
  406. }
  407. return Json(new { error = "Unable to send reset link" });
  408. }
  409. [HttpGet]
  410. [AllowAnonymous]
  411. public ActionResult VerifyResetPassword(string username, string code)
  412. {
  413. bool verified = true;
  414. if (string.IsNullOrEmpty(code))
  415. verified &= false;
  416. verified &= UserHelper.VerifyResetPassword(db, Config, username, code);
  417. if (verified)
  418. {
  419. // The password reset code is valid, let's log them in
  420. User user = UserHelper.GetUser(db, username);
  421. user.LastSeen = DateTime.Now;
  422. db.Entry(user).State = EntityState.Modified;
  423. db.SaveChanges();
  424. HttpCookie authcookie = UserHelper.CreateAuthCookie(user.Username, false, Request.Url.Host.GetDomain(), Request.IsLocal);
  425. Response.Cookies.Add(authcookie);
  426. }
  427. ResetPasswordVerificationViewModel model = new ResetPasswordVerificationViewModel();
  428. model.Success = verified;
  429. return View("/Areas/User/Views/User/ResetPasswordVerification.cshtml", model);
  430. }
  431. [HttpPost]
  432. public ActionResult SetUserPassword(string password, string confirmPassword)
  433. {
  434. if (ModelState.IsValid)
  435. {
  436. try
  437. {
  438. User user = UserHelper.GetUser(db, User.Identity.Name);
  439. if (user != null)
  440. {
  441. if (string.IsNullOrEmpty(password))
  442. {
  443. return Json(new { error = "Password must not be empty" });
  444. }
  445. if (password != confirmPassword)
  446. {
  447. return Json(new { error = "Passwords must match" });
  448. }
  449. UserHelper.EditAccount(db, Config, user, true, password);
  450. return Json(new { result = true });
  451. }
  452. return Json(new { error = "User does not exist" });
  453. }
  454. catch (Exception ex)
  455. {
  456. return Json(new { error = ex.GetFullMessage(true) });
  457. }
  458. }
  459. return Json(new { error = "Unable to reset user password" });
  460. }
  461. }
  462. }