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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  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. // Query the Email DB
  804. // We need to check the actual git database
  805. MysqlDatabase mySQL = new MysqlDatabase(config.EmailConfig.CounterDatabase.Server, config.EmailConfig.CounterDatabase.Database, config.EmailConfig.CounterDatabase.Username, config.EmailConfig.CounterDatabase.Password, config.EmailConfig.CounterDatabase.Port);
  806. string sql = @"INSERT INTO mailcounter.counts (qname, lastdate, qlimit, count) VALUES ({1}, NOW(), {0}, 0)
  807. ON DUPLICATE KEY UPDATE qlimit = {0}";
  808. mySQL.Execute(sql, new object[] { maxPerDay, email });
  809. }
  810. }
  811. catch (Exception ex)
  812. {
  813. throw new Exception("Unable to edit email account mailbox size.", ex);
  814. }
  815. }
  816. public static void DeleteUserEmail(Config config, string email)
  817. {
  818. try
  819. {
  820. // If Email Server is enabled
  821. if (config.EmailConfig.Enabled)
  822. {
  823. var app = new hMailServer.Application();
  824. app.Connect();
  825. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  826. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  827. var account = domain.Accounts.ItemByAddress[email];
  828. if (account != null)
  829. {
  830. account.Delete();
  831. }
  832. }
  833. }
  834. catch (Exception ex)
  835. {
  836. throw new Exception("Unable to delete email account.", ex);
  837. }
  838. }
  839. #endregion
  840. #region Git Management
  841. public static bool UserGitExists(Config config, string username)
  842. {
  843. if (config.GitConfig.Enabled)
  844. {
  845. try
  846. {
  847. Uri baseUri = new Uri(config.GitConfig.Host);
  848. Uri finalUri = new Uri(baseUri, "api/v1/users/" + username + "?token=" + config.GitConfig.AccessToken);
  849. WebRequest request = WebRequest.Create(finalUri);
  850. request.Method = "GET";
  851. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  852. if (response.StatusCode == HttpStatusCode.OK)
  853. {
  854. return true;
  855. }
  856. }
  857. catch { }
  858. }
  859. return false;
  860. }
  861. public static DateTime UserGitLastActive(Config config, string username)
  862. {
  863. DateTime lastActive = new DateTime(1900, 1, 1);
  864. if (config.GitConfig.Enabled)
  865. {
  866. // Git user exists?
  867. if (UserGitExists(config, username))
  868. {
  869. throw new Exception($"Git User '{username}' does not exist.");
  870. }
  871. string email = GetUserEmailAddress(config, username);
  872. // We need to check the actual git database
  873. MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database.Server, config.GitConfig.Database.Database, config.GitConfig.Database.Username, config.GitConfig.Database.Password, config.GitConfig.Database.Port);
  874. string sql = @"SELECT
  875. CASE
  876. WHEN MAX(gogs.action.created) >= MAX(gogs.user.updated) THEN MAX(gogs.action.created)
  877. WHEN MAX(gogs.user.updated) >= MAX(gogs.action.created) THEN MAX(gogs.user.updated)
  878. ELSE MAX(gogs.user.updated)
  879. END AS LastUpdate
  880. FROM gogs.user
  881. LEFT JOIN gogs.action ON gogs.user.id = gogs.action.act_user_id
  882. WHERE gogs.user.login_name = {0}";
  883. var results = mySQL.Query(sql, new object[] { email });
  884. if (results != null && results.Any())
  885. {
  886. var result = results.First();
  887. DateTime tmpLast = lastActive;
  888. DateTime.TryParse(result["LastUpdate"].ToString(), out tmpLast);
  889. if (lastActive < tmpLast)
  890. lastActive = tmpLast;
  891. }
  892. }
  893. return lastActive;
  894. }
  895. public static void AddUserGit(Config config, string username, string password)
  896. {
  897. try
  898. {
  899. // If Git is enabled
  900. if (config.GitConfig.Enabled)
  901. {
  902. string email = GetUserEmailAddress(config, username);
  903. // Add gogs user
  904. using (var client = new WebClient())
  905. {
  906. var obj = new { source_id = config.GitConfig.SourceId, username = username, email = email, login_name = email, password = password };
  907. string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  908. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  909. Uri baseUri = new Uri(config.GitConfig.Host);
  910. Uri finalUri = new Uri(baseUri, "api/v1/admin/users?token=" + config.GitConfig.AccessToken);
  911. string result = client.UploadString(finalUri, "POST", json);
  912. }
  913. }
  914. }
  915. catch (Exception ex)
  916. {
  917. throw new Exception("Unable to add git account.", ex);
  918. }
  919. }
  920. public static void EditUserGitPassword(Config config, string username, string password)
  921. {
  922. try
  923. {
  924. // If Git is enabled
  925. if (config.GitConfig.Enabled)
  926. {
  927. // Git user exists?
  928. if (UserGitExists(config, username))
  929. {
  930. throw new Exception($"Git User '{username}' does not exist.");
  931. }
  932. string email = GetUserEmailAddress(config, username);
  933. using (var client = new WebClient())
  934. {
  935. var obj = new {source_id = config.GitConfig.SourceId, email = email, login_name = email, password = password};
  936. string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  937. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  938. Uri baseUri = new Uri(config.GitConfig.Host);
  939. Uri finalUri = new Uri(baseUri, "api/v1/admin/users/" + username + "?token=" + config.GitConfig.AccessToken);
  940. string result = client.UploadString(finalUri, "PATCH", json);
  941. }
  942. }
  943. }
  944. catch (Exception ex)
  945. {
  946. throw new Exception("Unable to edit git account password.", ex);
  947. }
  948. }
  949. public static void CreateUserGitTwoFactor(Config config, string username, string secret, int unixTime)
  950. {
  951. try
  952. {
  953. // If Git is enabled
  954. if (config.GitConfig.Enabled)
  955. {
  956. // Git user exists?
  957. if (UserGitExists(config, username))
  958. {
  959. throw new Exception($"Git User '{username}' does not exist.");
  960. }
  961. // Generate the scratch token
  962. string token = StringHelper.RandomString(8);
  963. // Get the Encryption Key from the git secret key
  964. byte[] keyBytes = MD5.Hash(Encoding.UTF8.GetBytes(config.GitConfig.SecretKey));
  965. // Modify the input secret
  966. byte[] secBytes = Encoding.UTF8.GetBytes(secret);
  967. // Generate the encrypted secret using AES CGM
  968. byte[] encValue = Aes128CFB.Encrypt(secBytes, keyBytes);
  969. string finalSecret = Convert.ToBase64String(encValue);
  970. // Create connection to the DB
  971. MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database.Server, config.GitConfig.Database.Database, config.GitConfig.Database.Username, config.GitConfig.Database.Password, config.GitConfig.Database.Port);
  972. // Get the user's UID
  973. string email = GetUserEmailAddress(config, username);
  974. string userSelect = @"SELECT id FROM gogs.user WHERE gogs.user.login_name = {0}";
  975. var uid = mySQL.ScalarQuery(userSelect, new object[] { email });
  976. // See if they have Two Factor already
  977. string sqlSelect = @"SELECT id
  978. FROM gogs.two_factor
  979. LEFT JOIN gogs.user ON gogs.user.id = gogs.gogs.two_factor.uid
  980. WHERE gogs.user.login_name = {0}";
  981. var result = mySQL.ScalarQuery(sqlSelect, new object[] { email });
  982. if (result != null)
  983. {
  984. // They have an entry! Let's update it
  985. string insert = @"UPDATE gogs.two_factor SET uid = {1}, secret = {2}, scratch_token = {3}, updated_unix = {4} WHERE gogs.two_factor.id = {0}";
  986. mySQL.Execute(insert, new object[] { result, uid, finalSecret, token, unixTime });
  987. }
  988. else
  989. {
  990. // They need a new entry
  991. string update = @"INSERT INTO gogs.two_factor SET (uid, secret, scratch_token, created_unix, updated_unix) VALUES ({0}, {1}, {2}, {3}, {4})";
  992. mySQL.Execute(update, new object[] { uid, finalSecret, token, unixTime, 0 });
  993. }
  994. }
  995. }
  996. catch (Exception ex)
  997. {
  998. throw new Exception("Unable to edit git account two factor.", ex);
  999. }
  1000. }
  1001. public static void DeleteUserGitTwoFactor(Config config, string username)
  1002. {
  1003. try
  1004. {
  1005. // If Git is enabled
  1006. if (config.GitConfig.Enabled)
  1007. {
  1008. // Git user exists?
  1009. if (UserGitExists(config, username))
  1010. {
  1011. throw new Exception($"Git User '{username}' does not exist.");
  1012. }
  1013. // Create connection to the DB
  1014. MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database.Server, config.GitConfig.Database.Database, config.GitConfig.Database.Username, config.GitConfig.Database.Password, config.GitConfig.Database.Port);
  1015. // Get the user's UID
  1016. string email = GetUserEmailAddress(config, username);
  1017. // See if they have Two Factor already
  1018. string deleteSql = @"DELETE tf.*
  1019. FROM gogs.two_factor tf
  1020. LEFT JOIN gogs.user u ON u.id = tf.uid
  1021. WHERE u.login_name = {0}";
  1022. mySQL.Execute(deleteSql, new object[] { email });
  1023. }
  1024. }
  1025. catch (Exception ex)
  1026. {
  1027. throw new Exception("Unable to delete git account two factor.", ex);
  1028. }
  1029. }
  1030. public static void DeleteUserGit(Config config, string username)
  1031. {
  1032. try
  1033. {
  1034. // If Git is enabled
  1035. if (config.GitConfig.Enabled)
  1036. {
  1037. // Git user exists?
  1038. if (UserGitExists(config, username))
  1039. {
  1040. throw new Exception($"Git User '{username}' does not exist.");
  1041. }
  1042. try
  1043. {
  1044. Uri baseUri = new Uri(config.GitConfig.Host);
  1045. Uri finalUri = new Uri(baseUri, "api/v1/admin/users/" + username + "?token=" + config.GitConfig.AccessToken);
  1046. WebRequest request = WebRequest.Create(finalUri);
  1047. request.Method = "DELETE";
  1048. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  1049. if (response.StatusCode != HttpStatusCode.NotFound && response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NoContent)
  1050. {
  1051. throw new Exception("Unable to delete git account. Response Code: " + response.StatusCode);
  1052. }
  1053. }
  1054. catch (HttpException htex)
  1055. {
  1056. if (htex.GetHttpCode() != 404)
  1057. throw new Exception("Unable to delete git account. Http Exception: " + htex.Message);
  1058. }
  1059. catch (Exception ex)
  1060. {
  1061. // This error signifies the user doesn't exist, so we can continue deleting
  1062. if (ex.Message != "The remote server returned an error: (404) Not Found.")
  1063. {
  1064. throw new Exception("Unable to delete git account. Exception: " + ex.Message);
  1065. }
  1066. }
  1067. }
  1068. }
  1069. catch (Exception ex)
  1070. {
  1071. throw new Exception("Unable to delete git account.", ex);
  1072. }
  1073. }
  1074. #endregion
  1075. public static HttpCookie CreateAuthCookie(string username, bool remember, string domain, bool local)
  1076. {
  1077. DateTime curTime = DateTime.Now;
  1078. DateTime expireTime = curTime.AddMonths(1);
  1079. Config config = Config.Load();
  1080. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
  1081. 1,
  1082. username,
  1083. curTime,
  1084. expireTime,
  1085. remember,
  1086. username
  1087. );
  1088. string encTicket = FormsAuthentication.Encrypt(ticket);
  1089. HttpCookie authcookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
  1090. authcookie.HttpOnly = true;
  1091. authcookie.Secure = true;
  1092. if (remember)
  1093. {
  1094. authcookie.Expires = expireTime;
  1095. }
  1096. // Set domain dependent on where it's being ran from
  1097. if (local) // localhost
  1098. {
  1099. authcookie.Domain = null;
  1100. }
  1101. else if (config.DevEnvironment) // dev.example.com
  1102. {
  1103. authcookie.Domain = string.Format("dev.{0}", domain);
  1104. }
  1105. else // A production instance
  1106. {
  1107. authcookie.Domain = string.Format(".{0}", domain);
  1108. }
  1109. return authcookie;
  1110. }
  1111. public static HttpCookie CreateTrustedDeviceCookie(string username, string domain, bool local)
  1112. {
  1113. Config config = Config.Load();
  1114. byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
  1115. byte[] key = Guid.NewGuid().ToByteArray();
  1116. string token = Convert.ToBase64String(time.Concat(key).ToArray());
  1117. HttpCookie trustCookie = new HttpCookie(Constants.TRUSTEDDEVICECOOKIE + "_" + username);
  1118. trustCookie.Value = token;
  1119. trustCookie.HttpOnly = true;
  1120. trustCookie.Secure = true;
  1121. trustCookie.Expires = DateTime.Now.AddYears(1);
  1122. // Set domain dependent on where it's being ran from
  1123. if (local) // localhost
  1124. {
  1125. trustCookie.Domain = null;
  1126. }
  1127. else if (config.DevEnvironment) // dev.example.com
  1128. {
  1129. trustCookie.Domain = string.Format("dev.{0}", domain);
  1130. }
  1131. else // A production instance
  1132. {
  1133. trustCookie.Domain = string.Format(".{0}", domain);
  1134. }
  1135. return trustCookie;
  1136. }
  1137. }
  1138. }