The next generation of the Teknik Services. Written in ASP.NET. Fork for blog tags.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UserHelper.cs 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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. i--;
  238. }
  239. db.Entry(user).State = EntityState.Modified;
  240. db.SaveChanges();
  241. }
  242. catch (Exception ex)
  243. {
  244. throw new Exception("Unable to transfer user info.", ex);
  245. }
  246. }
  247. public static void AddUser(TeknikEntities db, Config config, User user, string password)
  248. {
  249. try
  250. {
  251. // Add User
  252. user.HashedPassword = GeneratePassword(config, user, password);
  253. db.Users.Add(user);
  254. db.SaveChanges();
  255. // Generate blog for the user
  256. var newBlog = db.Blogs.Create();
  257. newBlog.UserId = user.UserId;
  258. db.Blogs.Add(newBlog);
  259. db.SaveChanges();
  260. }
  261. catch (Exception ex)
  262. {
  263. throw new Exception("Unable to create user.", ex);
  264. }
  265. }
  266. public static void EditUser(TeknikEntities db, Config config, User user, bool changePass, string password)
  267. {
  268. try
  269. {
  270. // Changing Password?
  271. if (changePass)
  272. {
  273. // Update User password
  274. user.HashedPassword = SHA384.Hash(user.Username.ToLower(), password).ToHex();
  275. }
  276. db.Entry(user).State = EntityState.Modified;
  277. db.SaveChanges();
  278. }
  279. catch (Exception ex)
  280. {
  281. throw new Exception("Unable to edit user.", ex);
  282. }
  283. }
  284. public static void DeleteUser(TeknikEntities db, Config config, User user)
  285. {
  286. try
  287. {
  288. // Update uploads
  289. List<Upload.Models.Upload> uploads = db.Uploads.Where(u => u.User.Username == user.Username).ToList();
  290. if (uploads != null)
  291. {
  292. foreach (Upload.Models.Upload upload in uploads)
  293. {
  294. upload.UserId = null;
  295. db.Entry(upload).State = EntityState.Modified;
  296. }
  297. }
  298. // Update pastes
  299. List<Paste.Models.Paste> pastes = db.Pastes.Where(u => u.User.Username == user.Username).ToList();
  300. if (pastes != null)
  301. {
  302. foreach (Paste.Models.Paste paste in pastes)
  303. {
  304. paste.UserId = null;
  305. db.Entry(paste).State = EntityState.Modified;
  306. }
  307. }
  308. // Update shortened urls
  309. List<ShortenedUrl> shortUrls = db.ShortenedUrls.Where(u => u.User.Username == user.Username).ToList();
  310. if (shortUrls != null)
  311. {
  312. foreach (ShortenedUrl shortUrl in shortUrls)
  313. {
  314. shortUrl.UserId = null;
  315. db.Entry(shortUrl).State = EntityState.Modified;
  316. }
  317. }
  318. // Delete Blogs
  319. Blog.Models.Blog blog = db.Blogs.Where(u => u.User.Username == user.Username).FirstOrDefault();
  320. if (blog != null)
  321. {
  322. db.Blogs.Remove(blog);
  323. }
  324. // Delete post comments
  325. List<BlogPostComment> postComments = db.BlogComments.Where(u => u.User.Username == user.Username).ToList();
  326. if (postComments != null)
  327. {
  328. foreach (BlogPostComment postComment in postComments)
  329. {
  330. db.BlogComments.Remove(postComment);
  331. }
  332. }
  333. // Delete podcast comments
  334. List<Podcast.Models.PodcastComment> podComments = db.PodcastComments.Where(u => u.User.Username == user.Username).ToList();
  335. if (podComments != null)
  336. {
  337. foreach (Podcast.Models.PodcastComment podComment in podComments)
  338. {
  339. db.PodcastComments.Remove(podComment);
  340. }
  341. }
  342. // Delete Recovery Email Verifications
  343. List<RecoveryEmailVerification> verCodes = db.RecoveryEmailVerifications.Where(r => r.User.Username == user.Username).ToList();
  344. if (verCodes != null)
  345. {
  346. foreach (RecoveryEmailVerification verCode in verCodes)
  347. {
  348. db.RecoveryEmailVerifications.Remove(verCode);
  349. }
  350. }
  351. // Delete Password Reset Verifications
  352. List<ResetPasswordVerification> verPass = db.ResetPasswordVerifications.Where(r => r.User.Username == user.Username).ToList();
  353. if (verPass != null)
  354. {
  355. foreach (ResetPasswordVerification ver in verPass)
  356. {
  357. db.ResetPasswordVerifications.Remove(ver);
  358. }
  359. }
  360. // Delete User
  361. db.Users.Remove(user);
  362. db.SaveChanges();
  363. }
  364. catch (Exception ex)
  365. {
  366. throw new Exception("Unable to delete user.", ex);
  367. }
  368. }
  369. public static string CreateRecoveryEmailVerification(TeknikEntities db, Config config, User user)
  370. {
  371. // Check to see if there already is a verification code for the user
  372. List<RecoveryEmailVerification> verCodes = db.RecoveryEmailVerifications.Where(r => r.User.Username == user.Username).ToList();
  373. if (verCodes != null && verCodes.Any())
  374. {
  375. foreach (RecoveryEmailVerification verCode in verCodes)
  376. {
  377. db.RecoveryEmailVerifications.Remove(verCode);
  378. }
  379. }
  380. // Create a new verification code and add it
  381. string verifyCode = Teknik.Utility.RandomString(24);
  382. RecoveryEmailVerification ver = new RecoveryEmailVerification();
  383. ver.UserId = user.UserId;
  384. ver.Code = verifyCode;
  385. ver.DateCreated = DateTime.Now;
  386. db.RecoveryEmailVerifications.Add(ver);
  387. db.SaveChanges();
  388. return verifyCode;
  389. }
  390. public static void SendRecoveryEmailVerification(Config config, string username, string email, string resetUrl, string verifyUrl)
  391. {
  392. SmtpClient client = new SmtpClient();
  393. client.Host = config.ContactConfig.Host;
  394. client.Port = config.ContactConfig.Port;
  395. client.EnableSsl = config.ContactConfig.SSL;
  396. client.DeliveryMethod = SmtpDeliveryMethod.Network;
  397. client.UseDefaultCredentials = true;
  398. client.Credentials = new NetworkCredential(config.NoReplyEmail, config.ContactConfig.Password);
  399. client.Timeout = 5000;
  400. MailMessage mail = new MailMessage(config.NoReplyEmail, email);
  401. mail.Subject = "Recovery Email Validation";
  402. mail.Body = string.Format(@"Hello {0},
  403. Welcome to Teknik!
  404. 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.
  405. In order to verify that you own this email, please click the following link or paste it into your browser: {2}
  406. If you recieved this email and you did not sign up for an account, please email us at {3} and ignore the verification link.
  407. Thank you and enjoy!
  408. - Teknik Administration", username, resetUrl, verifyUrl, config.SupportEmail);
  409. mail.BodyEncoding = UTF8Encoding.UTF8;
  410. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
  411. client.Send(mail);
  412. }
  413. public static bool VerifyRecoveryEmail(TeknikEntities db, Config config, string username, string code)
  414. {
  415. User user = GetUser(db, username);
  416. RecoveryEmailVerification verCode = db.RecoveryEmailVerifications.Where(r => r.User.Username == username && r.Code == code).FirstOrDefault();
  417. if (verCode != null)
  418. {
  419. // We have a match, so clear out the verifications for that user
  420. List<RecoveryEmailVerification> verCodes = db.RecoveryEmailVerifications.Where(r => r.User.Username == username).ToList();
  421. if (verCodes != null && verCodes.Any())
  422. {
  423. foreach (RecoveryEmailVerification ver in verCodes)
  424. {
  425. db.RecoveryEmailVerifications.Remove(ver);
  426. }
  427. }
  428. // Update the user
  429. user.RecoveryVerified = true;
  430. db.Entry(user).State = EntityState.Modified;
  431. db.SaveChanges();
  432. return true;
  433. }
  434. return false;
  435. }
  436. public static string CreateResetPasswordVerification(TeknikEntities db, Config config, User user)
  437. {
  438. // Check to see if there already is a verification code for the user
  439. List<ResetPasswordVerification> verCodes = db.ResetPasswordVerifications.Where(r => r.User.Username == user.Username).ToList();
  440. if (verCodes != null && verCodes.Any())
  441. {
  442. foreach (ResetPasswordVerification verCode in verCodes)
  443. {
  444. db.ResetPasswordVerifications.Remove(verCode);
  445. }
  446. }
  447. // Create a new verification code and add it
  448. string verifyCode = Teknik.Utility.RandomString(24);
  449. ResetPasswordVerification ver = new ResetPasswordVerification();
  450. ver.UserId = user.UserId;
  451. ver.Code = verifyCode;
  452. ver.DateCreated = DateTime.Now;
  453. db.ResetPasswordVerifications.Add(ver);
  454. db.SaveChanges();
  455. return verifyCode;
  456. }
  457. public static void SendResetPasswordVerification(Config config, string username, string email, string resetUrl)
  458. {
  459. SmtpClient client = new SmtpClient();
  460. client.Host = config.ContactConfig.Host;
  461. client.Port = config.ContactConfig.Port;
  462. client.EnableSsl = config.ContactConfig.SSL;
  463. client.DeliveryMethod = SmtpDeliveryMethod.Network;
  464. client.UseDefaultCredentials = true;
  465. client.Credentials = new NetworkCredential(config.NoReplyEmail, config.ContactConfig.Password);
  466. client.Timeout = 5000;
  467. MailMessage mail = new MailMessage(config.NoReplyEmail, email);
  468. mail.Subject = "Password Reset Request";
  469. mail.Body = string.Format(@"Hello {0},
  470. 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.
  471. To proceed in resetting your password, please click the following link or paste it into your browser: {1}
  472. 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.
  473. - Teknik Administration", username, resetUrl, config.SupportEmail);
  474. mail.BodyEncoding = UTF8Encoding.UTF8;
  475. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
  476. client.Send(mail);
  477. }
  478. public static bool VerifyResetPassword(TeknikEntities db, Config config, string username, string code)
  479. {
  480. User user = GetUser(db, username);
  481. ResetPasswordVerification verCode = db.ResetPasswordVerifications.Where(r => r.User.Username == username && r.Code == code).FirstOrDefault();
  482. if (verCode != null)
  483. {
  484. // We have a match, so clear out the verifications for that user
  485. List<ResetPasswordVerification> verCodes = db.ResetPasswordVerifications.Where(r => r.User.Username == username).ToList();
  486. if (verCodes != null && verCodes.Any())
  487. {
  488. foreach (ResetPasswordVerification ver in verCodes)
  489. {
  490. db.ResetPasswordVerifications.Remove(ver);
  491. }
  492. }
  493. db.SaveChanges();
  494. return true;
  495. }
  496. return false;
  497. }
  498. #endregion
  499. #region Email Management
  500. public static string GetUserEmailAddress(Config config, string username)
  501. {
  502. return string.Format("{0}@{1}", username, config.EmailConfig.Domain);
  503. }
  504. public static bool UserEmailExists(Config config, string email)
  505. {
  506. // If Email Server is enabled
  507. if (config.EmailConfig.Enabled)
  508. {
  509. // Connect to hmailserver COM
  510. var app = new hMailServer.Application();
  511. app.Connect();
  512. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  513. try
  514. {
  515. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  516. var account = domain.Accounts.ItemByAddress[email];
  517. // We didn't error out, so the email exists
  518. return true;
  519. }
  520. catch { }
  521. }
  522. return false;
  523. }
  524. public static DateTime UserEmailLastActive(Config config, string email)
  525. {
  526. DateTime lastActive = new DateTime(1900, 1, 1);
  527. if (config.EmailConfig.Enabled)
  528. {
  529. var app = new hMailServer.Application();
  530. app.Connect();
  531. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  532. try
  533. {
  534. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  535. var account = domain.Accounts.ItemByAddress[email];
  536. DateTime lastEmail = (DateTime)account.LastLogonTime;
  537. if (lastActive < lastEmail)
  538. lastActive = lastEmail;
  539. }
  540. catch { }
  541. }
  542. return lastActive;
  543. }
  544. public static void AddUserEmail(Config config, string email, string password)
  545. {
  546. try
  547. {
  548. // If Email Server is enabled
  549. if (config.EmailConfig.Enabled)
  550. {
  551. // Connect to hmailserver COM
  552. var app = new hMailServer.Application();
  553. app.Connect();
  554. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  555. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  556. var newAccount = domain.Accounts.Add();
  557. newAccount.Address = email;
  558. newAccount.Password = password;
  559. newAccount.Active = true;
  560. newAccount.MaxSize = config.EmailConfig.MaxSize;
  561. newAccount.Save();
  562. }
  563. }
  564. catch (Exception ex)
  565. {
  566. throw new Exception("Unable to add email.", ex);
  567. }
  568. }
  569. public static void EditUserEmailPassword(Config config, string email, string password)
  570. {
  571. try
  572. {
  573. // If Email Server is enabled
  574. if (config.EmailConfig.Enabled)
  575. {
  576. var app = new hMailServer.Application();
  577. app.Connect();
  578. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  579. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  580. var account = domain.Accounts.ItemByAddress[email];
  581. account.Password = password;
  582. account.Save();
  583. }
  584. }
  585. catch (Exception ex)
  586. {
  587. throw new Exception("Unable to edit email account password.", ex);
  588. }
  589. }
  590. public static void DeleteUserEmail(Config config, string email)
  591. {
  592. try
  593. {
  594. // If Email Server is enabled
  595. if (config.EmailConfig.Enabled)
  596. {
  597. var app = new hMailServer.Application();
  598. app.Connect();
  599. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  600. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  601. var account = domain.Accounts.ItemByAddress[email];
  602. if (account != null)
  603. {
  604. account.Delete();
  605. }
  606. }
  607. }
  608. catch (Exception ex)
  609. {
  610. throw new Exception("Unable to delete email account.", ex);
  611. }
  612. }
  613. #endregion
  614. #region Git Management
  615. public static bool UserGitExists(Config config, string username)
  616. {
  617. if (config.GitConfig.Enabled)
  618. {
  619. try
  620. {
  621. Uri baseUri = new Uri(config.GitConfig.Host);
  622. Uri finalUri = new Uri(baseUri, "api/v1/users/" + username + "?token=" + config.GitConfig.AccessToken);
  623. WebRequest request = WebRequest.Create(finalUri);
  624. request.Method = "GET";
  625. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  626. if (response.StatusCode == HttpStatusCode.OK)
  627. {
  628. return true;
  629. }
  630. }
  631. catch { }
  632. }
  633. return false;
  634. }
  635. public static DateTime UserGitLastActive(Config config, string username)
  636. {
  637. DateTime lastActive = new DateTime(1900, 1, 1);
  638. if (config.GitConfig.Enabled)
  639. {
  640. string email = GetUserEmailAddress(config, username);
  641. // We need to check the actual git database
  642. MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database);
  643. string sql = @"SELECT
  644. CASE
  645. WHEN MAX(gogs.action.created) >= MAX(gogs.user.updated) THEN MAX(gogs.action.created)
  646. WHEN MAX(gogs.user.updated) >= MAX(gogs.action.created) THEN MAX(gogs.user.updated)
  647. ELSE MAX(gogs.user.updated)
  648. END AS LastUpdate
  649. FROM gogs.user
  650. LEFT JOIN gogs.action ON gogs.user.id = gogs.action.act_user_id
  651. WHERE gogs.user.login_name = {0}";
  652. var results = mySQL.Query(sql, new object[] { email });
  653. if (results != null && results.Any())
  654. {
  655. var result = results.First();
  656. DateTime tmpLast = lastActive;
  657. DateTime.TryParse(result["LastUpdate"].ToString(), out tmpLast);
  658. if (lastActive < tmpLast)
  659. lastActive = tmpLast;
  660. }
  661. }
  662. return lastActive;
  663. }
  664. public static void AddUserGit(Config config, string username, string password)
  665. {
  666. try
  667. {
  668. // If Git is enabled
  669. if (config.GitConfig.Enabled)
  670. {
  671. string email = GetUserEmailAddress(config, username);
  672. // Add gogs user
  673. using (var client = new WebClient())
  674. {
  675. var obj = new { source_id = config.GitConfig.SourceId, username = username, email = email, login_name = email, password = password };
  676. string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  677. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  678. Uri baseUri = new Uri(config.GitConfig.Host);
  679. Uri finalUri = new Uri(baseUri, "api/v1/admin/users?token=" + config.GitConfig.AccessToken);
  680. string result = client.UploadString(finalUri, "POST", json);
  681. }
  682. }
  683. }
  684. catch (Exception ex)
  685. {
  686. throw new Exception("Unable to add git account.", ex);
  687. }
  688. }
  689. public static void EditUserGitPassword(Config config, string username, string password)
  690. {
  691. try
  692. {
  693. // If Git is enabled
  694. if (config.GitConfig.Enabled)
  695. {
  696. string email = GetUserEmailAddress(config, username);
  697. using (var client = new WebClient())
  698. {
  699. var obj = new { source_id = config.GitConfig.SourceId, email = email, password = password };
  700. string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  701. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  702. Uri baseUri = new Uri(config.GitConfig.Host);
  703. Uri finalUri = new Uri(baseUri, "api/v1/admin/users/" + username + "?token=" + config.GitConfig.AccessToken);
  704. string result = client.UploadString(finalUri, "PATCH", json);
  705. }
  706. }
  707. }
  708. catch (Exception ex)
  709. {
  710. throw new Exception("Unable to edit git account password.", ex);
  711. }
  712. }
  713. public static void DeleteUserGit(Config config, string username)
  714. {
  715. try
  716. {
  717. // If Git is enabled
  718. if (config.GitConfig.Enabled)
  719. {
  720. try
  721. {
  722. Uri baseUri = new Uri(config.GitConfig.Host);
  723. Uri finalUri = new Uri(baseUri, "api/v1/admin/users/" + username + "?token=" + config.GitConfig.AccessToken);
  724. WebRequest request = WebRequest.Create(finalUri);
  725. request.Method = "DELETE";
  726. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  727. if (response.StatusCode != HttpStatusCode.NotFound && response.StatusCode != HttpStatusCode.OK)
  728. {
  729. throw new Exception("Unable to delete git account. Response Code: " + response.StatusCode);
  730. }
  731. }
  732. catch (HttpException htex)
  733. {
  734. if (htex.GetHttpCode() != 404)
  735. throw new Exception("Unable to delete git account. Http Exception: " + htex.Message);
  736. }
  737. catch (Exception ex)
  738. {
  739. // This error signifies the user doesn't exist, so we can continue deleting
  740. if (ex.Message != "The remote server returned an error: (404) Not Found.")
  741. {
  742. throw new Exception("Unable to delete git account. Exception: " + ex.Message);
  743. }
  744. }
  745. }
  746. }
  747. catch (Exception ex)
  748. {
  749. throw new Exception("Unable to delete git account.", ex);
  750. }
  751. }
  752. #endregion
  753. public static HttpCookie CreateAuthCookie(string username, bool remember, string domain, bool local)
  754. {
  755. Config config = Config.Load();
  756. HttpCookie authcookie = FormsAuthentication.GetAuthCookie(username, remember);
  757. authcookie.Name = "TeknikAuth";
  758. authcookie.HttpOnly = true;
  759. authcookie.Secure = true;
  760. // Set domain dependent on where it's being ran from
  761. if (local) // localhost
  762. {
  763. authcookie.Domain = null;
  764. }
  765. else if (config.DevEnvironment) // dev.example.com
  766. {
  767. authcookie.Domain = string.Format("dev.{0}", domain);
  768. }
  769. else // A production instance
  770. {
  771. authcookie.Domain = string.Format(".{0}", domain);
  772. }
  773. return authcookie;
  774. }
  775. }
  776. }