public async Task <ActionResult> ResetPassword(ResetPasswordViewModel model) { try { if (!ModelState.IsValid) { return(View(model)); } Int64 UserId = model.userCode.DecryptID(); var user = await UserManager.FindByIdAsync(UserId); if (user == null) { // Don't reveal that the user does not exist return(RedirectToAction("ResetPasswordConfirmation", "Account")); } //check here if password exist b4 if (HasNewPasswordBeenUsedRecently(user.Id, model.Password)) { //return false; ModelState.AddModelError("A previous password can't be used as your new password", "Kindly provide a new password this password "); return(View(model)); } else { var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password); if (result.Succeeded) { ApplicationUserPasswordHistory passwordModel = new ApplicationUserPasswordHistory(); passwordModel.UserId = user.Id; passwordModel.DateCreated = DateTime.Now; passwordModel.HashPassword = ExtentionUtility.Encrypt(model.Password); _passwordCommand.Insert(passwordModel); _passwordCommand.SaveChanges(); ApplicationUser xmodel = UserManager.FindById(user.Id); xmodel.IsFirstLogin = false; UserManager.Update(xmodel); return(RedirectToAction("ResetPasswordConfirmation", "Account")); } AddErrors(result); return(View()); } } catch (Exception ex) { _log.Error(ex); return(View("Error")); } }
public async Task <ActionResult> SetFirstlogin(SetFirstPasswordViewModel model) { try { if (!ModelState.IsValid) { return(View(model)); } long UserId = model.code.DecryptID(); if (HasNewPasswordBeenUsedRecently(UserId, model.Password)) { //return false; ModelState.AddModelError("A previous password can't be used as your new password", "Kindly provide a new password this password "); return(View(model)); } else { // string code = await _userManager.GeneratePasswordResetTokenAsync(UserId); // var result = await _userManager.ResetPasswordAsync(UserId,code, model.Password); var result = await _userManager.ChangePasswordAsync(UserId, "Password", model.Password); if (result.Succeeded) { ApplicationUserPasswordHistory passwordModel = new ApplicationUserPasswordHistory(); passwordModel.UserId = UserId; passwordModel.DateCreated = DateTime.Now; passwordModel.HashPassword = ExtentionUtility.Encrypt(model.Password); _passwordCommand.Insert(passwordModel); _passwordCommand.SaveChanges(); ApplicationUser xmodel = _userManager.FindById(UserId); xmodel.IsFirstLogin = false; _userManager.Update(xmodel); return(RedirectToAction("SetPasswordConfirmation", "Account")); } AddErrors(result); } return(View(model)); } catch (Exception ex) { _log.Error(ex); return(View("Error")); } }
public async Task <IActionResult> ChangePassword(changepasswordViewModel model) { if (!ModelState.IsValid) { return(PartialView(model)); } //how to get login User in asp.net core //First //ClaimsPrincipal currentUser = this.User; //var currentUserID = currentUser.FindFirst(ClaimTypes.NameIdentifier).Value; ////second //var userId = long.Parse(_userManager.GetUserId(HttpContext.User)); //ApplicationUser usermodel = _userManager.Users.FirstOrDefault(m => m.Id == userId); //third var user = await _userManager.GetUserAsync(User); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.Password); if (result.Succeeded) { ApplicationUserPasswordHistory passwordModel = new ApplicationUserPasswordHistory(); passwordModel.UserId = user.Id; passwordModel.DateCreated = DateTime.Now; //passwordModel.HashPassword = ""; //_passwordCommand.Insert(passwordModel); //_passwordCommand.SaveChanges(); TempData["MESSAGE"] = "Password change successfully"; // return RedirectToAction("ChangePassword"); ModelState.Clear(); return(Json(new { success = true })); } AddErrors(result); return(PartialView(model)); }
public void OrganizationManagementService_OpenOrganization() { ApplicationDbContext applicationDb = new ApplicationDbContext(); IdentityDbContext identityDb = new IdentityDbContext(); applicationDb.Database.CreateIfNotExists(); identityDb.Database.CreateIfNotExists(); RegisterOrganizationViewModel model = new RegisterOrganizationViewModel() { FullName = "TestCompany_01", IdentificationNumber = "22222222", OrganizationType = "ТОО", CeoFirstName = "TestCeo", CeoLastName = "TestCeo", CeoEmail = "*****@*****.**", CeoDoB = new DateTime(1985, 3, 9), Password = "******", PasswordConfirm = "test111" }; OrganizationManagementService sut = new OrganizationManagementService(); sut.OpenOrganization(model); Organization org = applicationDb.Organizations .SingleOrDefault(p => p.FullName == "TestCompany_01" && p.IdentificationNumber == "22222222"); Employee emp = applicationDb.Employees.SingleOrDefault(p => p.FirstName == "TestCeo" && p.LastName == "TestCeo"); ApplicationUser user = identityDb.ApplicationUsers.SingleOrDefault(p => p.Email == "*****@*****.**"); ApplicationUserPasswordHistory userPasswordHistory = identityDb.ApplicationUserPasswordHistories .SingleOrDefault(p => p.ApplicationUserId == user.Id && p.Password == "test111"); ApplicationUserSignInHistory userSignInHistory = identityDb.ApplicationUserSignInHistories .SingleOrDefault(p => p.ApplicationUserId == user.Id); Assert.IsNotNull(org); Assert.IsNotNull(emp); Assert.IsNotNull(user); Assert.IsNotNull(userPasswordHistory); Assert.IsNotNull(userSignInHistory); }
public async Task <ActionResult> ChangePassword(ChangePasswordViewModel model) { CreateViewBagParams(); if (!ModelState.IsValid) { return(PartialView(model)); } long UserId = User.Identity.GetUserId <Int64>(); if (HasNewPasswordBeenUsedRecently(UserId, model.NewPassword)) { ModelState.AddModelError("A previous password can't be used as your new password", "Kindly provide a new password this password "); ViewBag.ErrMsg = "A previous password can't be used as your new password, Kindly provide a new password this password "; return(PartialView(model)); } else { var result = await UserManager.ChangePasswordAsync(UserId, model.OldPassword, model.NewPassword); if (result.Succeeded) { ApplicationUserPasswordHistory passwordModel = new ApplicationUserPasswordHistory(); passwordModel.UserId = UserId; passwordModel.DateCreated = DateTime.Now; passwordModel.HashPassword = ExtentionUtility.Encrypt(model.NewPassword); _passwordCommand.Insert(passwordModel); _passwordCommand.SaveChanges(); TempData["MESSAGE"] = "Password change successfully"; ModelState.Clear(); return(Json(new { success = true })); } else { AddErrors(result); return(PartialView(model)); } } }
public async Task <ActionResult> Create(UserViewModel model) { string code = string.Empty; model.Roles = _utility.GetRoles(); try { CreateViewBagParams(); if (ModelState.IsValid) { //checking if emailaddress does not exist b4 var organizerAdminEmailExist = _applicationUserQuery.GetAllList(m => m.Email.ToLower().Trim() == model.Email.ToLower().Trim()).ToList(); if (organizerAdminEmailExist.Any()) { ModelState.AddModelError("", "email address already exist"); return(PartialView("_PartialAddEdit", model)); } //checking if username does not exist b4 var organizerAdminUsernameExist = _applicationUserQuery.GetAllList(m => m.UserName.ToLower().Trim() == model.UserName.ToLower().Trim()).ToList(); if (organizerAdminUsernameExist.Any()) { ModelState.AddModelError("", "username already exist"); return(PartialView("_PartialAddEdit", model)); } ApplicationUser usermodel = UserViewModel.ModeltoEntity(model); var result = await UserManager.CreateAsync(usermodel, "Password"); if (result.Succeeded) { _activityRepo.CreateActivityLog(string.Format("Assinging User Id:{0} with Name :{1} to role Id's:{2}", usermodel.Id, (usermodel.LastName + " " + usermodel.FirstName), model.SelectedRole), this.GetContollerName(), this.GetContollerName(), usermodel.Id, null); ApplicationUserPasswordHistory passwordModel = new ApplicationUserPasswordHistory(); passwordModel.UserId = usermodel.Id; passwordModel.DateCreated = DateTime.Now; passwordModel.HashPassword = ExtentionUtility.Encrypt("Password"); passwordModel.CreatedBy = usermodel.Id; _applicationUserPwdhistoryCommand.Insert(passwordModel); _applicationUserPwdhistoryCommand.Save(); var addRoleResult = await UserManager.AddToRolesAsync(usermodel.Id, model.SelectedRole.ToArray <string>()); if (addRoleResult.Succeeded) { //send user reset mail code = await UserManager.GeneratePasswordResetTokenAsync(usermodel.Id); string portalUrl = System.Web.HttpContext.Current.Request.Url.Scheme + "://" + System.Web.HttpContext.Current.Request.Url.Authority + System.Web.HttpContext.Current.Request.ApplicationPath.TrimEnd('/') + "/"; var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = usermodel.Id, code = code }); string mPre = portalUrl + callbackUrl; _log.Info(string.Format("Reset URL:{0}", mPre)); if (!String.IsNullOrEmpty(usermodel.Email)) { try { _utility.SendWelcomeAndPasswordResetEmail(usermodel, mPre); } catch { } } TempData["MESSAGE"] = "Portal User " + (usermodel.LastName + " " + usermodel.FirstName) + " was successfully created"; ModelState.Clear(); return(Json(new { success = true })); } } else { ModelState.AddModelError("", result.Errors.FirstOrDefault().ToString()); } ModelState.Clear(); return(Json(new { success = true })); } else { StringBuilder errorMsg = new StringBuilder(); foreach (var modelError in ModelState.Values.SelectMany(modelState => modelState.Errors)) { errorMsg.AppendLine(modelError.ErrorMessage); ModelState.AddModelError(string.Empty, modelError.ErrorMessage); } ViewBag.ErrMsg = errorMsg.ToString(); return(PartialView("_PartialAddEdit", model)); } } catch (Exception exp) { _log.Error(exp); //return View("Error"); StringBuilder errorMsg = new StringBuilder(); foreach (var modelError in ModelState.Values.SelectMany(modelState => modelState.Errors)) { errorMsg.AppendLine(modelError.ErrorMessage); ModelState.AddModelError(string.Empty, modelError.ErrorMessage); } ViewBag.ErrMsg = errorMsg.ToString(); return(PartialView("_PartialAddEdit", model)); } }
public async Task <ActionResult> FramewokAdmin(FrameworkSetupViewModel model, string nextButton, string backButton) { string msg; if (backButton != null) { return(RedirectToAction("FrameworkSetting")); } if (nextButton != null) { if (!ModelState.IsValid) { return(View(model)); } if (string.Compare(model.AdminUserSetting.Password, model.AdminUserSetting.ConfirmPassword, StringComparison.InvariantCultureIgnoreCase) != 0) { ViewBag.ErrMsg = "Password and confirm password must be equal"; // ModelState.AddModelError("","Password and confirm password must be equal"); return(View(model)); } var roleIndb = _applicationRoleQuery.GetAllList(); if (_userManager.Users.ToList().Any()) { var adminusermodel = _userManager.Users.ToList().FirstOrDefault(); var tokencode = await _userManager.GeneratePasswordResetTokenAsync(adminusermodel); var result = await _userManager.ResetPasswordAsync(adminusermodel, tokencode, model.AdminUserSetting.Password); if (result.Succeeded) { ApplicationUserPasswordHistory passwordModel = new ApplicationUserPasswordHistory(); passwordModel.UserId = adminusermodel.Id; passwordModel.DateCreated = DateTime.Now; passwordModel.HashPassword = ""; //ExtensionUtility.Encrypt(model.AdminUserSetting.Password); passwordModel.CreatedBy = adminusermodel.Id; _applicationUserPwdhistoryCommand.Insert(passwordModel); _applicationUserPwdhistoryCommand.Save(); var addRoleResult = await _userManager.AddToRoleAsync(adminusermodel, "PortalAdmin"); if (addRoleResult.Succeeded) { Application applicationmodel = _applicationQuery.GetAll().FirstOrDefault(); applicationmodel.HasAdminUserConfigured = true; _applicationCommand.Update(applicationmodel); _applicationCommand.SaveChanges(); return(RedirectToAction("Login", "Account")); } } else { ModelState.AddModelError("", result.Errors.FirstOrDefault().ToString()); } } else { var usermodel = new ApplicationUser { FirstName = model.AdminUserSetting.FirstName, LastName = model.AdminUserSetting.LastName, MiddleName = model.AdminUserSetting.MiddleName, UserName = model.AdminUserSetting.UserName, Email = model.AdminUserSetting.Email, MobileNumber = model.AdminUserSetting.MobileNumber, PhoneNumber = model.AdminUserSetting.PhoneNumber, EmailConfirmed = true, PhoneNumberConfirmed = true, TwoFactorEnabled = false, LockoutEnabled = false, AccessFailedCount = 0, DateCreated = DateTime.Now, IsFirstLogin = false }; var result = await _userManager.CreateAsync(usermodel, model.AdminUserSetting.Password); if (result.Succeeded) { ApplicationUserPasswordHistory passwordModel = new ApplicationUserPasswordHistory(); passwordModel.UserId = usermodel.Id; passwordModel.DateCreated = DateTime.Now; passwordModel.HashPassword = ""; //ExtensionUtility.Encrypt(model.AdminUserSetting.Password); passwordModel.CreatedBy = usermodel.Id; _applicationUserPwdhistoryCommand.Insert(passwordModel); _applicationUserPwdhistoryCommand.Save(); var addRoleResult = await _userManager.AddToRoleAsync(usermodel, "PortalAdmin"); if (addRoleResult.Succeeded) { Application applicationmodel = _applicationQuery.GetAll().FirstOrDefault(); applicationmodel.HasAdminUserConfigured = true; _applicationCommand.Update(applicationmodel); _applicationCommand.SaveChanges(); return(RedirectToAction("Login", "Account")); } } else { ModelState.AddModelError("", result.Errors.FirstOrDefault().ToString()); } } return(View(_setupContract)); } var user = _userManager.Users.ToList().FirstOrDefault(); var userInfo = _mapper.Map <AdminUserSettingViewModel>(user); if (userInfo == null) { //ModelState.AddModelError("", "Unable to initialize admin user information due to internal error! Please try again later"); return(View(_setupContract)); } _setupContract.AdminUserSetting = userInfo; return(View(_setupContract)); }
public void ChangeUserPassword(ChangePasswordVm model) { var userExists = _identityDbContext.ApplicationUsers.SingleOrDefault(p => p.Email == model.UserEmail); if (userExists == null) { throw new Exception("Пользователь с таким мэйлом отсутствует в системе"); } var passwordCheck = _identityDbContext.ApplicationUserPasswordHistories .Where(p => p.Password == model.UserPassword && p.ApplicationUserId == userExists.Id) .OrderByDescending(p => p.SetupDate).Take(1); if (passwordCheck == null) { throw new Exception("Неправильный пароль"); } var userPasswordHistory = _identityDbContext.ApplicationUserPasswordHistories .Where(p => p.ApplicationUser.Email == model.UserEmail).OrderByDescending(p => p.SetupDate).Take(5); bool passwordValidationCheck = true; foreach (var item in userPasswordHistory) { if (item.Password == model.UserNewPassword) { passwordValidationCheck = false; } } if (!passwordValidationCheck) { throw new Exception("Данный пароль уже использовался выберите другой"); } if (model.UserNewPassword != model.UserNewPasswordConfirmed) { throw new Exception("Новый пароль не соответствует подтвержденному"); } ApplicationUserPasswordHistory ApplicationUserPasswordHistory = new ApplicationUserPasswordHistory() { ApplicationUserId = userExists.Id, Password = model.UserNewPassword, SetupDate = DateTime.Now, InvalidatedDate = DateTime.Now.AddMonths(3) }; _identityDbContext.ApplicationUserPasswordHistories.Add(ApplicationUserPasswordHistory); var userIsActive = _identityDbContext.ApplicationUsers.SingleOrDefault(p => p.Email == model.UserEmail && p.IsActive == false); if (userIsActive != null) { userIsActive.IsActive = true; } _identityDbContext.SaveChanges(); }
public void OpenOrganization(RegisterOrganizationViewModel model) { var geoLocationInfo = GeoLocationInfo.GetGeolocationInfo(); if (model == null) { throw new Exception($"{typeof(RegisterOrganizationViewModel).Name} is null"); } var checkOrganization = _applicationDbContext.Organizations .SingleOrDefault(p => p.IdentificationNumber == model.IdentificationNumber || p.FullName == model.FullName); if (checkOrganization != null) { throw new Exception("Такая организация уже сущуствует в базе"); } var checkOrganizationType = _applicationDbContext.OrganizationTypes .SingleOrDefault(p => p.Name == model.OrganizationType); if (checkOrganizationType == null) { OrganizationType orgType = new OrganizationType() { Id = Guid.NewGuid(), Name = model.OrganizationType }; _applicationDbContext.OrganizationTypes.Add(orgType); _applicationDbContext.SaveChanges(); checkOrganizationType = orgType; } Organization organization = new Organization() { Id = Guid.NewGuid(), FullName = model.FullName, IdentificationNumber = model.IdentificationNumber, RegistrationDate = DateTime.Now, OrganizationTypeId = checkOrganizationType.Id }; _applicationDbContext.Organizations.Add(organization); _applicationDbContext.SaveChanges(); var checkEmployeeEmail = _applicationDbContext.Employees.Any(p => p.Email == model.CeoEmail); if (!checkEmployeeEmail) { var ceoPosition = _applicationDbContext.EmployeePositions.SingleOrDefault(p => p.Name == "CEO"); if (ceoPosition == null) { EmployeePosition pos = new EmployeePosition() { Id = Guid.NewGuid(), Name = "CEO" }; _applicationDbContext.EmployeePositions.Add(pos); _applicationDbContext.SaveChanges(); ceoPosition = pos; } Employee employee = new Employee() { Id = Guid.NewGuid(), FirstName = model.CeoFirstName, LastName = model.CeoLastName, DoB = model.CeoDoB, Email = model.CeoEmail, EmployeePositionId = new Guid(ceoPosition.Id.ToString()), OrganizationId = organization.Id }; _applicationDbContext.Employees.Add(employee); _applicationDbContext.SaveChanges(); ApplicationUser user = new ApplicationUser() { Id = Guid.NewGuid(), Email = model.CeoEmail, IsActive = true, FailedSignInCount = 0, CreatedDate = DateTime.Now, AssosiatedEmployeeId = employee.Id }; _identityDbContext.ApplicationUsers.Add(user); _identityDbContext.SaveChanges(); ApplicationUserPasswordHistory userPasswordHistory = new ApplicationUserPasswordHistory() { Id = Guid.NewGuid(), SetupDate = DateTime.Now, Password = model.Password, ApplicationUserId = user.Id }; _identityDbContext.ApplicationUserPasswordHistories.Add(userPasswordHistory); _identityDbContext.SaveChanges(); ApplicationUserSignInHistory userSignInHistory = new ApplicationUserSignInHistory() { Id = Guid.NewGuid(), SignInTime = DateTime.Now, MachineIp = geoLocationInfo.ip, IpToGeoCountry = geoLocationInfo.country_name, IpToGeoCity = geoLocationInfo.city, IpToGeoLatitude = geoLocationInfo.latitude, IpToGeoLongitude = geoLocationInfo.longitude, ApplicationUserId = user.Id }; _identityDbContext.ApplicationUserSignInHistories.Add(userSignInHistory); _identityDbContext.SaveChanges(); } }
public void EditEmployeeInfo(EmployeeInfoViewModel model) { var employee = _applicationDbContext.Employees.SingleOrDefault(p => p.Id.ToString() == model.EmployeeId); if (employee == null) { throw new Exception($"Работника с id {model.EmployeeId} в базе нет"); } var position = _applicationDbContext.EmployeePositions.SingleOrDefault(p => p.Name == model.PositionName); if (position == null) { EmployeePosition pos = new EmployeePosition() { Id = Guid.NewGuid(), Name = model.PositionName }; _applicationDbContext.EmployeePositions.Add(pos); _applicationDbContext.SaveChanges(); position = pos; } var oldEmail = employee.Email; employee.FirstName = model.FirstName; employee.LastName = model.LastName; employee.DoB = model.DoB; employee.Email = model.Email; employee.EmployeePositionId = position.Id; _applicationDbContext.SaveChanges(); var user = _identityDbContext.ApplicationUsers.Include("ApplicationUserPasswordHistories") .SingleOrDefault(p => p.AssosiatedEmployeeId.ToString() == model.EmployeeId && p.IsActive == true); var userPasswordHistory = user.ApplicationUserPasswordHistories .SingleOrDefault(p => p.InvalidatedDate == null); if (oldEmail != model.Email) { user.IsActive = false; userPasswordHistory.InvalidatedDate = DateTime.Now; _identityDbContext.SaveChanges(); ApplicationUser newUser = new ApplicationUser() { Id = Guid.NewGuid(), Email = model.Email, IsActive = true, FailedSignInCount = 0, CreatedDate = DateTime.Now, AssosiatedEmployeeId = employee.Id }; _identityDbContext.ApplicationUsers.Add(newUser); _identityDbContext.SaveChanges(); ApplicationUserPasswordHistory newUserPasswordHistory = new ApplicationUserPasswordHistory() { Id = Guid.NewGuid(), SetupDate = DateTime.Now, Password = model.Password, ApplicationUserId = newUser.Id }; _identityDbContext.ApplicationUserPasswordHistories.Add(newUserPasswordHistory); _identityDbContext.SaveChanges(); } else { if (userPasswordHistory.Password != model.Password) { userPasswordHistory.InvalidatedDate = DateTime.Now; _identityDbContext.SaveChanges(); ApplicationUserPasswordHistory userNewPasswordHistory = new ApplicationUserPasswordHistory() { Id = Guid.NewGuid(), SetupDate = DateTime.Now, Password = model.Password, ApplicationUserId = user.Id }; _identityDbContext.ApplicationUserPasswordHistories.Add(userNewPasswordHistory); _identityDbContext.SaveChanges(); } } }
public void CreateEmployeeByCeo(EmployeeInfoViewModel model, Guid ceoId) { var employee = _applicationDbContext.Employees.SingleOrDefault(p => p.Id == ceoId); if (employee == null) { throw new Exception($"Работника с id {ceoId} в базе нет"); } var ceo = _applicationDbContext.EmployeePositions.SingleOrDefault(p => p.Name == "CEO"); if (ceo == null) { EmployeePosition pos = new EmployeePosition() { Id = Guid.NewGuid(), Name = "CEO" }; _applicationDbContext.EmployeePositions.Add(pos); _applicationDbContext.SaveChanges(); ceo = pos; } if (employee.EmployeePositionId != ceo.Id) { throw new Exception($"Работник с id {ceoId} не может создавать аккаунты других сотрудников компании"); } var position = _applicationDbContext.EmployeePositions.SingleOrDefault(p => p.Name == model.PositionName); if (position == null) { EmployeePosition pos = new EmployeePosition() { Id = Guid.NewGuid(), Name = model.PositionName }; _applicationDbContext.EmployeePositions.Add(pos); _applicationDbContext.SaveChanges(); position = pos; } Employee newEmployee = new Employee() { Id = Guid.NewGuid(), FirstName = model.FirstName, LastName = model.LastName, DoB = model.DoB, Email = model.Email, EmployeePositionId = position.Id, OrganizationId = employee.OrganizationId }; _applicationDbContext.Employees.Add(newEmployee); _applicationDbContext.SaveChanges(); ApplicationUser user = new ApplicationUser() { Id = Guid.NewGuid(), Email = model.Email, IsActive = true, FailedSignInCount = 0, CreatedDate = DateTime.Now, AssosiatedEmployeeId = newEmployee.Id }; _identityDbContext.ApplicationUsers.Add(user); _identityDbContext.SaveChanges(); ApplicationUserPasswordHistory userPasswordHistory = new ApplicationUserPasswordHistory() { Id = Guid.NewGuid(), SetupDate = DateTime.Now, Password = model.Password, ApplicationUserId = user.Id }; _identityDbContext.ApplicationUserPasswordHistories.Add(userPasswordHistory); _identityDbContext.SaveChanges(); }
public void OpenOrganization(OpenOrganizationRequestVm model) { if (model == null) { throw new ArgumentNullException($"{typeof(OpenOrganizationRequestVm).Name} is null"); } var checkOrganization = /*(from o in _aplicationDbContext.Organizations * where o.IdentificationNumber == model.IdentificationNumber || * o.FullName == model.FullName * select o).ToList(); */ _aplicationDbContext.Organizations .SingleOrDefault(p => p.IdentificationNumber == model.IdentificationNumber || p.FullName == model.FullName); if (checkOrganization != null) { throw new Exception("Такая организация уже существует в базе"); } var checkOrganizationType = _aplicationDbContext.OrganizationTypes .SingleOrDefault(p => p.Name == model.OrganizationType); if (checkOrganizationType == null) { throw new Exception("Организационно-правовая форма организации не корректна"); } var Position = _aplicationDbContext.EmployeePositions.SingleOrDefault(p => p.PositionName == "Director"); if (Position == null) { throw new Exception("Данной должности не имеется в списке должностей"); } var UserExists = _identityDbContext.ApplicationUsers.SingleOrDefault(p => p.Email == model.DirectorEmail); if (UserExists != null) { throw new Exception("Пользователь с данным мэйлом уже существует"); } Organization organization = new Organization() { FullName = model.FullName, IdentificationNumber = model.IdentificationNumber, RegistrationDate = DateTime.Now, OrganizationTypeId = checkOrganizationType.Id, OrganizationEmail = model.OrganizationEmail, PhoneNumber = model.PhoneNumber, LinkToWebsite = model.LinkToWebsite, Address = model.Address, }; _aplicationDbContext.Organizations.Add(organization); _aplicationDbContext.SaveChanges(); Employee employee = new Employee() { FirstName = model.DirectorFirstName, LastName = model.DirectorLastName, DoB = model.DirectorDoB, Email = model.DirectorEmail, EmployeePositionId = Position.Id, OrganizationId = organization.Id }; _aplicationDbContext.Employees.Add(employee); _aplicationDbContext.SaveChanges(); ApplicationUser user = new ApplicationUser() { Email = model.DirectorEmail, IsActive = true, FailedSignInCount = 0, CreatedDate = DateTime.Now, AssosiatedEmployeeId = employee.Id }; _identityDbContext.ApplicationUsers.Add(user); _identityDbContext.SaveChanges(); ApplicationUserPasswordHistory userPasswordHistory = new ApplicationUserPasswordHistory() { SetupDate = DateTime.Now, InvalidatedDate = DateTime.Now.AddMonths(3), Password = model.Password, ApplicationUserId = user.Id }; _identityDbContext.ApplicationUserPasswordHistories.Add(userPasswordHistory); _identityDbContext.SaveChanges(); var geoLocationInfo = GeoLocationInfo.GetGeolocationInfo(); ApplicationUserSignInHistory userSignInHistory = new ApplicationUserSignInHistory() { SignInTime = DateTime.Now, MachineIp = geoLocationInfo.ip, IpToGeoCountry = geoLocationInfo.country_name, IpToGeoCity = geoLocationInfo.city, IpToGeoLatitude = geoLocationInfo.latitude, IpToGeoLongitude = geoLocationInfo.longitude, ApplicationUserId = user.Id }; _identityDbContext.ApplicationUserSignInHistories.Add(userSignInHistory); _identityDbContext.SaveChanges(); }
public void EmployeeManagementService_CreateEmployeeByCeo() { ApplicationDbContext applicationDb = new ApplicationDbContext(); IdentityDbContext identityDb = new IdentityDbContext(); applicationDb.Database.CreateIfNotExists(); identityDb.Database.CreateIfNotExists(); OrganizationType organizationType = new OrganizationType() { Id = Guid.NewGuid(), Name = "TestTypeE_01" }; applicationDb.OrganizationTypes.Add(organizationType); applicationDb.SaveChanges(); Organization organization = new Organization() { Id = Guid.NewGuid(), FullName = "TestCompanyE_01", IdentificationNumber = "1111111", Address = "Almaty, Abai ave", Email = "*****@*****.**", Contacts = "+7777123456", Site = "test.org", RegistrationDate = DateTime.Now, OrganizationTypeId = organizationType.Id }; applicationDb.Organizations.Add(organization); applicationDb.SaveChanges(); var ceoPos = applicationDb.EmployeePositions.SingleOrDefault(p => p.Name == "CEO"); if (ceoPos == null) { EmployeePosition employeePosition = new EmployeePosition() { Id = Guid.NewGuid(), Name = "CEO" }; applicationDb.EmployeePositions.Add(employeePosition); applicationDb.SaveChanges(); ceoPos = employeePosition; } Employee ceo = new Employee() { Id = Guid.NewGuid(), FirstName = "TestECeo_01", LastName = "TestECeo_01", DoB = new DateTime(1985, 3, 4), Email = "*****@*****.**", OrganizationId = organization.Id, EmployeePositionId = ceoPos.Id }; applicationDb.Employees.Add(ceo); applicationDb.SaveChanges(); EmployeeInfoViewModel model = new EmployeeInfoViewModel() { PositionName = "TestE_Position01", FirstName = "TestEmployee_01", LastName = "TestEmployee_01", DoB = new DateTime(1983, 5, 22), Email = "*****@*****.**", Password = "******", PasswordConfirm = "ttt01qwerty123" }; EmployeeManagementService sut = new EmployeeManagementService(); var ceoId = ceo.Id; sut.CreateEmployeeByCeo(model, ceoId); Employee emp = applicationDb.Employees .SingleOrDefault(p => p.FirstName == "TestEmployee_01" && p.LastName == "TestEmployee_01"); ApplicationUser user = identityDb.ApplicationUsers.SingleOrDefault(p => p.Email == "*****@*****.**"); ApplicationUserPasswordHistory userPasswordHistory = identityDb.ApplicationUserPasswordHistories .SingleOrDefault(p => p.ApplicationUserId == user.Id && p.Password == "ttt01qwerty123"); Assert.IsNotNull(emp); Assert.IsNotNull(user); Assert.IsNotNull(userPasswordHistory); }
public void EmployeeManagementService_EditEmployeeInfo() { ApplicationDbContext applicationDb = new ApplicationDbContext(); IdentityDbContext identityDb = new IdentityDbContext(); applicationDb.Database.CreateIfNotExists(); identityDb.Database.CreateIfNotExists(); OrganizationType organizationType = new OrganizationType() { Id = Guid.NewGuid(), Name = "TestTypeE_02" }; applicationDb.OrganizationTypes.Add(organizationType); applicationDb.SaveChanges(); Organization organization = new Organization() { Id = Guid.NewGuid(), FullName = "TestCompanyE_02", RegistrationDate = DateTime.Now, OrganizationTypeId = organizationType.Id }; applicationDb.Organizations.Add(organization); applicationDb.SaveChanges(); EmployeePosition employeePosition = new EmployeePosition() { Id = Guid.NewGuid(), Name = "TestE_Position02" }; applicationDb.EmployeePositions.Add(employeePosition); applicationDb.SaveChanges(); Employee employee = new Employee() { Id = Guid.NewGuid(), FirstName = "TestEmployee_02", LastName = "TestEmployee_02", DoB = new DateTime(1983, 5, 22), Email = "*****@*****.**", EmployeePositionId = employeePosition.Id, OrganizationId = organization.Id }; applicationDb.Employees.Add(employee); applicationDb.SaveChanges(); ApplicationUser applicationUser = new ApplicationUser() { Id = Guid.NewGuid(), CreatedDate = DateTime.Now, Email = employee.Email, IsActive = true, FailedSignInCount = 0, AssosiatedEmployeeId = employee.Id }; identityDb.ApplicationUsers.Add(applicationUser); identityDb.SaveChanges(); ApplicationUserPasswordHistory applicationUserPassword = new ApplicationUserPasswordHistory() { Id = Guid.NewGuid(), SetupDate = DateTime.Now, Password = "******", ApplicationUserId = applicationUser.Id }; identityDb.ApplicationUserPasswordHistories.Add(applicationUserPassword); identityDb.SaveChanges(); EmployeeInfoViewModel model = new EmployeeInfoViewModel() { EmployeeId = employee.Id.ToString(), PositionName = "Accountant", FirstName = "AnotherTestEmployee_02", LastName = "AnotherTestEmployee_02", DoB = new DateTime(1970, 6, 18), Email = "*****@*****.**", Password = "******", PasswordConfirm = "ttt03qwerty123" }; EmployeeManagementService sut = new EmployeeManagementService(); sut.EditEmployeeInfo(model); Employee emp = applicationDb.Employees .SingleOrDefault(p => p.Id == employee.Id && p.FirstName == "AnotherTestEmployee_02" && p.LastName == "AnotherTestEmployee_02"); ApplicationUser user = identityDb.ApplicationUsers.SingleOrDefault(p => p.Email == "*****@*****.**"); ApplicationUserPasswordHistory userPasswordHistory = identityDb.ApplicationUserPasswordHistories .SingleOrDefault(p => p.ApplicationUserId == user.Id && p.Password == "ttt03qwerty123"); Assert.IsNotNull(employee); Assert.IsNotNull(user); Assert.IsNotNull(userPasswordHistory); }
public async Task <ActionResult> FramewokAdmin(string nextButton, string backButton) { string msg; if (backButton != null) { return(RedirectToAction("FrameworkSetting")); } if (nextButton != null) { if (!ModelState.IsValid) { return(View(_setupContract)); } if (string.Compare(_setupContract.AdminUserSetting.Password, _setupContract.AdminUserSetting.ConfirmPassword, StringComparison.InvariantCultureIgnoreCase) != 0) { ViewBag.ErrMsg = "Password and confirm password must be equal"; // ModelState.AddModelError("","Password and confirm password must be equal"); return(View(_setupContract)); } var user = new ApplicationUser { FirstName = _setupContract.AdminUserSetting.FirstName, LastName = _setupContract.AdminUserSetting.LastName, MiddleName = _setupContract.AdminUserSetting.MiddleName, UserName = _setupContract.AdminUserSetting.UserName, Email = _setupContract.AdminUserSetting.Email, MobileNumber = _setupContract.AdminUserSetting.MobileNumber, PhoneNumber = _setupContract.AdminUserSetting.PhoneNumber, EmailConfirmed = true, PhoneNumberConfirmed = true, TwoFactorEnabled = false, LockoutEnabled = false, AccessFailedCount = 0, DateCreated = DateTime.Now, IsFirstLogin = false }; var result = await UserManager.CreateAsync(user, _setupContract.AdminUserSetting.Password); if (result.Succeeded) { ApplicationUserPasswordHistory passwordModel = new ApplicationUserPasswordHistory(); passwordModel.UserId = user.Id; passwordModel.DateCreated = DateTime.Now; passwordModel.HashPassword = ExtentionUtility.Encrypt(_setupContract.AdminUserSetting.Password); passwordModel.CreatedBy = user.Id; _applicationUserPwdhistoryCommand.Insert(passwordModel); _applicationUserPwdhistoryCommand.Save(); var addRoleResult = await UserManager.AddToRoleAsync(user.Id, "PortalAdmin"); if (addRoleResult.Succeeded) { Application applicationmodel = _applicationQuery.GetAll().FirstOrDefault(); applicationmodel.HasAdminUserConfigured = true; _applicationCommand.Update(applicationmodel); _applicationCommand.SaveChanges(); _activityRepo.CreateActivityLog("creating Framework admin user details", this.GetContollerName(), this.GetContollerName(), _setupContract.AdminUserSetting.Id, _setupContract.AdminUserSetting); return(RedirectToAction("Login", "Account", new { area = "" })); } } else { ModelState.AddModelError("", result.Errors.FirstOrDefault().ToString()); } return(View(_setupContract)); } var userInfo = UserManager.Users.ToList().Select(AdminUserSettingViewModel.EntityToModels).FirstOrDefault(); if (userInfo == null) { //ModelState.AddModelError("", "Unable to initialize admin user information due to internal error! Please try again later"); return(View(_setupContract)); } _setupContract.AdminUserSetting = userInfo; return(View(_setupContract)); }
public async Task <ActionResult> Create(ArtistViewModel model, HttpPostedFileBase profileImage) { string code = string.Empty; string profilePath = string.Empty; try { CreateViewBagParams(); if (ModelState.IsValid) { if (profileImage != null && profileImage.ContentLength > 0) { var ext = Path.GetExtension(profileImage.FileName).Trim().ToLower(); string[] allowedExtension = new string[] { ".jpeg", ".jpg", ".png" }; if (allowedExtension.Contains(ext)) { profilePath = _utility.Upload(profileImage, _utility.GetAppSetting("AppUploadFolder")); } else { ModelState.AddModelError("", string.Format("Invalid image extension,allowed extension are: .jpeg,.jpg,.png ", allowedExtension)); //return PartialView("_PartialAddEdit", staffVm); return(View("_PartialAddEdit", model)); } } //checking if emailaddress does not exist b4 var organizerAdminEmailExist = _applicationUserQuery.GetAllList(m => m.Email.ToLower().Trim() == model.Email.ToLower().Trim()).ToList(); if (organizerAdminEmailExist.Any()) { ModelState.AddModelError("", "email address already exist"); return(PartialView("_PartialAddEdit", model)); } //checking if username does not exist b4 var organizerAdminUsernameExist = _applicationUserQuery.GetAllList(m => m.UserName.ToLower().Trim() == model.UserName.ToLower().Trim()).ToList(); if (organizerAdminUsernameExist.Any()) { ModelState.AddModelError("", "username already exist"); return(PartialView("_PartialAddEdit", model)); } ApplicationUser usermodel = ArtistViewModel.ModeltoEntity(model); usermodel.PicturePath = Path.GetFileName(profilePath); usermodel.FacebookURL = model.FacebookURL; var result = await UserManager.CreateAsync(usermodel, "Password"); if (result.Succeeded) { _activityRepo.CreateActivityLog(string.Format("Assinging User Id:{0} with Name :{1} to role Id's:{2}", usermodel.Id, (usermodel.LastName + " " + usermodel.FirstName), ""), this.GetContollerName(), this.GetContollerName(), usermodel.Id, null); ApplicationUserPasswordHistory passwordModel = new ApplicationUserPasswordHistory(); passwordModel.UserId = usermodel.Id; passwordModel.DateCreated = DateTime.Now; passwordModel.HashPassword = ExtentionUtility.Encrypt("Password"); passwordModel.CreatedBy = usermodel.Id; _applicationUserPwdhistoryCommand.Insert(passwordModel); _applicationUserPwdhistoryCommand.Save(); var addRoleResult = await UserManager.AddToRoleAsync(usermodel.Id, "Artist"); if (addRoleResult.Succeeded) { //send user reset mail code = await UserManager.GeneratePasswordResetTokenAsync(usermodel.Id); string portalUrl = System.Web.HttpContext.Current.Request.Url.Scheme + "://" + System.Web.HttpContext.Current.Request.Url.Authority + System.Web.HttpContext.Current.Request.ApplicationPath.TrimEnd('/') + "/"; var callbackUrl = Url.Action("ResetPassword", "Account", new { userCode = usermodel.Id.EncryptID(), code = code }); string mPre = portalUrl + callbackUrl; _log.Info(string.Format("Reset URL:{0}", mPre)); if (!String.IsNullOrEmpty(usermodel.Email)) { _utility.SendWelcomeAndPasswordResetEmail(usermodel, mPre); } TempData["MESSAGE"] = "Artist " + (usermodel.LastName + " " + usermodel.FirstName) + " was successfully created"; ModelState.Clear(); return(Json(new { success = true })); } } else { ModelState.AddModelError("", result.Errors.FirstOrDefault().ToString()); } ModelState.Clear(); return(Json(new { success = true })); } else { StringBuilder errorMsg = new StringBuilder(); foreach (var modelError in ModelState.Values.SelectMany(modelState => modelState.Errors)) { errorMsg.AppendLine(modelError.ErrorMessage); ModelState.AddModelError(string.Empty, modelError.ErrorMessage); } ViewBag.ErrMsg = errorMsg.ToString(); return(PartialView("_PartialAddEdit", model)); } } catch (Exception exp) { _log.Error(exp); //return View("Error"); StringBuilder errorMsg = new StringBuilder(); foreach (var modelError in ModelState.Values.SelectMany(modelState => modelState.Errors)) { errorMsg.AppendLine(modelError.ErrorMessage); ModelState.AddModelError(string.Empty, modelError.ErrorMessage); } ViewBag.ErrMsg = errorMsg.ToString(); return(PartialView("_PartialAddEdit", model)); } }