public ActionResult Login(UserLoginVM model) //notice we’re using the ViewModel { if (ModelState.IsValid) { //var hashedPassword = Crypto.HashPassword(model.Password); var hashed = HashClass.Encode(model.Password); var db = new MyDBEntities(); var v = db.users.Where(u => u.Username.Equals(model.Username) && u.Password.Equals(hashed)).FirstOrDefault(); if (v != null) { ViewData["Message"] = "Login Successful"; Session["loggedIn"] = true; Session["user"] = v.Username; Session["id"] = v.Id; Session["isAdmin"] = v.isAdmin; if ((int)Session["isAdmin"] == 1) { return(RedirectToAction("DisplayCars", "Car")); } else { return(RedirectToAction("UserArea", "Car")); } } else { ViewData["Message"] = "Login Unsuccessful"; } } return(View(model)); }
public async Task <ActionResult> Register(RegisterModel model) { if (ModelState.IsValid) { User us = await db.Users.Where(u => u.Mail == model.Mail).FirstOrDefaultAsync(); if (us != null) { return(Ok(new { msg = $"Пользователь с {model.Mail} уже зарегистрирован" })); } us = await db.Users.Where(u => u.Login == model.Login).FirstOrDefaultAsync(); if (us != null) { return(Ok(new { msg = $"Пользователь с {model.Login} уже зарегистрирован" })); } User user = new User { Mail = model.Mail, Login = model.Login, Password = HashClass.GetHash(model.Password), RoleId = 1, Avatar = "user_icon.png" }; try { db.Users.Add(user); await db.SaveChangesAsync(); } catch (Exception ex) { return(BadRequest(ex.InnerException.Message)); } return(Ok(new { msg = "" })); } return(BadRequest()); }
private void ButtonSaveUser_OnClick(object sender, RoutedEventArgs e) { CheckPassAndLogin check = new CheckPassAndLogin(); CaffeDataContext db = new CaffeDataContext(); HashClass hash = new HashClass(); if (check.ChceckPassEqals(Pass1TB.Text, Pass2TB.Text) && check.ChceckPassNumeric(Pass1TB.Text) && check.CheckPassLength(Pass1TB.Text)) { int IdMax = db.Users.Max(s => s.Id_user); User u = new User() { Name = UserNameTB.Text, Id_user = IdMax + 1, Password = hash.GetHashString(Pass1TB.Text) }; db.Users.InsertOnSubmit(u); db.SubmitChanges(); MessageBox.Show("Zapisoano zmiany !!!"); Pass1TB.Text = ""; Pass2TB.Text = ""; UserNameTB.Text = ""; } else { MessageBox.Show("Nieprawidłowe dane !"); } }
private void HashFilebtn_Click(object sender, EventArgs e) { dataGridViewX1.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; HashFiletxt.Text = HashClass.GetHashFile(FilePathtxt.Text, new SHA512CryptoServiceProvider()); SetDataGridSource(); dataGridViewX1.Visible = true; }
public async Task <IActionResult> PostUsers([FromBody] PassedData <PassedNewEmail> data) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } DateTime now = DateTime.UtcNow; if (data.UserToken == null) { return(BadRequest(new DataError("securityErr", "No authorization controll."))); } UserToken dbtoken = Security.CheckUserToken(this._context, data.UserToken); if (dbtoken == null) { return(BadRequest(new DataError("securityErr", "Your data has probably been stolen or modified manually. We suggest password's change."))); } else { if (!dbtoken.IsTimeValid(now)) { return(BadRequest(new DataError("timeoutErr", "You have been too long inactive. Relogin is required."))); } else { dbtoken.UpdateToken(now); } } Users user = _context.Users.FirstOrDefault(e => e.Name == dbtoken.UserName); if (user.Password != HashClass.GenHash(data.Data.Password)) { return(BadRequest(new DataError("passwordErr", "Password is incorrect."))); } if (data.Data.NewEmail != data.Data.ConfirmEmail) { return(BadRequest(new DataError("newEmailErr", "New email was not confirmed correctly."))); } //all went well user.Email = data.Data.NewEmail; try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { if (_context.Users.FirstOrDefault(e => ((e.Email == data.Data.NewEmail) && (e.Name != dbtoken.UserName))) != null) { return(BadRequest(new DataError("newEmailErr", "New email has been already used."))); } return(BadRequest(new DataError("serverErr", "Failed to save new password."))); } return(Ok(new { success = true })); }
public void AddNewManagerTest() { managerContext1 = managerDataAccess.AddManager(ManagerFirstName1, ManagerLastName1, ManagerLogin1, HashClass.CreateFirstHash(ManagerPassword1, ManagerLogin1)); Assert.IsNotNull(managerContext1); Assert.AreNotEqual(managerContext1.Id, 0); Assert.AreEqual(managerContext1.FirstName, ManagerFirstName1); Assert.AreEqual(managerContext1.LastName, ManagerLastName1); Assert.AreEqual(managerContext1.Role, UserRole.Manager); }
public async Task <IActionResult> Register([FromBody] RegisterDTO model) { EnsureDatabaseCreated(_context); if (ModelState.IsValid) { bool duplicate = false; var user = await _userManager.FindByNameAsync(model.NationalCode); if (user != null) { duplicate = true; ModelState.AddModelError("NationalCode", "کد ملی در سیستم قبلا ثبت شده است"); } var user1 = _context.Users.Any(x => x.PhoneNumber == model.PhonNumber); if (user1) { duplicate = true; ModelState.AddModelError("PhoneNumber", "شماره تلفن همراه قبلا ثبت شده است"); } if (!model.PhonNumber.IsValidIranianMobileNumber()) { duplicate = true; ModelState.AddModelError("PhoneNumber", "شماره تلفن همراه صحیح نمی باشد"); } if (duplicate) { return(BadRequest(ModelState)); } user = new ApplicationUser { UserName = model.PhonNumber, PhoneNumber = model.PhonNumber, PasswordHash = HashClass.BitConverterHasj(model.Password), FullName = model.FullName, NationalCode = model.NationalCode }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { return(Ok(true)); } AddErrors(result); } // If we got this far, something failed. return(BadRequest(ModelState)); }
public void AddNewClientTest() { clientContext1 = clientDataAccess.AddClient(ClientFirstName1, ClientLastName1, ClientLogin1, HashClass.CreateFirstHash(ClientPassword1, ClientLogin1)); Assert.IsNotNull(clientContext1); Assert.AreNotEqual(clientContext1.Id, 0); Assert.AreEqual(clientContext1.FirstName, ClientFirstName1); Assert.AreEqual(clientContext1.LastName, ClientLastName1); Assert.AreEqual(clientContext1.Role, UserRole.Client); }
public async Task <IActionResult> PostUsers([FromBody] RegistrationUser users) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (UsersExists(users.Username)) { return(BadRequest(new DataError("sameloginErr", "Login with same name already exists."))); } if (EmailExists(users.Email)) { return(BadRequest(new DataError("sameemailErr", "Email already used."))); } if (users.Password != users.Password_Confrim) { return(BadRequest(new DataError("confirmErr", "Bad confirmation password."))); } //TODO: regex validation Users user = new Users() { Email = users.Email, Name = users.Username, Password = HashClass.GenHash(users.Password), RegistryDate = DateTime.UtcNow, LastLogin = DateTime.UtcNow }; _context.Users.Add(user); try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { if (UsersExists(users.Username)) { return(new StatusCodeResult(StatusCodes.Status409Conflict)); } else { throw; } } try { SendEmail.SendInvitationEmail(user, users.Password); } catch (Exception e) { Console.WriteLine(e.ToString()); } return(Ok()); }
public void ClientLogInTest() { if (clientContext1 == null) { AddNewClientTest(); } var context = clientDataAccess.LogIn(ClientLogin1, HashClass.CreateFirstHash(ClientPassword1, ClientLogin1)); Assert.IsNotNull(context); Assert.AreEqual(context.Login, ClientLogin1); Assert.AreEqual(context.Role, UserRole.Client); }
private void btnLogin_Click(object sender, RoutedEventArgs e) { try { if (!string.IsNullOrWhiteSpace(txtuser.Text) && !string.IsNullOrWhiteSpace(txtpass.Password)) { string password = HashClass.EncodePassword(string.Concat(txtuser.Text.ToLower(), txtpass.Password)); var obj = new tbUserEmpaque { nombreUsuario = txtuser.Text.ToLower(), contraseña = password }; var resp = UsuarioNeg.GetUsuario(obj); switch (resp.rol.Trim()) { case "error": MessageBox.Show(resp.nombreUsuario, "Ha ocurrido un error intente nuevamente"); break; case "null": MessageBox.Show("Icorrecto", "Las credenciales proporcionadas no son validas"); break; case "Tickets": App.Current.Properties["User"] = resp; var form2 = new PricipalTickets(); this.Close(); form2.Show(); // stackPanelContenido.Children.Add(new TicktesScan()); break; default: App.Current.Properties["User"] = resp; var form = new Principal(); this.Close(); form.Show(); break; } } } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } }
/// <summary> /// Finds the cached version or will try to retrieve the type from assemblies. /// </summary> /// <param name="namespace"></param> /// <param name="className"></param> /// <returns></returns> public HashClass GetType(string @namespace, string className) { int hash = @namespace.GetHashCode() + className.GetHashCode(); // Check if cached. for (int i = 0; i < this.indexLeft; i++) { if (this.classes[i].hash == hash) { return(this.classes[i]); } } try { // Populate new file. HashClass hashClass = new HashClass(hash); if (string.IsNullOrEmpty(@namespace) == false) { hashClass.type = Utility.GetType(@namespace, className); } else { hashClass.type = Utility.GetType(className); } if (hashClass.type != null) { hashClass.methods = new FastMethodCache(hashClass.type); } // Check array overflow. if (this.indexLeft == this.classes.Length) { Array.Resize(ref this.classes, this.classes.Length << 1); } this.classes[this.indexLeft] = hashClass; ++this.indexLeft; //Debug.Log("Cached class:" + className); return(hashClass); } catch (Exception ex) { InternalNGDebug.LogException(ex); } return(null); }
public void ManagerLogInTest() { if (managerContext1 == null) { AddNewManagerTest(); } UserContext context = managerDataAccess.LogIn(ManagerLogin1, HashClass.CreateFirstHash(ManagerPassword1, ManagerLogin1)); Assert.IsNotNull(context); Assert.AreEqual(context.Login, ManagerLogin1); Assert.AreEqual(context.Role, UserRole.Manager); }
public async Task <IActionResult> Register(RegisterModel model, string baseUrl) { User us = await db.Users.Where(u => u.Mail == model.Mail).FirstOrDefaultAsync(); if (us != null) { return(new OkObjectResult(new { msg = $"Пользователь с {model.Mail} уже зарегистрирован" })); } us = await db.Users.Where(u => u.Login == model.Login).FirstOrDefaultAsync(); if (us != null) { return(new OkObjectResult(new { msg = $"Пользователь с {model.Login} уже зарегистрирован" })); } User user = new User { Mail = model.Mail, Login = model.Login, Password = HashClass.GetHash(model.Password), RoleId = 1, IsMailConfirmed = false, VerifyCode = Guid.NewGuid(), Avatar = options.Value.DefaultUserImageLink, AvatarFile = options.Value.DefaultUserImageFile, RegistrationDate = DateTime.Now }; try { db.Users.Add(user); await db.SaveChangesAsync(); var emailInfo = new EmailInfo(); emailInfo.Subject = "Подтверждение почты в приложении MusicApp"; emailInfo.Body = $"<div><p>Кликните по ссылке ниже, чтобы подтвердить свою почту</p><a href='{baseUrl}{confirmMailLink}?userId={user.UserId}&verifyCode={user.VerifyCode}'>Подтвердить почту</a></div>"; emailInfo.ToMails.Add(user.Mail); var emailResult = emailManager.Send(emailInfo); if (!emailResult.Sended) { throw new Exception(emailResult.ErrorMessage); } return(new OkResult()); } catch (Exception ex) { return(new BadRequestObjectResult(ex.InnerException.Message)); } }
public void EqualValuesTest() { // тест на добавление одного и того же ключа дважды с разными значениями, которое сохраняет последнее добавленное значение var similarValuesTable = new HashClass(); int size = 2; similarValuesTable.HashTableCreate(size); similarValuesTable.PutPair(1, " Ты"); similarValuesTable.PutPair(1, "Я"); int tableKey = 1; var tableValue = "Я"; if (!(similarValuesTable.GetValueByKey(tableKey)).Equals(tableValue)) { throw new Exception(); } }
public async Task <ActionResult> Register(RegisterModel model) { if (ModelState.IsValid) { User us = await db.Users.Where(u => u.Mail == model.Mail).FirstOrDefaultAsync(); if (us != null) { return(Ok(new { msg = $"Пользователь с {model.Mail} уже зарегистрирован" })); } us = await db.Users.Where(u => u.Login == model.Login).FirstOrDefaultAsync(); if (us != null) { return(Ok(new { msg = $"Пользователь с {model.Login} уже зарегистрирован" })); } User user = new User { Mail = model.Mail, Login = model.Login, Password = HashClass.GetHash(model.Password), RoleId = 1, IsMailConfirmed = false }; try { db.Users.Add(user); await db.SaveChangesAsync(); MailClass mailClass = new MailClass(); mailClass.Subject = "Подтверждение почты"; mailClass.Body = mailService.GetMailBody(authOptions.Value.Issuer + $"api/RegisterUser/ConfirmEmail?username={model.Login}", model.Login); mailClass.ToMails = new List <string>() { model.Mail }; await mailService.SendMail(mailClass); return(Ok(new { msg = $"Регистрация прошла успешно, на {model.Mail} было отправлено письмо для подтверждения почты" })); } catch (Exception ex) { return(BadRequest(ex.InnerException.Message)); } } return(BadRequest()); }
public void MissedKeysTest() { //тест на добавление 10000 элементов и поиск 1000 недобавленных ключей. Возвращает null. var missedKeys = new HashClass(); int size = 10000; missedKeys.HashTableCreate(size); for (int i = 0; i < size; i++) { missedKeys.PutPair(i, "v" + i); } for (int i = size; i < size + 1000; i++) { if (!(missedKeys.GetValueByKey(i) == null)) { throw new Exception(); } } }
public void ManyElementsTest() { //тест на добавление 10000 элементов и поиск одного var bigArray = new HashClass(); var size = 10000; bigArray.HashTableCreate(size); var tableKey = 1; var tableValue = "Number1"; for (int i = 0; i < size; i++) { bigArray.PutPair(i, "Number" + i); } if (!(bigArray.GetValueByKey(tableKey)).Equals(tableValue)) { throw new Exception(); } }
public void ThreeElementsTest() { //тест добавления и поиска трех элементов var threeElementsTable = new HashClass(); int size = 3; threeElementsTable.HashTableCreate(size); threeElementsTable.PutPair(1905, "Челси"); threeElementsTable.PutPair(1911, "ЦСКА"); threeElementsTable.PutPair(1930, "Урал"); var arrayKeys = new object[] { 1905, 1911, 1930 }; var arrayValues = new object[] { "Челси", "ЦСКА", "Урал" }; for (int i = 0; i < size; i++) { if (!(threeElementsTable.GetValueByKey(arrayKeys[i])).Equals(arrayValues[i])) { throw new Exception(); } } }
private void btReg_Click(object sender, RoutedEventArgs e) { List <TextBox> tb = new List <TextBox>() { tbFam, tbIm, tbOtch, tbdate_Rojd, tbSer_Pas, tbNum_Pas, tbLogin }; ArrayList field = new ArrayList() { DBNull.Value }; Procedure_CLass procedureCLass = new Procedure_CLass(); foreach (TextBox textBox in tb) { field.Add(textBox.Text); } HashClass hashClass = new HashClass(); if (tbPassword.Password == tbConfPassword.Password) { field.Add(hashClass.HashPassword(tbPassword.Password)); } else { MessageBox.Show("Не совпадают пароли!!!", "ИНЖПРОМТОРГ", MessageBoxButton.OK, MessageBoxImage.Warning); return; } field.Add(DBNull.Value); field.Add(DBNull.Value); procedureCLass.procedure_Execution("Sotrudniki_IU", field); MainWindow mainWindow = new MainWindow(); mainWindow.Show(); Visibility = Visibility.Collapsed; }
private void ButtonSavePassChange_OnClick(object sender, RoutedEventArgs e) { CheckPassAndLogin check = new CheckPassAndLogin(); if (check.ChceckPassEqals(Pass11TB.Text, Pass22TB.Text) && check.ChceckPassNumeric(Pass11TB.Text) && check.CheckPassLength(Pass11TB.Text)) { CaffeDataContext db = new CaffeDataContext(); HashClass hash = new HashClass(); User u = db.Users.FirstOrDefault(s => s.Id_user == userID); u.Password = hash.GetHashString(Pass11TB.Text); db.SubmitChanges(); MessageBox.Show("Zapisano zmieny !!!"); Pass11TB.Text = ""; Pass22TB.Text = ""; } else { MessageBox.Show("Nieprawidłowe dane !"); } }
private void ButtonLoginClick(object sender, RoutedEventArgs e) { HashClass hs = new HashClass(); CaffeDataContext db = new CaffeDataContext(); User user = db.Users.FirstOrDefault(s => s.Password.Equals(hs.GetHashString(_loginString))); if (user == null) { MessageBox.Show("Nieprawidłowe dane logowania !"); _loginString = ""; } else if (user.Name.Equals("Admin")) { AdminWindow aw = new AdminWindow(); this.Close(); aw.Show(); } else { AllOrdersWindow allOrdersWindow = new AllOrdersWindow(user); this.Close(); allOrdersWindow.Show(); } }
private void btEnter_Click(object sender, RoutedEventArgs e) { string Login = tbLogin.Text; string Password = tbPassword.Password; Table_Class @class = new Table_Class($"select ID_Sotrudnika, Sotrudnika_Password from Sotrudniki where Sotrudnika_Login = '******' "); try { if (@class.table.Rows[0][0] != DBNull.Value) { HashClass hashClass = new HashClass(); bool Proverka = hashClass.VerifyHashedPassword(@class.table.Rows[0][1].ToString(), Password); if (Proverka) { Table_Class tableClass = new Table_Class($"select dbo.Auth('{Login}','{@class.table.Rows[0][1]}')"); string Acess = tableClass.table.Rows[0][0].ToString(); App.intID = @class.table.Rows[0][0].ToString(); MessageBox.Show("Vse zbs", "ИНЖПРОМТОРГ", MessageBoxButton.OK, MessageBoxImage.Warning); } else { MessageBox.Show("Не правильно введен логин или пароль!!!", "ИНЖПРОМТОРГ", MessageBoxButton.OK, MessageBoxImage.Warning); tbPassword.Password = ""; } } } catch { MessageBox.Show("Не правильно введен логин или пароль!!!", "ИНЖПРОМТОРГ", MessageBoxButton.OK, MessageBoxImage.Warning); tbPassword.Password = ""; } }
public async Task <IActionResult> ForgotPasswordChange(ForgotPasswordModel model) { try { var user = await db.Users.FindAsync(model.UserId); if (user == null) { return(new NotFoundObjectResult(new { msg = "Пользователя с указанным id не существует" })); } if (user.VerifyCode != model.VerifyCode) { return(new NotFoundObjectResult(new { msg = "Неверный код верификации" })); } user.Password = HashClass.GetHash(model.Password); await db.SaveChangesAsync(); return(new OkResult()); } catch { return(new StatusCodeResult(500)); } }
public async Task <IActionResult> ChangeUserPassword(ChangePasswordModel model, int userId) { try { var user = await db.Users.FindAsync(userId); if (user == null) { return(new NotFoundResult()); } if (user.Password != HashClass.GetHash(model.OldPassword)) { return(new ForbidResult()); } user.Password = HashClass.GetHash(model.NewPassword); await db.SaveChangesAsync(); return(new OkResult()); } catch { return(new StatusCodeResult(500)); } }
public void LogIn(string login, string password) { waiterUserContext = _waiterDataAccess.LogIn(login, HashClass.CreateFirstHash(password, login)); }
public async Task <User> GetUserByNameEmail(AuthModel model) { return(await db.Users.Where(u => (u.Login == model.Login || u.Mail == model.Login) && u.Password == HashClass.GetHash(model.Password)).FirstOrDefaultAsync()); }
public void Login(string login, string password) { _userContext = _clientDataAccess.LogIn(login, HashClass.CreateFirstHash(password, login)); }
public void AddClient(string firstName, string lastName, string login, string password) { _clientDataAccess.AddClient(firstName, lastName, login, HashClass.CreateFirstHash(password, login)); }
public async Task <IActionResult> PostHeros([FromBody] PassedData <PassedRemoveCharacter> passedData) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } DateTime now = DateTime.UtcNow; if (passedData.UserToken == null) { return(BadRequest(new DataError("securityErr", "No authorization controll."))); } UserToken dbtoken = Security.CheckUserToken(this._context, passedData.UserToken); if (dbtoken == null) { return(BadRequest(new DataError("securityErr", "Your data has probably been stolen or modified manually. We suggest password's change."))); } else { if (!dbtoken.IsTimeValid(now)) { return(BadRequest(new DataError("timeoutErr", "You have been too long inactive. Relogin is required."))); } else { dbtoken.UpdateToken(now); } } Users user = _context.Users.FirstOrDefault(e => e.Name == dbtoken.UserName); if (user.Password != HashClass.GenHash(passedData.Data.Password)) { return(BadRequest(new DataError("passwordErr", "Password is incorrect."))); } Heros herotoremove = _context.Heros.FirstOrDefault(e => e.Name == passedData.Data.HeroName); UsersHeros conntoremove = _context.UsersHeros.FirstOrDefault(e => e.UserName == dbtoken.UserName && e.HeroId == herotoremove.HeroId); var tokentoremove = _context.ActionToken.Where(e => e.HeroId == herotoremove.HeroId); var locationstoremove = _context.HerosLocations.Where(e => e.HeroId == herotoremove.HeroId); var travelingtoremove = _context.Traveling.Where(e => e.HeroId == herotoremove.HeroId); var equipmenttoremove = _context.Equipment.Where(e => e.HeroId == herotoremove.HeroId); var backpacktoremove = _context.Backpack.Where(e => e.HeroId == herotoremove.HeroId); var healingremove = _context.Healing.Where(e => e.HeroId == herotoremove.HeroId); var fightingremove = _context.Fighting.Where(e => e.HeroId == herotoremove.HeroId); // TODO: remove other features if (tokentoremove.Count() > 0) { _context.ActionToken.RemoveRange(tokentoremove); } if (locationstoremove.Count() > 0) { _context.HerosLocations.RemoveRange(locationstoremove); } if (travelingtoremove.Count() > 0) { _context.Traveling.RemoveRange(travelingtoremove); } if (equipmenttoremove.Count() > 0) { _context.Equipment.RemoveRange(equipmenttoremove); } if (backpacktoremove.Count() > 0) { _context.Backpack.RemoveRange(backpacktoremove); } if (healingremove.Count() > 0) { _context.Healing.RemoveRange(healingremove); } if (fightingremove.Count() > 0) { _context.Fighting.RemoveRange(fightingremove); } _context.Heros.Remove(herotoremove); _context.UsersHeros.Remove(conntoremove); try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { return(BadRequest(new DataError("serverErr", "Failed to remove hero."))); } return(Ok(new { success = true, removedHero = herotoremove.Name })); }