The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

4 лет назад
4 лет назад
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  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.Utilities;
  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 string GenerateAuthToken(TeknikEntities db, string username)
  117. {
  118. try
  119. {
  120. bool validToken = false;
  121. string token = string.Empty;
  122. while (!validToken)
  123. {
  124. username = username.ToLower();
  125. byte[] hashBytes = SHA384.Hash(username, StringHelper.RandomString(24));
  126. token = hashBytes.ToHex();
  127. // Make sure it isn't a duplicate
  128. string hashedToken = SHA256.Hash(token);
  129. if (!db.AuthTokens.Where(t => t.HashedToken == hashedToken).Any())
  130. {
  131. validToken = true;
  132. }
  133. }
  134. return token;
  135. }
  136. catch (Exception ex)
  137. {
  138. throw new Exception("Unable to generate user auth token.", ex);
  139. }
  140. }
  141. public static void AddAccount(TeknikEntities db, Config config, User user, string password)
  142. {
  143. try
  144. {
  145. // Create an Email Account
  146. AddUserEmail(config, GetUserEmailAddress(config, user.Username), password);
  147. // Create a Git Account
  148. AddUserGit(config, user.Username, password);
  149. // Add User
  150. AddUser(db, config, user, password);
  151. }
  152. catch (Exception ex)
  153. {
  154. throw new Exception("Unable to create account.", ex);
  155. }
  156. }
  157. public static void EditAccount(TeknikEntities db, Config config, User user, bool changePass, string password)
  158. {
  159. try
  160. {
  161. // Changing Password?
  162. if (changePass)
  163. {
  164. // Change email password
  165. EditUserEmailPassword(config, GetUserEmailAddress(config, user.Username), password);
  166. // Update Git password
  167. EditUserGitPassword(config, user.Username, password);
  168. }
  169. // Update User
  170. EditUser(db, config, user, changePass, password);
  171. }
  172. catch (Exception ex)
  173. {
  174. throw new Exception("Unable to edit account.", ex);
  175. }
  176. }
  177. public static void DeleteAccount(TeknikEntities db, Config config, User user)
  178. {
  179. try
  180. {
  181. // Delete Email Account
  182. if (UserEmailExists(config, GetUserEmailAddress(config, user.Username)))
  183. DeleteUserEmail(config, GetUserEmailAddress(config, user.Username));
  184. // Delete Git Account
  185. if (UserGitExists(config, user.Username))
  186. DeleteUserGit(config, user.Username);
  187. // Delete User Account
  188. DeleteUser(db, config, user);
  189. }
  190. catch (Exception ex)
  191. {
  192. throw new Exception("Unable to delete account.", ex);
  193. }
  194. }
  195. #endregion
  196. #region User Management
  197. public static User GetUser(TeknikEntities db, string username)
  198. {
  199. User user = db.Users.Where(b => b.Username == username).FirstOrDefault();
  200. if (user != null)
  201. {
  202. user.UserSettings = db.UserSettings.Find(user.UserId);
  203. user.SecuritySettings = db.SecuritySettings.Find(user.UserId);
  204. user.BlogSettings = db.BlogSettings.Find(user.UserId);
  205. user.UploadSettings = db.UploadSettings.Find(user.UserId);
  206. }
  207. return user;
  208. }
  209. public static User GetUserFromToken(TeknikEntities db, string username, string token)
  210. {
  211. if (token != null && !string.IsNullOrEmpty(username))
  212. {
  213. string hashedToken = SHA256.Hash(token);
  214. return db.Users.FirstOrDefault(u => u.AuthTokens.Select(a => a.HashedToken).Contains(hashedToken) && u.Username == username);
  215. }
  216. return null;
  217. }
  218. public static bool UserExists(TeknikEntities db, string username)
  219. {
  220. User user = GetUser(db, username);
  221. if (user != null)
  222. {
  223. return true;
  224. }
  225. return false;
  226. }
  227. public static DateTime UserLastActive(TeknikEntities db, Config config, User user)
  228. {
  229. try
  230. {
  231. DateTime lastActive = new DateTime(1900, 1, 1);
  232. if (lastActive < user.LastSeen)
  233. lastActive = user.LastSeen;
  234. return lastActive;
  235. }
  236. catch (Exception ex)
  237. {
  238. throw new Exception("Unable to determine last user activity.", ex);
  239. }
  240. }
  241. public static void UpdateTokenLastUsed(TeknikEntities db, string username, string token, DateTime lastUsed)
  242. {
  243. User foundUser = GetUser(db, username);
  244. if (foundUser != null)
  245. {
  246. string hashedToken = SHA256.Hash(token);
  247. List<AuthToken> tokens = foundUser.AuthTokens.Where(t => t.HashedToken == hashedToken).ToList();
  248. if (tokens != null)
  249. {
  250. foreach (AuthToken foundToken in tokens)
  251. {
  252. foundToken.LastDateUsed = lastUsed;
  253. db.Entry(foundToken).State = EntityState.Modified;
  254. }
  255. db.SaveChanges();
  256. }
  257. }
  258. }
  259. public static bool UserPasswordCorrect(TeknikEntities db, Config config, User user, string password)
  260. {
  261. try
  262. {
  263. string hash = GeneratePassword(config, user, password);
  264. return db.Users.Any(b => b.Username == user.Username && b.HashedPassword == hash);
  265. }
  266. catch (Exception ex)
  267. {
  268. throw new Exception("Unable to determine if password is correct.", ex);
  269. }
  270. }
  271. public static bool UserTokenCorrect(TeknikEntities db, string username, string token)
  272. {
  273. User foundUser = GetUserFromToken(db, username, token);
  274. if (foundUser != null)
  275. {
  276. return true;
  277. }
  278. return false;
  279. }
  280. public static bool UserHasRoles(TeknikEntities db, User user, params string[] roles)
  281. {
  282. bool hasRole = true;
  283. if (user != null)
  284. {
  285. // Check if they have the role specified
  286. if (roles.Any())
  287. {
  288. foreach (string role in roles)
  289. {
  290. if (!string.IsNullOrEmpty(role))
  291. {
  292. if (user.Groups.Where(g => g.Roles.Where(r => role == r.Name).Any()).Any())
  293. {
  294. // They have the role!
  295. return true;
  296. }
  297. else
  298. {
  299. // They don't have this role, so let's reset the hasRole
  300. hasRole = false;
  301. }
  302. }
  303. else
  304. {
  305. // Only set this if we haven't failed once already
  306. hasRole &= true;
  307. }
  308. }
  309. }
  310. else
  311. {
  312. // No roles to check, so they pass!
  313. return true;
  314. }
  315. }
  316. else
  317. {
  318. hasRole = false;
  319. }
  320. return hasRole;
  321. }
  322. public static void TransferUser(TeknikEntities db, Config config, User user, string password)
  323. {
  324. try
  325. {
  326. List<TransferType> transfers = user.Transfers.ToList();
  327. for (int i = 0; i < transfers.Count; i++)
  328. {
  329. TransferType transfer = transfers[i];
  330. switch (transfer.Type)
  331. {
  332. case TransferTypes.Sha256Password:
  333. case TransferTypes.CaseSensitivePassword:
  334. case TransferTypes.ASCIIPassword:
  335. user.HashedPassword = SHA384.Hash(user.Username.ToLower(), password).ToHex();
  336. break;
  337. default:
  338. break;
  339. }
  340. user.Transfers.Remove(transfer);
  341. }
  342. db.Entry(user).State = EntityState.Modified;
  343. db.SaveChanges();
  344. }
  345. catch (Exception ex)
  346. {
  347. throw new Exception("Unable to transfer user info.", ex);
  348. }
  349. }
  350. public static void AddUser(TeknikEntities db, Config config, User user, string password)
  351. {
  352. try
  353. {
  354. // Add User
  355. user.HashedPassword = GeneratePassword(config, user, password);
  356. db.Users.Add(user);
  357. db.SaveChanges();
  358. // Generate blog for the user
  359. var newBlog = db.Blogs.Create();
  360. newBlog.UserId = user.UserId;
  361. db.Blogs.Add(newBlog);
  362. db.SaveChanges();
  363. }
  364. catch (Exception ex)
  365. {
  366. throw new Exception("Unable to create user.", ex);
  367. }
  368. }
  369. public static void EditUser(TeknikEntities db, Config config, User user, bool changePass, string password)
  370. {
  371. try
  372. {
  373. // Changing Password?
  374. if (changePass)
  375. {
  376. // Update User password
  377. user.HashedPassword = SHA384.Hash(user.Username.ToLower(), password).ToHex();
  378. }
  379. db.Entry(user).State = EntityState.Modified;
  380. db.SaveChanges();
  381. }
  382. catch (Exception ex)
  383. {
  384. throw new Exception(string.Format("Unable to edit user {0}.", user.Username), ex);
  385. }
  386. }
  387. public static void DeleteUser(TeknikEntities db, Config config, User user)
  388. {
  389. try
  390. {
  391. // Update uploads
  392. List<Upload.Models.Upload> uploads = db.Uploads.Where(u => u.User.Username == user.Username).ToList();
  393. if (uploads != null)
  394. {
  395. foreach (Upload.Models.Upload upload in uploads)
  396. {
  397. upload.UserId = null;
  398. db.Entry(upload).State = EntityState.Modified;
  399. }
  400. db.SaveChanges();
  401. }
  402. // Update pastes
  403. List<Paste.Models.Paste> pastes = db.Pastes.Where(u => u.User.Username == user.Username).ToList();
  404. if (pastes != null)
  405. {
  406. foreach (Paste.Models.Paste paste in pastes)
  407. {
  408. paste.UserId = null;
  409. db.Entry(paste).State = EntityState.Modified;
  410. }
  411. db.SaveChanges();
  412. }
  413. // Update shortened urls
  414. List<ShortenedUrl> shortUrls = db.ShortenedUrls.Where(u => u.User.Username == user.Username).ToList();
  415. if (shortUrls != null)
  416. {
  417. foreach (ShortenedUrl shortUrl in shortUrls)
  418. {
  419. shortUrl.UserId = null;
  420. db.Entry(shortUrl).State = EntityState.Modified;
  421. }
  422. db.SaveChanges();
  423. }
  424. // Delete Blogs
  425. Blog.Models.Blog blog = db.Blogs.Where(u => u.User.Username == user.Username).FirstOrDefault();
  426. if (blog != null)
  427. {
  428. db.Blogs.Remove(blog);
  429. db.SaveChanges();
  430. }
  431. // Delete post comments
  432. List<BlogPostComment> postComments = db.BlogComments.Where(u => u.User.Username == user.Username).ToList();
  433. if (postComments != null)
  434. {
  435. foreach (BlogPostComment postComment in postComments)
  436. {
  437. db.BlogComments.Remove(postComment);
  438. }
  439. db.SaveChanges();
  440. }
  441. // Delete podcast comments
  442. List<Podcast.Models.PodcastComment> podComments = db.PodcastComments.Where(u => u.User.Username == user.Username).ToList();
  443. if (podComments != null)
  444. {
  445. foreach (Podcast.Models.PodcastComment podComment in podComments)
  446. {
  447. db.PodcastComments.Remove(podComment);
  448. }
  449. db.SaveChanges();
  450. }
  451. // Delete Recovery Email Verifications
  452. List<RecoveryEmailVerification> verCodes = db.RecoveryEmailVerifications.Where(r => r.User.Username == user.Username).ToList();
  453. if (verCodes != null)
  454. {
  455. foreach (RecoveryEmailVerification verCode in verCodes)
  456. {
  457. db.RecoveryEmailVerifications.Remove(verCode);
  458. }
  459. db.SaveChanges();
  460. }
  461. // Delete Password Reset Verifications
  462. List<ResetPasswordVerification> verPass = db.ResetPasswordVerifications.Where(r => r.User.Username == user.Username).ToList();
  463. if (verPass != null)
  464. {
  465. foreach (ResetPasswordVerification ver in verPass)
  466. {
  467. db.ResetPasswordVerifications.Remove(ver);
  468. }
  469. db.SaveChanges();
  470. }
  471. // Delete User
  472. db.Users.Remove(user);
  473. db.SaveChanges();
  474. }
  475. catch (Exception ex)
  476. {
  477. throw new Exception(string.Format("Unable to delete user {0}.", user.Username), ex);
  478. }
  479. }
  480. public static string CreateRecoveryEmailVerification(TeknikEntities db, Config config, User user)
  481. {
  482. // Check to see if there already is a verification code for the user
  483. List<RecoveryEmailVerification> verCodes = db.RecoveryEmailVerifications.Where(r => r.User.Username == user.Username).ToList();
  484. if (verCodes != null && verCodes.Any())
  485. {
  486. foreach (RecoveryEmailVerification verCode in verCodes)
  487. {
  488. db.RecoveryEmailVerifications.Remove(verCode);
  489. }
  490. }
  491. // Create a new verification code and add it
  492. string verifyCode = StringHelper.RandomString(24);
  493. RecoveryEmailVerification ver = new RecoveryEmailVerification();
  494. ver.UserId = user.UserId;
  495. ver.Code = verifyCode;
  496. ver.DateCreated = DateTime.Now;
  497. db.RecoveryEmailVerifications.Add(ver);
  498. db.SaveChanges();
  499. return verifyCode;
  500. }
  501. public static void SendRecoveryEmailVerification(Config config, string username, string email, string resetUrl, string verifyUrl)
  502. {
  503. SmtpClient client = new SmtpClient();
  504. client.Host = config.ContactConfig.EmailAccount.Host;
  505. client.Port = config.ContactConfig.EmailAccount.Port;
  506. client.EnableSsl = config.ContactConfig.EmailAccount.SSL;
  507. client.DeliveryMethod = SmtpDeliveryMethod.Network;
  508. client.UseDefaultCredentials = true;
  509. client.Credentials = new NetworkCredential(config.ContactConfig.EmailAccount.Username, config.ContactConfig.EmailAccount.Password);
  510. client.Timeout = 5000;
  511. MailMessage mail = new MailMessage(config.ContactConfig.EmailAccount.EmailAddress, email);
  512. mail.Subject = "Recovery Email Validation";
  513. mail.Body = string.Format(@"Hello {0},
  514. Welcome to Teknik!
  515. 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.
  516. In order to verify that you own this email, please click the following link or paste it into your browser: {2}
  517. If you recieved this email and you did not sign up for an account, please email us at {3} and ignore the verification link.
  518. Thank you and enjoy!
  519. - Teknik Administration", username, resetUrl, verifyUrl, config.SupportEmail);
  520. mail.BodyEncoding = UTF8Encoding.UTF8;
  521. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
  522. client.Send(mail);
  523. }
  524. public static bool VerifyRecoveryEmail(TeknikEntities db, Config config, string username, string code)
  525. {
  526. User user = GetUser(db, username);
  527. RecoveryEmailVerification verCode = db.RecoveryEmailVerifications.Where(r => r.User.Username == username && r.Code == code).FirstOrDefault();
  528. if (verCode != null)
  529. {
  530. // We have a match, so clear out the verifications for that user
  531. List<RecoveryEmailVerification> verCodes = db.RecoveryEmailVerifications.Where(r => r.User.Username == username).ToList();
  532. if (verCodes != null && verCodes.Any())
  533. {
  534. foreach (RecoveryEmailVerification ver in verCodes)
  535. {
  536. db.RecoveryEmailVerifications.Remove(ver);
  537. }
  538. }
  539. // Update the user
  540. user.SecuritySettings.RecoveryVerified = true;
  541. db.Entry(user).State = EntityState.Modified;
  542. db.SaveChanges();
  543. return true;
  544. }
  545. return false;
  546. }
  547. public static string CreateResetPasswordVerification(TeknikEntities db, Config config, User user)
  548. {
  549. // Check to see if there already is a verification code for the user
  550. List<ResetPasswordVerification> verCodes = db.ResetPasswordVerifications.Where(r => r.User.Username == user.Username).ToList();
  551. if (verCodes != null && verCodes.Any())
  552. {
  553. foreach (ResetPasswordVerification verCode in verCodes)
  554. {
  555. db.ResetPasswordVerifications.Remove(verCode);
  556. }
  557. }
  558. // Create a new verification code and add it
  559. string verifyCode = StringHelper.RandomString(24);
  560. ResetPasswordVerification ver = new ResetPasswordVerification();
  561. ver.UserId = user.UserId;
  562. ver.Code = verifyCode;
  563. ver.DateCreated = DateTime.Now;
  564. db.ResetPasswordVerifications.Add(ver);
  565. db.SaveChanges();
  566. return verifyCode;
  567. }
  568. public static void SendResetPasswordVerification(Config config, string username, string email, string resetUrl)
  569. {
  570. SmtpClient client = new SmtpClient();
  571. client.Host = config.ContactConfig.EmailAccount.Host;
  572. client.Port = config.ContactConfig.EmailAccount.Port;
  573. client.EnableSsl = config.ContactConfig.EmailAccount.SSL;
  574. client.DeliveryMethod = SmtpDeliveryMethod.Network;
  575. client.UseDefaultCredentials = true;
  576. client.Credentials = new NetworkCredential(config.ContactConfig.EmailAccount.Username, config.ContactConfig.EmailAccount.Password);
  577. client.Timeout = 5000;
  578. MailMessage mail = new MailMessage(config.ContactConfig.EmailAccount.EmailAddress, email);
  579. mail.Subject = "Password Reset Request";
  580. mail.Body = string.Format(@"Hello {0},
  581. 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.
  582. To proceed in resetting your password, please click the following link or paste it into your browser: {1}
  583. 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.
  584. - Teknik Administration", username, resetUrl, config.SupportEmail);
  585. mail.BodyEncoding = UTF8Encoding.UTF8;
  586. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
  587. client.Send(mail);
  588. }
  589. public static bool VerifyResetPassword(TeknikEntities db, Config config, string username, string code)
  590. {
  591. User user = GetUser(db, username);
  592. ResetPasswordVerification verCode = db.ResetPasswordVerifications.Where(r => r.User.Username == username && r.Code == code).FirstOrDefault();
  593. if (verCode != null)
  594. {
  595. // We have a match, so clear out the verifications for that user
  596. List<ResetPasswordVerification> verCodes = db.ResetPasswordVerifications.Where(r => r.User.Username == username).ToList();
  597. if (verCodes != null && verCodes.Any())
  598. {
  599. foreach (ResetPasswordVerification ver in verCodes)
  600. {
  601. db.ResetPasswordVerifications.Remove(ver);
  602. }
  603. }
  604. db.SaveChanges();
  605. return true;
  606. }
  607. return false;
  608. }
  609. #endregion
  610. #region Email Management
  611. public static string GetUserEmailAddress(Config config, string username)
  612. {
  613. return string.Format("{0}@{1}", username, config.EmailConfig.Domain);
  614. }
  615. public static bool UserEmailExists(Config config, string email)
  616. {
  617. // If Email Server is enabled
  618. if (config.EmailConfig.Enabled)
  619. {
  620. // Connect to hmailserver COM
  621. var app = new hMailServer.Application();
  622. app.Connect();
  623. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  624. try
  625. {
  626. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  627. var account = domain.Accounts.ItemByAddress[email];
  628. // We didn't error out, so the email exists
  629. return true;
  630. }
  631. catch { }
  632. }
  633. return false;
  634. }
  635. public static DateTime UserEmailLastActive(Config config, string email)
  636. {
  637. DateTime lastActive = new DateTime(1900, 1, 1);
  638. if (config.EmailConfig.Enabled)
  639. {
  640. var app = new hMailServer.Application();
  641. app.Connect();
  642. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  643. try
  644. {
  645. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  646. var account = domain.Accounts.ItemByAddress[email];
  647. DateTime lastEmail = (DateTime)account.LastLogonTime;
  648. if (lastActive < lastEmail)
  649. lastActive = lastEmail;
  650. }
  651. catch { }
  652. }
  653. return lastActive;
  654. }
  655. public static void AddUserEmail(Config config, string email, string password)
  656. {
  657. try
  658. {
  659. // If Email Server is enabled
  660. if (config.EmailConfig.Enabled)
  661. {
  662. // Connect to hmailserver COM
  663. var app = new hMailServer.Application();
  664. app.Connect();
  665. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  666. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  667. var newAccount = domain.Accounts.Add();
  668. newAccount.Address = email;
  669. newAccount.Password = password;
  670. newAccount.Active = true;
  671. newAccount.MaxSize = config.EmailConfig.MaxSize;
  672. newAccount.Save();
  673. }
  674. }
  675. catch (Exception ex)
  676. {
  677. throw new Exception("Unable to add email.", ex);
  678. }
  679. }
  680. public static void EditUserEmailPassword(Config config, string email, string password)
  681. {
  682. try
  683. {
  684. // If Email Server is enabled
  685. if (config.EmailConfig.Enabled)
  686. {
  687. var app = new hMailServer.Application();
  688. app.Connect();
  689. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  690. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  691. var account = domain.Accounts.ItemByAddress[email];
  692. account.Password = password;
  693. account.Save();
  694. }
  695. }
  696. catch (Exception ex)
  697. {
  698. throw new Exception("Unable to edit email account password.", ex);
  699. }
  700. }
  701. public static void DeleteUserEmail(Config config, string email)
  702. {
  703. try
  704. {
  705. // If Email Server is enabled
  706. if (config.EmailConfig.Enabled)
  707. {
  708. var app = new hMailServer.Application();
  709. app.Connect();
  710. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  711. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  712. var account = domain.Accounts.ItemByAddress[email];
  713. if (account != null)
  714. {
  715. account.Delete();
  716. }
  717. }
  718. }
  719. catch (Exception ex)
  720. {
  721. throw new Exception("Unable to delete email account.", ex);
  722. }
  723. }
  724. #endregion
  725. #region Git Management
  726. public static bool UserGitExists(Config config, string username)
  727. {
  728. if (config.GitConfig.Enabled)
  729. {
  730. try
  731. {
  732. Uri baseUri = new Uri(config.GitConfig.Host);
  733. Uri finalUri = new Uri(baseUri, "api/v1/users/" + username + "?token=" + config.GitConfig.AccessToken);
  734. WebRequest request = WebRequest.Create(finalUri);
  735. request.Method = "GET";
  736. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  737. if (response.StatusCode == HttpStatusCode.OK)
  738. {
  739. return true;
  740. }
  741. }
  742. catch { }
  743. }
  744. return false;
  745. }
  746. public static DateTime UserGitLastActive(Config config, string username)
  747. {
  748. DateTime lastActive = new DateTime(1900, 1, 1);
  749. if (config.GitConfig.Enabled)
  750. {
  751. string email = GetUserEmailAddress(config, username);
  752. // We need to check the actual git database
  753. MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database.Server, config.GitConfig.Database.Database, config.GitConfig.Database.Username, config.GitConfig.Database.Password, config.GitConfig.Database.Port);
  754. string sql = @"SELECT
  755. CASE
  756. WHEN MAX(gogs.action.created) >= MAX(gogs.user.updated) THEN MAX(gogs.action.created)
  757. WHEN MAX(gogs.user.updated) >= MAX(gogs.action.created) THEN MAX(gogs.user.updated)
  758. ELSE MAX(gogs.user.updated)
  759. END AS LastUpdate
  760. FROM gogs.user
  761. LEFT JOIN gogs.action ON gogs.user.id = gogs.action.act_user_id
  762. WHERE gogs.user.login_name = {0}";
  763. var results = mySQL.Query(sql, new object[] { email });
  764. if (results != null && results.Any())
  765. {
  766. var result = results.First();
  767. DateTime tmpLast = lastActive;
  768. DateTime.TryParse(result["LastUpdate"].ToString(), out tmpLast);
  769. if (lastActive < tmpLast)
  770. lastActive = tmpLast;
  771. }
  772. }
  773. return lastActive;
  774. }
  775. public static void AddUserGit(Config config, string username, string password)
  776. {
  777. try
  778. {
  779. // If Git is enabled
  780. if (config.GitConfig.Enabled)
  781. {
  782. string email = GetUserEmailAddress(config, username);
  783. // Add gogs user
  784. using (var client = new WebClient())
  785. {
  786. var obj = new { source_id = config.GitConfig.SourceId, username = username, email = email, login_name = email, password = password };
  787. string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  788. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  789. Uri baseUri = new Uri(config.GitConfig.Host);
  790. Uri finalUri = new Uri(baseUri, "api/v1/admin/users?token=" + config.GitConfig.AccessToken);
  791. string result = client.UploadString(finalUri, "POST", json);
  792. }
  793. }
  794. }
  795. catch (Exception ex)
  796. {
  797. throw new Exception("Unable to add git account.", ex);
  798. }
  799. }
  800. public static void EditUserGitPassword(Config config, string username, string password)
  801. {
  802. try
  803. {
  804. // If Git is enabled
  805. if (config.GitConfig.Enabled)
  806. {
  807. string email = GetUserEmailAddress(config, username);
  808. using (var client = new WebClient())
  809. {
  810. var obj = new { source_id = config.GitConfig.SourceId, email = email, login_name = email, password = password };
  811. string json = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
  812. client.Headers[HttpRequestHeader.ContentType] = "application/json";
  813. Uri baseUri = new Uri(config.GitConfig.Host);
  814. Uri finalUri = new Uri(baseUri, "api/v1/admin/users/" + username + "?token=" + config.GitConfig.AccessToken);
  815. string result = client.UploadString(finalUri, "PATCH", json);
  816. }
  817. }
  818. }
  819. catch (Exception ex)
  820. {
  821. throw new Exception("Unable to edit git account password.", ex);
  822. }
  823. }
  824. public static void DeleteUserGit(Config config, string username)
  825. {
  826. try
  827. {
  828. // If Git is enabled
  829. if (config.GitConfig.Enabled)
  830. {
  831. try
  832. {
  833. Uri baseUri = new Uri(config.GitConfig.Host);
  834. Uri finalUri = new Uri(baseUri, "api/v1/admin/users/" + username + "?token=" + config.GitConfig.AccessToken);
  835. WebRequest request = WebRequest.Create(finalUri);
  836. request.Method = "DELETE";
  837. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  838. if (response.StatusCode != HttpStatusCode.NotFound && response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NoContent)
  839. {
  840. throw new Exception("Unable to delete git account. Response Code: " + response.StatusCode);
  841. }
  842. }
  843. catch (HttpException htex)
  844. {
  845. if (htex.GetHttpCode() != 404)
  846. throw new Exception("Unable to delete git account. Http Exception: " + htex.Message);
  847. }
  848. catch (Exception ex)
  849. {
  850. // This error signifies the user doesn't exist, so we can continue deleting
  851. if (ex.Message != "The remote server returned an error: (404) Not Found.")
  852. {
  853. throw new Exception("Unable to delete git account. Exception: " + ex.Message);
  854. }
  855. }
  856. }
  857. }
  858. catch (Exception ex)
  859. {
  860. throw new Exception("Unable to delete git account.", ex);
  861. }
  862. }
  863. #endregion
  864. public static HttpCookie CreateAuthCookie(string username, bool remember, string domain, bool local)
  865. {
  866. Config config = Config.Load();
  867. HttpCookie authcookie = FormsAuthentication.GetAuthCookie(username, remember);
  868. authcookie.Name = Constants.AUTHCOOKIE;
  869. authcookie.HttpOnly = true;
  870. authcookie.Secure = true;
  871. // Set domain dependent on where it's being ran from
  872. if (local) // localhost
  873. {
  874. authcookie.Domain = null;
  875. }
  876. else if (config.DevEnvironment) // dev.example.com
  877. {
  878. authcookie.Domain = string.Format("dev.{0}", domain);
  879. }
  880. else // A production instance
  881. {
  882. authcookie.Domain = string.Format(".{0}", domain);
  883. }
  884. return authcookie;
  885. }
  886. public static HttpCookie CreateTrustedDeviceCookie(string username, string domain, bool local)
  887. {
  888. Config config = Config.Load();
  889. byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
  890. byte[] key = Guid.NewGuid().ToByteArray();
  891. string token = Convert.ToBase64String(time.Concat(key).ToArray());
  892. HttpCookie trustCookie = new HttpCookie(Constants.TRUSTEDDEVICECOOKIE + "_" + username);
  893. trustCookie.Value = token;
  894. trustCookie.HttpOnly = true;
  895. trustCookie.Secure = true;
  896. trustCookie.Expires = DateTime.Now.AddYears(1);
  897. // Set domain dependent on where it's being ran from
  898. if (local) // localhost
  899. {
  900. trustCookie.Domain = null;
  901. }
  902. else if (config.DevEnvironment) // dev.example.com
  903. {
  904. trustCookie.Domain = string.Format("dev.{0}", domain);
  905. }
  906. else // A production instance
  907. {
  908. trustCookie.Domain = string.Format(".{0}", domain);
  909. }
  910. return trustCookie;
  911. }
  912. }
  913. }