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

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