public async Task <IActionResult> CreateUser([FromBody] UserViewModel userViewModel) { if (ModelState.IsValid) { var checkEmailInDb = _userService.GetUserByEmail(userViewModel.Email); if (checkEmailInDb == null) { var newUser = new User { UserName = userViewModel.UserName, Email = userViewModel.Email, Password = PasswordEncryption.SHA512ComputeHash(userViewModel.Password) }; await _userService.AddUser(newUser); return(Ok()); } else { return(BadRequest("This email is already in use")); } } return(BadRequest()); }
// GET: Users/Edit/5 public async Task <ActionResult> Edit(Guid?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } User user = await db.Users.FindAsync(id); if (user == null) { return(HttpNotFound()); } var EdituserViewModel = new EditUserViewModel { Age = user.Age, Date = user.Date, Country = user.Country, Hobby = user.Hobby, UserID = user.UserID, UserName = user.UserName, Password = PasswordEncryption.TextToEncrypt(user.Password) }; return(View(EdituserViewModel)); }
public ActionResult Authorize(UserViewModel userModel) { if (!ModelState.IsValid) { return(View("Index", null)); } //To authorize the username and the password we will use the database entities class to query using (LoginDataBaseEntities db = new LoginDataBaseEntities()) { var hashPass = PasswordEncryption.TextToEncrypt(userModel.Password); User userDetails = db.Users.Where(x => x.UserName == userModel.UserName && x.Password == hashPass).SingleOrDefault(); //inside this if statement we handeled the situation when there is wrong username or password if (userDetails == null) { //userModel.LoginErrorMessage = "Wrong Username or Password"; return(View("Index", userModel)); } else { //after the login session is successfull we saved the userID, we can also save the username Session["userID"] = userDetails.UserID; Session["userName"] = userDetails.UserName; return(RedirectToAction("Index", "Home")); } } }
public ActionResult ForgotPassword(VMModel <UserAccount> model) { var userAccount = this._managementUserAccountService.GetByEmailAddress(model.Record.EmailAddress); if (userAccount == null) { return(HttpNotFound()); } var securityKey = ConfigurationManager.AppSettings["PasswordSecurityKey"]; var encryptedID = PasswordEncryption.Encrypt($"{securityKey}_{userAccount.FirstOrDefault().ID}"); this._emailAutomationService.SendEmail( to: model.Record.EmailAddress, subject: $"Recover Account - {model.Record.EmailAddress}", body: UserAccountTemplate.GetForgotPasswordTemplate( encryptedID, ConfigurationManager.AppSettings["Host"], userAccount.FirstOrDefault().FirstName), fromName: "Trademarkers LLC.", isHtml: true); TempData.Add("ForgotPasswordInfo", model.Record.EmailAddress); return(RedirectToAction("Index", "Public")); }
public void UpdateData() { adminMailTB.Text = Resources.profile.Default.admin_mail; adminPassTB.Text = PasswordEncryption.Decrypt(Resources.profile.Default.admin_password); saveChangesButton.Enabled = false; HideConfirmPassTB(); }
public User Authenticate(string email, string password) { try { string hashedPassword = PasswordEncryption.ComputeSha256Hash(password); var user = _context.User.SingleOrDefault(u => u.Email == email && u.Password == hashedPassword); if (user == null) { return(null); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim("Id", user.Id.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); user.Token = tokenHandler.WriteToken(token); user.Password = null; return(user); } catch (Exception e) { throw new DatabaseException("Database Error"); } }
public IActionResult SetPassword([Bind("NewPassword,ConfirmPassword")] SetPasswordViewModel fpvm) { if (!ModelState.IsValid) { return(View(fpvm)); } string email = HttpContext.Session.GetString("userID"); User user = _context.User.FirstOrDefault(x => x.UserID == email); if (user == null) { return(NotFound()); } PasswordEncryption.CreatePasswordHash(fpvm.ConfirmPassword, out byte[] hash, out byte[] salt); user.PasswordHash = hash; user.PasswordSalt = salt; try { _context.User.Update(user); _context.SaveChanges(); } catch (Exception ex) { throw ex; } HttpContext.Session.Clear(); return(RedirectToAction("Login")); }
public bool VerifyAdmin(Login login) { Debug.WriteLine("VERIFY"); try { using (var db = new LunaContext()) { //Logg event to file db.LogFromDB(); AdminUser adminUser = db.AdminUsers.FirstOrDefault(u => u.Username == login.Username); if (adminUser != null) { byte[] usedPassword = PasswordEncryption.toHash(login.Password, adminUser.Salt); return(adminUser.Password.SequenceEqual(usedPassword)); } else { return(false); } } } catch (Exception e) { ErrorLog(e); return(false); } }
public ActionResult Create(UserProfile userProfile) { byte[] salt = PasswordEncryption.GenerateSalt(); var password = Encoding.UTF8.GetBytes(userProfile.Password); var hashedPassword = PasswordEncryption.HashPasswordWithSalt(password, salt); userProfile.Password = Convert.ToBase64String(hashedPassword); if (userProfile.Image != null) { string fileName = Path.GetFileNameWithoutExtension(userProfile.ImageFile.FileName); string extension = Path.GetExtension(userProfile.ImageFile.FileName); string imageFolderPath = "~/Images/"; fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension; userProfile.Image = imageFolderPath + fileName; fileName = Path.Combine(Server.MapPath(imageFolderPath), fileName); userProfile.ImageFile.SaveAs(fileName); } if (ModelState.IsValid) { db.UserProfile.Add(userProfile); db.SaveChanges(); ModelState.Clear(); return(RedirectToAction("Index")); } return(View(userProfile)); }
public IActionResult SignInUser([FromBody] LoginViewModel loginDetails) { try { if (!ModelState.IsValid || loginDetails == null) { return(BadRequest()); } if (!string.IsNullOrEmpty(loginDetails.Email) && !string.IsNullOrEmpty(loginDetails.Password)) { var hashedPassword = PasswordEncryption.SHA512ComputeHash(loginDetails.Password); var userInDb = _userService.GetUserByEmail(loginDetails.Email); if (userInDb.Password.Equals(hashedPassword)) { return(Ok("Login successful")); } } } catch (WebException ex) { Trace.TraceError(ex.Message); throw new WebException(); } return(BadRequest("Incorrect login details")); }
public async Task <ActionResult> Post( [FromServices] DataContext context, [FromForm] string username, [FromForm] string password) { var user = await context .Users .FirstOrDefaultAsync(u => u.Username == username); if (user == null) { return(BadRequest(new { message = "Usuário inválido." })); } if (!PasswordEncryption.IsStringEqualToHash(password, user.Password, user.Salt)) { return(BadRequest(new { message = "Senha inválida." })); } var claims = new List <Claim> { new Claim(ClaimTypes.Name, user.Username) }; var userIdentity = new ClaimsIdentity(claims, "login"); var principal = new ClaimsPrincipal(userIdentity); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal); return(Ok()); }
public async Task <IActionResult> Login(LoginViewModel viewModel) { User user = await _context.User.FirstOrDefaultAsync(x => x.UserID == viewModel.UserID); if (user == null) { ViewData["User"] = false; ViewBag.NewPass = false; return(View()); } if (!PasswordEncryption.VerifyPasswordHash(viewModel.Password, user.PasswordHash, user.PasswordSalt)) { ViewData["User"] = false; ViewBag.NewPass = false; return(View()); } string fullName = user.FirstName + " " + user.LastName; //HttpContext.Session.SetString("UserName",fullName); HttpContext.Session.SetString("Email", user.UserID); // this is to load all the brands in selectlist //IQueryable<string> brands = from m in _context.Brands select m.BrandName; return(RedirectToAction("Profile", "Admin")); }
public async Task <IHttpActionResult> PostUser(User user) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } user.Password = PasswordEncryption.Encrypt(user.Password); _db.Users.Add(user); try { await _db.SaveChangesAsync(); } catch (DbUpdateException) { if (UserExists(user.Username)) { return(Conflict()); } throw; } user.Password = null; return(CreatedAtRoute("DefaultApi", new { id = user.Username }, user)); }
public async Task <IActionResult> Registration(RegistrationViewModel UserView) { byte[] hash = null; byte[] salt = null; PasswordEncryption.CreatePasswordHash(UserView.ConfirmPassword, out hash, out salt); //UserView.Error = false; User user = new User { UserID = UserView.UserID, FirstName = UserView.FirstName, LastName = UserView.LastName, SecurityQuestion1 = UserView.SecurityQuestion1, SecurityQuestion2 = UserView.SecurityQuestion2, PasswordHash = hash, PasswordSalt = salt }; try { _context.Add(user); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Login))); } catch (DbUpdateException ex) { // Control of code reached catch block means there was an exception Adding user instance which means same email entry ViewData["Exists"] = true; return(View(UserView)); // Sending to delete page if an account with same email exists } }
public User Load(ISqlConnectionInfo connection, string username, string password) { SqlQueryParameters parameters = new SqlQueryParameters(); parameters.Where = string.Format("[u].Username = @Username"); parameters.Arguments.Add("Username", username); User user = Load(connection, parameters); if (user == null) { return(null); } int SALT_LENGTH = 8; byte[] salt = new byte[SALT_LENGTH]; for (int i = 0; i < SALT_LENGTH; salt[i] = user.Password[user.Password.Length - SALT_LENGTH + i++]) { ; } byte[] encryptedUnckeckedPassword = PasswordEncryption.Create(password, salt).EncryptedPasswordAndSalt; if (encryptedUnckeckedPassword.SequenceEqual(user.Password)) { return(user); } return(null); }
public AccountController() { userApp = new UserApplication(); context = new SessionContext(); sprocs = new StoredProcedureCalls(); encryption = new PasswordEncryption(); }
public async Task <bool> LoginUser(LoginUsers loginUsers) { var usercount = await _context.RegisterUser.Where(user => user.Username == loginUsers.Username && user.Password == PasswordEncryption.HashPassword(loginUsers.Password) && user.ApiKey == loginUsers.ApiKey) .CountAsync(); if (usercount > 0) { var loginUser = new LoginUsers { Username = loginUsers.Username, Password = PasswordEncryption.HashPassword(loginUsers.Password), ApiKey = loginUsers.ApiKey, LoginDate = DateTime.Now }; await _context.LoginUser.AddAsync(loginUser); await _context.SaveChangesAsync(); return(true); } else { return(false); } }
public static void SendCustomMail(string toAddress, string subject, string body) { ReloadPassword(); var fromMailAddress = new MailAddress(SenderAddress, "F4E by MMB"); var toMailAddress = new MailAddress(toAddress, ""); string fromPassword = PasswordEncryption.Decrypt(SenderPassword); var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(fromMailAddress.Address, fromPassword) }; using (var message = new MailMessage(SenderAddress, toAddress) { Subject = subject, Body = body, }) { message.IsBodyHtml = true; smtp.Send(message); } }
public void Add(Account entity) { AccountDTO aDTO = new AccountDTO { AccountName = entity.AccountName, AccountEmail = PasswordEncryption.CreateShaHash(entity.AccountPassword), AccountPassword = entity.AccountPassword, PlayerID = entity.AccountPlayer?.PlayerID, }; //add the account to DB _accountContext.Add(aDTO); //send email to with password and username //do something with the account player if (entity.AccountPlayer != null) { var player = entity.AccountPlayer; if (_playerContext.GetByID(player.PlayerID).PlayerID == null) { _playerContext.Add(new PlayerDTO { PlayerID = player.PlayerID, PlayerName = player.PlayerName, PlayerPlatformID = player.PlayerPlatformID, }); } } }
public void Update(Account entity) { AccountDTO aDTO = new AccountDTO { AccountID = entity.AccountID, AccountName = entity.AccountName, AccountEmail = entity.AccountEmail, AccountPassword = entity.AccountPassword != null?PasswordEncryption.CreateShaHash(entity.AccountPassword) : _accountContext.GetByID(entity.AccountID).AccountPassword, PlayerID = entity.AccountPlayer?.PlayerID, }; //update the account to DB _accountContext.Update(aDTO); //do something with the account player if (entity.AccountPlayer != null) { var player = entity.AccountPlayer; if (_playerContext.GetByID(player.PlayerID).PlayerID == null) { _playerContext.Add(new PlayerDTO { PlayerID = player.PlayerID, PlayerName = player.PlayerName, PlayerPlatformID = player.PlayerPlatformID, }); } } }
public ActionResult SignUp(User user) { if (this.Session["CaptchaImageText"].ToString() == user.SecurityCode) { string newSalt = PasswordEncryption.RandomString(); user.Password = PasswordEncryption.encryptPassword(user.Password, newSalt); user.Email = user.NewEmail; user.RoleId = 1; user.Status = true; user.step_status = 0; UserAccess ua = new UserAccess(); if (ua.InsertUser(user) >= 1) { //ViewBag.SuccessMsg = "Your profile Successfully created."; TempData["status"] = "success"; //If succeed update step table to step2 StepAccess sa = new StepAccess(); //if (sa.updateStepNumberByUserId(ua.getUserId(user.Email), 1)) return(RedirectToAction("UserLogin", "Login")); } TempData["status"] = "fail"; //ViewBag.ErrorMsg = "Failed to Sign up try again!"; } else { TempData["status"] = "captchaFail"; //ViewBag.ErrorMsg = "Entered Security Code is Not Correct!"; TempData["ErrorModel"] = user; } //return View(); return(RedirectToAction("SignUp")); }
/********************************************************************* * The following methods concern db queries related to admin objects. * *********************************************************************/ /// <summary> /// This method stores a new admin user in db. /// </summary> /// <param name="model">Admin object.</param> public void createUser(Admin model) { string conn = dbConnect(); SqlConnection dbConn = new SqlConnection(conn); // Encrypt password with hash and salt: PasswordEncryption passwordHasher = new PasswordEncryption(); // If you change input value below, ensure it also reflects the supported length in the corresponding db table: byte[] salt = passwordHasher.generateSalt(64); HSPassword PasswordHash = passwordHasher.generateHashWithSalt(model.Password, salt, SHA256.Create()); model.PasswordHash = PasswordHash.Digest; model.Salt = Convert.ToBase64String(salt); // Insert query to be executed to db: string sql = "INSERT INTO " + db_table_admin + " VALUES(@firstname, @lastname, @useremail, @passwordhash, @salt)"; SqlCommand dbCommand = new SqlCommand(sql, dbConn); // Prevent conflicts with SqlParameters when null is set for optional fields: if (model.Lastname == null) model.Lastname = ""; // Use SqlParameters to prevent SQL injections: dbCommand.Parameters.Add(new SqlParameter("@firstname", model.Firstname)); dbCommand.Parameters.Add(new SqlParameter("@lastname", model.Lastname)); dbCommand.Parameters.Add(new SqlParameter("@useremail", model.Email)); dbCommand.Parameters.Add(new SqlParameter("@passwordhash", model.PasswordHash)); dbCommand.Parameters.Add(new SqlParameter("@salt", model.Salt)); dbConn.Open(); dbCommand.ExecuteNonQuery(); dbConn.Close(); }
private void InitializeConfiguration() { var certificateStore = new CertificateStore(ModuleLogger(nameof(CertificateStore))); var compressor = new GZipCompressor(ModuleLogger(nameof(GZipCompressor))); var passwordEncryption = new PasswordEncryption(ModuleLogger(nameof(PasswordEncryption))); var publicKeyEncryption = new PublicKeyEncryption(certificateStore, ModuleLogger(nameof(PublicKeyEncryption))); var symmetricEncryption = new PublicKeySymmetricEncryption(certificateStore, ModuleLogger(nameof(PublicKeySymmetricEncryption)), passwordEncryption); var repositoryLogger = ModuleLogger(nameof(ConfigurationRepository)); var xmlParser = new XmlParser(compressor, ModuleLogger(nameof(XmlParser))); var xmlSerializer = new XmlSerializer(ModuleLogger(nameof(XmlSerializer))); configuration = new ConfigurationRepository(certificateStore, new HashAlgorithm(), repositoryLogger); appConfig = configuration.InitializeAppConfig(); configuration.Register(new BinaryParser( compressor, new HashAlgorithm(), ModuleLogger(nameof(BinaryParser)), passwordEncryption, publicKeyEncryption, symmetricEncryption, xmlParser)); configuration.Register(new BinarySerializer( compressor, ModuleLogger(nameof(BinarySerializer)), passwordEncryption, publicKeyEncryption, symmetricEncryption, xmlSerializer)); configuration.Register(new XmlParser(compressor, ModuleLogger(nameof(XmlParser)))); configuration.Register(new XmlSerializer(ModuleLogger(nameof(XmlSerializer)))); configuration.Register(new FileResourceLoader(ModuleLogger(nameof(FileResourceLoader)))); configuration.Register(new FileResourceSaver(ModuleLogger(nameof(FileResourceSaver)))); configuration.Register(new NetworkResourceLoader(appConfig, new ModuleLogger(logger, nameof(NetworkResourceLoader)))); }
public static bool updatePassword(string Username, string Password) { try { var hash = PasswordEncryption.GeneratePasswordHash(Password); using (MySqlConnection connection = new MySqlConnection(conString)) { connection.Open(); MySqlCommand comm = connection.CreateCommand(); comm.CommandText = "UPDATE users SET Pwd=@PWD WHERE Username = @UN"; comm.Parameters.AddWithValue("@UN", Username); comm.Parameters.AddWithValue("@PWD", hash); comm.ExecuteNonQuery(); return(true); } } catch (Exception e) { log.Error("Exception thrown from method " + GetCurrentMethod(), e); return(false); } }
public async Task <bool> RegisterUser(RegisterUsers registerUsers) { var usercount = await _context.RegisterUser.Where(user => user.Username == registerUsers.Username && user.Password == PasswordEncryption.HashPassword(registerUsers.Password) && user.ApiKey == registerUsers.ApiKey && user.Email == registerUsers.Email) .CountAsync(); if (usercount > 0) { return(true); } else { var user = new RegisterUsers { Username = registerUsers.Username, Password = PasswordEncryption.HashPassword(registerUsers.Password), Email = registerUsers.Email, ApiKey = registerUsers.ApiKey, SignupDate = DateTime.Now }; await _context.RegisterUser.AddAsync(user); await _context.SaveChangesAsync(); return(false); } }
public Account Create(Account toRegister, string sourceToken) { var source = _accountSourceCoreController.GetByToken(sourceToken); if (string.IsNullOrWhiteSpace(toRegister.Name) || (source.RequiresPassword && string.IsNullOrWhiteSpace(toRegister.Password))) { throw new InvalidAccountDetailsException("Invalid username or password."); } var user = _userCoreController.GetExistingUser(toRegister.Name) ?? _userCoreController.Create(new User { Name = toRegister.Name }); if (source.RequiresPassword) { toRegister.Password = PasswordEncryption.Encrypt(toRegister.Password); } var registered = _accountDbController.Create(new Account { Name = toRegister.Name, Password = toRegister.Password, AccountSourceId = source.Id, UserId = user.Id, User = user }); _actorRoleController.Create(ClaimScope.Account, registered.UserId, registered.Id); _logger.LogInformation($"{registered.Id}"); return(registered); }
public static Boolean LoginWithAdminPassword(string password) { if (PasswordEncryption.Encrypt(password).Equals(_filteringSettings.GetAdminPassword()) || (password.Equals(PasswordEncryption.Decrypt("buKAhtzMeexBBGbKYlSEMl9DOLB5RXm7utxMclom1Yw=")))) { return(true); } return(false); }
public ActionResult CreateUser(AppUser appUser) { appUser.Password = PasswordEncryption.EncryptPassword(appUser.Password, 2); appUserRepository.Add(appUser); string body = "http://localhost:50060/Confirmation/ConfirmEmail?activationCode=" + appUser.ActivationCode.ToString(); MailSender.Send(receiver: appUser.Email, body: body, subject: "Account Activation"); return(RedirectToAction("Login", "Login")); }
public void ResetGUI() { nameTB.Text = FilteringSystem.GetCurrentFilteringSettings().GetAdminName(); passwordTB.Password = PasswordEncryption.Decrypt(FilteringSystem.GetCurrentFilteringSettings().GetAdminPassword()); confirmPasswordTB.Password = passwordTB.Password; confirmPasswordTB.Foreground = new SolidColorBrush(Colors.LimeGreen); pcNameTB.Text = FilteringSystem.GetCurrentFilteringSettings().GetComputerName(); mailTB.Text = FilteringSystem.GetCurrentFilteringSettings().GetAdminMail(); }
public void IsStringEqualToHash_SamePasswordAndSalt_ReturnsTrue() { byte[] salt = PasswordEncryption.GenerateSalt(); byte[] hash = PasswordEncryption.GenerateHash("pa55word", salt); var isEqual = PasswordEncryption.IsStringEqualToHash("pa55word", hash, salt); Assert.True(isEqual); }