private void Reset(object obj) { var UserReset = _model.db.StaffSet.Where(i => i.Id == Id).FirstOrDefault(); if (UserReset == null) { return; } if (UserReset.secret_word == SecretWord || UserReset.secret_word == hashing.HashPassword(SecretWord)) { _model.db.StaffSet.Remove(UserReset); _model.db.SaveChanges(); UserReset.password = hashing.HashPassword(_p1); _model.db.StaffSet.Add(UserReset); _model.db.SaveChanges(); _p1 = string.Empty; _p2 = string.Empty; SecretWord = string.Empty; DelVis?.Invoke(obj, null); WpfMessageBox.Show("Изменение пароля", "Пароль успешно изменен.", MessageBoxType.Information); DelVis?.Invoke(obj, null); ResetVis = false; pwb?.ClearPassword(); } else { DelVis?.Invoke(obj, null); WpfMessageBox.Show("Изменение пароля", "Секретное слово неправильное.", MessageBoxType.Information); DelVis?.Invoke(obj, null); } }
public User GetCredentials(string login, string password) { password = HashingPassword.HashPassword(password); using (UserRepository repository = new UserRepository()) { User user = repository.Get((u => u.Login == login && u.Password == password)).FirstOrDefault(); if (user != null) { user.Password = String.Empty; return(user); } return(null); } }
public HttpResponseMessage ChangePassword([FromUri] int id, PasswordModel passwordModel) { var identity = (ClaimsIdentity)User.Identity; if (identity.Name != id.ToString()) { return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid Token")); } using (var db = new OnlineMusicEntities()) { try { var user = (from u in db.Users where u.Id == id select u).FirstOrDefault(); if (user == null) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, $"Tài khoản với id={id} không tồn tại")); } else { MemoryCacher cache = new MemoryCacher(); string cachePassword = cache.Get(user.Username) != null ? (string)cache.Get(user.Username) : String.Empty; bool isValid = HashingPassword.ValidatePassword(passwordModel.OldPassword, user.Password); if (!isValid) { // Try check cache password isValid = !String.IsNullOrEmpty(cachePassword) && HashingPassword.ValidatePassword(passwordModel.OldPassword, cachePassword); } if (!isValid) { return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Mật khẩu cũ không đúng")); } else { user.Password = HashingPassword.HashPassword(passwordModel.NewPassword); cache.Delete(user.Username); db.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK)); } } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message)); } } }
public IActionResult Register(RegisterAccountViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var res = baseRepository.ExecuteCommand(conn => conn.Query <Company>("SELECT [Id] FROM [TavanirStage].[Basic].[Companies] WHERE [Code] = @Code", new { model.Code }).ToList()); if (res?.Any() ?? false) { ModelState.AddModelError(model.Code, "کد شرکت تکراری است."); return(View(model)); } res = baseRepository.ExecuteCommand(conn => conn.Query <Company>("SELECT [Id] FROM [TavanirStage].[Basic].[Companies] WHERE [Name] = @Name", new { model.Name }).ToList()); if (res?.Any() ?? false) { ModelState.AddModelError(model.Username, "نام شرکت تکراری است."); return(View(model)); } res = baseRepository.ExecuteCommand(conn => conn.Query <Company>("SELECT [Id] FROM [TavanirStage].[Basic].[Companies] WHERE [Username] = @Username", new { model.Username }).ToList()); if (res?.Any() ?? false) { ModelState.AddModelError(model.Username, "نام کاربری تکراری است."); return(View(model)); } var passHashed = hashingPassword.HashPassword(model.Password); baseRepository.ExecuteCommand(conn => { var query = conn.Query("INSERT INTO [TavanirStage].[Basic].[Companies] ([Id], [Code], [Name], [LocationId], [Description], [Username], [Password], [PasswordHash], [PasswordSalt]) VALUES (NEWID(), @Code, @Name, @LocationId, @Description, @Username, @Password, @PasswordHash, @PasswordSalt)", new { model.Code, model.Name, model.LocationId, model.Description, model.Username, model.Password, passHashed.PasswordHash, passHashed.PasswordSalt }); }); return(Redirect("/Login/Register")); }
public HttpResponseMessage Add(HttpRequestMessage request, User user) { try { using (UserRepository rep = new UserRepository()) { user.Password = HashingPassword.HashPassword(user.Password); rep.Add(user); rep.SaveAll(); } user.Password = null; return(request.CreateResponse <User>(HttpStatusCode.OK, user)); } catch (Exception e) { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, "Não foi possível inserir usuário [" + e.Message + "]")); } }
public HttpResponseMessage Update(HttpRequestMessage request, User user, int?modifyPWd) { try { using (UserRepository rep = new UserRepository()) { if (modifyPWd != null && modifyPWd == 1) { user.Password = HashingPassword.HashPassword(user.Password); } rep.Update(user); rep.SaveAll(); } return(request.CreateResponse <User>(HttpStatusCode.Accepted, user)); } catch (Exception e) { return(request.CreateErrorResponse(HttpStatusCode.BadRequest, e.Message)); } }
public HttpResponseMessage RecoveryPassword([FromBody] UserModel user) { try { using (var db = new OnlineMusicEntities()) { var userData = (from u in db.Users where u.Username.ToLower() == user.Username.ToLower() && u.Email.ToLower() == user.Email.ToLower() select u).FirstOrDefault(); if (userData == null) { return(Request.CreateErrorResponse(HttpStatusCode.Forbidden, "Email sử dụng không trùng khớp với tài khoản")); } MemoryCacher cache = new MemoryCacher(); if (cache.Get(userData.Username) == null) { // Recovery password for user var rand = new Random(); byte[] randomBytes = Encoding.UTF8.GetBytes(rand.Next(100000, 999999).ToString()); string newPassword = Convert.ToBase64String(randomBytes); string subject = "Recovery password in Musikai"; string htmlBody = String.Format(@"<html><body> <h1>Hello, {0}</h1> <p style=""font-size: 30px"">Your temporary password is <em>{1}</em></p> <p style=""font-size: 27px"">The password is temporary and will expire within 3 days</p> <p style=""font-size: 25px""><strong>We recommend you change your own password after you login</strong></p> </body></html>", userData.Username, newPassword); if (PostEmail.Send(userData.Email, subject, htmlBody)) { newPassword = Convert.ToBase64String(Encoding.UTF8.GetBytes(newPassword)); string encryptedPassword = HashingPassword.HashPassword(newPassword); cache.Add(userData.Username, encryptedPassword, DateTimeOffset.Now.AddDays(3)); Notification notification = new Notification() { Title = "Phục hồi mật khẩu", Message = "Mật khẩu tạm thời của bạn đã được gửi tới email. Sau khi đăng nhập khuyên cáo bạn nên thay đổi mật khẩu của mình", UserId = userData.Id, IsMark = false, CreatedAt = DateTime.Now, Action = NotificationAction.RECOVERY_PASSWORD }; db.Notifications.Add(notification); db.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, "Mật khẩu khôi phục đã được gửi tới email " + userData.Email)); } else { return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } } else { return(Request.CreateResponse(HttpStatusCode.OK, "Mật khẩu phục hồi đã gửi tới email")); } } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.StackTrace)); } }
public HttpResponseMessage Register(UserLoginModel user) { if (IsUsernameExisted(user.Username)) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Tên đăng nhập đã tồn tại")); } if (IsEmailExisted(user.Email)) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Email đã được sử dụng")); } using (var db = new OnlineMusicEntities()) { using (var transaction = db.Database.BeginTransaction()) { try { var newUser = new User(); user.Password = HashingPassword.HashPassword(user.Password); user.UpdateEntity(newUser); newUser.RoleId = (int)RoleManager.User; newUser.Blocked = false; db.Users.Add(newUser); db.SaveChanges(); var userInfo = new UserInfo(); userInfo.FullName = newUser.Username; userInfo.UserId = newUser.Id; if (newUser.RoleId == (int)RoleManager.Admin) { userInfo.Avatar = Storage.GoogleDriveServices.DEFAULT_ADMIN; } else { userInfo.Avatar = Storage.GoogleDriveServices.DEFAULT_AVATAR; } db.UserInfoes.Add(userInfo); db.SaveChanges(); Notification notification = new Notification() { Title = "Chào, " + newUser.Username, Message = "Chào mừng bạn đến với ứng dụng nghe nhạc đỉnh cao Musikai\n mọi thắc mắc có thể liên hệ qua mail [email protected]", UserId = newUser.Id, IsMark = false, CreatedAt = DateTime.Now, Action = NotificationAction.REGISTER }; db.Notifications.Add(notification); db.SaveChanges(); transaction.Commit(); return(Request.CreateResponse(HttpStatusCode.Created, new UserModel { User = newUser })); } catch (SqlException ex) { transaction.Rollback(); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message)); } } } }
private async void MainWindowShow(object obj) { ILogin temp_obj = obj as ILogin; if (temp_obj == null) { return; } LoadVisible = true; _waitHandle = new AutoResetEvent(false); await Task.Run(() => { foreach (var item in _model.db.StaffSet) { if (item.login == Login && (item.password == temp_obj.GetPassword() || item.password == hashing.HashPassword(temp_obj.GetPassword()))) { Cur_session.New_session(item.Staff_PosId, item.login, item.password, item.FirstName, item.LastName, item.Staff_Pos.Position, item.phone_number); _waitHandle.Set(); break; } } _waitHandle.Set(); }); _waitHandle.WaitOne(); if (Cur_session.Id == -1) { WpfMessageBox.Show("Ошибка авторизации", "Пользователь с таким логином или паролем не найден.", 0, MessageBoxImage.Warning); LoadVisible = false; return; } if (Cur_session.Id == 1) { LoadVisible = false; _waitHandle.Close(); AdminWnd adminWnd = new AdminWnd(); adminWnd.Show(); temp_obj.Close(); } if (Cur_session.Id == 3) { LoadVisible = false; _waitHandle.Close(); WaiterWnd waiterWnd = new WaiterWnd(); waiterWnd.Show(); temp_obj.Close(); } }