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

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