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

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