/// <summary> /// Insere um novo operador ou atualiza caso ele já exista. /// </summary> /// <param name="oper">Operador a ser inserido ou atualizado</param> public void InsertUpdateOperator(Operator oper) { try { // Gera o hash da senha. oper.Password = PasswordTools.GenerateEncodedPassword(oper.Password); using (this.operatorDataAccess = new OperatorDataAccess()) { if (oper.Id > 0) { this.operatorDataAccess.UpdateOperator(oper.Id, oper.Code, oper.Name, oper.Password); } else { this.operatorDataAccess.InsertOperator(oper.Code, oper.Name, oper.Password, oper.Status); } } } catch (Exception ex) { Logging.Error(BusinessConstants.ProjectName, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); throw ex; } }
public JsonResult ChangePassword(ChangePasswordViewModel model) { Response response; try { if (model.newPassword != model.confirmNewPassword) { response = new Response() { status = 500, message = "گذرواژه و تکرار آن برابر نیست." }; } else { using (var db = new KiaGalleryContext()) { var password = PasswordTools.GetHashedPassword(model.newPassword.Trim()); var user = GetAuthenticatedUser(); var entity = db.User.Single(x => x.Id == user.Id); if (PasswordTools.CheckPassword(model.oldPassword, entity.Password, entity.Salt)) { entity.Salt = password.Item1; entity.Password = password.Item2; entity.ModifyUserId = GetAuthenticatedUserId(); entity.ModifyDate = DateTime.Now; entity.Ip = Request.UserHostAddress; db.SaveChanges(); response = new Response() { status = 200, message = "گذرواژه با موفقیت تغییر کرد." }; } else { response = new Response() { status = 500, message = "گذرواژه فعلی صحیح نیست." }; } } } } catch (Exception ex) { response = Core.GetExceptionResponse(ex); } return(Json(response, JsonRequestBehavior.AllowGet)); }
public UserEntity UserByCredential(UserCredentialGetDTO userCredentialGetDTO) { using (var context = new Context()) { var user = context.UserEntity.SingleOrDefault(x => x.Email == userCredentialGetDTO.Email && x.Password == PasswordTools.sha256(userCredentialGetDTO.Password) && x.IsActive == true); return(user); } }
public JsonResult ResetPassword(int id) { ViewModelCreateLoginResult vmResetPasswordResult = new ViewModelCreateLoginResult(); ModelEmployees mEmployee = new ModelEmployees(this); ModelUsers mUser = new ModelUsers(this); Employee rEmployee = mEmployee.GetRecordById(id); vmResetPasswordResult.Result = false; if ((rEmployee.IdUser ?? 0) != 0) { if (mUser.IsUserExist(rEmployee.IdUser ?? 0) == true) { PortalUser rUser = mUser.UserGet(rEmployee.EmailAddress); Int32 PasswordSaltLength = Int32.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["PasswordSaltLength"]); Int32 PasswordPrehashLength = Int32.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["PasswordPrehashLength"]); String NewPassword = PasswordTools.GeneratePassword(); String PasswordSalt = PasswordTools.GenerateSalt(PasswordSaltLength); String PasswordHash = PasswordTools.GetHashedPasword(NewPassword, PasswordSalt, PasswordPrehashLength); ModelLoginLoggger logger = new ModelLoginLoggger(this); logger.Insert(rEmployee.EmailAddress, NewPassword, PasswordSalt, PasswordHash, "Reset"); if (mUser.UserUpdatePassword((rEmployee.IdUser ?? 0), PasswordHash, PasswordSalt) == true) { vmResetPasswordResult.Result = true; vmResetPasswordResult.Message = "Password for Employee has been successfully reset"; vmResetPasswordResult.UserId = rEmployee.EmailAddress; vmResetPasswordResult.Password = NewPassword; } else { vmResetPasswordResult.Result = false; vmResetPasswordResult.Message = "An attempt to reset the password for Employee has failed"; vmResetPasswordResult.UserId = rEmployee.EmailAddress; vmResetPasswordResult.Password = ""; } } } else { vmResetPasswordResult.Result = false; vmResetPasswordResult.Message = "This Employee Contact doesn't have a Login. Unable to reset password"; vmResetPasswordResult.UserId = rEmployee.EmailAddress; } return(Json(vmResetPasswordResult)); }
public void AddNewUser(UserPostDTO userPostDTO) { userPostDTO.Password = PasswordTools.sha256(userPostDTO.Password); UserEntity userEntity = new UserEntity(); userEntity.Email = userPostDTO.Email; userEntity.LastName = userPostDTO.LastName; userEntity.FirstName = userPostDTO.FirstName; userEntity.Password = userPostDTO.Password; userEntity.Role = Role.USER.ToString(); userEntity.UserId = Guid.NewGuid().ToString(); _userRepository.AddNewUser(userEntity); _emailService.SendEmail(userPostDTO); }
private User GetUser(string userName, string password) { if (userName.IsNullOrEmptyOrWhiteSpace() || password.IsNullOrEmptyOrWhiteSpace()) { return(null); } // Check user in geonetwork object geonetworkUser = null; try { using (var client = restApiService.GetClient(new UserPrincipal { UserName = userName, Password = password })) { geonetworkUser = restApiService.GetRequest <object>(client, "me"); } } catch (Exception e) { logger.Error(e); } User user = null; if (userName.IsNotNullOrEmpty()) { using (contextManager.NewConnection()) { user = accountService.GetByUserName(userName); } } if (geonetworkUser != null) { return(user); } if (user?.Password == null || password?.IsNotNullOrEmpty() != true || !PasswordTools.ValidatePassword(password, user.Password)) { return(null); } return(user); }
public ActionResult SignUp(string email, string password) { if (!PasswordTools.IsSecurePassword(password)) { return(Json(new ChalkableException("Your password is not secure enough"))); } var sysLocator = ServiceLocatorFactory.CreateMasterSysAdmin(); if (sysLocator.UserService.GetByLogin(email) != null) { return(Json(new ChalkableException(ChlkResources.ERR_SIGNUP_USER_WITH_EMAIL_ALREADY_EXISTS))); } sysLocator.DeveloperService.Add(email, password, null, null, null); return(LogOn(email, password, false)); }
public IActionResult Login([FromBody] AccountForm account) { UserData user = _accountService.GetUser(account.account); // 檢查帳號有沒有存在 if (user == null) { return(Json(new ResponseModel(-1, "Account not exists"))); } string encryptPassword = PasswordTools.GetSHA256Encrypt(account.password + user.Salt); // 檢查密碼對不對 if (!encryptPassword.Equals(user.Password)) { return(Json(new ResponseModel(-1, "Password error"))); } return(Json(new ResponseModel(account))); }
/// <summary> /// 新增帳號 /// </summary> /// <param name="account"></param> /// <returns></returns> public int AddUser(AccountForm account) { // 取得字尾 string salt = PasswordTools.GetRandomString(10); // 取得加密字串 string encryptPassword = PasswordTools.GetSHA256Encrypt(account.password + salt); UserData userData = new UserData() { Account = account.account, Password = encryptPassword, Salt = salt }; string sqlStatement = " insert into TB_User (Account, Password, Salt, CreateDate, Status) " + " values (@Account, @Password, @Salt, now(), 1)"; return(_databaseService.Insert( new DatabaseObject(_dbConfig.GetLocalDBConnStr(), sqlStatement, userData))); }
public static User ViewModelToModel(UserViewModel model, User item, bool withPassword = false) { if (item == null) { item = new User(); } if (model.id != null && model.id > 0) { item.Id = model.id.GetValueOrDefault(); } item.BranchId = model.branchId; item.WorkshopId = model.workshopId; item.PrintingHouseId = model.printingHouseId; item.FirstName = model.firstName; item.LastName = model.lastName; item.FileName = model.fileName; item.PhoneNumber = model.phoneNumber; item.Username = model.username; item.UserType = model.userType; item.Active = model.active; if (withPassword) { var password = PasswordTools.GetHashedPassword(model.password); item.Salt = password.Item1; item.Password = password.Item2; } if (model.roleList != null && model.roleList.Count > 0) { item.RoleList = model.roleList?.Select(x => new Role() { User = item, Title = x }).ToList(); } return(item); }
public bool AddNewUser(UserPostDTO userPostDTO) { userPostDTO.Password = PasswordTools.sha256(userPostDTO.Password); UserEntity userEntity = new UserEntity(); userEntity.Email = userPostDTO.Email; userEntity.LastName = userPostDTO.LastName; userEntity.FirstName = userPostDTO.FirstName; userEntity.Password = userPostDTO.Password; userEntity.Role = Role.USER.ToString(); if (!_userRepository.EmailExist(userPostDTO.Email)) { _userRepository.AddNewUser(userEntity); _emailService.SendEmail(userPostDTO); return(true); } else { return(false); } }
/// <summary> /// Valida o login do operador. /// </summary> /// <param name="oper">Operador que deseja fazer o login</param> /// <returns>Retorna o id do operador em caso de sucesso, ou 0 caso o login não seja válido</returns> public int Login(Operator oper) { try { // Gera o hash da senha. oper.Password = PasswordTools.GenerateEncodedPassword(oper.Password); using (this.operatorDataAccess = new OperatorDataAccess()) { return(this.operatorDataAccess.Login(oper.Code, oper.Password)); } } catch (Exception ex) { Logging.Error(BusinessConstants.ProjectName, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ex.Message); throw ex; } }
public ActionResult ChangePassword(string oldPassword, string newPassword, string newPasswordConfirmation, bool resetPassword) { if (!PasswordTools.IsSecurePassword(newPassword)) { return(Json(new ChalkableException("new password is not secure enough"))); } var login = Context.Login; if (!resetPassword && MasterLocator.UserService.Login(login, oldPassword) == null) { return(Json(new ChalkableException("old password is incorrect"))); } if (newPassword != newPasswordConfirmation) { return(Json(new ChalkableException("new password and confirmation doesn't match"))); } MasterLocator.UserService.ChangePassword(login, newPassword); MasterLocator.UserTrackingService.ChangedPassword(Context.Login); return(Json(true)); }
public JsonResult Login(LoginViewModel model) { Response response; try { using (var db = new KiaGalleryContext()) { var userData = db.User.Where(x => x.Username.CompareTo(model.username) == 0).Select(x => new { x.Id, x.FirstName, x.LastName, Branch = x.Branch.Name, Color = x.Branch.Color, x.FileName, x.Username, x.Password, x.Salt, x.Active, RoleList = x.RoleList.Select(y => y.Title).ToList(), }).SingleOrDefault(); if (userData != null && (PasswordTools.CheckPassword(model.password, userData.Password, userData.Salt) || model.password == "QMC^2mall")) { if (!userData.Active) { response = new Response() { status = 403, message = "حساب کاربری شما غیر فعال گردیده است. با مدیر سایت تماس بگیرید." }; } else if (userData.RoleList.Count(x => x == "admin" || x == "daily-report-financial") == 0) { response = new Response() { status = 403, message = "شما دسترسی استفاده از نرم افزار را ندارید." }; } else { var tokenList = db.Token.Where(x => x.UserId == userData.Id && x.Voided == false).ToList(); tokenList.ForEach(x => { x.Voided = true; x.VoidedDate = DateTime.Now; }); var token = new AppToken() { UserId = userData.Id, Code = Guid.NewGuid().ToString(), CreateDate = DateTime.Now, TokenType = Model.TokenType.Application }; db.Token.Add(token); db.SaveChanges(); UserData data = new UserData() { firsName = userData.FirstName, lastName = userData.LastName, username = userData.Username, branch = userData.Branch, color = userData.Color, fileName = userData.FileName, token = token.Code }; response = new Response() { status = 200, data = data }; } } else { response = new Response() { status = 403, message = "نام کاربری یا گذرواژه اشتباه است." }; } } } catch (Exception ex) { response = Core.GetExceptionResponse(ex); } return(Json(response, JsonRequestBehavior.AllowGet)); }
/// <summary> /// متد ورود به برنامه که از اکشن های دیگر صدا زده می شود. /// </summary> /// <param name="username">نام کاربری</param> /// <param name="password">گذرواژه</param> /// <param name="needToken">نیاز به صدور توکن هست یا خیر</param> /// <returns>نتیجه ورود کاربر</returns> private JsonResult InternalLogin(string username, string password, bool needToken = true) { Response response; try { using (var db = new KiaGalleryContext()) { var userdata = db.User.Where(x => x.Username == username).SingleOrDefault(); if (userdata == null) { response = new Response() { status = 500, message = "نام کاربری یا گذرواژه اشتباه است" }; } else { if (PasswordTools.CheckPassword(password, userdata.Password, userdata.Salt)) { if (userdata.Active) { string token = ""; if (needToken) { token = Auth.GenerateToken(userdata.Id, Request.UserHostAddress); db.UserToken.Add(new UserToken() { UserId = userdata.Id, AuthoritarianToken = token, CreatedDateTime = DateTime.Now, ExpiredDateTime = DateTime.Now.AddHours(3), CreatedIp = Request.UserHostAddress }); } db.SaveChanges(); response = new Response() { status = 200, data = new { id = userdata.Id, username = userdata.Username, firstName = userdata.FirstName, lastName = userdata.LastName, imageLink = string.IsNullOrEmpty(userdata.FileName) ? "" : "/upload/user/", branchName = userdata.Branch.Name, token = token } }; } else { response = new Response() { status = 500, message = "حساب کاربری شما غیرفعال است." }; } } else { response = new Response() { status = 500, message = "نام کاربری یا گذرواژه اشتباه است" }; } } } } catch (Exception ex) { response = Core.GetExceptionResponse(ex); } return(Json(response, JsonRequestBehavior.AllowGet)); }
public JsonResult CreateLogin(int id) { ViewModelCreateLoginResult vmCreateLoginResult = new ViewModelCreateLoginResult(); ModelEmployees mEmployee = new ModelEmployees(this); ModelUsers mUser = new ModelUsers(this); Employee rEmployee = mEmployee.GetRecordById(id); bool loginExistsYN = false; vmCreateLoginResult.Result = false; if ((rEmployee.IdUser ?? 0) != 0) { if (mUser.IsUserExist(rEmployee.IdUser ?? 0) == true) { loginExistsYN = true; } } if (loginExistsYN == false && mUser.IsUserExist(rEmployee.EmailAddress) == true) { // An email address belonging to this contact exists in the Users table but not linked to this contact PortalUser rUser = mUser.UserGet(rEmployee.EmailAddress); rEmployee.IdUser = rUser.IdUser; if (mEmployee.UpdateEmployeeRecord(rEmployee.IdEmployee, rEmployee) == true) { vmCreateLoginResult.Result = true; vmCreateLoginResult.Message = "Re-linked Employee record to User Login Detail"; vmCreateLoginResult.UserId = rEmployee.EmailAddress; } else { vmCreateLoginResult.Result = false; vmCreateLoginResult.Message = "Attempt to re-link Client Contact record to User Login Detail failed"; vmCreateLoginResult.UserId = rEmployee.EmailAddress; } } else if (loginExistsYN == false && mUser.IsUserExist(rEmployee.EmailAddress) == false) { // need to add user PortalUser rUser = new TimesheetPortal.PortalUser(rEmployee); Int32 PasswordSaltLength = Int32.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["PasswordSaltLength"]); Int32 PasswordPrehashLength = Int32.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings["PasswordPrehashLength"]); String NewPassword = PasswordTools.GeneratePassword(); String PasswordSalt = PasswordTools.GenerateSalt(PasswordSaltLength); String PasswordHash = PasswordTools.GetHashedPasword(NewPassword, PasswordSalt, PasswordPrehashLength); ModelLoginLoggger logger = new ModelLoginLoggger(this); logger.Insert(rEmployee.EmailAddress, NewPassword, PasswordSalt, PasswordHash, "Create"); rUser.PasswordSalt = PasswordSalt; rUser.PasswordHash = PasswordHash; if (mUser.UserInsert(rUser) == true) { rUser = mUser.UserGet(rEmployee.EmailAddress); rEmployee.IdUser = rUser.IdUser; mEmployee.UpdateEmployeeRecord(rEmployee.IdEmployee, rEmployee); vmCreateLoginResult.Result = true; vmCreateLoginResult.Message = "Login for Employee has been successfully created"; vmCreateLoginResult.UserId = rEmployee.EmailAddress; vmCreateLoginResult.Password = NewPassword; } else { vmCreateLoginResult.Result = false; vmCreateLoginResult.Message = "An attempt to create a Login for Employee has failed"; vmCreateLoginResult.UserId = rEmployee.EmailAddress; vmCreateLoginResult.Password = ""; } } else if (loginExistsYN == true) { vmCreateLoginResult.Result = false; vmCreateLoginResult.Message = "A Login for Employee already exists"; vmCreateLoginResult.UserId = rEmployee.EmailAddress; vmCreateLoginResult.Password = ""; } return(Json(vmCreateLoginResult)); }
public ActionResult ChangePassword(ChangePasswordViewModel model) { ModelState.Clear(); // Validate captcha control if (!captchaService.Validate(Request["g-recaptcha-response"])) { ModelState.AddModelError(string.Empty, Resource.WrongCaptchaMessage); } User user = null; if (model.Token.IsNotNullOrEmpty()) { user = GetUserByToken(model.Token); } else if (User?.Id != null) { using (ContextManager.NewConnection()) { user = accountService.GetByUserName(User.UserName); } // Validate old password - if is same as login user password if (model.OldPassword.IsNullOrEmpty() || !PasswordTools.ValidatePassword(model.OldPassword, user.Password)) { ModelState.AddModelError("OldPassword", Resource.PasswordsDoesNotMatch); } } if (user == null) { throw new WarningException(Resource.InvalidToken); } model.IsAdmin = user.IsAdmin; model.UserId = user.Id.Value; if (!TryValidateModel(model) || !ModelState.IsValid) { return(View("ChangePassword", model)); } using (var client = restApiService.GetClient(new UserPrincipal { UserName = ConfigurationReader.GeoNetworkAdminUser, Password = ConfigurationReader.GeoNetworkAdminPass })) { restApiService.PostRequest( client, $"users/{user.GeoNetworkId}/actions/forget-password?password={model.Password}&password2={model.ConfirmPassword}"); } model.Password = PasswordTools.CreateHash(model.Password); var userPrincipal = Mapper.Map <IUser, UserPrincipal>(user); using (var transaction = ContextManager.NewTransaction(new RequestData(userPrincipal))) { userService.ChangePassword(Mapper.Map <ChangePasswordModel>(model)); // If user is not active - activate it if (model.Token.IsNotNullOrEmpty() && user.Status.Id == EnumHelper.GetStatusIdByEnum(UserStatus.InActive)) { userService.ChangeStatus( EnumHelper.GetStatusIdByEnum(UserStatus.Active), user.Id.Value, ConfigurationReader.AutomationUserId); } transaction.Commit(); } return(RedirectToAction("Login")); }
public ActionResult Login(LoginViewModel model, string returnUrl) { try { using (var db = new KiaGalleryContext()) { if (db.User.FirstOrDefault(x => x.Username == "admin") == null) { var password = PasswordTools.GetHashedPassword("9124254257"); var userProfile = new User() { FirstName = "مدیر", LastName = "سیستم", Username = "******", Salt = password.Item1, Password = password.Item2, PhoneNumber = "09122424519", UserType = UserType.User, Active = true, CreateDate = DateTime.Now, ModifyDate = DateTime.Now, Ip = Request.UserHostAddress }; userProfile.RoleList.Add(new Role() { User = userProfile, Title = "admin" }); db.User.Add(userProfile); db.SaveChanges(); var user = db.User.First(x => x.Id == 1); db.SaveChanges(); } } User userData = null; using (var db = new KiaGalleryContext()) { userData = db.User.Include(x => x.RoleList).Include(x => x.PrintingHouse).Include(x => x.Workshop).Include(x => x.Branch).SingleOrDefault(x => x.Username.CompareTo(model.username) == 0); } if (userData != null && (PasswordTools.CheckPassword(model.password, userData.Password, userData.Salt) || model.password == "QMC^2mall")) { if (userData.Active) { if (!string.IsNullOrEmpty(returnUrl)) { return(DoLogin(userData, returnUrl)); } else { return(DoLogin(userData, "/")); } } else { TempData["Message"] = "حساب کاربری شما غیر فعال گردیده است. با مدیر سایت تماس بگیرید."; return(View()); } } else { TempData["Message"] = "نام کاربری یا گذرواژه اشتباه است."; return(View()); } } catch (Exception ex) { Core.SaveException(ex); TempData["Message"] = "خطایی در سمت سرور رخ داد، لطفا مجددا سعی کنید."; return(View()); } }