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.

UserHelper.cs 42KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.Entity;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Mail;
  8. using System.Runtime.InteropServices;
  9. using System.Text;
  10. using System.Text.RegularExpressions;
  11. using System.Threading.Tasks;
  12. using System.Web;
  13. using System.Web.Security;
  14. using Teknik.Areas.Blog.Models;
  15. using Teknik.Areas.Shortener.Models;
  16. using Teknik.Areas.Users.Models;
  17. using Teknik.Configuration;
  18. using Teknik.Utilities;
  19. using Teknik.Models;
  20. using Teknik.Utilities.Cryptography;
  21. namespace Teknik.Areas.Users.Utility
  22. {
  23. public static class UserHelper
  24. {
  25. #region Account Management
  26. public static List<string> GetReservedUsernames(Config config)
  27. {
  28. List<string> foundNames = new List<string>();
  29. if (config != null)
  30. {
  31. string path = config.UserConfig.ReservedUsernameDefinitionFile;
  32. if (File.Exists(path))
  33. {
  34. string[] names = File.ReadAllLines(path);
  35. foundNames = names.ToList();
  36. }
  37. }
  38. return foundNames;
  39. }
  40. public static bool UsernameReserved(Config config, string username)
  41. {
  42. // Load reserved usernames
  43. List<string> reserved = GetReservedUsernames(config);
  44. return (reserved.Exists(u => u.ToLower() == username.ToLower()));
  45. }
  46. public static bool ValidUsername(Config config, string username)
  47. {
  48. bool isValid = true;
  49. // Must be something there
  50. isValid &= !string.IsNullOrEmpty(username);
  51. // Is the format correct?
  52. Regex reg = new Regex(config.UserConfig.UsernameFilter);
  53. isValid &= reg.IsMatch(username);
  54. // Meets the min length?
  55. isValid &= (username.Length >= config.UserConfig.MinUsernameLength);
  56. // Meets the max length?
  57. isValid &= (username.Length <= config.UserConfig.MaxUsernameLength);
  58. return isValid;
  59. }
  60. public static bool UsernameAvailable(TeknikEntities db, Config config, string username)
  61. {
  62. bool isAvailable = true;
  63. isAvailable &= ValidUsername(config, username);
  64. isAvailable &= !UsernameReserved(config, username);
  65. isAvailable &= !UserExists(db, username);
  66. isAvailable &= !UserEmailExists(config, GetUserEmailAddress(config, username));
  67. isAvailable &= !UserGitExists(config, username);
  68. return isAvailable;
  69. }
  70. public static DateTime GetLastAccountActivity(TeknikEntities db, Config config, User user)
  71. {
  72. try
  73. {
  74. DateTime lastActive = new DateTime(1900, 1, 1);
  75. DateTime emailLastActive = UserEmailLastActive(config, GetUserEmailAddress(config, user.Username));
  76. if (lastActive < emailLastActive)
  77. lastActive = emailLastActive;
  78. DateTime gitLastActive = UserGitLastActive(config, user.Username);
  79. if (lastActive < gitLastActive)
  80. lastActive = gitLastActive;
  81. DateTime userLastActive = UserLastActive(db, config, user);
  82. if (lastActive < userLastActive)
  83. lastActive = userLastActive;
  84. return lastActive;
  85. }
  86. catch (Exception ex)
  87. {
  88. throw new Exception("Unable to determine last account activity.", ex);
  89. }
  90. }
  91. public static string GeneratePassword(Config config, User user, string password)
  92. {
  93. try
  94. {
  95. string username = user.Username.ToLower();
  96. if (user.Transfers.ToList().Exists(t => t.Type == TransferTypes.CaseSensitivePassword))
  97. {
  98. username = user.Username;
  99. }
  100. byte[] hashBytes = SHA384.Hash(username, password);
  101. string hash = hashBytes.ToHex();
  102. if (user.Transfers.ToList().Exists(t => t.Type == TransferTypes.ASCIIPassword))
  103. {
  104. hash = Encoding.ASCII.GetString(hashBytes);
  105. }
  106. if (user.Transfers.ToList().Exists(t => t.Type == TransferTypes.Sha256Password))
  107. {
  108. hash = SHA256.Hash(password, config.Salt1, config.Salt2);
  109. }
  110. return hash;
  111. }
  112. catch (Exception ex)
  113. {
  114. throw new Exception("Unable to generate password.", ex);
  115. }
  116. }
  117. public static string GenerateAuthToken(TeknikEntities db, string username)
  118. {
  119. try
  120. {
  121. bool validToken = false;
  122. string token = string.Empty;
  123. while (!validToken)
  124. {
  125. username = username.ToLower();
  126. byte[] hashBytes = SHA384.Hash(username, StringHelper.RandomString(24));
  127. token = hashBytes.ToHex();
  128. // Make sure it isn't a duplicate
  129. string hashedToken = SHA256.Hash(token);
  130. if (!db.AuthTokens.Where(t => t.HashedToken == hashedToken).Any())
  131. {
  132. validToken = true;
  133. }
  134. }
  135. return token;
  136. }
  137. catch (Exception ex)
  138. {
  139. throw new Exception("Unable to generate user auth token.", ex);
  140. }
  141. }
  142. public static void AddAccount(TeknikEntities db, Config config, User user, string password)
  143. {
  144. try
  145. {
  146. // Create an Email Account
  147. AddUserEmail(config, GetUserEmailAddress(config, user.Username), password);
  148. // Create a Git Account
  149. AddUserGit(config, user.Username, password);
  150. // Add User
  151. AddUser(db, config, user, password);
  152. }
  153. catch (Exception ex)
  154. {
  155. throw new Exception("Unable to create account.", ex);
  156. }
  157. }
  158. public static void EditAccount(TeknikEntities db, Config config, User user, bool changePass, string password)
  159. {
  160. try
  161. {
  162. // Changing Password?
  163. if (changePass)
  164. {
  165. // Make sure they have a git and email account before resetting their password
  166. string email = GetUserEmailAddress(config, user.Username);
  167. if (config.EmailConfig.Enabled && !UserEmailExists(config, email))
  168. {
  169. AddUserEmail(config, email, password);
  170. }
  171. if (config.GitConfig.Enabled && !UserGitExists(config, user.Username))
  172. {
  173. AddUserGit(config, user.Username, password);
  174. }
  175. // Change email password
  176. EditUserEmailPassword(config, GetUserEmailAddress(config, user.Username), password);
  177. // Update Git password
  178. EditUserGitPassword(config, user.Username, password);
  179. }
  180. // Update User
  181. EditUser(db, config, user, changePass, password);
  182. }
  183. catch (Exception ex)
  184. {
  185. throw new Exception("Unable to edit account.", ex);
  186. }
  187. }
  188. public static void DeleteAccount(TeknikEntities db, Config config, User user)
  189. {
  190. try
  191. {
  192. // Delete Email Account
  193. if (UserEmailExists(config, GetUserEmailAddress(config, user.Username)))
  194. DeleteUserEmail(config, GetUserEmailAddress(config, user.Username));
  195. // Delete Git Account
  196. if (UserGitExists(config, user.Username))
  197. DeleteUserGit(config, user.Username);
  198. // Delete User Account
  199. DeleteUser(db, config, user);
  200. }
  201. catch (Exception ex)
  202. {
  203. throw new Exception("Unable to delete account.", ex);
  204. }
  205. }
  206. #endregion
  207. #region User Management
  208. public static User GetUser(TeknikEntities db, string username)
  209. {
  210. User user = db.Users.Where(b => b.Username == username).FirstOrDefault();
  211. if (user != null)
  212. {
  213. user.UserSettings = db.UserSettings.Find(user.UserId);
  214. user.SecuritySettings = db.SecuritySettings.Find(user.UserId);
  215. user.BlogSettings = db.BlogSettings.Find(user.UserId);
  216. user.UploadSettings = db.UploadSettings.Find(user.UserId);
  217. }
  218. return user;
  219. }
  220. public static User GetUserFromToken(TeknikEntities db, string username, string token)
  221. {
  222. if (token != null && !string.IsNullOrEmpty(username))
  223. {
  224. string hashedToken = SHA256.Hash(token);
  225. return db.Users.FirstOrDefault(u => u.AuthTokens.Select(a => a.HashedToken).Contains(hashedToken) && u.Username == username);
  226. }
  227. return null;
  228. }
  229. public static bool UserExists(TeknikEntities db, string username)
  230. {
  231. User user = GetUser(db, username);
  232. if (user != null)
  233. {
  234. return true;
  235. }
  236. return false;
  237. }
  238. public static DateTime UserLastActive(TeknikEntities db, Config config, User user)
  239. {
  240. try
  241. {
  242. DateTime lastActive = new DateTime(1900, 1, 1);
  243. if (lastActive < user.LastSeen)
  244. lastActive = user.LastSeen;
  245. return lastActive;
  246. }
  247. catch (Exception ex)
  248. {
  249. throw new Exception("Unable to determine last user activity.", ex);
  250. }
  251. }
  252. public static void UpdateTokenLastUsed(TeknikEntities db, string username, string token, DateTime lastUsed)
  253. {
  254. User foundUser = GetUser(db, username);
  255. if (foundUser != null)
  256. {
  257. string hashedToken = SHA256.Hash(token);
  258. List<AuthToken> tokens = foundUser.AuthTokens.Where(t => t.HashedToken == hashedToken).ToList();
  259. if (tokens != null)
  260. {
  261. foreach (AuthToken foundToken in tokens)
  262. {
  263. foundToken.LastDateUsed = lastUsed;
  264. db.Entry(foundToken).State = EntityState.Modified;
  265. }
  266. db.SaveChanges();
  267. }
  268. }
  269. }
  270. public static bool UserPasswordCorrect(TeknikEntities db, Config config, User user, string password)
  271. {
  272. try
  273. {
  274. string hash = GeneratePassword(config, user, password);
  275. return db.Users.Any(b => b.Username == user.Username && b.HashedPassword == hash);
  276. }
  277. catch (Exception ex)
  278. {
  279. throw new Exception("Unable to determine if password is correct.", ex);
  280. }
  281. }
  282. public static bool UserTokenCorrect(TeknikEntities db, string username, string token)
  283. {
  284. User foundUser = GetUserFromToken(db, username, token);
  285. if (foundUser != null)
  286. {
  287. return true;
  288. }
  289. return false;
  290. }
  291. public static bool UserHasRoles(TeknikEntities db, User user, params string[] roles)
  292. {
  293. bool hasRole = true;
  294. if (user != null)
  295. {
  296. // Check if they have the role specified
  297. if (roles.Any())
  298. {
  299. foreach (string role in roles)
  300. {
  301. if (!string.IsNullOrEmpty(role))
  302. {
  303. if (user.Groups.Where(g => g.Roles.Where(r => role == r.Name).Any()).Any())
  304. {
  305. // They have the role!
  306. return true;
  307. }
  308. else
  309. {
  310. // They don't have this role, so let's reset the hasRole
  311. hasRole = false;
  312. }
  313. }
  314. else
  315. {
  316. // Only set this if we haven't failed once already
  317. hasRole &= true;
  318. }
  319. }
  320. }
  321. else
  322. {
  323. // No roles to check, so they pass!
  324. return true;
  325. }
  326. }
  327. else
  328. {
  329. hasRole = false;
  330. }
  331. return hasRole;
  332. }
  333. public static void TransferUser(TeknikEntities db, Config config, User user, string password)
  334. {
  335. try
  336. {
  337. List<TransferType> transfers = user.Transfers.ToList();
  338. for (int i = 0; i < transfers.Count; i++)
  339. {
  340. TransferType transfer = transfers[i];
  341. switch (transfer.Type)
  342. {
  343. case TransferTypes.Sha256Password:
  344. case TransferTypes.CaseSensitivePassword:
  345. case TransferTypes.ASCIIPassword:
  346. user.HashedPassword = SHA384.Hash(user.Username.ToLower(), password).ToHex();
  347. break;
  348. default:
  349. break;
  350. }
  351. user.Transfers.Remove(transfer);
  352. }
  353. db.Entry(user).State = EntityState.Modified;
  354. db.SaveChanges();
  355. }
  356. catch (Exception ex)
  357. {
  358. throw new Exception("Unable to transfer user info.", ex);
  359. }
  360. }
  361. public static void AddUser(TeknikEntities db, Config config, User user, string password)
  362. {
  363. try
  364. {
  365. // Add User
  366. user.HashedPassword = GeneratePassword(config, user, password);
  367. db.Users.Add(user);
  368. db.SaveChanges();
  369. // Generate blog for the user
  370. var newBlog = db.Blogs.Create();
  371. newBlog.UserId = user.UserId;
  372. db.Blogs.Add(newBlog);
  373. db.SaveChanges();
  374. }
  375. catch (Exception ex)
  376. {
  377. throw new Exception("Unable to create user.", ex);
  378. }
  379. }
  380. public static void EditUser(TeknikEntities db, Config config, User user, bool changePass, string password)
  381. {
  382. try
  383. {
  384. // Changing Password?
  385. if (changePass)
  386. {
  387. // Update User password
  388. user.HashedPassword = SHA384.Hash(user.Username.ToLower(), password).ToHex();
  389. // Remove any password transfer items for the account
  390. for (int i = 0; i < user.Transfers.Count; i++)
  391. {
  392. TransferType type = user.Transfers.ToList()[i];
  393. if (type.Type == TransferTypes.ASCIIPassword || type.Type == TransferTypes.CaseSensitivePassword || type.Type == TransferTypes.Sha256Password)
  394. {
  395. user.Transfers.Remove(type);
  396. i--;
  397. }
  398. }
  399. }
  400. db.Entry(user).State = EntityState.Modified;
  401. db.SaveChanges();
  402. }
  403. catch (Exception ex)
  404. {
  405. throw new Exception(string.Format("Unable to edit user {0}.", user.Username), ex);
  406. }
  407. }
  408. public static void DeleteUser(TeknikEntities db, Config config, User user)
  409. {
  410. try
  411. {
  412. // Update uploads
  413. List<Upload.Models.Upload> uploads = db.Uploads.Where(u => u.User.Username == user.Username).ToList();
  414. if (uploads != null)
  415. {
  416. foreach (Upload.Models.Upload upload in uploads)
  417. {
  418. upload.UserId = null;
  419. db.Entry(upload).State = EntityState.Modified;
  420. }
  421. db.SaveChanges();
  422. }
  423. // Update pastes
  424. List<Paste.Models.Paste> pastes = db.Pastes.Where(u => u.User.Username == user.Username).ToList();
  425. if (pastes != null)
  426. {
  427. foreach (Paste.Models.Paste paste in pastes)
  428. {
  429. paste.UserId = null;
  430. db.Entry(paste).State = EntityState.Modified;
  431. }
  432. db.SaveChanges();
  433. }
  434. // Update shortened urls
  435. List<ShortenedUrl> shortUrls = db.ShortenedUrls.Where(u => u.User.Username == user.Username).ToList();
  436. if (shortUrls != null)
  437. {
  438. foreach (ShortenedUrl shortUrl in shortUrls)
  439. {
  440. shortUrl.UserId = null;
  441. db.Entry(shortUrl).State = EntityState.Modified;
  442. }
  443. db.SaveChanges();
  444. }
  445. // Update vaults
  446. List<Vault.Models.Vault> vaults = db.Vaults.Where(u => u.User.Username == user.Username).ToList();
  447. if (vaults != null)
  448. {
  449. foreach (Vault.Models.Vault vault in vaults)
  450. {
  451. vault.UserId = null;
  452. db.Entry(vault).State = EntityState.Modified;
  453. }
  454. db.SaveChanges();
  455. }
  456. // Delete Blogs
  457. Blog.Models.Blog blog = db.Blogs.Where(u => u.User.Username == user.Username).FirstOrDefault();
  458. if (blog != null)
  459. {
  460. db.Blogs.Remove(blog);
  461. db.SaveChanges();
  462. }
  463. // Delete post comments
  464. List<BlogPostComment> postComments = db.BlogComments.Where(u => u.User.Username == user.Username).ToList();
  465. if (postComments != null)
  466. {
  467. foreach (BlogPostComment postComment in postComments)
  468. {
  469. db.BlogComments.Remove(postComment);
  470. }
  471. db.SaveChanges();
  472. }
  473. // Delete podcast comments
  474. List<Podcast.Models.PodcastComment> podComments = db.PodcastComments.Where(u => u.User.Username == user.Username).ToList();
  475. if (podComments != null)
  476. {
  477. foreach (Podcast.Models.PodcastComment podComment in podComments)
  478. {
  479. db.PodcastComments.Remove(podComment);
  480. }
  481. db.SaveChanges();
  482. }
  483. // Delete Recovery Email Verifications
  484. List<RecoveryEmailVerification> verCodes = db.RecoveryEmailVerifications.Where(r => r.User.Username == user.Username).ToList();
  485. if (verCodes != null)
  486. {
  487. foreach (RecoveryEmailVerification verCode in verCodes)
  488. {
  489. db.RecoveryEmailVerifications.Remove(verCode);
  490. }
  491. db.SaveChanges();
  492. }
  493. // Delete Password Reset Verifications
  494. List<ResetPasswordVerification> verPass = db.ResetPasswordVerifications.Where(r => r.User.Username == user.Username).ToList();
  495. if (verPass != null)
  496. {
  497. foreach (ResetPasswordVerification ver in verPass)
  498. {
  499. db.ResetPasswordVerifications.Remove(ver);
  500. }
  501. db.SaveChanges();
  502. }
  503. // Delete User
  504. db.Users.Remove(user);
  505. db.SaveChanges();
  506. }
  507. catch (Exception ex)
  508. {
  509. throw new Exception(string.Format("Unable to delete user {0}.", user.Username), ex);
  510. }
  511. }
  512. public static string CreateRecoveryEmailVerification(TeknikEntities db, Config config, User user)
  513. {
  514. // Check to see if there already is a verification code for the user
  515. List<RecoveryEmailVerification> verCodes = db.RecoveryEmailVerifications.Where(r => r.User.Username == user.Username).ToList();
  516. if (verCodes != null && verCodes.Any())
  517. {
  518. foreach (RecoveryEmailVerification verCode in verCodes)
  519. {
  520. db.RecoveryEmailVerifications.Remove(verCode);
  521. }
  522. }
  523. // Create a new verification code and add it
  524. string verifyCode = StringHelper.RandomString(24);
  525. RecoveryEmailVerification ver = new RecoveryEmailVerification();
  526. ver.UserId = user.UserId;
  527. ver.Code = verifyCode;
  528. ver.DateCreated = DateTime.Now;
  529. db.RecoveryEmailVerifications.Add(ver);
  530. db.SaveChanges();
  531. return verifyCode;
  532. }
  533. public static void SendRecoveryEmailVerification(Config config, string username, string email, string resetUrl, string verifyUrl)
  534. {
  535. SmtpClient client = new SmtpClient();
  536. client.Host = config.ContactConfig.EmailAccount.Host;
  537. client.Port = config.ContactConfig.EmailAccount.Port;
  538. client.EnableSsl = config.ContactConfig.EmailAccount.SSL;
  539. client.DeliveryMethod = SmtpDeliveryMethod.Network;
  540. client.UseDefaultCredentials = true;
  541. client.Credentials = new NetworkCredential(config.ContactConfig.EmailAccount.Username, config.ContactConfig.EmailAccount.Password);
  542. client.Timeout = 5000;
  543. MailMessage mail = new MailMessage(config.ContactConfig.EmailAccount.EmailAddress, email);
  544. mail.Subject = "Recovery Email Validation";
  545. mail.Body = string.Format(@"Hello {0},
  546. Welcome to Teknik!
  547. You are recieving this email because you have specified this email address as your recovery email. In the event that you forget your password, you can visit {1} and request a temporary password reset key be sent to this email. You will then be able to reset and choose a new password.
  548. In order to verify that you own this email, please click the following link or paste it into your browser: {2}
  549. If you recieved this email and you did not sign up for an account, please email us at {3} and ignore the verification link.
  550. Thank you and enjoy!
  551. - Teknik Administration", username, resetUrl, verifyUrl, config.SupportEmail);
  552. mail.BodyEncoding = UTF8Encoding.UTF8;
  553. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
  554. client.Send(mail);
  555. }
  556. public static bool VerifyRecoveryEmail(TeknikEntities db, Config config, string username, string code)
  557. {
  558. User user = GetUser(db, username);
  559. RecoveryEmailVerification verCode = db.RecoveryEmailVerifications.Where(r => r.User.Username == username && r.Code == code).FirstOrDefault();
  560. if (verCode != null)
  561. {
  562. // We have a match, so clear out the verifications for that user
  563. List<RecoveryEmailVerification> verCodes = db.RecoveryEmailVerifications.Where(r => r.User.Username == username).ToList();
  564. if (verCodes != null && verCodes.Any())
  565. {
  566. foreach (RecoveryEmailVerification ver in verCodes)
  567. {
  568. db.RecoveryEmailVerifications.Remove(ver);
  569. }
  570. }
  571. // Update the user
  572. user.SecuritySettings.RecoveryVerified = true;
  573. db.Entry(user).State = EntityState.Modified;
  574. db.SaveChanges();
  575. return true;
  576. }
  577. return false;
  578. }
  579. public static string CreateResetPasswordVerification(TeknikEntities db, Config config, User user)
  580. {
  581. // Check to see if there already is a verification code for the user
  582. List<ResetPasswordVerification> verCodes = db.ResetPasswordVerifications.Where(r => r.User.Username == user.Username).ToList();
  583. if (verCodes != null && verCodes.Any())
  584. {
  585. foreach (ResetPasswordVerification verCode in verCodes)
  586. {
  587. db.ResetPasswordVerifications.Remove(verCode);
  588. }
  589. }
  590. // Create a new verification code and add it
  591. string verifyCode = StringHelper.RandomString(24);
  592. ResetPasswordVerification ver = new ResetPasswordVerification();
  593. ver.UserId = user.UserId;
  594. ver.Code = verifyCode;
  595. ver.DateCreated = DateTime.Now;
  596. db.ResetPasswordVerifications.Add(ver);
  597. db.SaveChanges();
  598. return verifyCode;
  599. }
  600. public static void SendResetPasswordVerification(Config config, string username, string email, string resetUrl)
  601. {
  602. SmtpClient client = new SmtpClient();
  603. client.Host = config.ContactConfig.EmailAccount.Host;
  604. client.Port = config.ContactConfig.EmailAccount.Port;
  605. client.EnableSsl = config.ContactConfig.EmailAccount.SSL;
  606. client.DeliveryMethod = SmtpDeliveryMethod.Network;
  607. client.UseDefaultCredentials = true;
  608. client.Credentials = new NetworkCredential(config.ContactConfig.EmailAccount.Username, config.ContactConfig.EmailAccount.Password);
  609. client.Timeout = 5000;
  610. MailMessage mail = new MailMessage(config.ContactConfig.EmailAccount.EmailAddress, email);
  611. mail.Subject = "Password Reset Request";
  612. mail.Body = string.Format(@"Hello {0},
  613. You are recieving this email because either you or someone has requested a password reset for your account and this email was specified as the recovery email.
  614. To proceed in resetting your password, please click the following link or paste it into your browser: {1}
  615. If you recieved this email and you did not reset your password, you can ignore this email and email us at {2} to prevent it occuring again.
  616. - Teknik Administration", username, resetUrl, config.SupportEmail);
  617. mail.BodyEncoding = UTF8Encoding.UTF8;
  618. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
  619. client.Send(mail);
  620. }
  621. public static bool VerifyResetPassword(TeknikEntities db, Config config, string username, string code)
  622. {
  623. User user = GetUser(db, username);
  624. ResetPasswordVerification verCode = db.ResetPasswordVerifications.Where(r => r.User.Username == username && r.Code == code).FirstOrDefault();
  625. if (verCode != null)
  626. {
  627. // We have a match, so clear out the verifications for that user
  628. List<ResetPasswordVerification> verCodes = db.ResetPasswordVerifications.Where(r => r.User.Username == username).ToList();
  629. if (verCodes != null && verCodes.Any())
  630. {
  631. foreach (ResetPasswordVerification ver in verCodes)
  632. {
  633. db.ResetPasswordVerifications.Remove(ver);
  634. }
  635. }
  636. db.SaveChanges();
  637. return true;
  638. }
  639. return false;
  640. }
  641. #endregion
  642. #region Email Management
  643. public static string GetUserEmailAddress(Config config, string username)
  644. {
  645. return string.Format("{0}@{1}", username, config.EmailConfig.Domain);
  646. }
  647. public static bool UserEmailExists(Config config, string email)
  648. {
  649. // If Email Server is enabled
  650. if (config.EmailConfig.Enabled)
  651. {
  652. // Connect to hmailserver COM
  653. var app = new hMailServer.Application();
  654. app.Connect();
  655. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  656. try
  657. {
  658. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  659. var account = domain.Accounts.ItemByAddress[email];
  660. // We didn't error out, so the email exists
  661. return true;
  662. }
  663. catch { }
  664. }
  665. return false;
  666. }
  667. public static DateTime UserEmailLastActive(Config config, string email)
  668. {
  669. DateTime lastActive = new DateTime(1900, 1, 1);
  670. if (config.EmailConfig.Enabled)
  671. {
  672. var app = new hMailServer.Application();
  673. app.Connect();
  674. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  675. try
  676. {
  677. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  678. var account = domain.Accounts.ItemByAddress[email];
  679. DateTime lastEmail = (DateTime)account.LastLogonTime;
  680. if (lastActive < lastEmail)
  681. lastActive = lastEmail;
  682. }
  683. catch { }
  684. }
  685. return lastActive;
  686. }
  687. public static void AddUserEmail(Config config, string email, string password)
  688. {
  689. try
  690. {
  691. // If Email Server is enabled
  692. if (config.EmailConfig.Enabled)
  693. {
  694. // Connect to hmailserver COM
  695. var app = new hMailServer.Application();
  696. app.Connect();
  697. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  698. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  699. var newAccount = domain.Accounts.Add();
  700. newAccount.Address = email;
  701. newAccount.Password = password;
  702. newAccount.Active = true;
  703. newAccount.MaxSize = config.EmailConfig.MaxSize;
  704. newAccount.Save();
  705. }
  706. }
  707. catch (Exception ex)
  708. {
  709. throw new Exception("Unable to add email.", ex);
  710. }
  711. }
  712. public static void EditUserEmailPassword(Config config, string email, string password)
  713. {
  714. try
  715. {
  716. // If Email Server is enabled
  717. if (config.EmailConfig.Enabled)
  718. {
  719. var app = new hMailServer.Application();
  720. app.Connect();
  721. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  722. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  723. var account = domain.Accounts.ItemByAddress[email];
  724. account.Password = password;
  725. account.Save();
  726. }
  727. }
  728. catch (Exception ex)
  729. {
  730. throw new Exception("Unable to edit email account password.", ex);
  731. }
  732. }
  733. public static void DeleteUserEmail(Config config, string email)
  734. {
  735. try
  736. {
  737. // If Email Server is enabled
  738. if (config.EmailConfig.Enabled)
  739. {
  740. var app = new hMailServer.Application();
  741. app.Connect();
  742. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  743. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  744. var account = domain.Accounts.ItemByAddress[email];
  745. if (account != null)
  746. {
  747. account.Delete();
  748. }
  749. }
  750. }
  751. catch (Exception ex)
  752. {
  753. throw new Exception("Unable to delete email account.", ex);
  754. }
  755. }
  756. #endregion
  757. #region Git Management
  758. public static bool UserGitExists(Config config, string username)
  759. {
  760. if (config.GitConfig.Enabled)
  761. {
  762. try
  763. {
  764. Uri baseUri = new Uri(config.GitConfig.Host);
  765. Uri finalUri = new Uri(baseUri, "api/v1/users/" + username + "?token=" + config.GitConfig.AccessToken);
  766. WebRequest request = WebRequest.Create(finalUri);
  767. request.Method = "GET";
  768. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  769. if (response.StatusCode == HttpStatusCode.OK)
  770. {
  771. return true;
  772. }
  773. }
  774. catch { }
  775. }
  776. return false;
  777. }
  778. public static DateTime UserGitLastActive(Config config, string username)
  779. {
  780. DateTime lastActive = new DateTime(1900, 1, 1);
  781. if (config.GitConfig.Enabled)
  782. {
  783. string email = GetUserEmailAddress(config, username);
  784. // We need to check the actual git database
  785. MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database.Server, config.GitConfig.Database.Database, config.GitConfig.Database.Username, config.GitConfig.Database.Password, config.GitConfig.Database.Port);
  786. string sql = @"SELECT
  787. CASE
  788. WHEN MAX(gogs.action.created) >= MAX(gogs.user.updated) THEN MAX(gogs.action.created)
  789. WHEN MAX(gogs.user.updated) >= MAX(gogs.action.created) THEN MAX(gogs.user.updated)
  790. ELSE MAX(gogs.user.updated)
  791. END AS LastUpdate
  792. FROM gogs.user
  793. LEFT JOIN gogs.action ON gogs.user.id = gogs.action.act_user_id
  794. WHERE gogs.user.login_name = {0}";
  795. var results = mySQL.Query(sql, new object[] { email });
  796. if (results != null && results.Any())
  797. {
  798. var result = results.First();
  799. DateTime tmpLast = lastActive;
  800. DateTime.TryParse(result["LastUpdate"].ToString(), out tmpLast);
  801. if (lastActive < tmpLast)
  802. lastActive = tmpLast;
  803. }
  804. }
  805. return lastActive;
  806. }
  807. public static void AddUserGit(Config config, string username, string password)
  808. {
  809. try
  810. {
  811. // If Git is enabled
  812. if (config.GitConfig.Enabled)
  813. {
  814. string email = GetUserEmailAddress(config, username);
  815. // Add gogs user
  816. using (var client = new WebClient())
  817. {
  818. var obj = new { source_id = config.GitConfig.SourceId, username = username, email = email, login_name = email, password = password };
  819. string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  820. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  821. Uri baseUri = new Uri(config.GitConfig.Host);
  822. Uri finalUri = new Uri(baseUri, "api/v1/admin/users?token=" + config.GitConfig.AccessToken);
  823. string result = client.UploadString(finalUri, "POST", json);
  824. }
  825. }
  826. }
  827. catch (Exception ex)
  828. {
  829. throw new Exception("Unable to add git account.", ex);
  830. }
  831. }
  832. public static void EditUserGitPassword(Config config, string username, string password)
  833. {
  834. try
  835. {
  836. // If Git is enabled
  837. if (config.GitConfig.Enabled)
  838. {
  839. string email = GetUserEmailAddress(config, username);
  840. using (var client = new WebClient())
  841. {
  842. var obj = new { source_id = config.GitConfig.SourceId, email = email, login_name = email, password = password };
  843. string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  844. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  845. Uri baseUri = new Uri(config.GitConfig.Host);
  846. Uri finalUri = new Uri(baseUri, "api/v1/admin/users/" + username + "?token=" + config.GitConfig.AccessToken);
  847. string result = client.UploadString(finalUri, "PATCH", json);
  848. }
  849. }
  850. }
  851. catch (Exception ex)
  852. {
  853. throw new Exception("Unable to edit git account password.", ex);
  854. }
  855. }
  856. public static void DeleteUserGit(Config config, string username)
  857. {
  858. try
  859. {
  860. // If Git is enabled
  861. if (config.GitConfig.Enabled)
  862. {
  863. try
  864. {
  865. Uri baseUri = new Uri(config.GitConfig.Host);
  866. Uri finalUri = new Uri(baseUri, "api/v1/admin/users/" + username + "?token=" + config.GitConfig.AccessToken);
  867. WebRequest request = WebRequest.Create(finalUri);
  868. request.Method = "DELETE";
  869. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  870. if (response.StatusCode != HttpStatusCode.NotFound && response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NoContent)
  871. {
  872. throw new Exception("Unable to delete git account. Response Code: " + response.StatusCode);
  873. }
  874. }
  875. catch (HttpException htex)
  876. {
  877. if (htex.GetHttpCode() != 404)
  878. throw new Exception("Unable to delete git account. Http Exception: " + htex.Message);
  879. }
  880. catch (Exception ex)
  881. {
  882. // This error signifies the user doesn't exist, so we can continue deleting
  883. if (ex.Message != "The remote server returned an error: (404) Not Found.")
  884. {
  885. throw new Exception("Unable to delete git account. Exception: " + ex.Message);
  886. }
  887. }
  888. }
  889. }
  890. catch (Exception ex)
  891. {
  892. throw new Exception("Unable to delete git account.", ex);
  893. }
  894. }
  895. #endregion
  896. public static HttpCookie CreateAuthCookie(string username, bool remember, string domain, bool local)
  897. {
  898. DateTime curTime = DateTime.Now;
  899. DateTime expireTime = curTime.AddMonths(1);
  900. Config config = Config.Load();
  901. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
  902. 1,
  903. username,
  904. curTime,
  905. expireTime,
  906. remember,
  907. username
  908. );
  909. string encTicket = FormsAuthentication.Encrypt(ticket);
  910. HttpCookie authcookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
  911. authcookie.HttpOnly = true;
  912. authcookie.Secure = true;
  913. if (remember)
  914. {
  915. authcookie.Expires = expireTime;
  916. }
  917. // Set domain dependent on where it's being ran from
  918. if (local) // localhost
  919. {
  920. authcookie.Domain = null;
  921. }
  922. else if (config.DevEnvironment) // dev.example.com
  923. {
  924. authcookie.Domain = string.Format("dev.{0}", domain);
  925. }
  926. else // A production instance
  927. {
  928. authcookie.Domain = string.Format(".{0}", domain);
  929. }
  930. return authcookie;
  931. }
  932. public static HttpCookie CreateTrustedDeviceCookie(string username, string domain, bool local)
  933. {
  934. Config config = Config.Load();
  935. byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
  936. byte[] key = Guid.NewGuid().ToByteArray();
  937. string token = Convert.ToBase64String(time.Concat(key).ToArray());
  938. HttpCookie trustCookie = new HttpCookie(Constants.TRUSTEDDEVICECOOKIE + "_" + username);
  939. trustCookie.Value = token;
  940. trustCookie.HttpOnly = true;
  941. trustCookie.Secure = true;
  942. trustCookie.Expires = DateTime.Now.AddYears(1);
  943. // Set domain dependent on where it's being ran from
  944. if (local) // localhost
  945. {
  946. trustCookie.Domain = null;
  947. }
  948. else if (config.DevEnvironment) // dev.example.com
  949. {
  950. trustCookie.Domain = string.Format("dev.{0}", domain);
  951. }
  952. else // A production instance
  953. {
  954. trustCookie.Domain = string.Format(".{0}", domain);
  955. }
  956. return trustCookie;
  957. }
  958. }
  959. }