The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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