public static List <string> GetOrphanedEmail(Config config, TeknikEntities db) { List <string> foundEmail = new List <string>(); if (config.EmailConfig.Enabled) { List <User> curUsers = db.Users.ToList(); // Connect to hmailserver COM var app = new hMailServer.Application(); app.Connect(); app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password); var domain = app.Domains.ItemByName[config.EmailConfig.Domain]; var accounts = domain.Accounts; for (int i = 0; i < accounts.Count; i++) { var account = accounts[i]; bool userExists = curUsers.Exists(u => UserHelper.GetUserEmailAddress(config, u.Username) == account.Address); bool isReserved = UserHelper.GetReservedUsernames(config).Exists(r => UserHelper.GetUserEmailAddress(config, r).ToLower() == account.Address.ToLower()); if (!userExists && !isReserved) { foundEmail.Add(account.Address); } } } return(foundEmail); }
public static List <string> GetOrphanedGit(Config config, TeknikEntities db) { List <string> foundGit = new List <string>(); if (config.GitConfig.Enabled) { List <User> curUsers = db.Users.ToList(); // We need to check the actual git database MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database.Server, config.GitConfig.Database.Database, config.GitConfig.Database.Username, config.GitConfig.Database.Password, config.GitConfig.Database.Port); string sql = @"SELECT gogs.user.login_name AS login_name, gogs.user.lower_name AS username FROM gogs.user"; var results = mySQL.Query(sql); if (results != null && results.Any()) { foreach (var account in results) { bool userExists = curUsers.Exists(u => UserHelper.GetUserEmailAddress(config, u.Username).ToLower() == account["login_name"].ToString().ToLower()); bool isReserved = UserHelper.GetReservedUsernames(config).Exists(r => UserHelper.GetUserEmailAddress(config, r) == account["login_name"].ToString().ToLower()); if (!userExists && !isReserved) { foundGit.Add(account["username"].ToString()); } } } } return(foundGit); }
public static void GenerateInvalidAccounts(Config config, TeknikEntities db, string fileName) { Output(string.Format("[{0}] Started Generation of Invalid Account List.", DateTime.Now)); List <string> invalidAccounts = GetInvalidAccounts(config, db); StringBuilder sb = new StringBuilder(); sb.AppendLine("Username,Last Activity,Creation Date,Last Website Activity,Last Email Activity,Last Git Activity"); foreach (string account in invalidAccounts) { User user = UserHelper.GetUser(db, account); sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5}", user.Username, UserHelper.GetLastAccountActivity(db, config, user).ToString("g"), user.JoinDate.ToString("g"), user.LastSeen.ToString("g"), UserHelper.UserEmailLastActive(config, UserHelper.GetUserEmailAddress(config, user.Username)).ToString("g"), UserHelper.UserGitLastActive(config, user.Username).ToString("g"))); } string dir = Path.GetDirectoryName(fileName); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.WriteAllText(fileName, sb.ToString()); Output(string.Format("[{0}] Finished Generating Invalid Account List.", DateTime.Now)); }
public static void ScanUploads(Config config, TeknikEntities db) { Output(string.Format("[{0}] Started Virus Scan.", DateTime.Now)); List <Upload> uploads = db.Uploads.ToList(); int totalCount = uploads.Count(); int totalScans = 0; int totalViruses = 0; List <Task> runningTasks = new List <Task>(); foreach (Upload upload in uploads) { int currentScan = totalScans++; Task scanTask = Task.Factory.StartNew(async() => { var virusDetected = await ScanUpload(config, db, upload, totalCount, currentScan); if (virusDetected) { totalViruses++; } }); if (scanTask != null) { runningTasks.Add(scanTask); } } bool running = true; while (running) { running = runningTasks.Exists(s => s != null && !s.IsCompleted && !s.IsCanceled && !s.IsFaulted); } Output(string.Format("Scanning Complete. {0} Scanned | {1} Viruses Found | {2} Total Files", totalScans, totalViruses, totalCount)); }
public static void CleanGit(Config config, TeknikEntities db) { Output(string.Format("[{0}] Started Cleaning of Orphaned Git Accounts.", DateTime.Now)); List <string> gitAccounts = GetOrphanedGit(config, db); foreach (string account in gitAccounts) { // User doesn't exist, and it isn't reserved. Let's nuke it. UserHelper.DeleteUserGit(config, account); } if (gitAccounts.Count > 0) { // Add to transparency report if any users were removed Takedown report = db.Takedowns.Create(); report.Requester = TAKEDOWN_REPORTER; report.RequesterContact = config.SupportEmail; report.DateRequested = DateTime.Now; report.Reason = "Orphaned Git Account"; report.ActionTaken = string.Format("{0} Accounts Removed", gitAccounts.Count); report.DateActionTaken = DateTime.Now; db.Takedowns.Add(report); db.SaveChanges(); } Output(string.Format("[{0}] Finished Cleaning of Orphaned Git Accounts. {1} Accounts Removed.", DateTime.Now, gitAccounts.Count)); }
public static bool RunMigration(TeknikEntities db, Config config) { bool success = false; MigratePastes(db, config); return(success); }
public DefaultController(ILogger <Logger> logger, Config config, TeknikEntities dbContext) { _logger = logger; _config = config; _dbContext = dbContext; ViewBag.Title = string.Empty; ViewBag.Description = _config.Description; }
public static User GetUser(TeknikEntities db, string username) { User user = db.Users .Include(u => u.UserSettings) .Include(u => u.BlogSettings) .Include(u => u.UploadSettings) .Where(b => b.Username == username).FirstOrDefault(); return(user); }
public static bool UserExists(TeknikEntities db, string username) { User user = GetUser(db, username); if (user != null) { return(true); } return(false); }
public static void EditAccount(TeknikEntities db, Config config, User user) { try { // Update User EditUser(db, config, user); } catch (Exception ex) { throw new Exception("Unable to edit account.", ex); } }
public static void EditUser(TeknikEntities db, Config config, User user) { try { db.Entry(user).State = EntityState.Modified; db.SaveChanges(); } catch (Exception ex) { throw new Exception(string.Format("Unable to edit user {0}.", user.Username), ex); } }
public static async Task ResetAccountPassword(TeknikEntities db, Config config, string username, string token, string newPassword) { IdentityResult result = await IdentityHelper.ResetPassword(config, username, token, newPassword); if (result.Success) { ChangeServicePasswords(db, config, username, newPassword); } else { throw new Exception(result.Message); } }
public static async Task <bool> UsernameAvailable(TeknikEntities db, Config config, string username) { bool isAvailable = true; isAvailable &= ValidUsername(config, username); isAvailable &= !UsernameReserved(config, username); isAvailable &= !await IdentityHelper.UserExists(config, username); isAvailable &= !UserExists(db, username); isAvailable &= !UserEmailExists(config, GetUserEmailAddress(config, username)); isAvailable &= !UserGitExists(config, username); return(isAvailable); }
public static void WarnInvalidAccounts(Config config, TeknikEntities db) { Output(string.Format("[{0}] Started Warning of Invalid Accounts.", DateTime.Now)); List <string> invalidAccounts = GetInvalidAccounts(config, db); foreach (string account in invalidAccounts) { // Let's send them an email :D string email = UserHelper.GetUserEmailAddress(config, account); SmtpClient client = new SmtpClient(); client.Host = config.ContactConfig.EmailAccount.Host; client.Port = config.ContactConfig.EmailAccount.Port; client.EnableSsl = config.ContactConfig.EmailAccount.SSL; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = true; client.Credentials = new NetworkCredential(config.ContactConfig.EmailAccount.Username, config.ContactConfig.EmailAccount.Password); client.Timeout = 5000; try { MailMessage mail = new MailMessage(config.ContactConfig.EmailAccount.EmailAddress, email); mail.Subject = "Invalid Account Notice"; mail.Body = string.Format(@" The account {0} does not meet the requirements for a valid username. The username must meet the following requirements: {1} It must also be greater than or equal to {2} characters in length, and less than or equal to {3} characters in length. This email is to let you know that this account will be deleted in {4} days ({5}) in order to comply with the username restrictions. If you would like to keep your data, you should create a new account and transfer the data over to the new account. In order to make the process as easy as possible, you can reply to this email to ask for your current account to be renamed to another available account. This would keep all your data intact, and just require you to change all references to your email/git/user to the new username. If you wish to do this, please respond within {6} days ({7}) with the new username you would like to use. Thank you for your continued use of Teknik! - Teknik Administration", account, config.UserConfig.UsernameFilterLabel, config.UserConfig.MinUsernameLength, config.UserConfig.MaxUsernameLength, 30, DateTime.Now.AddDays(30).ToShortDateString(), 15, DateTime.Now.AddDays(15).ToShortDateString()); mail.BodyEncoding = UTF8Encoding.UTF8; mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never; client.Send(mail); } catch (Exception ex) { Output(string.Format("[{0}] Unable to send email to {1}. Exception: {2}", DateTime.Now, email, ex.Message)); } } Output(string.Format("[{0}] Finished Warning of Invalid Accounts. {1} Accounts Warned.", DateTime.Now, invalidAccounts.Count)); }
public static void CleanAccounts(Config config, TeknikEntities db, int maxDays) { Output(string.Format("[{0}] Started Cleaning of Inactive/Invalid Users.", DateTime.Now)); List <string> invalidAccounts = GetInvalidAccounts(config, db); List <string> inactiveAccounts = GetInactiveAccounts(config, db, maxDays); // Delete invalid accounts foreach (string account in invalidAccounts) { UserHelper.DeleteAccount(db, config, UserHelper.GetUser(db, account)); } if (invalidAccounts.Count > 0) { // Add to transparency report if any users were removed Takedown report = db.Takedowns.Create(); report.Requester = TAKEDOWN_REPORTER; report.RequesterContact = config.SupportEmail; report.DateRequested = DateTime.Now; report.Reason = "Username Invalid"; report.ActionTaken = string.Format("{0} Accounts Removed", invalidAccounts.Count); report.DateActionTaken = DateTime.Now; db.Takedowns.Add(report); db.SaveChanges(); } // Delete inactive accounts foreach (string account in inactiveAccounts) { UserHelper.DeleteAccount(db, config, UserHelper.GetUser(db, account)); } if (invalidAccounts.Count > 0) { // Add to transparency report if any users were removed Takedown report = db.Takedowns.Create(); report.Requester = TAKEDOWN_REPORTER; report.RequesterContact = config.SupportEmail; report.DateRequested = DateTime.Now; report.Reason = "Account Inactive"; report.ActionTaken = string.Format("{0} Accounts Removed", inactiveAccounts.Count); report.DateActionTaken = DateTime.Now; db.Takedowns.Add(report); db.SaveChanges(); } Output(string.Format("[{0}] Finished Cleaning of Inactive/Invalid Users. {1} Accounts Removed.", DateTime.Now, invalidAccounts.Count + inactiveAccounts.Count)); }
public static ShortenedUrl ShortenUrl(TeknikEntities db, string url, int length) { // Generate the shortened url string shortUrl = StringHelper.RandomString(length); while (db.ShortenedUrls.Where(s => s.ShortUrl == shortUrl).FirstOrDefault() != null) { shortUrl = StringHelper.RandomString(length); } ShortenedUrl newUrl = new ShortenedUrl(); newUrl.OriginalUrl = url; newUrl.ShortUrl = shortUrl; newUrl.DateAdded = DateTime.Now; return(newUrl); }
public static async Task EditAccountStatus(TeknikEntities db, Config config, string username, AccountStatus status) { try { if (!UserExists(db, username)) { throw new Exception($"The user provided does not exist: {username}"); } var result = await IdentityHelper.UpdateAccountStatus(config, username, status); if (result.Success) { string email = GetUserEmailAddress(config, username); // Add/Remove account type features depending on the type switch (status) { case AccountStatus.Active: // Enable Email EnableUserEmail(config, email); // Enable Git EnableUserGit(config, username); break; case AccountStatus.Banned: // Disable Email DisableUserEmail(config, email); // Disable Git DisableUserGit(config, username); break; } } else { throw new Exception($"Unable to edit the account status [{status}] for {username}: " + result.Message); } } catch (Exception ex) { throw new Exception($"Unable to edit the account status [{status}] for: {username}", ex); } }
public static void ProcessExpirations(Config config, TeknikEntities db) { Output(string.Format("[{0}] Starting processing expirations.", DateTime.Now)); var curDate = DateTime.Now; // Process uploads List <Upload> uploads = db.Uploads.Where(u => u.ExpireDate != null && u.ExpireDate < curDate).ToList(); foreach (Upload upload in uploads) { string subDir = upload.FileName[0].ToString(); string filePath = Path.Combine(config.UploadConfig.UploadDirectory, subDir, upload.FileName); // Delete the File if (File.Exists(filePath)) { File.Delete(filePath); } } db.RemoveRange(uploads); db.SaveChanges(); // Process Pastes List <Paste> pastes = db.Pastes.Where(p => p.ExpireDate != null && p.ExpireDate < curDate).ToList(); foreach (Paste paste in pastes) { string subDir = paste.FileName[0].ToString(); string filePath = Path.Combine(config.PasteConfig.PasteDirectory, subDir, paste.FileName); // Delete the File if (File.Exists(filePath)) { File.Delete(filePath); } } db.RemoveRange(pastes); db.SaveChanges(); }
public static async Task CreateAccount(TeknikEntities db, Config config, IUrlHelper url, string username, string password, string recoveryEmail, string inviteCode) { try { var result = await IdentityHelper.CreateUser(config, username, password, recoveryEmail); if (result.Success) { // Get the userId passed back string userId = (string)result.Data; // Create an Email Account CreateUserEmail(config, GetUserEmailAddress(config, username), password); // Disable the email account DisableUserEmail(config, GetUserEmailAddress(config, username)); // Create a Git Account CreateUserGit(config, username, password, userId); // Add User User newUser = CreateUser(db, config, username, inviteCode); // If they have a recovery email, let's send a verification if (!string.IsNullOrEmpty(recoveryEmail)) { var token = await IdentityHelper.UpdateRecoveryEmail(config, username, recoveryEmail); string resetUrl = url.SubRouteUrl("account", "User.ResetPassword", new { Username = username }); string verifyUrl = url.SubRouteUrl("account", "User.VerifyRecoveryEmail", new { Code = WebUtility.UrlEncode(token) }); SendRecoveryEmailVerification(config, username, recoveryEmail, resetUrl, verifyUrl); } return; } throw new Exception("Error creating account: " + result.Message); } catch (Exception ex) { throw new Exception("Unable to create account.", ex); } }
public static DateTime GetLastAccountActivity(TeknikEntities db, Config config, string username, IdentityUserInfo userInfo) { try { DateTime lastActive = new DateTime(1900, 1, 1); if (UserEmailExists(config, GetUserEmailAddress(config, username))) { DateTime emailLastActive = UserEmailLastActive(config, GetUserEmailAddress(config, username)); if (lastActive < emailLastActive) { lastActive = emailLastActive; } } if (UserGitExists(config, username)) { DateTime gitLastActive = UserGitLastActive(config, username); if (lastActive < gitLastActive) { lastActive = gitLastActive; } } if (userInfo.LastSeen.HasValue) { DateTime userLastActive = userInfo.LastSeen.Value; if (lastActive < userLastActive) { lastActive = userLastActive; } } return(lastActive); } catch (Exception ex) { throw new Exception("Unable to determine last account activity.", ex); } }
public static void MigratePastes(TeknikEntities db, Config config) { if (!Directory.Exists(config.PasteConfig.PasteDirectory)) { Directory.CreateDirectory(config.PasteConfig.PasteDirectory); } var pastes = db.Pastes.Select(p => p.PasteId).ToList(); foreach (var pasteId in pastes) { var paste = db.Pastes.Where(p => p.PasteId == pasteId).FirstOrDefault(); if (!string.IsNullOrEmpty(paste.Content) && string.IsNullOrEmpty(paste.FileName) && string.IsNullOrEmpty(paste.HashedPassword)) { // Generate a unique file name that does not currently exist string filePath = FileHelper.GenerateRandomFileName(config.PasteConfig.PasteDirectory, config.PasteConfig.FileExtension, 10); string fileName = Path.GetFileName(filePath); string key = PasteHelper.GenerateKey(config.PasteConfig.KeySize); string iv = PasteHelper.GenerateIV(config.PasteConfig.BlockSize); // Encrypt the contents to the file PasteHelper.EncryptContents(paste.Content, filePath, null, key, iv, config.PasteConfig.KeySize, config.PasteConfig.ChunkSize); // Generate a deletion key paste.DeleteKey = StringHelper.RandomString(config.PasteConfig.DeleteKeyLength); paste.Key = key; paste.KeySize = config.PasteConfig.KeySize; paste.IV = iv; paste.BlockSize = config.PasteConfig.BlockSize; paste.FileName = fileName; paste.Content = string.Empty; db.Entry(paste).State = EntityState.Modified; db.SaveChanges(); } } }
public static async Task EditAccountType(TeknikEntities db, Config config, string username, AccountType type) { try { if (!UserExists(db, username)) { throw new Exception($"The user provided does not exist: {username}"); } var result = await IdentityHelper.UpdateAccountType(config, username, type); if (result.Success) { string email = GetUserEmailAddress(config, username); // Add/Remove account type features depending on the type switch (type) { case AccountType.Basic: // Disable their email DisableUserEmail(config, email); break; case AccountType.Premium: // Enable their email account EnableUserEmail(config, email); break; } } else { throw new Exception($"Unable to edit the account type [{type}] for {username}: " + result.Message); } } catch (Exception ex) { throw new Exception($"Unable to edit the account type [{type}] for: {username}", ex); } }
public static void ChangeServicePasswords(TeknikEntities db, Config config, string username, string newPassword) { try { // Make sure they have a git and email account before resetting their password string email = GetUserEmailAddress(config, username); if (config.EmailConfig.Enabled && UserEmailExists(config, email)) { // Change email password EditUserEmailPassword(config, GetUserEmailAddress(config, username), newPassword); } if (config.GitConfig.Enabled && UserGitExists(config, username)) { // Update Git password EditUserGitPassword(config, username, newPassword); } } catch (Exception ex) { throw new Exception("Unable to change service password.", ex); } }
public static List <string> GetInvalidAccounts(Config config, TeknikEntities db) { List <string> foundUsers = new List <string>(); List <User> curUsers = db.Users.ToList(); foreach (User user in curUsers) { // If the username is reserved, let's add it to the list if (UserHelper.UsernameReserved(config, user.Username) && user.Username != Constants.SERVERUSER) { foundUsers.Add(user.Username); continue; } // If the username is invalid, let's add it to the list if (!UserHelper.ValidUsername(config, user.Username) && user.Username != Constants.SERVERUSER) { foundUsers.Add(user.Username); continue; } } return(foundUsers); }
public static User CreateUser(TeknikEntities db, Config config, string username, string inviteCode) { try { User newUser = new User(); newUser.Username = username; newUser.UserSettings = new UserSettings(); newUser.BlogSettings = new BlogSettings(); newUser.UploadSettings = new UploadSettings(); // if they provided an invite code, let's assign them to it if (!string.IsNullOrEmpty(inviteCode)) { InviteCode code = db.InviteCodes.Where(c => c.Code == inviteCode).FirstOrDefault(); db.Entry(code).State = EntityState.Modified; newUser.ClaimedInviteCode = code; } // Add User db.Users.Add(newUser); // Generate blog for the user var newBlog = new Blog.Models.Blog(); newBlog.User = newUser; db.Blogs.Add(newBlog); // Save the changes db.SaveChanges(); return(newUser); } catch (Exception ex) { throw new Exception("Unable to create user.", ex); } }
public static async Task DeleteAccount(TeknikEntities db, Config config, User user) { try { string username = user.Username; // Delete identity account var result = await IdentityHelper.DeleteUser(config, username); if (result) { // Delete User Account DeleteUser(db, config, user); // Delete Email Account if (UserEmailExists(config, GetUserEmailAddress(config, username))) { DeleteUserEmail(config, GetUserEmailAddress(config, username)); } // Delete Git Account if (UserGitExists(config, username)) { DeleteUserGit(config, username); } } else { throw new Exception("Unable to delete identity account."); } } catch (Exception ex) { throw new Exception("Unable to delete account.", ex); } }
public PasteController(ILogger <Logger> logger, Config config, TeknikEntities dbContext) : base(logger, config, dbContext) { }
public static void DeleteUser(TeknikEntities db, Config config, User user) { try { // Update uploads List <Upload.Models.Upload> uploads = db.Uploads.Where(u => u.User.Username == user.Username).ToList(); if (uploads.Any()) { foreach (Upload.Models.Upload upload in uploads) { upload.UserId = null; db.Entry(upload).State = EntityState.Modified; } db.SaveChanges(); } // Update pastes List <Paste.Models.Paste> pastes = db.Pastes.Where(u => u.User.Username == user.Username).ToList(); if (pastes.Any()) { foreach (Paste.Models.Paste paste in pastes) { paste.UserId = null; db.Entry(paste).State = EntityState.Modified; } db.SaveChanges(); } // Update shortened urls List <ShortenedUrl> shortUrls = db.ShortenedUrls.Where(u => u.User.Username == user.Username).ToList(); if (shortUrls.Any()) { foreach (ShortenedUrl shortUrl in shortUrls) { shortUrl.UserId = null; db.Entry(shortUrl).State = EntityState.Modified; } db.SaveChanges(); } // Update vaults List <Vault.Models.Vault> vaults = db.Vaults.Where(u => u.User.Username == user.Username).ToList(); if (vaults.Any()) { foreach (Vault.Models.Vault vault in vaults) { vault.UserId = null; db.Entry(vault).State = EntityState.Modified; } db.SaveChanges(); } // Delete Blogs Blog.Models.Blog blog = db.Blogs.Where(u => u.User.Username == user.Username).FirstOrDefault(); if (blog != null) { db.Blogs.Remove(blog); db.SaveChanges(); } // Delete post comments List <BlogPostComment> postComments = db.BlogPostComments.Where(u => u.User.Username == user.Username).ToList(); if (postComments.Any()) { foreach (BlogPostComment postComment in postComments) { db.BlogPostComments.Remove(postComment); } db.SaveChanges(); } // Delete podcast comments List <Podcast.Models.PodcastComment> podComments = db.PodcastComments.Where(u => u.User.Username == user.Username).ToList(); if (podComments.Any()) { foreach (Podcast.Models.PodcastComment podComment in podComments) { db.PodcastComments.Remove(podComment); } db.SaveChanges(); } // Delete Owned Invite Codes List <InviteCode> ownedCodes = db.InviteCodes.Where(i => i.Owner.Username == user.Username).ToList(); if (ownedCodes.Any()) { foreach (InviteCode code in ownedCodes) { db.InviteCodes.Remove(code); } db.SaveChanges(); } // Delete Claimed Invite Code List <InviteCode> claimedCodes = db.InviteCodes.Where(i => i.ClaimedUser.Username == user.Username).ToList(); if (claimedCodes.Any()) { foreach (InviteCode code in claimedCodes) { db.InviteCodes.Remove(code); } db.SaveChanges(); } // Delete Auth Tokens //List<AuthToken> authTokens = db.AuthTokens.Where(t => t.User.UserId == user.UserId).ToList(); //if (authTokens.Any()) //{ // foreach (AuthToken authToken in authTokens) // { // db.AuthTokens.Remove(authToken); // } // db.SaveChanges(); //} // Delete User db.Users.Remove(user); db.SaveChanges(); } catch (Exception ex) { throw new Exception(string.Format("Unable to delete user {0}.", user.Username), ex); } }
public static async Task <DateTime> GetLastAccountActivity(TeknikEntities db, Config config, string username) { var userInfo = await IdentityHelper.GetIdentityUserInfo(config, username); return(GetLastAccountActivity(db, config, username, userInfo)); }
public AdminAPIv1Controller(ILogger <Logger> logger, Config config, TeknikEntities dbContext) : base(logger, config, dbContext) { }