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.

UserController.cs 45KB

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