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.

UserHelper.cs 45KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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 EditAccountType(TeknikEntities db, Config config, string username, AccountType type)
  189. {
  190. try
  191. {
  192. if (!UserExists(db, username))
  193. throw new Exception($"The user provided does not exist: {username}");
  194. // Get the user to edit
  195. User user = GetUser(db, username);
  196. string email = GetUserEmailAddress(config, username);
  197. // Edit the user type
  198. user.AccountType = type;
  199. EditUser(db, config, user);
  200. // Add/Remove account type features depending on the type
  201. switch (type)
  202. {
  203. case AccountType.Basic:
  204. // Set the email size to 1GB
  205. EditUserEmailMaxSize(config, email, config.EmailConfig.MaxSize);
  206. // Set the email max/day to 100
  207. EditUserEmailMaxEmailsPerDay(config, email, 100);
  208. break;
  209. case AccountType.Premium:
  210. // Set the email size to 5GB
  211. EditUserEmailMaxSize(config, email, 5000);
  212. // Set the email max/day to infinite (-1)
  213. EditUserEmailMaxEmailsPerDay(config, email, -1);
  214. break;
  215. }
  216. }
  217. catch (Exception ex)
  218. {
  219. throw new Exception($"Unable to edit the account type [{type}] for: {username}", ex);
  220. }
  221. }
  222. public static void DeleteAccount(TeknikEntities db, Config config, User user)
  223. {
  224. try
  225. {
  226. // Delete Email Account
  227. if (UserEmailExists(config, GetUserEmailAddress(config, user.Username)))
  228. DeleteUserEmail(config, GetUserEmailAddress(config, user.Username));
  229. // Delete Git Account
  230. if (UserGitExists(config, user.Username))
  231. DeleteUserGit(config, user.Username);
  232. // Delete User Account
  233. DeleteUser(db, config, user);
  234. }
  235. catch (Exception ex)
  236. {
  237. throw new Exception("Unable to delete account.", ex);
  238. }
  239. }
  240. #endregion
  241. #region User Management
  242. public static User GetUser(TeknikEntities db, string username)
  243. {
  244. User user = db.Users.Where(b => b.Username == username).FirstOrDefault();
  245. if (user != null)
  246. {
  247. user.UserSettings = db.UserSettings.Find(user.UserId);
  248. user.SecuritySettings = db.SecuritySettings.Find(user.UserId);
  249. user.BlogSettings = db.BlogSettings.Find(user.UserId);
  250. user.UploadSettings = db.UploadSettings.Find(user.UserId);
  251. }
  252. return user;
  253. }
  254. public static User GetUserFromToken(TeknikEntities db, string username, string token)
  255. {
  256. if (token != null && !string.IsNullOrEmpty(username))
  257. {
  258. string hashedToken = SHA256.Hash(token);
  259. return db.Users.FirstOrDefault(u => u.AuthTokens.Select(a => a.HashedToken).Contains(hashedToken) && u.Username == username);
  260. }
  261. return null;
  262. }
  263. public static bool UserExists(TeknikEntities db, string username)
  264. {
  265. User user = GetUser(db, username);
  266. if (user != null)
  267. {
  268. return true;
  269. }
  270. return false;
  271. }
  272. public static DateTime UserLastActive(TeknikEntities db, Config config, User user)
  273. {
  274. try
  275. {
  276. DateTime lastActive = new DateTime(1900, 1, 1);
  277. if (lastActive < user.LastSeen)
  278. lastActive = user.LastSeen;
  279. return lastActive;
  280. }
  281. catch (Exception ex)
  282. {
  283. throw new Exception("Unable to determine last user activity.", ex);
  284. }
  285. }
  286. public static void UpdateTokenLastUsed(TeknikEntities db, string username, string token, DateTime lastUsed)
  287. {
  288. User foundUser = GetUser(db, username);
  289. if (foundUser != null)
  290. {
  291. string hashedToken = SHA256.Hash(token);
  292. List<AuthToken> tokens = foundUser.AuthTokens.Where(t => t.HashedToken == hashedToken).ToList();
  293. if (tokens != null)
  294. {
  295. foreach (AuthToken foundToken in tokens)
  296. {
  297. foundToken.LastDateUsed = lastUsed;
  298. db.Entry(foundToken).State = EntityState.Modified;
  299. }
  300. db.SaveChanges();
  301. }
  302. }
  303. }
  304. public static bool UserPasswordCorrect(TeknikEntities db, Config config, User user, string password)
  305. {
  306. try
  307. {
  308. string hash = GeneratePassword(config, user, password);
  309. return db.Users.Any(b => b.Username == user.Username && b.HashedPassword == hash);
  310. }
  311. catch (Exception ex)
  312. {
  313. throw new Exception("Unable to determine if password is correct.", ex);
  314. }
  315. }
  316. public static bool UserTokenCorrect(TeknikEntities db, string username, string token)
  317. {
  318. User foundUser = GetUserFromToken(db, username, token);
  319. if (foundUser != null)
  320. {
  321. return true;
  322. }
  323. return false;
  324. }
  325. public static bool UserHasRoles(TeknikEntities db, User user, params string[] roles)
  326. {
  327. bool hasRole = true;
  328. if (user != null)
  329. {
  330. // Check if they have the role specified
  331. if (roles.Any())
  332. {
  333. foreach (string role in roles)
  334. {
  335. if (!string.IsNullOrEmpty(role))
  336. {
  337. if (user.Groups.Where(g => g.Roles.Where(r => role == r.Name).Any()).Any())
  338. {
  339. // They have the role!
  340. return true;
  341. }
  342. else
  343. {
  344. // They don't have this role, so let's reset the hasRole
  345. hasRole = false;
  346. }
  347. }
  348. else
  349. {
  350. // Only set this if we haven't failed once already
  351. hasRole &= true;
  352. }
  353. }
  354. }
  355. else
  356. {
  357. // No roles to check, so they pass!
  358. return true;
  359. }
  360. }
  361. else
  362. {
  363. hasRole = false;
  364. }
  365. return hasRole;
  366. }
  367. public static void TransferUser(TeknikEntities db, Config config, User user, string password)
  368. {
  369. try
  370. {
  371. List<TransferType> transfers = user.Transfers.ToList();
  372. for (int i = 0; i < transfers.Count; i++)
  373. {
  374. TransferType transfer = transfers[i];
  375. switch (transfer.Type)
  376. {
  377. case TransferTypes.Sha256Password:
  378. case TransferTypes.CaseSensitivePassword:
  379. case TransferTypes.ASCIIPassword:
  380. user.HashedPassword = SHA384.Hash(user.Username.ToLower(), password).ToHex();
  381. break;
  382. default:
  383. break;
  384. }
  385. user.Transfers.Remove(transfer);
  386. }
  387. db.Entry(user).State = EntityState.Modified;
  388. db.SaveChanges();
  389. }
  390. catch (Exception ex)
  391. {
  392. throw new Exception("Unable to transfer user info.", ex);
  393. }
  394. }
  395. public static void AddUser(TeknikEntities db, Config config, User user, string password)
  396. {
  397. try
  398. {
  399. // Add User
  400. user.HashedPassword = GeneratePassword(config, user, password);
  401. db.Users.Add(user);
  402. db.SaveChanges();
  403. // Generate blog for the user
  404. var newBlog = db.Blogs.Create();
  405. newBlog.UserId = user.UserId;
  406. db.Blogs.Add(newBlog);
  407. db.SaveChanges();
  408. }
  409. catch (Exception ex)
  410. {
  411. throw new Exception("Unable to create user.", ex);
  412. }
  413. }
  414. public static void EditUser(TeknikEntities db, Config config, User user)
  415. {
  416. EditUser(db, config, user, false, string.Empty);
  417. }
  418. public static void EditUser(TeknikEntities db, Config config, User user, bool changePass, string password)
  419. {
  420. try
  421. {
  422. // Changing Password?
  423. if (changePass)
  424. {
  425. // Update User password
  426. user.HashedPassword = SHA384.Hash(user.Username.ToLower(), password).ToHex();
  427. // Remove any password transfer items for the account
  428. for (int i = 0; i < user.Transfers.Count; i++)
  429. {
  430. TransferType type = user.Transfers.ToList()[i];
  431. if (type.Type == TransferTypes.ASCIIPassword || type.Type == TransferTypes.CaseSensitivePassword || type.Type == TransferTypes.Sha256Password)
  432. {
  433. user.Transfers.Remove(type);
  434. i--;
  435. }
  436. }
  437. }
  438. db.Entry(user).State = EntityState.Modified;
  439. db.SaveChanges();
  440. }
  441. catch (Exception ex)
  442. {
  443. throw new Exception(string.Format("Unable to edit user {0}.", user.Username), ex);
  444. }
  445. }
  446. public static void DeleteUser(TeknikEntities db, Config config, User user)
  447. {
  448. try
  449. {
  450. // Update uploads
  451. List<Upload.Models.Upload> uploads = db.Uploads.Where(u => u.User.Username == user.Username).ToList();
  452. if (uploads != null)
  453. {
  454. foreach (Upload.Models.Upload upload in uploads)
  455. {
  456. upload.UserId = null;
  457. db.Entry(upload).State = EntityState.Modified;
  458. }
  459. db.SaveChanges();
  460. }
  461. // Update pastes
  462. List<Paste.Models.Paste> pastes = db.Pastes.Where(u => u.User.Username == user.Username).ToList();
  463. if (pastes != null)
  464. {
  465. foreach (Paste.Models.Paste paste in pastes)
  466. {
  467. paste.UserId = null;
  468. db.Entry(paste).State = EntityState.Modified;
  469. }
  470. db.SaveChanges();
  471. }
  472. // Update shortened urls
  473. List<ShortenedUrl> shortUrls = db.ShortenedUrls.Where(u => u.User.Username == user.Username).ToList();
  474. if (shortUrls != null)
  475. {
  476. foreach (ShortenedUrl shortUrl in shortUrls)
  477. {
  478. shortUrl.UserId = null;
  479. db.Entry(shortUrl).State = EntityState.Modified;
  480. }
  481. db.SaveChanges();
  482. }
  483. // Update vaults
  484. List<Vault.Models.Vault> vaults = db.Vaults.Where(u => u.User.Username == user.Username).ToList();
  485. if (vaults != null)
  486. {
  487. foreach (Vault.Models.Vault vault in vaults)
  488. {
  489. vault.UserId = null;
  490. db.Entry(vault).State = EntityState.Modified;
  491. }
  492. db.SaveChanges();
  493. }
  494. // Delete Blogs
  495. Blog.Models.Blog blog = db.Blogs.Where(u => u.User.Username == user.Username).FirstOrDefault();
  496. if (blog != null)
  497. {
  498. db.Blogs.Remove(blog);
  499. db.SaveChanges();
  500. }
  501. // Delete post comments
  502. List<BlogPostComment> postComments = db.BlogComments.Where(u => u.User.Username == user.Username).ToList();
  503. if (postComments != null)
  504. {
  505. foreach (BlogPostComment postComment in postComments)
  506. {
  507. db.BlogComments.Remove(postComment);
  508. }
  509. db.SaveChanges();
  510. }
  511. // Delete podcast comments
  512. List<Podcast.Models.PodcastComment> podComments = db.PodcastComments.Where(u => u.User.Username == user.Username).ToList();
  513. if (podComments != null)
  514. {
  515. foreach (Podcast.Models.PodcastComment podComment in podComments)
  516. {
  517. db.PodcastComments.Remove(podComment);
  518. }
  519. db.SaveChanges();
  520. }
  521. // Delete Recovery Email Verifications
  522. List<RecoveryEmailVerification> verCodes = db.RecoveryEmailVerifications.Where(r => r.User.Username == user.Username).ToList();
  523. if (verCodes != null)
  524. {
  525. foreach (RecoveryEmailVerification verCode in verCodes)
  526. {
  527. db.RecoveryEmailVerifications.Remove(verCode);
  528. }
  529. db.SaveChanges();
  530. }
  531. // Delete Password Reset Verifications
  532. List<ResetPasswordVerification> verPass = db.ResetPasswordVerifications.Where(r => r.User.Username == user.Username).ToList();
  533. if (verPass != null)
  534. {
  535. foreach (ResetPasswordVerification ver in verPass)
  536. {
  537. db.ResetPasswordVerifications.Remove(ver);
  538. }
  539. db.SaveChanges();
  540. }
  541. // Delete User
  542. db.Users.Remove(user);
  543. db.SaveChanges();
  544. }
  545. catch (Exception ex)
  546. {
  547. throw new Exception(string.Format("Unable to delete user {0}.", user.Username), ex);
  548. }
  549. }
  550. public static string CreateRecoveryEmailVerification(TeknikEntities db, Config config, User user)
  551. {
  552. // Check to see if there already is a verification code for the user
  553. List<RecoveryEmailVerification> verCodes = db.RecoveryEmailVerifications.Where(r => r.User.Username == user.Username).ToList();
  554. if (verCodes != null && verCodes.Any())
  555. {
  556. foreach (RecoveryEmailVerification verCode in verCodes)
  557. {
  558. db.RecoveryEmailVerifications.Remove(verCode);
  559. }
  560. }
  561. // Create a new verification code and add it
  562. string verifyCode = StringHelper.RandomString(24);
  563. RecoveryEmailVerification ver = new RecoveryEmailVerification();
  564. ver.UserId = user.UserId;
  565. ver.Code = verifyCode;
  566. ver.DateCreated = DateTime.Now;
  567. db.RecoveryEmailVerifications.Add(ver);
  568. db.SaveChanges();
  569. return verifyCode;
  570. }
  571. public static void SendRecoveryEmailVerification(Config config, string username, string email, string resetUrl, string verifyUrl)
  572. {
  573. SmtpClient client = new SmtpClient();
  574. client.Host = config.ContactConfig.EmailAccount.Host;
  575. client.Port = config.ContactConfig.EmailAccount.Port;
  576. client.EnableSsl = config.ContactConfig.EmailAccount.SSL;
  577. client.DeliveryMethod = SmtpDeliveryMethod.Network;
  578. client.UseDefaultCredentials = true;
  579. client.Credentials = new NetworkCredential(config.ContactConfig.EmailAccount.Username, config.ContactConfig.EmailAccount.Password);
  580. client.Timeout = 5000;
  581. MailMessage mail = new MailMessage(config.ContactConfig.EmailAccount.EmailAddress, email);
  582. mail.Subject = "Recovery Email Validation";
  583. mail.Body = string.Format(@"Hello {0},
  584. Welcome to Teknik!
  585. 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.
  586. In order to verify that you own this email, please click the following link or paste it into your browser: {2}
  587. If you recieved this email and you did not sign up for an account, please email us at {3} and ignore the verification link.
  588. Thank you and enjoy!
  589. - Teknik Administration", username, resetUrl, verifyUrl, config.SupportEmail);
  590. mail.BodyEncoding = UTF8Encoding.UTF8;
  591. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
  592. client.Send(mail);
  593. }
  594. public static bool VerifyRecoveryEmail(TeknikEntities db, Config config, string username, string code)
  595. {
  596. User user = GetUser(db, username);
  597. RecoveryEmailVerification verCode = db.RecoveryEmailVerifications.Where(r => r.User.Username == username && r.Code == code).FirstOrDefault();
  598. if (verCode != null)
  599. {
  600. // We have a match, so clear out the verifications for that user
  601. List<RecoveryEmailVerification> verCodes = db.RecoveryEmailVerifications.Where(r => r.User.Username == username).ToList();
  602. if (verCodes != null && verCodes.Any())
  603. {
  604. foreach (RecoveryEmailVerification ver in verCodes)
  605. {
  606. db.RecoveryEmailVerifications.Remove(ver);
  607. }
  608. }
  609. // Update the user
  610. user.SecuritySettings.RecoveryVerified = true;
  611. db.Entry(user).State = EntityState.Modified;
  612. db.SaveChanges();
  613. return true;
  614. }
  615. return false;
  616. }
  617. public static string CreateResetPasswordVerification(TeknikEntities db, Config config, User user)
  618. {
  619. // Check to see if there already is a verification code for the user
  620. List<ResetPasswordVerification> verCodes = db.ResetPasswordVerifications.Where(r => r.User.Username == user.Username).ToList();
  621. if (verCodes != null && verCodes.Any())
  622. {
  623. foreach (ResetPasswordVerification verCode in verCodes)
  624. {
  625. db.ResetPasswordVerifications.Remove(verCode);
  626. }
  627. }
  628. // Create a new verification code and add it
  629. string verifyCode = StringHelper.RandomString(24);
  630. ResetPasswordVerification ver = new ResetPasswordVerification();
  631. ver.UserId = user.UserId;
  632. ver.Code = verifyCode;
  633. ver.DateCreated = DateTime.Now;
  634. db.ResetPasswordVerifications.Add(ver);
  635. db.SaveChanges();
  636. return verifyCode;
  637. }
  638. public static void SendResetPasswordVerification(Config config, string username, string email, string resetUrl)
  639. {
  640. SmtpClient client = new SmtpClient();
  641. client.Host = config.ContactConfig.EmailAccount.Host;
  642. client.Port = config.ContactConfig.EmailAccount.Port;
  643. client.EnableSsl = config.ContactConfig.EmailAccount.SSL;
  644. client.DeliveryMethod = SmtpDeliveryMethod.Network;
  645. client.UseDefaultCredentials = true;
  646. client.Credentials = new NetworkCredential(config.ContactConfig.EmailAccount.Username, config.ContactConfig.EmailAccount.Password);
  647. client.Timeout = 5000;
  648. MailMessage mail = new MailMessage(config.ContactConfig.EmailAccount.EmailAddress, email);
  649. mail.Subject = "Password Reset Request";
  650. mail.Body = string.Format(@"Hello {0},
  651. 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.
  652. To proceed in resetting your password, please click the following link or paste it into your browser: {1}
  653. 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.
  654. - Teknik Administration", username, resetUrl, config.SupportEmail);
  655. mail.BodyEncoding = UTF8Encoding.UTF8;
  656. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
  657. client.Send(mail);
  658. }
  659. public static bool VerifyResetPassword(TeknikEntities db, Config config, string username, string code)
  660. {
  661. User user = GetUser(db, username);
  662. ResetPasswordVerification verCode = db.ResetPasswordVerifications.Where(r => r.User.Username == username && r.Code == code).FirstOrDefault();
  663. if (verCode != null)
  664. {
  665. // We have a match, so clear out the verifications for that user
  666. List<ResetPasswordVerification> verCodes = db.ResetPasswordVerifications.Where(r => r.User.Username == username).ToList();
  667. if (verCodes != null && verCodes.Any())
  668. {
  669. foreach (ResetPasswordVerification ver in verCodes)
  670. {
  671. db.ResetPasswordVerifications.Remove(ver);
  672. }
  673. }
  674. db.SaveChanges();
  675. return true;
  676. }
  677. return false;
  678. }
  679. #endregion
  680. #region Email Management
  681. public static string GetUserEmailAddress(Config config, string username)
  682. {
  683. return string.Format("{0}@{1}", username, config.EmailConfig.Domain);
  684. }
  685. public static bool UserEmailExists(Config config, string email)
  686. {
  687. // If Email Server is enabled
  688. if (config.EmailConfig.Enabled)
  689. {
  690. // Connect to hmailserver COM
  691. var app = new hMailServer.Application();
  692. app.Connect();
  693. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  694. try
  695. {
  696. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  697. var account = domain.Accounts.ItemByAddress[email];
  698. // We didn't error out, so the email exists
  699. return true;
  700. }
  701. catch { }
  702. }
  703. return false;
  704. }
  705. public static DateTime UserEmailLastActive(Config config, string email)
  706. {
  707. DateTime lastActive = new DateTime(1900, 1, 1);
  708. if (config.EmailConfig.Enabled)
  709. {
  710. var app = new hMailServer.Application();
  711. app.Connect();
  712. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  713. try
  714. {
  715. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  716. var account = domain.Accounts.ItemByAddress[email];
  717. DateTime lastEmail = (DateTime)account.LastLogonTime;
  718. if (lastActive < lastEmail)
  719. lastActive = lastEmail;
  720. }
  721. catch { }
  722. }
  723. return lastActive;
  724. }
  725. public static void AddUserEmail(Config config, string email, string password)
  726. {
  727. try
  728. {
  729. // If Email Server is enabled
  730. if (config.EmailConfig.Enabled)
  731. {
  732. // Connect to hmailserver COM
  733. var app = new hMailServer.Application();
  734. app.Connect();
  735. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  736. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  737. var newAccount = domain.Accounts.Add();
  738. newAccount.Address = email;
  739. newAccount.Password = password;
  740. newAccount.Active = true;
  741. newAccount.MaxSize = config.EmailConfig.MaxSize;
  742. newAccount.Save();
  743. }
  744. }
  745. catch (Exception ex)
  746. {
  747. throw new Exception("Unable to add email.", ex);
  748. }
  749. }
  750. public static void EditUserEmailPassword(Config config, string email, string password)
  751. {
  752. try
  753. {
  754. // If Email Server is enabled
  755. if (config.EmailConfig.Enabled)
  756. {
  757. var app = new hMailServer.Application();
  758. app.Connect();
  759. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  760. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  761. var account = domain.Accounts.ItemByAddress[email];
  762. account.Password = password;
  763. account.Save();
  764. }
  765. }
  766. catch (Exception ex)
  767. {
  768. throw new Exception("Unable to edit email account password.", ex);
  769. }
  770. }
  771. public static void EditUserEmailMaxSize(Config config, string email, int size)
  772. {
  773. try
  774. {
  775. // If Email Server is enabled
  776. if (config.EmailConfig.Enabled)
  777. {
  778. var app = new hMailServer.Application();
  779. app.Connect();
  780. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  781. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  782. var account = domain.Accounts.ItemByAddress[email];
  783. account.MaxSize = size;
  784. account.Save();
  785. }
  786. }
  787. catch (Exception ex)
  788. {
  789. throw new Exception("Unable to edit email account mailbox size.", ex);
  790. }
  791. }
  792. public static void EditUserEmailMaxEmailsPerDay(Config config, string email, int maxPerDay)
  793. {
  794. try
  795. {
  796. // If Email Server is enabled
  797. if (config.EmailConfig.Enabled)
  798. {
  799. // Query the Email DB
  800. // We need to check the actual git database
  801. MysqlDatabase mySQL = new MysqlDatabase(config.EmailConfig.CounterDatabase.Server, config.EmailConfig.CounterDatabase.Database, config.EmailConfig.CounterDatabase.Username, config.EmailConfig.CounterDatabase.Password, config.EmailConfig.CounterDatabase.Port);
  802. string sql = @"INSERT INTO mailcounter.counts (qname, lastdate, qlimit, count) VALUES ({1}, NOW(), {0}, 0)
  803. ON DUPLICATE KEY UPDATE qlimit = {0}";
  804. mySQL.Execute(sql, new object[] { maxPerDay, email });
  805. }
  806. }
  807. catch (Exception ex)
  808. {
  809. throw new Exception("Unable to edit email account mailbox size.", ex);
  810. }
  811. }
  812. public static void DeleteUserEmail(Config config, string email)
  813. {
  814. try
  815. {
  816. // If Email Server is enabled
  817. if (config.EmailConfig.Enabled)
  818. {
  819. var app = new hMailServer.Application();
  820. app.Connect();
  821. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  822. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  823. var account = domain.Accounts.ItemByAddress[email];
  824. if (account != null)
  825. {
  826. account.Delete();
  827. }
  828. }
  829. }
  830. catch (Exception ex)
  831. {
  832. throw new Exception("Unable to delete email account.", ex);
  833. }
  834. }
  835. #endregion
  836. #region Git Management
  837. public static bool UserGitExists(Config config, string username)
  838. {
  839. if (config.GitConfig.Enabled)
  840. {
  841. try
  842. {
  843. Uri baseUri = new Uri(config.GitConfig.Host);
  844. Uri finalUri = new Uri(baseUri, "api/v1/users/" + username + "?token=" + config.GitConfig.AccessToken);
  845. WebRequest request = WebRequest.Create(finalUri);
  846. request.Method = "GET";
  847. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  848. if (response.StatusCode == HttpStatusCode.OK)
  849. {
  850. return true;
  851. }
  852. }
  853. catch { }
  854. }
  855. return false;
  856. }
  857. public static DateTime UserGitLastActive(Config config, string username)
  858. {
  859. DateTime lastActive = new DateTime(1900, 1, 1);
  860. if (config.GitConfig.Enabled)
  861. {
  862. string email = GetUserEmailAddress(config, username);
  863. // We need to check the actual git database
  864. MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database.Server, config.GitConfig.Database.Database, config.GitConfig.Database.Username, config.GitConfig.Database.Password, config.GitConfig.Database.Port);
  865. string sql = @"SELECT
  866. CASE
  867. WHEN MAX(gogs.action.created) >= MAX(gogs.user.updated) THEN MAX(gogs.action.created)
  868. WHEN MAX(gogs.user.updated) >= MAX(gogs.action.created) THEN MAX(gogs.user.updated)
  869. ELSE MAX(gogs.user.updated)
  870. END AS LastUpdate
  871. FROM gogs.user
  872. LEFT JOIN gogs.action ON gogs.user.id = gogs.action.act_user_id
  873. WHERE gogs.user.login_name = {0}";
  874. var results = mySQL.Query(sql, new object[] { email });
  875. if (results != null && results.Any())
  876. {
  877. var result = results.First();
  878. DateTime tmpLast = lastActive;
  879. DateTime.TryParse(result["LastUpdate"].ToString(), out tmpLast);
  880. if (lastActive < tmpLast)
  881. lastActive = tmpLast;
  882. }
  883. }
  884. return lastActive;
  885. }
  886. public static void AddUserGit(Config config, string username, string password)
  887. {
  888. try
  889. {
  890. // If Git is enabled
  891. if (config.GitConfig.Enabled)
  892. {
  893. string email = GetUserEmailAddress(config, username);
  894. // Add gogs user
  895. using (var client = new WebClient())
  896. {
  897. var obj = new { source_id = config.GitConfig.SourceId, username = username, email = email, login_name = email, password = password };
  898. string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  899. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  900. Uri baseUri = new Uri(config.GitConfig.Host);
  901. Uri finalUri = new Uri(baseUri, "api/v1/admin/users?token=" + config.GitConfig.AccessToken);
  902. string result = client.UploadString(finalUri, "POST", json);
  903. }
  904. }
  905. }
  906. catch (Exception ex)
  907. {
  908. throw new Exception("Unable to add git account.", ex);
  909. }
  910. }
  911. public static void EditUserGitPassword(Config config, string username, string password)
  912. {
  913. try
  914. {
  915. // If Git is enabled
  916. if (config.GitConfig.Enabled)
  917. {
  918. string email = GetUserEmailAddress(config, username);
  919. using (var client = new WebClient())
  920. {
  921. var obj = new { source_id = config.GitConfig.SourceId, email = email, login_name = email, password = password };
  922. string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  923. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  924. Uri baseUri = new Uri(config.GitConfig.Host);
  925. Uri finalUri = new Uri(baseUri, "api/v1/admin/users/" + username + "?token=" + config.GitConfig.AccessToken);
  926. string result = client.UploadString(finalUri, "PATCH", json);
  927. }
  928. }
  929. }
  930. catch (Exception ex)
  931. {
  932. throw new Exception("Unable to edit git account password.", ex);
  933. }
  934. }
  935. public static void DeleteUserGit(Config config, string username)
  936. {
  937. try
  938. {
  939. // If Git is enabled
  940. if (config.GitConfig.Enabled)
  941. {
  942. try
  943. {
  944. Uri baseUri = new Uri(config.GitConfig.Host);
  945. Uri finalUri = new Uri(baseUri, "api/v1/admin/users/" + username + "?token=" + config.GitConfig.AccessToken);
  946. WebRequest request = WebRequest.Create(finalUri);
  947. request.Method = "DELETE";
  948. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  949. if (response.StatusCode != HttpStatusCode.NotFound && response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NoContent)
  950. {
  951. throw new Exception("Unable to delete git account. Response Code: " + response.StatusCode);
  952. }
  953. }
  954. catch (HttpException htex)
  955. {
  956. if (htex.GetHttpCode() != 404)
  957. throw new Exception("Unable to delete git account. Http Exception: " + htex.Message);
  958. }
  959. catch (Exception ex)
  960. {
  961. // This error signifies the user doesn't exist, so we can continue deleting
  962. if (ex.Message != "The remote server returned an error: (404) Not Found.")
  963. {
  964. throw new Exception("Unable to delete git account. Exception: " + ex.Message);
  965. }
  966. }
  967. }
  968. }
  969. catch (Exception ex)
  970. {
  971. throw new Exception("Unable to delete git account.", ex);
  972. }
  973. }
  974. #endregion
  975. public static HttpCookie CreateAuthCookie(string username, bool remember, string domain, bool local)
  976. {
  977. DateTime curTime = DateTime.Now;
  978. DateTime expireTime = curTime.AddMonths(1);
  979. Config config = Config.Load();
  980. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
  981. 1,
  982. username,
  983. curTime,
  984. expireTime,
  985. remember,
  986. username
  987. );
  988. string encTicket = FormsAuthentication.Encrypt(ticket);
  989. HttpCookie authcookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
  990. authcookie.HttpOnly = true;
  991. authcookie.Secure = true;
  992. if (remember)
  993. {
  994. authcookie.Expires = expireTime;
  995. }
  996. // Set domain dependent on where it's being ran from
  997. if (local) // localhost
  998. {
  999. authcookie.Domain = null;
  1000. }
  1001. else if (config.DevEnvironment) // dev.example.com
  1002. {
  1003. authcookie.Domain = string.Format("dev.{0}", domain);
  1004. }
  1005. else // A production instance
  1006. {
  1007. authcookie.Domain = string.Format(".{0}", domain);
  1008. }
  1009. return authcookie;
  1010. }
  1011. public static HttpCookie CreateTrustedDeviceCookie(string username, string domain, bool local)
  1012. {
  1013. Config config = Config.Load();
  1014. byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
  1015. byte[] key = Guid.NewGuid().ToByteArray();
  1016. string token = Convert.ToBase64String(time.Concat(key).ToArray());
  1017. HttpCookie trustCookie = new HttpCookie(Constants.TRUSTEDDEVICECOOKIE + "_" + username);
  1018. trustCookie.Value = token;
  1019. trustCookie.HttpOnly = true;
  1020. trustCookie.Secure = true;
  1021. trustCookie.Expires = DateTime.Now.AddYears(1);
  1022. // Set domain dependent on where it's being ran from
  1023. if (local) // localhost
  1024. {
  1025. trustCookie.Domain = null;
  1026. }
  1027. else if (config.DevEnvironment) // dev.example.com
  1028. {
  1029. trustCookie.Domain = string.Format("dev.{0}", domain);
  1030. }
  1031. else // A production instance
  1032. {
  1033. trustCookie.Domain = string.Format(".{0}", domain);
  1034. }
  1035. return trustCookie;
  1036. }
  1037. }
  1038. }