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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Entity;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. using System.Web.Security;
  8. using Teknik.Areas.Users.Models;
  9. using Teknik.Areas.Users.ViewModels;
  10. using Teknik.Controllers;
  11. using Teknik.Utilities;
  12. using Teknik.Models;
  13. using Teknik.Areas.Users.Utility;
  14. using Teknik.Filters;
  15. using QRCoder;
  16. using TwoStepsAuthenticator;
  17. using System.Drawing;
  18. using Teknik.Attributes;
  19. namespace Teknik.Areas.Users.Controllers
  20. {
  21. [TeknikAuthorize]
  22. public class UserController : DefaultController
  23. {
  24. private static readonly UsedCodesManager usedCodesManager = new UsedCodesManager();
  25. [TrackPageView]
  26. [AllowAnonymous]
  27. public ActionResult GetPremium()
  28. {
  29. ViewBag.Title = "Get a Premium Account - " + Config.Title;
  30. GetPremiumViewModel model = new GetPremiumViewModel();
  31. return View(model);
  32. }
  33. // GET: Profile/Profile
  34. [TrackPageView]
  35. [AllowAnonymous]
  36. public ActionResult ViewProfile(string username)
  37. {
  38. if (string.IsNullOrEmpty(username))
  39. {
  40. username = User.Identity.Name;
  41. }
  42. ProfileViewModel model = new ProfileViewModel();
  43. ViewBag.Title = "User Does Not Exist - " + Config.Title;
  44. ViewBag.Description = "The User does not exist";
  45. try
  46. {
  47. using (TeknikEntities db = new TeknikEntities())
  48. {
  49. User user = UserHelper.GetUser(db, username);
  50. if (user != null)
  51. {
  52. ViewBag.Title = username + "'s Profile - " + Config.Title;
  53. ViewBag.Description = "Viewing " + username + "'s Profile";
  54. model.UserID = user.UserId;
  55. model.Username = user.Username;
  56. if (Config.EmailConfig.Enabled)
  57. {
  58. model.Email = string.Format("{0}@{1}", user.Username, Config.EmailConfig.Domain);
  59. }
  60. model.JoinDate = user.JoinDate;
  61. model.LastSeen = UserHelper.GetLastAccountActivity(db, Config, user);
  62. model.UserSettings = user.UserSettings;
  63. model.SecuritySettings = user.SecuritySettings;
  64. model.BlogSettings = user.BlogSettings;
  65. model.UploadSettings = user.UploadSettings;
  66. model.Uploads = db.Uploads.Where(u => u.UserId == user.UserId).OrderByDescending(u => u.DateUploaded).ToList();
  67. model.Pastes = db.Pastes.Where(u => u.UserId == user.UserId).OrderByDescending(u => u.DatePosted).ToList();
  68. model.ShortenedUrls = db.ShortenedUrls.Where(s => s.UserId == user.UserId).OrderByDescending(s => s.DateAdded).ToList();
  69. model.Vaults = db.Vaults.Where(v => v.UserId == user.UserId).OrderByDescending(v => v.DateCreated).ToList();
  70. return View(model);
  71. }
  72. model.Error = true;
  73. model.ErrorMessage = "The user does not exist";
  74. }
  75. }
  76. catch (Exception ex)
  77. {
  78. model.Error = true;
  79. model.ErrorMessage = ex.GetFullMessage(true);
  80. }
  81. return View(model);
  82. }
  83. [TrackPageView]
  84. public ActionResult Settings()
  85. {
  86. string username = User.Identity.Name;
  87. SettingsViewModel model = new SettingsViewModel();
  88. ViewBag.Title = "User Does Not Exist - " + Config.Title;
  89. ViewBag.Description = "The User does not exist";
  90. using (TeknikEntities db = new TeknikEntities())
  91. {
  92. User user = UserHelper.GetUser(db, username);
  93. if (user != null)
  94. {
  95. Session["AuthenticatedUser"] = user;
  96. ViewBag.Title = "Settings - " + Config.Title;
  97. ViewBag.Description = "Your " + Config.Title + " Settings";
  98. model.UserID = user.UserId;
  99. model.Username = user.Username;
  100. model.TrustedDeviceCount = user.TrustedDevices.Count;
  101. model.AuthTokens = new List<AuthTokenViewModel>();
  102. foreach (AuthToken token in user.AuthTokens)
  103. {
  104. AuthTokenViewModel tokenModel = new AuthTokenViewModel();
  105. tokenModel.AuthTokenId = token.AuthTokenId;
  106. tokenModel.Name = token.Name;
  107. tokenModel.LastDateUsed = token.LastDateUsed;
  108. model.AuthTokens.Add(tokenModel);
  109. }
  110. model.UserSettings = user.UserSettings;
  111. model.SecuritySettings = user.SecuritySettings;
  112. model.BlogSettings = user.BlogSettings;
  113. model.UploadSettings = user.UploadSettings;
  114. return View(model);
  115. }
  116. }
  117. model.Error = true;
  118. return View(model);
  119. }
  120. [HttpGet]
  121. [TrackPageView]
  122. [AllowAnonymous]
  123. public ActionResult ViewRawPGP(string username)
  124. {
  125. ViewBag.Title = username + "'s Public Key - " + Config.Title;
  126. ViewBag.Description = "The PGP public key for " + username;
  127. using (TeknikEntities db = new TeknikEntities())
  128. {
  129. User user = UserHelper.GetUser(db, username);
  130. if (user != null)
  131. {
  132. if (!string.IsNullOrEmpty(user.SecuritySettings.PGPSignature))
  133. {
  134. return Content(user.SecuritySettings.PGPSignature, "text/plain");
  135. }
  136. }
  137. }
  138. return Redirect(Url.SubRouteUrl("error", "Error.Http404"));
  139. }
  140. [HttpGet]
  141. [TrackPageView]
  142. [AllowAnonymous]
  143. public ActionResult Login(string ReturnUrl)
  144. {
  145. LoginViewModel model = new LoginViewModel();
  146. model.ReturnUrl = ReturnUrl;
  147. return View("/Areas/User/Views/User/ViewLogin.cshtml", model);
  148. }
  149. [HttpPost]
  150. [AllowAnonymous]
  151. public ActionResult Login([Bind(Prefix = "Login")]LoginViewModel model)
  152. {
  153. if (ModelState.IsValid)
  154. {
  155. string username = model.Username;
  156. using (TeknikEntities db = new TeknikEntities())
  157. {
  158. User user = UserHelper.GetUser(db, username);
  159. if (user != null)
  160. {
  161. bool userValid = UserHelper.UserPasswordCorrect(db, Config, user, model.Password);
  162. if (userValid)
  163. {
  164. // Perform transfer actions on the account
  165. UserHelper.TransferUser(db, Config, user, model.Password);
  166. user.LastSeen = DateTime.Now;
  167. db.Entry(user).State = EntityState.Modified;
  168. db.SaveChanges();
  169. // Let's double check their email and git accounts to make sure they exist
  170. string email = UserHelper.GetUserEmailAddress(Config, username);
  171. if (Config.EmailConfig.Enabled && !UserHelper.UserEmailExists(Config, email))
  172. {
  173. UserHelper.AddUserEmail(Config, email, model.Password);
  174. }
  175. if (Config.GitConfig.Enabled && !UserHelper.UserGitExists(Config, username))
  176. {
  177. UserHelper.AddUserGit(Config, username, model.Password);
  178. }
  179. bool twoFactor = false;
  180. string returnUrl = model.ReturnUrl;
  181. if (user.SecuritySettings.TwoFactorEnabled)
  182. {
  183. twoFactor = true;
  184. // We need to check their device, and two factor them
  185. if (user.SecuritySettings.AllowTrustedDevices)
  186. {
  187. // Check for the trusted device cookie
  188. HttpCookie cookie = Request.Cookies[Constants.TRUSTEDDEVICECOOKIE + "_" + username];
  189. if (cookie != null)
  190. {
  191. string token = cookie.Value;
  192. if (user.TrustedDevices.Where(d => d.Token == token).FirstOrDefault() != null)
  193. {
  194. // The device token is attached to the user, let's let it slide
  195. twoFactor = false;
  196. }
  197. }
  198. }
  199. }
  200. if (twoFactor)
  201. {
  202. Session["AuthenticatedUser"] = user;
  203. if (string.IsNullOrEmpty(model.ReturnUrl))
  204. returnUrl = Request.UrlReferrer.AbsoluteUri.ToString();
  205. returnUrl = Url.SubRouteUrl("user", "User.CheckAuthenticatorCode", new { returnUrl = returnUrl, rememberMe = model.RememberMe });
  206. model.ReturnUrl = string.Empty;
  207. }
  208. else
  209. {
  210. returnUrl = Request.UrlReferrer.AbsoluteUri.ToString();
  211. // They don't need two factor auth.
  212. HttpCookie authcookie = UserHelper.CreateAuthCookie(user.Username, model.RememberMe, Request.Url.Host.GetDomain(), Request.IsLocal);
  213. Response.Cookies.Add(authcookie);
  214. }
  215. if (string.IsNullOrEmpty(model.ReturnUrl))
  216. {
  217. return GenerateActionResult(new { result = returnUrl }, Redirect(returnUrl));
  218. }
  219. else
  220. {
  221. return Redirect(model.ReturnUrl);
  222. }
  223. }
  224. }
  225. }
  226. }
  227. model.Error = true;
  228. model.ErrorMessage = "Invalid Username or Password.";
  229. return GenerateActionResult(new { error = model.ErrorMessage }, View("/Areas/User/Views/User/ViewLogin.cshtml", model));
  230. }
  231. public ActionResult Logout()
  232. {
  233. // Get cookie
  234. HttpCookie authCookie = UserHelper.CreateAuthCookie(User.Identity.Name, false, Request.Url.Host.GetDomain(), Request.IsLocal);
  235. // Signout
  236. FormsAuthentication.SignOut();
  237. Session.Abandon();
  238. // Destroy Cookies
  239. authCookie.Expires = DateTime.Now.AddYears(-1);
  240. Response.Cookies.Add(authCookie);
  241. return Redirect(Url.SubRouteUrl("www", "Home.Index"));
  242. }
  243. [HttpGet]
  244. [TrackPageView]
  245. [AllowAnonymous]
  246. public ActionResult Register(string ReturnUrl)
  247. {
  248. RegisterViewModel model = new RegisterViewModel();
  249. model.ReturnUrl = ReturnUrl;
  250. return View("/Areas/User/Views/User/ViewRegistration.cshtml", model);
  251. }
  252. [HttpPost]
  253. [AllowAnonymous]
  254. public ActionResult Register([Bind(Prefix="Register")]RegisterViewModel model)
  255. {
  256. model.Error = false;
  257. model.ErrorMessage = string.Empty;
  258. if (ModelState.IsValid)
  259. {
  260. if (Config.UserConfig.RegistrationEnabled)
  261. {
  262. using (TeknikEntities db = new TeknikEntities())
  263. {
  264. if (!model.Error && !UserHelper.ValidUsername(Config, model.Username))
  265. {
  266. model.Error = true;
  267. model.ErrorMessage = "That username is not valid";
  268. }
  269. if (!model.Error && !UserHelper.UsernameAvailable(db, Config, model.Username))
  270. {
  271. model.Error = true;
  272. model.ErrorMessage = "That username is not available";
  273. }
  274. if (!model.Error && model.Password != model.ConfirmPassword)
  275. {
  276. model.Error = true;
  277. model.ErrorMessage = "Passwords must match";
  278. }
  279. // PGP Key valid?
  280. if (!model.Error && !string.IsNullOrEmpty(model.PublicKey) && !PGP.IsPublicKey(model.PublicKey))
  281. {
  282. model.Error = true;
  283. model.ErrorMessage = "Invalid PGP Public Key";
  284. }
  285. if (!model.Error)
  286. {
  287. try
  288. {
  289. User newUser = db.Users.Create();
  290. newUser.JoinDate = DateTime.Now;
  291. newUser.Username = model.Username;
  292. newUser.UserSettings = new UserSettings();
  293. newUser.SecuritySettings = new SecuritySettings();
  294. newUser.BlogSettings = new BlogSettings();
  295. newUser.UploadSettings = new UploadSettings();
  296. if (!string.IsNullOrEmpty(model.PublicKey))
  297. newUser.SecuritySettings.PGPSignature = model.PublicKey;
  298. if (!string.IsNullOrEmpty(model.RecoveryEmail))
  299. newUser.SecuritySettings.RecoveryEmail = model.RecoveryEmail;
  300. UserHelper.AddAccount(db, Config, newUser, model.Password);
  301. // If they have a recovery email, let's send a verification
  302. if (!string.IsNullOrEmpty(model.RecoveryEmail))
  303. {
  304. string verifyCode = UserHelper.CreateRecoveryEmailVerification(db, Config, newUser);
  305. string resetUrl = Url.SubRouteUrl("user", "User.ResetPassword", new { Username = model.Username });
  306. string verifyUrl = Url.SubRouteUrl("user", "User.VerifyRecoveryEmail", new { Code = verifyCode });
  307. UserHelper.SendRecoveryEmailVerification(Config, model.Username, model.RecoveryEmail, resetUrl, verifyUrl);
  308. }
  309. }
  310. catch (Exception ex)
  311. {
  312. model.Error = true;
  313. model.ErrorMessage = ex.GetFullMessage(true);
  314. }
  315. if (!model.Error)
  316. {
  317. return Login(new LoginViewModel { Username = model.Username, Password = model.Password, RememberMe = false, ReturnUrl = model.ReturnUrl });
  318. }
  319. }
  320. }
  321. }
  322. if (!model.Error)
  323. {
  324. model.Error = true;
  325. model.ErrorMessage = "User Registration is Disabled";
  326. }
  327. }
  328. return GenerateActionResult(new { error = model.ErrorMessage }, View("/Areas/User/Views/User/ViewRegistration.cshtml", model));
  329. }
  330. [HttpPost]
  331. [ValidateAntiForgeryToken]
  332. public ActionResult Edit(string curPass, string newPass, string newPassConfirm, string pgpPublicKey, string recoveryEmail, bool allowTrustedDevices, bool twoFactorEnabled, string website, string quote, string about, string blogTitle, string blogDesc, bool encrypt)
  333. {
  334. if (ModelState.IsValid)
  335. {
  336. try
  337. {
  338. using (TeknikEntities db = new TeknikEntities())
  339. {
  340. User user = UserHelper.GetUser(db, User.Identity.Name);
  341. if (user != null)
  342. {
  343. bool changePass = false;
  344. string email = string.Format("{0}@{1}", User.Identity.Name, Config.EmailConfig.Domain);
  345. // Changing Password?
  346. if (!string.IsNullOrEmpty(curPass) && (!string.IsNullOrEmpty(newPass) || !string.IsNullOrEmpty(newPassConfirm)))
  347. {
  348. // Old Password Valid?
  349. if (!UserHelper.UserPasswordCorrect(db, Config, user, curPass))
  350. {
  351. return Json(new { error = "Invalid Original Password." });
  352. }
  353. // The New Password Match?
  354. if (newPass != newPassConfirm)
  355. {
  356. return Json(new { error = "New Password Must Match." });
  357. }
  358. // Are password resets enabled?
  359. if (!Config.UserConfig.PasswordResetEnabled)
  360. {
  361. return Json(new { error = "Password resets are disabled." });
  362. }
  363. changePass = true;
  364. }
  365. // PGP Key valid?
  366. if (!string.IsNullOrEmpty(pgpPublicKey) && !PGP.IsPublicKey(pgpPublicKey))
  367. {
  368. return Json(new { error = "Invalid PGP Public Key" });
  369. }
  370. user.SecuritySettings.PGPSignature = pgpPublicKey;
  371. // Recovery Email
  372. bool newRecovery = false;
  373. if (recoveryEmail != user.SecuritySettings.RecoveryEmail)
  374. {
  375. newRecovery = true;
  376. user.SecuritySettings.RecoveryEmail = recoveryEmail;
  377. user.SecuritySettings.RecoveryVerified = false;
  378. }
  379. // Trusted Devices
  380. user.SecuritySettings.AllowTrustedDevices = allowTrustedDevices;
  381. if (!allowTrustedDevices)
  382. {
  383. // They turned it off, let's clear the trusted devices
  384. user.TrustedDevices.Clear();
  385. List<TrustedDevice> foundDevices = db.TrustedDevices.Where(d => d.UserId == user.UserId).ToList();
  386. if (foundDevices != null)
  387. {
  388. foreach (TrustedDevice device in foundDevices)
  389. {
  390. db.TrustedDevices.Remove(device);
  391. }
  392. }
  393. }
  394. // Two Factor Authentication
  395. bool oldTwoFactor = user.SecuritySettings.TwoFactorEnabled;
  396. user.SecuritySettings.TwoFactorEnabled = twoFactorEnabled;
  397. string newKey = string.Empty;
  398. if (!oldTwoFactor && twoFactorEnabled)
  399. {
  400. // They just enabled it, let's regen the key
  401. newKey = Authenticator.GenerateKey();
  402. }
  403. else if (!twoFactorEnabled)
  404. {
  405. // remove the key when it's disabled
  406. newKey = string.Empty;
  407. }
  408. else
  409. {
  410. // No change, let's use the old value
  411. newKey = user.SecuritySettings.TwoFactorKey;
  412. }
  413. user.SecuritySettings.TwoFactorKey = newKey;
  414. // Profile Info
  415. user.UserSettings.Website = website;
  416. user.UserSettings.Quote = quote;
  417. user.UserSettings.About = about;
  418. // Blogs
  419. user.BlogSettings.Title = blogTitle;
  420. user.BlogSettings.Description = blogDesc;
  421. // Uploads
  422. user.UploadSettings.Encrypt = encrypt;
  423. UserHelper.EditAccount(db, Config, user, changePass, newPass);
  424. // If they have a recovery email, let's send a verification
  425. if (!string.IsNullOrEmpty(recoveryEmail) && newRecovery)
  426. {
  427. string verifyCode = UserHelper.CreateRecoveryEmailVerification(db, Config, user);
  428. string resetUrl = Url.SubRouteUrl("user", "User.ResetPassword", new { Username = user.Username });
  429. string verifyUrl = Url.SubRouteUrl("user", "User.VerifyRecoveryEmail", new { Code = verifyCode });
  430. UserHelper.SendRecoveryEmailVerification(Config, user.Username, user.SecuritySettings.RecoveryEmail, resetUrl, verifyUrl);
  431. }
  432. if (!oldTwoFactor && twoFactorEnabled)
  433. {
  434. return Json(new { result = new { checkAuth = true, key = newKey, qrUrl = Url.SubRouteUrl("user", "User.Action", new { action = "GenerateAuthQrCode", key = newKey }) } });
  435. }
  436. return Json(new { result = true });
  437. }
  438. return Json(new { error = "User does not exist" });
  439. }
  440. }
  441. catch (Exception ex)
  442. {
  443. return Json(new { error = ex.GetFullMessage(true) });
  444. }
  445. }
  446. return Json(new { error = "Invalid Parameters" });
  447. }
  448. [HttpPost]
  449. [ValidateAntiForgeryToken]
  450. public ActionResult Delete()
  451. {
  452. if (ModelState.IsValid)
  453. {
  454. try
  455. {
  456. using (TeknikEntities db = new TeknikEntities())
  457. {
  458. User user = UserHelper.GetUser(db, User.Identity.Name);
  459. if (user != null)
  460. {
  461. UserHelper.DeleteAccount(db, Config, user);
  462. // Sign Out
  463. Logout();
  464. return Json(new { result = true });
  465. }
  466. }
  467. }
  468. catch (Exception ex)
  469. {
  470. return Json(new { error = ex.GetFullMessage(true) });
  471. }
  472. }
  473. return Json(new { error = "Unable to delete user" });
  474. }
  475. [HttpGet]
  476. public ActionResult VerifyRecoveryEmail(string code)
  477. {
  478. bool verified = true;
  479. if (string.IsNullOrEmpty(code))
  480. verified &= false;
  481. // Is there a code?
  482. if (verified)
  483. {
  484. using (TeknikEntities db = new TeknikEntities())
  485. {
  486. verified &= UserHelper.VerifyRecoveryEmail(db, Config, User.Identity.Name, code);
  487. }
  488. }
  489. RecoveryEmailVerificationViewModel model = new RecoveryEmailVerificationViewModel();
  490. model.Success = verified;
  491. return View("/Areas/User/Views/User/ViewRecoveryEmailVerification.cshtml", model);
  492. }
  493. [HttpPost]
  494. [ValidateAntiForgeryToken]
  495. public ActionResult ResendVerifyRecoveryEmail()
  496. {
  497. if (ModelState.IsValid)
  498. {
  499. try
  500. {
  501. using (TeknikEntities db = new TeknikEntities())
  502. {
  503. User user = UserHelper.GetUser(db, User.Identity.Name);
  504. if (user != null)
  505. {
  506. // If they have a recovery email, let's send a verification
  507. if (!string.IsNullOrEmpty(user.SecuritySettings.RecoveryEmail))
  508. {
  509. if (!user.SecuritySettings.RecoveryVerified)
  510. {
  511. string verifyCode = UserHelper.CreateRecoveryEmailVerification(db, Config, user);
  512. string resetUrl = Url.SubRouteUrl("user", "User.ResetPassword", new { Username = user.Username });
  513. string verifyUrl = Url.SubRouteUrl("user", "User.VerifyRecoveryEmail", new { Code = verifyCode });
  514. UserHelper.SendRecoveryEmailVerification(Config, user.Username, user.SecuritySettings.RecoveryEmail, resetUrl, verifyUrl);
  515. return Json(new { result = true });
  516. }
  517. return Json(new { error = "The recovery email is already verified" });
  518. }
  519. }
  520. }
  521. }
  522. catch (Exception ex)
  523. {
  524. return Json(new { error = ex.GetFullMessage(true) });
  525. }
  526. }
  527. return Json(new { error = "Unable to resend verification" });
  528. }
  529. [HttpGet]
  530. [AllowAnonymous]
  531. public ActionResult ResetPassword(string username)
  532. {
  533. ResetPasswordViewModel model = new ResetPasswordViewModel();
  534. model.Username = username;
  535. return View("/Areas/User/Views/User/ResetPassword.cshtml", model);
  536. }
  537. [HttpPost]
  538. [AllowAnonymous]
  539. [ValidateAntiForgeryToken]
  540. public ActionResult SendResetPasswordVerification(string username)
  541. {
  542. if (ModelState.IsValid)
  543. {
  544. try
  545. {
  546. using (TeknikEntities db = new TeknikEntities())
  547. {
  548. User user = UserHelper.GetUser(db, username);
  549. if (user != null)
  550. {
  551. // If they have a recovery email, let's send a verification
  552. if (!string.IsNullOrEmpty(user.SecuritySettings.RecoveryEmail) && user.SecuritySettings.RecoveryVerified)
  553. {
  554. string verifyCode = UserHelper.CreateResetPasswordVerification(db, Config, user);
  555. string resetUrl = Url.SubRouteUrl("user", "User.VerifyResetPassword", new { Username = user.Username, Code = verifyCode });
  556. UserHelper.SendResetPasswordVerification(Config, user.Username, user.SecuritySettings.RecoveryEmail, resetUrl);
  557. return Json(new { result = true });
  558. }
  559. return Json(new { error = "The username doesn't have a recovery email specified" });
  560. }
  561. return Json(new { error = "The username is not valid" });
  562. }
  563. }
  564. catch (Exception ex)
  565. {
  566. return Json(new { error = ex.GetFullMessage(true) });
  567. }
  568. }
  569. return Json(new { error = "Unable to send reset link" });
  570. }
  571. [HttpGet]
  572. [AllowAnonymous]
  573. public ActionResult VerifyResetPassword(string username, string code)
  574. {
  575. bool verified = true;
  576. if (string.IsNullOrEmpty(code))
  577. verified &= false;
  578. // Is there a code?
  579. if (verified)
  580. {
  581. using (TeknikEntities db = new TeknikEntities())
  582. {
  583. verified &= UserHelper.VerifyResetPassword(db, Config, username, code);
  584. if (verified)
  585. {
  586. // The password reset code is valid, let's get their user account for this session
  587. User user = UserHelper.GetUser(db, username);
  588. Session["AuthenticatedUser"] = user;
  589. Session["AuthCode"] = code;
  590. }
  591. }
  592. }
  593. ResetPasswordVerificationViewModel model = new ResetPasswordVerificationViewModel();
  594. model.Success = verified;
  595. return View("/Areas/User/Views/User/ResetPasswordVerification.cshtml", model);
  596. }
  597. [HttpPost]
  598. [AllowAnonymous]
  599. [ValidateAntiForgeryToken]
  600. public ActionResult SetUserPassword(string password, string confirmPassword)
  601. {
  602. if (ModelState.IsValid)
  603. {
  604. try
  605. {
  606. string code = Session["AuthCode"].ToString();
  607. if (!string.IsNullOrEmpty(code))
  608. {
  609. User user = (User)Session["AuthenticatedUser"];
  610. if (user != null)
  611. {
  612. if (string.IsNullOrEmpty(password))
  613. {
  614. return Json(new { error = "Password must not be empty" });
  615. }
  616. if (password != confirmPassword)
  617. {
  618. return Json(new { error = "Passwords must match" });
  619. }
  620. using (TeknikEntities db = new TeknikEntities())
  621. {
  622. User newUser = UserHelper.GetUser(db, user.Username);
  623. UserHelper.EditAccount(db, Config, newUser, true, password);
  624. }
  625. return Json(new { result = true });
  626. }
  627. return Json(new { error = "User does not exist" });
  628. }
  629. return Json(new { error = "Invalid Code" });
  630. }
  631. catch (Exception ex)
  632. {
  633. return Json(new { error = ex.GetFullMessage(true) });
  634. }
  635. }
  636. return Json(new { error = "Unable to reset user password" });
  637. }
  638. [HttpGet]
  639. [AllowAnonymous]
  640. public ActionResult ConfirmTwoFactorAuth(string returnUrl, bool rememberMe)
  641. {
  642. User user = (User)Session["AuthenticatedUser"];
  643. if (user != null)
  644. {
  645. ViewBag.Title = "Unknown Device - " + Config.Title;
  646. ViewBag.Description = "We do not recognize this device.";
  647. TwoFactorViewModel model = new TwoFactorViewModel();
  648. model.ReturnUrl = returnUrl;
  649. model.RememberMe = rememberMe;
  650. model.AllowTrustedDevice = user.SecuritySettings.AllowTrustedDevices;
  651. return View("/Areas/User/Views/User/TwoFactorCheck.cshtml", model);
  652. }
  653. return Redirect(Url.SubRouteUrl("error", "Error.Http403"));
  654. }
  655. [HttpPost]
  656. [AllowAnonymous]
  657. [ValidateAntiForgeryToken]
  658. public ActionResult ConfirmAuthenticatorCode(string code, string returnUrl, bool rememberMe, bool rememberDevice, string deviceName)
  659. {
  660. User user = (User)Session["AuthenticatedUser"];
  661. if (user != null)
  662. {
  663. if (user.SecuritySettings.TwoFactorEnabled)
  664. {
  665. string key = user.SecuritySettings.TwoFactorKey;
  666. TimeAuthenticator ta = new TimeAuthenticator(usedCodeManager: usedCodesManager);
  667. bool isValid = ta.CheckCode(key, code, user);
  668. if (isValid)
  669. {
  670. // the code was valid, let's log them in!
  671. HttpCookie authcookie = UserHelper.CreateAuthCookie(user.Username, rememberMe, Request.Url.Host.GetDomain(), Request.IsLocal);
  672. Response.Cookies.Add(authcookie);
  673. if (user.SecuritySettings.AllowTrustedDevices && rememberDevice)
  674. {
  675. // They want to remember the device, and have allow trusted devices on
  676. HttpCookie trustedDeviceCookie = UserHelper.CreateTrustedDeviceCookie(user.Username, Request.Url.Host.GetDomain(), Request.IsLocal);
  677. Response.Cookies.Add(trustedDeviceCookie);
  678. using (TeknikEntities db = new TeknikEntities())
  679. {
  680. TrustedDevice device = new TrustedDevice();
  681. device.UserId = user.UserId;
  682. device.Name = (string.IsNullOrEmpty(deviceName)) ? "Unknown" : deviceName;
  683. device.DateSeen = DateTime.Now;
  684. device.Token = trustedDeviceCookie.Value;
  685. // Add the token
  686. db.TrustedDevices.Add(device);
  687. db.SaveChanges();
  688. }
  689. }
  690. if (string.IsNullOrEmpty(returnUrl))
  691. returnUrl = Request.UrlReferrer.AbsoluteUri.ToString();
  692. return Json(new { result = returnUrl });
  693. }
  694. return Json(new { error = "Invalid Authentication Code" });
  695. }
  696. return Json(new { error = "User does not have Two Factor Authentication enabled" });
  697. }
  698. return Json(new { error = "User does not exist" });
  699. }
  700. [HttpPost]
  701. [ValidateAntiForgeryToken]
  702. public ActionResult VerifyAuthenticatorCode(string code)
  703. {
  704. using (TeknikEntities db = new TeknikEntities())
  705. {
  706. User user = UserHelper.GetUser(db, User.Identity.Name);
  707. if (user != null)
  708. {
  709. if (user.SecuritySettings.TwoFactorEnabled)
  710. {
  711. string key = user.SecuritySettings.TwoFactorKey;
  712. TimeAuthenticator ta = new TimeAuthenticator(usedCodeManager: usedCodesManager);
  713. bool isValid = ta.CheckCode(key, code, user);
  714. if (isValid)
  715. {
  716. return Json(new { result = true });
  717. }
  718. return Json(new { error = "Invalid Authentication Code" });
  719. }
  720. return Json(new { error = "User does not have Two Factor Authentication enabled" });
  721. }
  722. return Json(new { error = "User does not exist" });
  723. }
  724. }
  725. [HttpGet]
  726. public ActionResult GenerateAuthQrCode(string key)
  727. {
  728. var ProvisionUrl = string.Format("otpauth://totp/{0}:{1}?secret={2}", Config.Title, User.Identity.Name, key);
  729. QRCodeGenerator qrGenerator = new QRCodeGenerator();
  730. QRCodeData qrCodeData = qrGenerator.CreateQrCode(ProvisionUrl, QRCodeGenerator.ECCLevel.Q);
  731. QRCode qrCode = new QRCode(qrCodeData);
  732. Bitmap qrCodeImage = qrCode.GetGraphic(20);
  733. return File(ByteHelper.ImageToByte(qrCodeImage), "image/png");
  734. }
  735. [HttpPost]
  736. [ValidateAntiForgeryToken]
  737. public ActionResult ClearTrustedDevices()
  738. {
  739. try
  740. {
  741. using (TeknikEntities db = new TeknikEntities())
  742. {
  743. User user = UserHelper.GetUser(db, User.Identity.Name);
  744. if (user != null)
  745. {
  746. if (user.SecuritySettings.AllowTrustedDevices)
  747. {
  748. // let's clear the trusted devices
  749. user.TrustedDevices.Clear();
  750. List<TrustedDevice> foundDevices = db.TrustedDevices.Where(d => d.UserId == user.UserId).ToList();
  751. if (foundDevices != null)
  752. {
  753. foreach (TrustedDevice device in foundDevices)
  754. {
  755. db.TrustedDevices.Remove(device);
  756. }
  757. }
  758. db.Entry(user).State = EntityState.Modified;
  759. db.SaveChanges();
  760. return Json(new { result = true });
  761. }
  762. return Json(new { error = "User does not allow trusted devices" });
  763. }
  764. return Json(new { error = "User does not exist" });
  765. }
  766. }
  767. catch (Exception ex)
  768. {
  769. return Json(new { error = ex.GetFullMessage(true) });
  770. }
  771. }
  772. [HttpPost]
  773. [ValidateAntiForgeryToken]
  774. public ActionResult GenerateToken(string name)
  775. {
  776. try
  777. {
  778. using (TeknikEntities db = new TeknikEntities())
  779. {
  780. User user = UserHelper.GetUser(db, User.Identity.Name);
  781. if (user != null)
  782. {
  783. string newTokenStr = UserHelper.GenerateAuthToken(db, user.Username);
  784. if (!string.IsNullOrEmpty(newTokenStr))
  785. {
  786. AuthToken token = db.AuthTokens.Create();
  787. token.UserId = user.UserId;
  788. token.HashedToken = SHA256.Hash(newTokenStr);
  789. token.Name = name;
  790. db.AuthTokens.Add(token);
  791. db.SaveChanges();
  792. AuthTokenViewModel model = new AuthTokenViewModel();
  793. model.AuthTokenId = token.AuthTokenId;
  794. model.Name = token.Name;
  795. model.LastDateUsed = token.LastDateUsed;
  796. return Json(new { result = new { token = newTokenStr, html = PartialView("~/Areas/User/Views/User/AuthToken.cshtml", model).RenderToString() } });
  797. }
  798. return Json(new { error = "Unable to generate Auth Token" });
  799. }
  800. return Json(new { error = "User does not exist" });
  801. }
  802. }
  803. catch (Exception ex)
  804. {
  805. return Json(new { error = ex.GetFullMessage(true) });
  806. }
  807. }
  808. [HttpPost]
  809. [ValidateAntiForgeryToken]
  810. public ActionResult RevokeAllTokens()
  811. {
  812. try
  813. {
  814. using (TeknikEntities db = new TeknikEntities())
  815. {
  816. User user = UserHelper.GetUser(db, User.Identity.Name);
  817. if (user != null)
  818. {
  819. user.AuthTokens.Clear();
  820. List<AuthToken> foundTokens = db.AuthTokens.Where(d => d.UserId == user.UserId).ToList();
  821. if (foundTokens != null)
  822. {
  823. foreach (AuthToken token in foundTokens)
  824. {
  825. db.AuthTokens.Remove(token);
  826. }
  827. }
  828. db.Entry(user).State = EntityState.Modified;
  829. db.SaveChanges();
  830. return Json(new { result = true });
  831. }
  832. return Json(new { error = "User does not exist" });
  833. }
  834. }
  835. catch (Exception ex)
  836. {
  837. return Json(new { error = ex.GetFullMessage(true) });
  838. }
  839. }
  840. [HttpPost]
  841. [ValidateAntiForgeryToken]
  842. public ActionResult EditTokenName(int tokenId, string name)
  843. {
  844. try
  845. {
  846. using (TeknikEntities db = new TeknikEntities())
  847. {
  848. User user = UserHelper.GetUser(db, User.Identity.Name);
  849. if (user != null)
  850. {
  851. AuthToken foundToken = db.AuthTokens.Where(d => d.UserId == user.UserId && d.AuthTokenId == tokenId).FirstOrDefault();
  852. if (foundToken != null)
  853. {
  854. foundToken.Name = name;
  855. db.Entry(foundToken).State = EntityState.Modified;
  856. db.SaveChanges();
  857. return Json(new { result = new { name = name } });
  858. }
  859. return Json(new { error = "Authentication Token does not exist" });
  860. }
  861. return Json(new { error = "User does not exist" });
  862. }
  863. }
  864. catch (Exception ex)
  865. {
  866. return Json(new { error = ex.GetFullMessage(true) });
  867. }
  868. }
  869. [HttpPost]
  870. [ValidateAntiForgeryToken]
  871. public ActionResult DeleteToken(int tokenId)
  872. {
  873. try
  874. {
  875. using (TeknikEntities db = new TeknikEntities())
  876. {
  877. User user = UserHelper.GetUser(db, User.Identity.Name);
  878. if (user != null)
  879. {
  880. AuthToken foundToken = db.AuthTokens.Where(d => d.UserId == user.UserId && d.AuthTokenId == tokenId).FirstOrDefault();
  881. if (foundToken != null)
  882. {
  883. db.AuthTokens.Remove(foundToken);
  884. user.AuthTokens.Remove(foundToken);
  885. db.Entry(user).State = EntityState.Modified;
  886. db.SaveChanges();
  887. return Json(new { result = true });
  888. }
  889. return Json(new { error = "Authentication Token does not exist" });
  890. }
  891. return Json(new { error = "User does not exist" });
  892. }
  893. }
  894. catch (Exception ex)
  895. {
  896. return Json(new { error = ex.GetFullMessage(true) });
  897. }
  898. }
  899. }
  900. }