public ActionResult PostBlabbers(string blabberUsername, string command) { if (IsUserLoggedIn() == false) { return(RedirectToLogin(HttpContext.Request.RawUrl)); } var username = GetLoggedInUsername(); if (whiteListCommands.Any(x => string.Compare(x, command, true) == 0)) { try { using (var dbContext = new BlabberDB()) { dbContext.Database.Connection.Open(); var commandType = Type.GetType("VeraDemoNet.Commands." + UpperCaseFirst(command) + "Command"); /* START BAD CODE */ var cmdObj = (IBlabberCommand)Activator.CreateInstance(commandType, dbContext.Database.Connection, username); cmdObj.Execute(blabberUsername); /* END BAD CODE */ } } catch (Exception ex) { logger.Error(ex); } } var viewModel = PopulateBlabbersViewModel("blab_name ASC", username); return(View(viewModel)); }
public ActionResult PostRegister(string username) { logger.Info("PostRegister processRegister"); var registerViewModel = new RegisterViewModel(); Session["username"] = username; var sql = "SELECT count(*) FROM users WHERE username = @username"; using (var dbContext = new BlabberDB()) { var connection = dbContext.Database.Connection; connection.Open(); var checkUsername = connection.CreateCommand(); checkUsername.CommandText = sql; checkUsername.Parameters.Add(new SqlParameter { ParameterName = "@username", Value = username.ToLower() }); var numUsernames = checkUsername.ExecuteScalar() as int?; registerViewModel.UserName = username; if (numUsernames != 0) { registerViewModel.Error = "Username '" + username + "' already exists!"; return(View(registerViewModel)); } return(View("RegisterFinish", registerViewModel)); } }
public ActionResult PostBlabbers(string blabberUsername, string command) { if (IsUserLoggedIn() == false) { return(RedirectToLogin(HttpContext.Request.RawUrl)); } if (command != "ignore" && command != "listen") { return(View(new BlabbersViewModel { Error = "Invalid command." })); } var username = GetLoggedInUsername(); try { using (var dbContext = new BlabberDB()) { dbContext.Database.Connection.Open(); var commandType = Type.GetType("VeraDemoNet.Commands." + UpperCaseFirst(command) + "Command"); var cmdObj = (IBlabberCommand)Activator.CreateInstance(commandType, dbContext.Database.Connection, username); cmdObj.Execute(blabberUsername); } } catch (Exception ex) { logger.Error(ex); } var viewModel = PopulateBlabbersViewModel("blab_name ASC", username); return(View(viewModel)); }
public ActionResult GetPasswordHint(string userName) { logger.Info("Entering password-hint with username: "******"No username provided, please type in your username first")); } try { using (var dbContext = new BlabberDB()) { var match = dbContext.Users.FirstOrDefault(x => x.UserName == userName); if (match == null) { return(Content("No password found for " + HttpUtility.HtmlEncode(userName))); } if (match.PasswordHint == null) { return(Content("Username '" + HttpUtility.HtmlEncode(userName) + "' has no password hint!")); } var formatString = "Username '" + HttpUtility.HtmlEncode(userName) + "' has password: {0}"; return(Content(string.Format(formatString, match.PasswordHint.Substring(0, 2) + new string('*', match.PasswordHint.Length - 2)))); } } catch (Exception) { return(Content("ERROR!")); } }
public ActionResult PostBlab(int blabId, string comment) { if (IsUserLoggedIn() == false) { return RedirectToLogin(HttpContext.Request.RawUrl); } var username = GetLoggedInUsername(); var error = ""; using (var dbContext = new BlabberDB()) { dbContext.Database.Connection.Open(); var result= dbContext.Database.ExecuteSqlCommand(sqlAddComment, new SqlParameter{ParameterName = "@blabid", Value = blabId}, new SqlParameter{ParameterName = "@blabber", Value = username}, new SqlParameter{ParameterName = "@content", Value = comment}, new SqlParameter{ParameterName = "@timestamp", Value = DateTime.Now}); if (result == 0) { error = "Failed to add comment"; } } var blabViewModel = CreateBlabViewModel(blabId); blabViewModel.Error = error; return View(blabViewModel); }
private ActionResult ExecuteCommand(string blabberUsername, Func<DbConnection, string, IBlabberCommand> createCommand) { if (IsUserLoggedIn() == false) { return RedirectToLogin(HttpContext.Request.RawUrl); } var username = GetLoggedInUsername(); try { using (var dbContext = new BlabberDB()) { dbContext.Database.Connection.Open(); var command = createCommand(dbContext.Database.Connection, username); command.Execute(blabberUsername); } } catch (Exception ex) { logger.Error(ex); } return RedirectToAction("Blabbers"); }
public ActionResult PostFeed(string blab) { if (IsUserLoggedIn() == false) { return(RedirectToLogin(HttpContext.Request.RawUrl)); } var username = GetLoggedInUsername(); using (var dbContext = new BlabberDB()) { dbContext.Database.Connection.Open(); dbContext.Database.ExecuteSqlCommand(sqlAddBlab, new SqlParameter { ParameterName = "@username", Value = username }, new SqlParameter { ParameterName = "@blabcontents", Value = HttpUtility.HtmlEncode(blab) }, new SqlParameter { ParameterName = "@timestamp", Value = DateTime.Now }); } return(RedirectToAction("Feed")); }
private BlabViewModel CreateBlabViewModel(int blabId) { var blabViewModel = new BlabViewModel { BlabId = blabId }; using (var dbContext = new BlabberDB()) { dbContext.Database.Connection.Open(); var blabDetails = dbContext.Database.Connection.CreateCommand(); blabDetails.CommandText = sqlBlabDetails; blabDetails.Parameters.Add(new SqlParameter("@blabId", blabId)); var blabDetailsResults = blabDetails.ExecuteReader(); // If there is a record... if (blabDetailsResults.Read()) { // Get the blab contents blabViewModel.Content = blabDetailsResults.GetString(0); blabViewModel.BlabName = blabDetailsResults.GetString(1); blabDetailsResults.Close(); // Now lets get the comments... var blabComments = dbContext.Database.Connection.CreateCommand(); blabComments.CommandText = sqlBlabComments; blabComments.Parameters.Add(new SqlParameter("@blabId", blabId)); var blabCommentsResults = blabComments.ExecuteReader(); var comments = new List <Comment>(); while (blabCommentsResults.Read()) { var author = new Blabber { UserName = blabCommentsResults.GetString(0), BlabName = blabCommentsResults.GetString(1) }; var comment = new Comment { Content = blabCommentsResults.GetString(2), TimeStamp = blabCommentsResults.GetDateTime(3), Author = author }; comments.Add(comment); } blabViewModel.Comments = comments; } } return(blabViewModel); }
private bool UsernameExists(string username) { username = username.ToLower(); // Check is the username already exists using (var dbContext = new BlabberDB()) { var results = dbContext.Users.FirstOrDefault(x => x.UserName == username); return(results != null); } }
private void AddUserData(BlabberDB context) { logger.Info("Preparing the Statement for adding users"); foreach (var user in _veraUsers) { logger.Info("Adding user " + user.UserName); context.Users.Add(user); } context.SaveChanges(); }
private bool UpdateUsername(string oldUsername, string newUsername) { // Enforce all lowercase usernames oldUsername = oldUsername.ToLower(); newUsername = newUsername.ToLower(); string[] sqlStrQueries = { "UPDATE users SET username=@newusername WHERE username=@oldusername", "UPDATE blabs SET blabber=@newusername WHERE blabber=@oldusername", "UPDATE comments SET blabber=@newusername WHERE blabber=@oldusername", "UPDATE listeners SET blabber=@newusername WHERE blabber=@oldusername", "UPDATE listeners SET listener=@newusername WHERE listener=@oldusername", "UPDATE users_history SET blabber=@newusername WHERE blabber=@oldusername" }; using (var dbContext = new BlabberDB()) { var connection = dbContext.Database.Connection; connection.Open(); foreach (var sql in sqlStrQueries) { using (var update = connection.CreateCommand()) { logger.Info("Preparing the Prepared Statement: " + sql); update.CommandText = sql; update.Parameters.Add(new SqlParameter { ParameterName = "@oldusername", Value = oldUsername }); update.Parameters.Add(new SqlParameter { ParameterName = "@newusername", Value = newUsername }); update.ExecuteNonQuery(); } } } var imageDir = HostingEnvironment.MapPath("~/Images/"); var oldFilename = Path.Combine(imageDir, oldUsername) + ".png"; var newFilename = Path.Combine(imageDir, newUsername) + ".png"; if (System.IO.File.Exists(oldFilename)) { System.IO.File.Move(oldFilename, newFilename); } return(true); }
public ActionResult PostRegisterFinish(CompleteRegisrationViewModel user, string cpassword) { if (user.Password != cpassword) { logger.Info("Password and Confirm Password do not match"); return(View(new RegisterViewModel { Error = "The Password and Confirm Password values do not match. Please try again.", UserName = user.UserName, RealName = user.RealName, BlabName = user.BlabName, })); } var dbUser = new User { Password = Sha256Hash(user.Password), CreatedAt = DateTime.Now, UserName = user.UserName, BlabName = user.BlabName, RealName = user.RealName, PasswordHint = user.PasswordHint, }; using (var dbContext = new BlabberDB()) { dbContext.Users.Add(dbUser); dbContext.SaveChanges(); } var imageDir = HostingEnvironment.MapPath("~/Images/"); try { System.IO.File.Copy(Path.Combine(imageDir, "default_profile.png"), Path.Combine(imageDir, user.UserName) + ".png"); } catch (Exception ex) { } //EmailUser(userName); return(RedirectToAction("Login", "Account", new LoginView { UserName = user.UserName })); }
public ActionResult PostSearchBlabs(string searchText) { if (IsUserLoggedIn() == false) { return(RedirectToLogin(HttpContext.Request.RawUrl)); } if (searchText == "error") { throw new Exception(); } var searchBlabslist = new List <BlabSearchResultViewModel>(); using (var dbContext = new BlabberDB()) { dbContext.Database.Connection.Open(); var searchBlabs = dbContext.Database.Connection.CreateCommand(); searchBlabs.CommandText = sqlSearchBlabs; var parm = searchBlabs.CreateParameter(); parm.ParameterName = "search"; parm.Value = searchText; searchBlabs.Parameters.Add(parm); var searchBlabsResults = searchBlabs.ExecuteReader(); while (searchBlabsResults.Read()) { var post = new BlabSearchResultViewModel { Blabber = searchBlabsResults.GetString(0), Content = searchBlabsResults.GetString(1), BlabDate = searchBlabsResults.GetDateTime(2), }; searchBlabslist.Add(post); } } var model = new SearchBlabsViewModel { Blabs = searchBlabslist, SearchText = searchText }; return(View("SearchBlabs", model)); }
private bool UsernameExists(string username) { username = username.ToLower(); // Check is the username already exists using (var dbContext = new BlabberDB()) { var connection = dbContext.Database.Connection; connection.Open(); var usernameCheck = connection.CreateCommand(); usernameCheck.CommandText = "SELECT username FROM users WHERE username=?"; var results = dbContext.Users.FirstOrDefault(x => x.UserName == username); return(results != null); } }
public string GetMoreBlabs(int start, int numResults) { var username = GetLoggedInUsername(); var template = "<li><div><div class='commenterImage'>" + "<img src='" + Url.Content("~/Images/") + "{0}.png'>" + "</div>" + "<div class='commentText'>" + "<p>{1}</p>" + "<span class='date sub-text'>by {2} on {3}</span><br>" + "<span class='date sub-text'><a href=\"Blab/Blab?blabid={4}\">{5} Comments</a></span>" + "</div>" + "</div></li>"; // Get the Database Connection var returnTemplate = new StringBuilder(); using (var dbContext = new BlabberDB()) { dbContext.Database.Connection.Open(); var listeningBlabs = dbContext.Database.Connection.CreateCommand(); listeningBlabs.CommandText = string.Format(sqlBlabsForMe, start, numResults); listeningBlabs.Parameters.Add(new SqlParameter("@listener", username)); var blabsForMeResults = listeningBlabs.ExecuteReader(); while (blabsForMeResults.Read()) { var blab = new Blab { PostDate = blabsForMeResults.GetDateTime(3) }; returnTemplate.Append(string.Format(template, blabsForMeResults.GetString(0), // username blabsForMeResults.GetString(2), // blab content blabsForMeResults.GetString(1), // blab name blab.PostDateString, // timestamp blabsForMeResults.GetInt32(5), // blabID blabsForMeResults.GetInt32(4) // comment count )); } } return(returnTemplate.ToString()); }
public ActionResult PostBlabbers(string blabberUsername, string command) { if (IsUserLoggedIn() == false) { return(RedirectToLogin(HttpContext.Request.RawUrl)); } var username = GetLoggedInUsername(); try { using (var dbContext = new BlabberDB()) { dbContext.Database.Connection.Open(); IBlabberCommand cmd; switch (command) { case "listen": cmd = new ListenCommand(dbContext.Database.Connection, username); break; case "ignore": cmd = new IgnoreCommand(dbContext.Database.Connection, username); break; default: throw new InvalidOperationException($"The command '{command}' was not recognized."); } cmd.Execute(blabberUsername); } } catch (Exception ex) { logger.Error(ex); } var viewModel = PopulateBlabbersViewModel("blab_name ASC", username); return(View(viewModel)); }
public ActionResult PostRegister(string username) { logger.Info("PostRegister processRegister"); var registerViewModel = new RegisterViewModel(); Session["username"] = username; using (var dbContext = new BlabberDB()) { registerViewModel.UserName = username; if (dbContext.Users.Any(t => t.UserName == username)) { registerViewModel.Error = "Username '" + username + "' already exists!"; return(View(registerViewModel)); } return(View("RegisterFinish", registerViewModel)); } }
protected BasicUser LoginUser(string userName, string passWord) { if (string.IsNullOrEmpty(userName)) { return(null); } using (var dbContext = new BlabberDB()) { var found = dbContext.Users.FirstOrDefault(x => x.UserName == userName); if (found != null && Crypto.VerifyHashedPassword(found.Password, passWord)) { Session["username"] = userName; return(new BasicUser(found.UserName, found.BlabName, found.RealName)); } } return(null); }
public ActionResult PostRegisterFinish([Bind(Include = "UserName,RealName,BlabName")] User user, string cpassword) { if (user.Password != cpassword) { logger.Info("Password and Confirm Password do not match"); return(View(new RegisterViewModel { Error = "The Password and Confirm Password values do not match. Please try again.", UserName = user.UserName, RealName = user.RealName, BlabName = user.BlabName, })); } // Use the user class to get the hashed password. user.Password = Crypto.HashPassword(user.Password); user.CreatedAt = DateTime.Now; using (var dbContext = new BlabberDB()) { dbContext.Users.Add(user); dbContext.SaveChanges(); } var imageDir = HostingEnvironment.MapPath("~/Images/"); try { System.IO.File.Copy(Path.Combine(imageDir, "default_profile.png"), Path.Combine(imageDir, user.UserName) + ".png"); } catch (Exception ex) { } //EmailUser(userName); return(RedirectToAction("Login", "Account", new LoginView { UserName = user.UserName })); }
private BlabbersViewModel PopulateBlabbersViewModel(string sort, string username) { var viewModel = new BlabbersViewModel(); var blabbersList = new List <Blabber>(); try { using (var dbContext = new BlabberDB()) { dbContext.Database.Connection.Open(); var blabbers = dbContext.Database.Connection.CreateCommand(); blabbers.CommandText = string.Format(sqlBlabbers, sort); blabbers.Parameters.Add(new SqlParameter("@username", username)); var blabbersResults = blabbers.ExecuteReader(); while (blabbersResults.Read()) { var blabber = new Blabber { UserName = blabbersResults.GetString(0), BlabName = blabbersResults.GetString(1), CreatedDate = blabbersResults.GetDateTime(2), Subscribed = blabbersResults.GetInt32(3) == 1, NumberListeners = blabbersResults.GetInt32(4), NumberListening = blabbersResults.GetInt32(5) }; blabbersList.Add(blabber); } } viewModel.Blabbers = blabbersList; } catch (DbException ex) { viewModel.Error = ex.Message; } return(viewModel); }
protected BasicUser LoginUser(string userName, string passWord) { if (string.IsNullOrEmpty(userName)) { return(null); } using (var dbContext = new BlabberDB()) { var found = dbContext.Database.SqlQuery <BasicUser>(@" SELECT username, real_name as realname, blab_name as blabname, is_admin as isadmin, password as hash FROM users WHERE username = @username", new SqlParameter("username", userName) ).ToList(); if (found.Count != 0) { PasswordHash ph; try { ph = new PasswordHash(Convert.FromBase64String(found[0].Hash)); } catch (FormatException) { return(null); } if (ph.Verify(passWord)) { //Session.Abandon(); //Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", "")); Session["username"] = userName; return(found[0]); } } } return(null); }
public ActionResult DownloadProfileImage(string userName) { if (IsUserLoggedIn() == false) { return(RedirectToLogin(HttpContext.Request.RawUrl)); } using (var db = new BlabberDB()) { var user = db.Users.FirstOrDefault(u => u.UserName == userName); if (user == null) { return(HttpNotFound()); } logger.Info("Entering downloadImage"); var imagePath = Path.Combine(HostingEnvironment.MapPath("~/Images/"), user.PictureName); logger.Info("Fetching profile image: " + imagePath); return(File(imagePath, System.Net.Mime.MediaTypeNames.Application.Octet)); } }
private bool UpdateUsername(string oldUsername, string newUsername) { // Enforce all lowercase usernames oldUsername = oldUsername.ToLower(); newUsername = newUsername.ToLower(); string[] sqlStrQueries = { "UPDATE users SET username=@newusername WHERE username=@oldusername", "UPDATE blabs SET blabber=@newusername WHERE blabber=@oldusername", "UPDATE comments SET blabber=@newusername WHERE blabber=@oldusername", "UPDATE listeners SET blabber=@newusername WHERE blabber=@oldusername", "UPDATE listeners SET listener=@newusername WHERE listener=@oldusername", "UPDATE users_history SET blabber=@newusername WHERE blabber=@oldusername" }; using (var dbContext = new BlabberDB()) { var connection = dbContext.Database.Connection; connection.Open(); foreach (var sql in sqlStrQueries) { using (var update = connection.CreateCommand()) { logger.Info("Preparing the Prepared Statement: " + sql); update.CommandText = sql; update.Parameters.Add(new SqlParameter { ParameterName = "@oldusername", Value = oldUsername }); update.Parameters.Add(new SqlParameter { ParameterName = "@newusername", Value = newUsername }); update.ExecuteNonQuery(); } } } return(true); }
protected BasicUser LoginUser(string userName, string passWord) { if (string.IsNullOrEmpty(userName)) { return(null); } using (var dbContext = new BlabberDB()) { var found = dbContext.Database.SqlQuery <BasicUser>( "select username, real_name as realname, blab_name as blabname, is_admin as isadmin from users where username ='******' and password='******';").ToList(); if (found.Count != 0) { Session["username"] = userName; return(found[0]); } } return(null); }
public ActionResult PostReset(string confirm, string primary) { logger.Info("Entering processReset"); var viewModel = new ResetViewModel(); if (string.IsNullOrEmpty(confirm)) { viewModel.Error = "You must confirm to proceed"; return(View(viewModel)); } try { logger.Info("Getting Database connection"); using (var dbContext = new BlabberDB()) { var connection = dbContext.Database.Connection; connection.Open(); RecreateDatabaseSchema(connection); AddUserData(dbContext); AddListeners(connection); var blabsList = AddBlabs(connection); AddComments(connection, blabsList); connection.Close(); } } catch (Exception ex) { logger.Error(ex); viewModel.Error = ex.Message; } return(View(viewModel)); }
public ActionResult PostSearchBlabs(string searchText) { if (IsUserLoggedIn() == false) { return(RedirectToLogin(HttpContext.Request.RawUrl)); } var searchBlabslist = new List <BlabSearchResultViewModel>(); using (var dbContext = new BlabberDB()) { dbContext.Database.Connection.Open(); var searchBlabs = (SqlCommand)dbContext.Database.Connection.CreateCommand(); searchBlabs.CommandText = sqlSearchBlabs; searchBlabs.Parameters.AddWithValue("@keywords", $"%{searchText}%"); var searchBlabsResults = searchBlabs.ExecuteReader(); while (searchBlabsResults.Read()) { var post = new BlabSearchResultViewModel { Blabber = searchBlabsResults.GetString(0), Content = searchBlabsResults.GetString(1), BlabDate = searchBlabsResults.GetDateTime(2), }; searchBlabslist.Add(post); } } var model = new SearchBlabsViewModel { Blabs = searchBlabslist, SearchText = searchText }; return(View("SearchBlabs", model)); }
protected BasicUser LoginUser(string userName, string passWord) { if (string.IsNullOrEmpty(userName)) { return(null); } using (var dbContext = new BlabberDB()) { var user = dbContext.Users.SingleOrDefault(t => t.UserName == userName); if (user != null) { if (Crypto.VerifyHashedPassword(user.Password, passWord)) { Session["username"] = userName; return(new BasicUser(user.UserName, user.BlabName, user.RealName)); } } } return(null); }
public ActionResult GetProfile() { logger.Info("Entering GetProfile"); if (IsUserLoggedIn() == false) { return(RedirectToLogin(HttpContext.Request.RawUrl)); } var viewModel = new ProfileViewModel(); var username = GetLoggedInUsername(); using (var dbContext = new BlabberDB()) { var connection = dbContext.Database.Connection; connection.Open(); viewModel.Hecklers = RetrieveMyHecklers(connection, username); viewModel.Events = RetrieveMyEvents(connection, username); PopulateProfileViewModel(connection, username, viewModel); } return(View(viewModel)); }
public ActionResult PostFeed(string blab) { Regex tagRegex = new Regex(@"<\s*([^ >]+)[^>]*>.*?<\s*/\s*\1\s*>"); if (tagRegex.IsMatch(blab)) throw new Exception("Invalid data"); if (IsUserLoggedIn() == false) { return RedirectToLogin(HttpContext.Request.RawUrl); } var username = GetLoggedInUsername(); using (var dbContext = new BlabberDB()) { dbContext.Database.Connection.Open(); dbContext.Database.ExecuteSqlCommand(sqlAddBlab, new SqlParameter{ParameterName = "@username", Value = username}, new SqlParameter{ParameterName = "@blabcontents", Value = blab}, new SqlParameter{ParameterName = "@timestamp", Value = DateTime.Now}); } return RedirectToAction("Feed"); }
public ActionResult GetFeed() { if (IsUserLoggedIn() == false) { return(RedirectToLogin(HttpContext.Request.RawUrl)); } var username = GetLoggedInUsername(); // Find the Blabs that this user listens to var feedBlabs = new List <Blab>(); using (var dbContext = new BlabberDB()) { dbContext.Database.Connection.Open(); var listeningBlabs = dbContext.Database.Connection.CreateCommand(); listeningBlabs.CommandText = string.Format(sqlBlabsForMe, 0, 10); listeningBlabs.Parameters.Add(new SqlParameter("@listener", username)); var blabsForMeResults = listeningBlabs.ExecuteReader(); while (blabsForMeResults.Read()) { var author = new Blabber { UserName = blabsForMeResults.GetString(0), BlabName = blabsForMeResults.GetString(1) }; var post = new Blab { Id = blabsForMeResults.GetInt32(5), Content = blabsForMeResults.GetString(2), PostDate = blabsForMeResults.GetDateTime(3), CommentCount = blabsForMeResults.GetInt32(4), Author = author }; feedBlabs.Add(post); } } // Find Blabs by this user var myBlabs = new List <Blab>(); using (var dbContext = new BlabberDB()) { dbContext.Database.Connection.Open(); var listeningBlabs = dbContext.Database.Connection.CreateCommand(); listeningBlabs.CommandText = sqlBlabsByMe; listeningBlabs.Parameters.Add(new SqlParameter { ParameterName = "@username", Value = username }); var blabsByMeResults = listeningBlabs.ExecuteReader(); while (blabsByMeResults.Read()) { var post = new Blab { Id = blabsByMeResults.GetInt32(3), Content = blabsByMeResults.GetString(0), PostDate = blabsByMeResults.GetDateTime(1), CommentCount = blabsByMeResults.GetInt32(2), }; myBlabs.Add(post); } } return(View(new FeedViewModel { BlabsByMe = myBlabs, BlabsByOthers = feedBlabs, CurrentUser = username } )); }