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

UserHelper.cs 39KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Mail;
  7. using System.Runtime.InteropServices;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using System.Text.RegularExpressions;
  11. using System.Threading.Tasks;
  12. using System.Web;
  13. using Teknik.Areas.Blog.Models;
  14. using Teknik.Areas.Shortener.Models;
  15. using Teknik.Areas.Users.Models;
  16. using Teknik.Configuration;
  17. using Teknik.Utilities;
  18. using Teknik.Models;
  19. using Teknik.Utilities.Cryptography;
  20. using MD5 = Teknik.Utilities.Cryptography.MD5;
  21. using SHA256 = Teknik.Utilities.Cryptography.SHA256;
  22. using SHA384 = Teknik.Utilities.Cryptography.SHA384;
  23. using Teknik.Data;
  24. using Microsoft.EntityFrameworkCore;
  25. using Microsoft.AspNetCore.Http;
  26. using System.Security.Claims;
  27. using Microsoft.AspNetCore.Authentication.Cookies;
  28. using Teknik.MailService;
  29. using Teknik.GitService;
  30. using IdentityModel.Client;
  31. using System.Net.Http;
  32. using Newtonsoft.Json.Linq;
  33. using Newtonsoft.Json;
  34. using Microsoft.AspNetCore.Mvc;
  35. namespace Teknik.Areas.Users.Utility
  36. {
  37. public static class UserHelper
  38. {
  39. #region Account Management
  40. public static List<string> GetReservedUsernames(Config config)
  41. {
  42. List<string> foundNames = new List<string>();
  43. if (config != null)
  44. {
  45. string path = config.UserConfig.ReservedUsernameDefinitionFile;
  46. if (File.Exists(path))
  47. {
  48. string[] names = File.ReadAllLines(path);
  49. foundNames = names.ToList();
  50. }
  51. }
  52. return foundNames;
  53. }
  54. public static bool UsernameReserved(Config config, string username)
  55. {
  56. // Load reserved usernames
  57. List<string> reserved = GetReservedUsernames(config);
  58. return (reserved.Exists(u => u.ToLower() == username.ToLower()));
  59. }
  60. public static bool ValidUsername(Config config, string username)
  61. {
  62. bool isValid = true;
  63. // Must be something there
  64. isValid &= !string.IsNullOrEmpty(username);
  65. // Is the format correct?
  66. Regex reg = new Regex(config.UserConfig.UsernameFilter);
  67. isValid &= reg.IsMatch(username);
  68. // Meets the min length?
  69. isValid &= (username.Length >= config.UserConfig.MinUsernameLength);
  70. // Meets the max length?
  71. isValid &= (username.Length <= config.UserConfig.MaxUsernameLength);
  72. return isValid;
  73. }
  74. public static async Task<bool> UsernameAvailable(TeknikEntities db, Config config, string username)
  75. {
  76. bool isAvailable = true;
  77. isAvailable &= ValidUsername(config, username);
  78. isAvailable &= !UsernameReserved(config, username);
  79. isAvailable &= !await IdentityHelper.UserExists(config, username);
  80. isAvailable &= !UserExists(db, username);
  81. isAvailable &= !UserEmailExists(config, GetUserEmailAddress(config, username));
  82. isAvailable &= !UserGitExists(config, username);
  83. return isAvailable;
  84. }
  85. public static async Task<DateTime> GetLastAccountActivity(TeknikEntities db, Config config, string username)
  86. {
  87. var userInfo = await IdentityHelper.GetIdentityUserInfo(config, username);
  88. return GetLastAccountActivity(db, config, username, userInfo);
  89. }
  90. public static DateTime GetLastAccountActivity(TeknikEntities db, Config config, string username, IdentityUserInfo userInfo)
  91. {
  92. try
  93. {
  94. DateTime lastActive = new DateTime(1900, 1, 1);
  95. if (UserEmailExists(config, GetUserEmailAddress(config, username)))
  96. {
  97. DateTime emailLastActive = UserEmailLastActive(config, GetUserEmailAddress(config, username));
  98. if (lastActive < emailLastActive)
  99. lastActive = emailLastActive;
  100. }
  101. if (UserGitExists(config, username))
  102. {
  103. DateTime gitLastActive = UserGitLastActive(config, username);
  104. if (lastActive < gitLastActive)
  105. lastActive = gitLastActive;
  106. }
  107. if (userInfo.LastSeen.HasValue)
  108. {
  109. DateTime userLastActive = userInfo.LastSeen.Value;
  110. if (lastActive < userLastActive)
  111. lastActive = userLastActive;
  112. }
  113. return lastActive;
  114. }
  115. catch (Exception ex)
  116. {
  117. throw new Exception("Unable to determine last account activity.", ex);
  118. }
  119. }
  120. public static async Task CreateAccount(TeknikEntities db, Config config, IUrlHelper url, string username, string password, string recoveryEmail, string inviteCode)
  121. {
  122. try
  123. {
  124. var result = await IdentityHelper.CreateUser(config, username, password, recoveryEmail);
  125. if (result.Success)
  126. {
  127. // Create an Email Account
  128. CreateUserEmail(config, GetUserEmailAddress(config, username), password);
  129. // Create a Git Account
  130. CreateUserGit(config, username, password);
  131. // Add User
  132. User newUser = CreateUser(db, config, username, inviteCode);
  133. // If they have a recovery email, let's send a verification
  134. if (!string.IsNullOrEmpty(recoveryEmail))
  135. {
  136. var token = await IdentityHelper.UpdateRecoveryEmail(config, username, recoveryEmail);
  137. string resetUrl = url.SubRouteUrl("account", "User.ResetPassword", new { Username = username });
  138. string verifyUrl = url.SubRouteUrl("account", "User.VerifyRecoveryEmail", new { Code = WebUtility.UrlEncode(token) });
  139. SendRecoveryEmailVerification(config, username, recoveryEmail, resetUrl, verifyUrl);
  140. }
  141. return;
  142. }
  143. throw new Exception("Error creating account: " + result.Message);
  144. }
  145. catch (Exception ex)
  146. {
  147. throw new Exception("Unable to create account.", ex);
  148. }
  149. }
  150. public static void EditAccount(TeknikEntities db, Config config, User user)
  151. {
  152. try
  153. {
  154. // Update User
  155. EditUser(db, config, user);
  156. }
  157. catch (Exception ex)
  158. {
  159. throw new Exception("Unable to edit account.", ex);
  160. }
  161. }
  162. public static async Task ChangeAccountPassword(TeknikEntities db, Config config, string username, string currentPassword, string newPassword)
  163. {
  164. IdentityResult result = await IdentityHelper.UpdatePassword(config, username, currentPassword, newPassword);
  165. if (result.Success)
  166. {
  167. ChangeServicePasswords(db, config, username, newPassword);
  168. }
  169. else
  170. {
  171. throw new Exception(result.Message);
  172. }
  173. }
  174. public static async Task ResetAccountPassword(TeknikEntities db, Config config, string username, string token, string newPassword)
  175. {
  176. IdentityResult result = await IdentityHelper.ResetPassword(config, username, token, newPassword);
  177. if (result.Success)
  178. {
  179. ChangeServicePasswords(db, config, username, newPassword);
  180. }
  181. else
  182. {
  183. throw new Exception(result.Message);
  184. }
  185. }
  186. public static void ChangeServicePasswords(TeknikEntities db, Config config, string username, string newPassword)
  187. {
  188. try
  189. {
  190. // Make sure they have a git and email account before resetting their password
  191. string email = GetUserEmailAddress(config, username);
  192. if (config.EmailConfig.Enabled && !UserEmailExists(config, email))
  193. {
  194. CreateUserEmail(config, email, newPassword);
  195. }
  196. if (config.GitConfig.Enabled && !UserGitExists(config, username))
  197. {
  198. CreateUserGit(config, username, newPassword);
  199. }
  200. // Change email password
  201. EditUserEmailPassword(config, GetUserEmailAddress(config, username), newPassword);
  202. // Update Git password
  203. EditUserGitPassword(config, username, newPassword);
  204. }
  205. catch (Exception ex)
  206. {
  207. throw new Exception("Unable to change service password.", ex);
  208. }
  209. }
  210. public static async Task EditAccountType(TeknikEntities db, Config config, string username, AccountType type)
  211. {
  212. try
  213. {
  214. if (!UserExists(db, username))
  215. throw new Exception($"The user provided does not exist: {username}");
  216. var result = await IdentityHelper.UpdateAccountType(config, username, type);
  217. if (result.Success)
  218. {
  219. string email = GetUserEmailAddress(config, username);
  220. // Add/Remove account type features depending on the type
  221. switch (type)
  222. {
  223. case AccountType.Basic:
  224. // Set the email size to 1GB
  225. EditUserEmailMaxSize(config, email, config.EmailConfig.MaxSize);
  226. // Set the email max/day to 100
  227. EditUserEmailMaxEmailsPerDay(config, email, 100);
  228. break;
  229. case AccountType.Premium:
  230. // Set the email size to 5GB
  231. EditUserEmailMaxSize(config, email, 5000);
  232. // Set the email max/day to infinite (-1)
  233. EditUserEmailMaxEmailsPerDay(config, email, -1);
  234. break;
  235. }
  236. }
  237. else
  238. {
  239. throw new Exception($"Unable to edit the account type [{type}] for {username}: " + result.Message);
  240. }
  241. }
  242. catch (Exception ex)
  243. {
  244. throw new Exception($"Unable to edit the account type [{type}] for: {username}", ex);
  245. }
  246. }
  247. public static async Task EditAccountStatus(TeknikEntities db, Config config, string username, AccountStatus status)
  248. {
  249. try
  250. {
  251. if (!UserExists(db, username))
  252. throw new Exception($"The user provided does not exist: {username}");
  253. var result = await IdentityHelper.UpdateAccountStatus(config, username, status);
  254. if (result.Success)
  255. {
  256. string email = GetUserEmailAddress(config, username);
  257. // Add/Remove account type features depending on the type
  258. switch (status)
  259. {
  260. case AccountStatus.Active:
  261. // Enable Email
  262. EnableUserEmail(config, email);
  263. // Enable Git
  264. EnableUserGit(config, username);
  265. break;
  266. case AccountStatus.Banned:
  267. // Disable Email
  268. DisableUserEmail(config, email);
  269. // Disable Git
  270. DisableUserGit(config, username);
  271. break;
  272. }
  273. }
  274. else
  275. {
  276. throw new Exception($"Unable to edit the account status [{status}] for {username}: " + result.Message);
  277. }
  278. }
  279. catch (Exception ex)
  280. {
  281. throw new Exception($"Unable to edit the account status [{status}] for: {username}", ex);
  282. }
  283. }
  284. public static async Task DeleteAccount(TeknikEntities db, Config config, User user)
  285. {
  286. try
  287. {
  288. string username = user.Username;
  289. // Delete identity account
  290. var result = await IdentityHelper.DeleteUser(config, username);
  291. if (result)
  292. {
  293. // Delete User Account
  294. DeleteUser(db, config, user);
  295. // Delete Email Account
  296. if (UserEmailExists(config, GetUserEmailAddress(config, username)))
  297. DeleteUserEmail(config, GetUserEmailAddress(config, username));
  298. // Delete Git Account
  299. if (UserGitExists(config, username))
  300. DeleteUserGit(config, username);
  301. }
  302. else
  303. {
  304. throw new Exception("Unable to delete identity account.");
  305. }
  306. }
  307. catch (Exception ex)
  308. {
  309. throw new Exception("Unable to delete account.", ex);
  310. }
  311. }
  312. #endregion
  313. #region User Management
  314. public static User GetUser(TeknikEntities db, string username)
  315. {
  316. User user = db.Users
  317. .Include(u => u.UserSettings)
  318. .Include(u => u.BlogSettings)
  319. .Include(u => u.UploadSettings)
  320. .Where(b => b.Username == username).FirstOrDefault();
  321. return user;
  322. }
  323. public static bool UserExists(TeknikEntities db, string username)
  324. {
  325. User user = GetUser(db, username);
  326. if (user != null)
  327. {
  328. return true;
  329. }
  330. return false;
  331. }
  332. public static async Task<bool> UserPasswordCorrect(Config config, string username, string password)
  333. {
  334. try
  335. {
  336. return await IdentityHelper.CheckPassword(config, username, password);
  337. }
  338. catch (Exception ex)
  339. {
  340. throw new Exception("Unable to determine if password is correct.", ex);
  341. }
  342. }
  343. public static User CreateUser(TeknikEntities db, Config config, string username, string inviteCode)
  344. {
  345. try
  346. {
  347. User newUser = new User();
  348. newUser.Username = username;
  349. newUser.UserSettings = new UserSettings();
  350. newUser.BlogSettings = new BlogSettings();
  351. newUser.UploadSettings = new UploadSettings();
  352. // if they provided an invite code, let's assign them to it
  353. if (!string.IsNullOrEmpty(inviteCode))
  354. {
  355. InviteCode code = db.InviteCodes.Where(c => c.Code == inviteCode).FirstOrDefault();
  356. db.Entry(code).State = EntityState.Modified;
  357. newUser.ClaimedInviteCode = code;
  358. }
  359. // Add User
  360. db.Users.Add(newUser);
  361. // Generate blog for the user
  362. var newBlog = new Blog.Models.Blog();
  363. newBlog.User = newUser;
  364. db.Blogs.Add(newBlog);
  365. // Save the changes
  366. db.SaveChanges();
  367. return newUser;
  368. }
  369. catch (Exception ex)
  370. {
  371. throw new Exception("Unable to create user.", ex);
  372. }
  373. }
  374. public static void EditUser(TeknikEntities db, Config config, User user)
  375. {
  376. try
  377. {
  378. db.Entry(user).State = EntityState.Modified;
  379. db.SaveChanges();
  380. }
  381. catch (Exception ex)
  382. {
  383. throw new Exception(string.Format("Unable to edit user {0}.", user.Username), ex);
  384. }
  385. }
  386. public static void DeleteUser(TeknikEntities db, Config config, User user)
  387. {
  388. try
  389. {
  390. // Update uploads
  391. List<Upload.Models.Upload> uploads = db.Uploads.Where(u => u.User.Username == user.Username).ToList();
  392. if (uploads.Any())
  393. {
  394. foreach (Upload.Models.Upload upload in uploads)
  395. {
  396. upload.UserId = null;
  397. db.Entry(upload).State = EntityState.Modified;
  398. }
  399. db.SaveChanges();
  400. }
  401. // Update pastes
  402. List<Paste.Models.Paste> pastes = db.Pastes.Where(u => u.User.Username == user.Username).ToList();
  403. if (pastes.Any())
  404. {
  405. foreach (Paste.Models.Paste paste in pastes)
  406. {
  407. paste.UserId = null;
  408. db.Entry(paste).State = EntityState.Modified;
  409. }
  410. db.SaveChanges();
  411. }
  412. // Update shortened urls
  413. List<ShortenedUrl> shortUrls = db.ShortenedUrls.Where(u => u.User.Username == user.Username).ToList();
  414. if (shortUrls.Any())
  415. {
  416. foreach (ShortenedUrl shortUrl in shortUrls)
  417. {
  418. shortUrl.UserId = null;
  419. db.Entry(shortUrl).State = EntityState.Modified;
  420. }
  421. db.SaveChanges();
  422. }
  423. // Update vaults
  424. List<Vault.Models.Vault> vaults = db.Vaults.Where(u => u.User.Username == user.Username).ToList();
  425. if (vaults.Any())
  426. {
  427. foreach (Vault.Models.Vault vault in vaults)
  428. {
  429. vault.UserId = null;
  430. db.Entry(vault).State = EntityState.Modified;
  431. }
  432. db.SaveChanges();
  433. }
  434. // Delete Blogs
  435. Blog.Models.Blog blog = db.Blogs.Where(u => u.User.Username == user.Username).FirstOrDefault();
  436. if (blog != null)
  437. {
  438. db.Blogs.Remove(blog);
  439. db.SaveChanges();
  440. }
  441. // Delete post comments
  442. List<BlogPostComment> postComments = db.BlogPostComments.Where(u => u.User.Username == user.Username).ToList();
  443. if (postComments.Any())
  444. {
  445. foreach (BlogPostComment postComment in postComments)
  446. {
  447. db.BlogPostComments.Remove(postComment);
  448. }
  449. db.SaveChanges();
  450. }
  451. // Delete podcast comments
  452. List<Podcast.Models.PodcastComment> podComments = db.PodcastComments.Where(u => u.User.Username == user.Username).ToList();
  453. if (podComments.Any())
  454. {
  455. foreach (Podcast.Models.PodcastComment podComment in podComments)
  456. {
  457. db.PodcastComments.Remove(podComment);
  458. }
  459. db.SaveChanges();
  460. }
  461. // Delete Owned Invite Codes
  462. List<InviteCode> ownedCodes = db.InviteCodes.Where(i => i.Owner.Username == user.Username).ToList();
  463. if (ownedCodes.Any())
  464. {
  465. foreach (InviteCode code in ownedCodes)
  466. {
  467. db.InviteCodes.Remove(code);
  468. }
  469. db.SaveChanges();
  470. }
  471. // Delete Claimed Invite Code
  472. List<InviteCode> claimedCodes = db.InviteCodes.Where(i => i.ClaimedUser.Username == user.Username).ToList();
  473. if (claimedCodes.Any())
  474. {
  475. foreach (InviteCode code in claimedCodes)
  476. {
  477. db.InviteCodes.Remove(code);
  478. }
  479. db.SaveChanges();
  480. }
  481. // Delete Auth Tokens
  482. //List<AuthToken> authTokens = db.AuthTokens.Where(t => t.User.UserId == user.UserId).ToList();
  483. //if (authTokens.Any())
  484. //{
  485. // foreach (AuthToken authToken in authTokens)
  486. // {
  487. // db.AuthTokens.Remove(authToken);
  488. // }
  489. // db.SaveChanges();
  490. //}
  491. // Delete User
  492. db.Users.Remove(user);
  493. db.SaveChanges();
  494. }
  495. catch (Exception ex)
  496. {
  497. throw new Exception(string.Format("Unable to delete user {0}.", user.Username), ex);
  498. }
  499. }
  500. public static void SendRecoveryEmailVerification(Config config, string username, string email, string resetUrl, string verifyUrl)
  501. {
  502. SmtpClient client = new SmtpClient();
  503. client.Host = config.ContactConfig.EmailAccount.Host;
  504. client.Port = config.ContactConfig.EmailAccount.Port;
  505. client.EnableSsl = config.ContactConfig.EmailAccount.SSL;
  506. client.DeliveryMethod = SmtpDeliveryMethod.Network;
  507. client.UseDefaultCredentials = true;
  508. client.Credentials = new NetworkCredential(config.ContactConfig.EmailAccount.Username, config.ContactConfig.EmailAccount.Password);
  509. client.Timeout = 5000;
  510. MailMessage mail = new MailMessage(new MailAddress(config.ContactConfig.EmailAccount.EmailAddress, "Teknik"), new MailAddress(email, username));
  511. mail.Subject = "Recovery Email Validation";
  512. mail.Body = string.Format(@"Hello {0},
  513. 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.
  514. In order to verify that you own this email, please click the following link or paste it into your browser: {2}
  515. If you recieved this email and you did not sign up for an account, please email us at {3} and ignore the verification link.
  516. - Teknik", username, resetUrl, verifyUrl, config.SupportEmail);
  517. mail.BodyEncoding = UTF8Encoding.UTF8;
  518. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
  519. client.Send(mail);
  520. }
  521. public static void SendResetPasswordVerification(Config config, string username, string email, string resetUrl)
  522. {
  523. SmtpClient client = new SmtpClient();
  524. client.Host = config.ContactConfig.EmailAccount.Host;
  525. client.Port = config.ContactConfig.EmailAccount.Port;
  526. client.EnableSsl = config.ContactConfig.EmailAccount.SSL;
  527. client.DeliveryMethod = SmtpDeliveryMethod.Network;
  528. client.UseDefaultCredentials = true;
  529. client.Credentials = new NetworkCredential(config.ContactConfig.EmailAccount.Username, config.ContactConfig.EmailAccount.Password);
  530. client.Timeout = 5000;
  531. MailMessage mail = new MailMessage(new MailAddress(config.ContactConfig.EmailAccount.EmailAddress, "Teknik"), new MailAddress(email, username));
  532. mail.Subject = "Password Reset Request";
  533. mail.Body = string.Format(@"Hello {0},
  534. 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.
  535. To proceed in resetting your password, please click the following link or paste it into your browser: {1}
  536. 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.
  537. - Teknik", username, resetUrl, config.SupportEmail);
  538. mail.BodyEncoding = UTF8Encoding.UTF8;
  539. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
  540. client.Send(mail);
  541. }
  542. #endregion
  543. #region Email Management
  544. public static string GetUserEmailAddress(Config config, string username)
  545. {
  546. return string.Format("{0}@{1}", username, config.EmailConfig.Domain);
  547. }
  548. public static IMailService CreateMailService(Config config)
  549. {
  550. return new HMailService(
  551. config.EmailConfig.MailHost,
  552. config.EmailConfig.Username,
  553. config.EmailConfig.Password,
  554. config.EmailConfig.Domain,
  555. config.EmailConfig.CounterDatabase.Server,
  556. config.EmailConfig.CounterDatabase.Database,
  557. config.EmailConfig.CounterDatabase.Username,
  558. config.EmailConfig.CounterDatabase.Password,
  559. config.EmailConfig.CounterDatabase.Port
  560. );
  561. }
  562. public static bool UserEmailExists(Config config, string email)
  563. {
  564. // If Email Server is enabled
  565. if (config.EmailConfig.Enabled)
  566. {
  567. var svc = CreateMailService(config);
  568. return svc.AccountExists(email);
  569. }
  570. return false;
  571. }
  572. public static DateTime UserEmailLastActive(Config config, string email)
  573. {
  574. DateTime lastActive = new DateTime(1900, 1, 1);
  575. if (config.EmailConfig.Enabled)
  576. {
  577. var svc = CreateMailService(config);
  578. var lastEmail = svc.LastActive(email);
  579. if (lastActive < lastEmail)
  580. lastActive = lastEmail;
  581. }
  582. return lastActive;
  583. }
  584. public static void CreateUserEmail(Config config, string email, string password)
  585. {
  586. try
  587. {
  588. // If Email Server is enabled
  589. if (config.EmailConfig.Enabled)
  590. {
  591. var svc = CreateMailService(config);
  592. svc.CreateAccount(email, password, config.EmailConfig.MaxSize);
  593. }
  594. }
  595. catch (Exception ex)
  596. {
  597. throw new Exception("Unable to add email.", ex);
  598. }
  599. }
  600. public static void EnableUserEmail(Config config, string email)
  601. {
  602. try
  603. {
  604. // If Email Server is enabled
  605. if (config.EmailConfig.Enabled)
  606. {
  607. var svc = CreateMailService(config);
  608. svc.EnableAccount(email);
  609. }
  610. }
  611. catch (Exception ex)
  612. {
  613. throw new Exception("Unable to enable email account.", ex);
  614. }
  615. }
  616. public static void DisableUserEmail(Config config, string email)
  617. {
  618. try
  619. {
  620. // If Email Server is enabled
  621. if (config.EmailConfig.Enabled)
  622. {
  623. var svc = CreateMailService(config);
  624. svc.DisableAccount(email);
  625. }
  626. }
  627. catch (Exception ex)
  628. {
  629. throw new Exception("Unable to disable email account.", ex);
  630. }
  631. }
  632. public static void EditUserEmailPassword(Config config, string email, string password)
  633. {
  634. try
  635. {
  636. // If Email Server is enabled
  637. if (config.EmailConfig.Enabled)
  638. {
  639. var svc = CreateMailService(config);
  640. svc.EditPassword(email, password);
  641. }
  642. }
  643. catch (Exception ex)
  644. {
  645. throw new Exception("Unable to edit email account password.", ex);
  646. }
  647. }
  648. public static void EditUserEmailMaxSize(Config config, string email, int size)
  649. {
  650. try
  651. {
  652. // If Email Server is enabled
  653. if (config.EmailConfig.Enabled)
  654. {
  655. var svc = CreateMailService(config);
  656. svc.EditMaxSize(email, size);
  657. }
  658. }
  659. catch (Exception ex)
  660. {
  661. throw new Exception("Unable to edit email account mailbox size.", ex);
  662. }
  663. }
  664. public static void EditUserEmailMaxEmailsPerDay(Config config, string email, int maxPerDay)
  665. {
  666. try
  667. {
  668. // If Email Server is enabled
  669. if (config.EmailConfig.Enabled)
  670. {
  671. var svc = CreateMailService(config);
  672. svc.EditMaxEmailsPerDay(email, maxPerDay);
  673. }
  674. }
  675. catch (Exception ex)
  676. {
  677. throw new Exception("Unable to edit email account mailbox size.", ex);
  678. }
  679. }
  680. public static void DeleteUserEmail(Config config, string email)
  681. {
  682. try
  683. {
  684. // If Email Server is enabled
  685. if (config.EmailConfig.Enabled)
  686. {
  687. var svc = CreateMailService(config);
  688. svc.DeleteAccount(email);
  689. }
  690. }
  691. catch (Exception ex)
  692. {
  693. throw new Exception("Unable to delete email account.", ex);
  694. }
  695. }
  696. #endregion
  697. #region Git Management
  698. public static IGitService CreateGitService(Config config)
  699. {
  700. return new GiteaService(
  701. config.GitConfig.SourceId,
  702. config.GitConfig.Host,
  703. config.GitConfig.AccessToken,
  704. config.GitConfig.Database.Server,
  705. config.GitConfig.Database.Database,
  706. config.GitConfig.Database.Username,
  707. config.GitConfig.Database.Password,
  708. config.GitConfig.Database.Port
  709. );
  710. }
  711. public static bool UserGitExists(Config config, string username)
  712. {
  713. if (config.GitConfig.Enabled)
  714. {
  715. try
  716. {
  717. var svc = CreateGitService(config);
  718. return svc.AccountExists(username);
  719. }
  720. catch { }
  721. }
  722. return false;
  723. }
  724. public static DateTime UserGitLastActive(Config config, string username)
  725. {
  726. DateTime lastActive = new DateTime(1900, 1, 1);
  727. if (config.GitConfig.Enabled)
  728. {
  729. // Git user exists?
  730. if (!UserGitExists(config, username))
  731. {
  732. throw new Exception($"Git User '{username}' does not exist.");
  733. }
  734. string email = GetUserEmailAddress(config, username);
  735. var svc = CreateGitService(config);
  736. DateTime tmpLast = svc.LastActive(email);
  737. if (lastActive < tmpLast)
  738. lastActive = tmpLast;
  739. }
  740. return lastActive;
  741. }
  742. public static void CreateUserGit(Config config, string username, string password)
  743. {
  744. try
  745. {
  746. // If Git is enabled
  747. if (config.GitConfig.Enabled)
  748. {
  749. string email = GetUserEmailAddress(config, username);
  750. var svc = CreateGitService(config);
  751. svc.CreateAccount(username, email, password);
  752. }
  753. }
  754. catch (Exception ex)
  755. {
  756. throw new Exception("Unable to add git account.", ex);
  757. }
  758. }
  759. public static void EditUserGitPassword(Config config, string username, string password)
  760. {
  761. try
  762. {
  763. // If Git is enabled
  764. if (config.GitConfig.Enabled)
  765. {
  766. // Git user exists?
  767. if (!UserGitExists(config, username))
  768. {
  769. throw new Exception($"Git User '{username}' does not exist.");
  770. }
  771. string email = GetUserEmailAddress(config, username);
  772. var svc = CreateGitService(config);
  773. svc.EditPassword(username, email, password);
  774. }
  775. }
  776. catch (Exception ex)
  777. {
  778. throw new Exception("Unable to edit git account password.", ex);
  779. }
  780. }
  781. public static void EnableUserGit(Config config, string username)
  782. {
  783. try
  784. {
  785. // If Git is enabled
  786. if (config.GitConfig.Enabled)
  787. {
  788. // Git user exists?
  789. if (!UserGitExists(config, username))
  790. {
  791. throw new Exception($"Git User '{username}' does not exist.");
  792. }
  793. string email = GetUserEmailAddress(config, username);
  794. var svc = CreateGitService(config);
  795. svc.EnableAccount(username, email);
  796. }
  797. }
  798. catch (Exception ex)
  799. {
  800. throw new Exception("Unable to enable git account.", ex);
  801. }
  802. }
  803. public static void DisableUserGit(Config config, string username)
  804. {
  805. try
  806. {
  807. // If Git is enabled
  808. if (config.GitConfig.Enabled)
  809. {
  810. // Git user exists?
  811. if (!UserGitExists(config, username))
  812. {
  813. throw new Exception($"Git User '{username}' does not exist.");
  814. }
  815. string email = GetUserEmailAddress(config, username);
  816. var svc = CreateGitService(config);
  817. svc.EnableAccount(username, email);
  818. }
  819. }
  820. catch (Exception ex)
  821. {
  822. throw new Exception("Unable to disable git account.", ex);
  823. }
  824. }
  825. public static void DeleteUserGit(Config config, string username)
  826. {
  827. try
  828. {
  829. // If Git is enabled
  830. if (config.GitConfig.Enabled)
  831. {
  832. // Git user exists?
  833. if (!UserGitExists(config, username))
  834. {
  835. throw new Exception($"Git User '{username}' does not exist.");
  836. }
  837. var svc = CreateGitService(config);
  838. svc.DeleteAccount(username);
  839. }
  840. }
  841. catch (Exception ex)
  842. {
  843. throw new Exception("Unable to delete git account.", ex);
  844. }
  845. }
  846. public static void CreateUserGitTwoFactor(Config config, string username, string secret, int unixTime)
  847. {
  848. try
  849. {
  850. // If Git is enabled
  851. if (config.GitConfig.Enabled)
  852. {
  853. // Git user exists?
  854. if (!UserGitExists(config, username))
  855. {
  856. throw new Exception($"Git User '{username}' does not exist.");
  857. }
  858. // Generate the scratch token
  859. string token = StringHelper.RandomString(8);
  860. // Get the Encryption Key from the git secret key
  861. byte[] keyBytes = MD5.Hash(Encoding.UTF8.GetBytes(config.GitConfig.SecretKey));
  862. // Modify the input secret
  863. byte[] secBytes = Encoding.UTF8.GetBytes(secret);
  864. // Generate the encrypted secret using AES CGM
  865. byte[] encValue = Aes128CFB.Encrypt(secBytes, keyBytes);
  866. string finalSecret = Convert.ToBase64String(encValue);
  867. // Create connection to the DB
  868. Utilities.MysqlDatabase mySQL = new Utilities.MysqlDatabase(config.GitConfig.Database.Server, config.GitConfig.Database.Database, config.GitConfig.Database.Username, config.GitConfig.Database.Password, config.GitConfig.Database.Port);
  869. mySQL.MysqlErrorEvent += (sender, s) =>
  870. {
  871. throw new Exception("Unable to edit git account two factor. Mysql Exception: " + s);
  872. };
  873. // Get the user's UID
  874. string email = GetUserEmailAddress(config, username);
  875. string userSelect = @"SELECT gogs.user.id FROM gogs.user WHERE gogs.user.login_name = {0}";
  876. var uid = mySQL.ScalarQuery(userSelect, new object[] { email });
  877. // See if they have Two Factor already
  878. string sqlSelect = @"SELECT tf.id
  879. FROM gogs.two_factor tf
  880. LEFT JOIN gogs.user u ON u.id = tf.uid
  881. WHERE u.login_name = {0}";
  882. var result = mySQL.ScalarQuery(sqlSelect, new object[] { email });
  883. if (result != null)
  884. {
  885. // They have an entry! Let's update it
  886. string update = @"UPDATE gogs.two_factor tf SET tf.uid = {1}, tf.secret = {2}, tf.scratch_token = {3}, tf.updated_unix = {4} WHERE tf.id = {0}";
  887. mySQL.Execute(update, new object[] { result, uid, finalSecret, token, unixTime });
  888. }
  889. else
  890. {
  891. // They need a new entry
  892. string insert = @"INSERT INTO gogs.two_factor (uid, secret, scratch_token, created_unix, updated_unix) VALUES ({0}, {1}, {2}, {3}, {4})";
  893. mySQL.Execute(insert, new object[] { uid, finalSecret, token, unixTime, 0 });
  894. }
  895. }
  896. }
  897. catch (Exception ex)
  898. {
  899. throw new Exception("Unable to edit git account two factor.", ex);
  900. }
  901. }
  902. public static void DeleteUserGitTwoFactor(Config config, string username)
  903. {
  904. try
  905. {
  906. // If Git is enabled
  907. if (config.GitConfig.Enabled)
  908. {
  909. // Git user exists?
  910. if (!UserGitExists(config, username))
  911. {
  912. throw new Exception($"Git User '{username}' does not exist.");
  913. }
  914. // Create connection to the DB
  915. Utilities.MysqlDatabase mySQL = new Utilities.MysqlDatabase(config.GitConfig.Database.Server, config.GitConfig.Database.Database, config.GitConfig.Database.Username, config.GitConfig.Database.Password, config.GitConfig.Database.Port);
  916. // Get the user's UID
  917. string email = GetUserEmailAddress(config, username);
  918. // See if they have Two Factor already
  919. string deleteSql = @"DELETE tf.*
  920. FROM gogs.two_factor tf
  921. LEFT JOIN gogs.user u ON u.id = tf.uid
  922. WHERE u.login_name = {0}";
  923. mySQL.Execute(deleteSql, new object[] { email });
  924. }
  925. }
  926. catch (Exception ex)
  927. {
  928. throw new Exception("Unable to delete git account two factor.", ex);
  929. }
  930. }
  931. #endregion
  932. }
  933. }