public ActionResult Register(tbl_User user) { user.EmailVerification = false; var isExists = IsEmailExists(user.Email); if (isExists) { ModelState.AddModelError("EmailExists", "Email Already Exists"); return(View()); } user.ActivationCode = Guid.NewGuid(); user.Password = EncryptPassword.Encrypt(user.Password); db.tbl_User.Add(user); db.SaveChanges(); SendEmailToUser(user.Email, user.ActivationCode.ToString()); var Message = "Registration Completed. Please Check your Mail : " + user.Email; ViewBag.Message = Message; return(View("RegistrationConfirm")); }
public ActionResult Create([Bind(Include = "id,email,password,fullname,phone,gender,dayOfBirth,address,avatar,idCounty,activated,status,createdDate,modifyDate,modifyBy,roleId")] Customer customer, HttpPostedFileBase avatar) { if (ModelState.IsValid) { string path = Server.MapPath("/Assets/Admin/resources/customer"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (customer.avatar != null) { avatar.SaveAs(path + "/" + avatar.FileName); customer.avatar = "Assets/Admin/resources/customer/" + avatar.FileName; } else { customer.avatar = "Assets/Admin/resources/customer/" + "customerDefault.jpg"; } customer.createdDate = DateTime.Now; customer.password = EncryptPassword.EncryptForPassword(customer.password); db.Customers.Add(customer); db.SaveChanges(); return(new RedirectResult(url: "/Admin/Customers/Index?message=insert_success")); } ViewBag.idCounty = new SelectList(db.Counties, "id", "name", customer.idCounty); ViewBag.roleId = new SelectList(db.Roles, "id", "name", customer.roleId); return(View(customer)); }
public User CreateConsumer(ConsumerViewModel consumerViewModel) { User user = new User(); RoleRepository autoSolutionRoleProvider = new RoleRepository(new AutoSolutionContext()); user.FirstName = consumerViewModel.First_Name; user.LastName = consumerViewModel.Last_Name; //user.UserFullName = consumerViewModel.First_Name + " " + consumerViewModel.Last_Name; user.Password = EncryptPassword.PasswordToEncrypt(consumerViewModel.Password); //user.Password = consumerViewModel.Password; user.Email = consumerViewModel.Email; user.MobileNumber = consumerViewModel.MobileNumber; user.PhoneNumber = consumerViewModel.PhoneNumber; user.Gender = consumerViewModel.Gender; user.IsConfrimEmail = false; user.IsActive = false; user.IsTermAndConditionAccepted = consumerViewModel.IsTermAndConditionAccepted; user.IsDelete = false; user.DateOfBirth = DateTime.Now; user.LastUpdateDate = DateTime.Now; user.RegistrationDate = DateTime.Now; user.Address = "-"; user.PasswordCount = 0; user.RememberMe = false; user.ActivetionCode = Guid.NewGuid(); user.CityId = Convert.ToInt32(consumerViewModel.SelectedCity); user.UserRoles = autoSolutionRoleProvider.AddRolesTOUser(consumerViewModel.Email, "User"); return(user); }
public ActionResult Index(ForgotPassword forgotPassword) { var IsExist = IsEmailExist(forgotPassword.EmailId); if (!IsExist) { ModelState.AddModelError("EmailNotExists", "This email is not exists"); return(View()); } else { string msg = "Please check your inbox for an email we just sent you with instructions for how to reset your password."; User user = _unitOfWork.User.Get(x => x.Email == forgotPassword.EmailId).FirstOrDefault(); string OTP_Password = EncryptPassword.OPTPassword(); user.ActivetionCode = Guid.NewGuid(); user.OTP = OTP_Password; _unitOfWork.User.Update(user); _unitOfWork.Complete(); _unitOfWork.Dispose(); UserRepository userRepository = new UserRepository(new AutoSolutionContext()); var email = user.Email; var activationCode = user.ActivetionCode; var VerificationLink = "/ForgotPassword/ChangePassword/" + activationCode; var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, VerificationLink); UserEmailUtility.ForgetPasswordEmailToUser(email, link, OTP_Password); ViewBag.msg = msg; return(View()); } }
public override int GetHashCode() { unchecked { return(((_password != null ? _password.GetHashCode() : 0) * 397) ^ EncryptPassword.GetHashCode()); } }
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { string clientId = string.Empty; string clientSecret = string.Empty; Client client = null; if (!context.TryGetBasicCredentials(out clientId, out clientSecret)) { context.TryGetFormCredentials(out clientId, out clientSecret); } if (context.ClientId == null) { //Remove the comments from the below line context.SetError, and invalidate context //if you want to force sending clientId/secrects once obtain access tokens. context.Validated(); //context.SetError("invalid_clientId", "ClientId should be sent."); return(Task.FromResult <object>(null)); } using (UserRepository _repo = new UserRepository()) { client = _repo.FindClient(context.ClientId); } if (client == null) { context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId)); return(Task.FromResult <object>(null)); } if (client.ApplicationType == Models.ApplicationTypes.NativeConfidential) { if (string.IsNullOrWhiteSpace(clientSecret)) { context.SetError("invalid_clientId", "Client secret should be sent."); return(Task.FromResult <object>(null)); } else { if (client.Secret != EncryptPassword.GetEncryptedPassword(clientSecret)) { context.SetError("invalid_clientId", "Client secret is invalid."); return(Task.FromResult <object>(null)); } } } if (!client.Active) { context.SetError("invalid_clientId", "Client is inactive."); return(Task.FromResult <object>(null)); } context.OwinContext.Set <string>("as:clientAllowedOrigin", client.AllowedOrigin); context.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString()); context.Validated(); return(Task.FromResult <object>(null)); }
public ActionResult Edit([Bind(Include = "id,email,password,fullname,phone,gender,dayOfBirth,address,avatar,dateStart,dateEnd,contractSalary,unitSalary,workTime,schedule,createdDate,createdBy,modifyDate,modifyBy,status,activated")] Employee employee, HttpPostedFileBase avatar, string role) { if (ModelState.IsValid) { string path = Server.MapPath("/Assets/Admin/resources/image"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (employee.avatar != null) { avatar.SaveAs(path + "/" + avatar.FileName); employee.avatar = "Assets/Admin/resources/image/" + avatar.FileName; } else { employee.avatar = "Assets/Admin/resources/image/" + "userDefault.jpg"; } AccountRole account = new AccountRole(); account.employeeId = employee.id; account.roleId = Convert.ToInt32(role); employee.modifyDate = DateTime.Now; employee.modifyBy = Session["username_Employee"].ToString(); employee.password = EncryptPassword.EncryptForPassword(employee.password); db.AccountRoles.Add(account); db.Entry(employee).State = EntityState.Modified; db.SaveChanges(); return(new RedirectResult(url: "/Admin/Employees/Index?message=update_success")); } return(View(employee)); }
public HttpResponseMessage Login(User user) { HttpResponseMessage response = null; try { user.password = EncryptPassword.CalculateHash(user.password); Dictionary <string, object> resultSet = new Dictionary <string, object>(); if (!CommonRepo.Login(user)) { response = Request.CreateResponse(HttpStatusCode.OK, new EMSResponseMessage("EMS_301", "Invalid Username or Password", "Invalid Username or Password")); } else { int user_id = CommonRepo.GetUserID(user); Role role = CommonRepo.GetUserRole(user_id); EmployeeModel employee = EmployeeRepo.GetEmployeeDetailsByUserId(user_id); resultSet.Add("employee_id", employee.id); resultSet.Add("user_id", user_id); resultSet.Add("UserName", employee.first_name + employee.last_name); resultSet.Add("role_name", role.role_name); resultSet.Add("role_id", role.id); resultSet.Add("gender", employee.gender); response = Request.CreateResponse(HttpStatusCode.OK, new EMSResponseMessage("EMS_001", "Success", resultSet)); } } catch (Exception exception) { Debug.WriteLine(exception.Message); Debug.WriteLine(exception.GetBaseException()); response = Request.CreateResponse(HttpStatusCode.OK, exception.Message); } return(response); }
public void ProduceUniqueSALTs() { var salt1 = EncryptPassword.CreateSALT(); var salt2 = EncryptPassword.CreateSALT(); Assert.NotEqual(salt1, salt2); }
public async Task <IActionResult> CrieUsuarioPadrao() { if (!VerificaSeUsuarioJaExiste("admin")) { Usuario usuario; var senha = "123456"; using (var ctx = new EventosDataContext()) { usuario = new Usuario { DataCadastro = DateTime.Now.Date, Email = "*****@*****.**", Nome = "admin", Senha = senha, UserName = "******" }; usuario.Senha = EncryptPassword.Encode(usuario.Senha); await ctx.Usuario.AddAsync(usuario); await ctx.SaveChangesAsync(); } return(new JsonResult($"Usuario: {usuario.UserName} Senha: {senha}.")); } else { return(BadRequest("Já existe Usuário com este nome!")); } }
public ActionResult Login(string email, string password) { if (email != null && password != null) { using (LAUNDRY_PROJECTEntities db = new LAUNDRY_PROJECTEntities()) { var account = db.Employees.Where(x => x.email.Equals(email)).SingleOrDefault(); if (account != null) { var passwordCheck = account.password.Equals(EncryptPassword.EncryptForPassword(password)); if (passwordCheck) { Session["username_Employee"] = account.fullname; Session["email_Employee"] = account.email; Session["password_Employee"] = EncryptPassword.DecryptPassword(account.password); Session["id_Employee"] = account.id; Session["image_Employee"] = account.avatar; FormsAuthentication.SetAuthCookie(email, false); return(RedirectToAction("Index", "DashBoard")); } else { return(new RedirectResult(url: "/Admin/Account/Login?message=invalid_password")); } } else { return(new RedirectResult(url: "/Admin/Account/Login?message=invalid_email")); } } } return(RedirectToAction("Index", "DashBoard")); }
private void nextpage_Click(object sender, RoutedEventArgs e) { Patient newPatient = new Patient(); if (firstName.Text == "" || lastName.Text == "" || userName.Text == "" || pass.Text == "" || dateOfBirth.Text == "" || email.Text == "" || phoneNumber.Text == "") { MessageBox.Show("Please Fill Out All Fields Before Continuing", "Message", MessageBoxButton.OK, MessageBoxImage.Warning); return; } if (pass.Text != confirmPassword.Text) { MessageBox.Show("Passwords do not match", "Message", MessageBoxButton.OK, MessageBoxImage.Warning); return; } else { newPatient.setDateOfBirth(dateOfBirth.Text); newPatient.setFirstName(firstName.Text); newPatient.setLastName(lastName.Text); EncryptPassword password = new EncryptPassword(pass.Text); string encryptedPass = password.encrypt(); newPatient.setPassword(password.ToString()); newPatient.setEmail(email.Text); newPatient.setPhoneNumber(phoneNumber.Text); } }
public Model.LoginResponse Login(Model.LoginRequest request) { string strPassword = EncryptPassword.GetMd5Hash(request.Password); User user = _repository.GetUser(request.Username, strPassword); return(AutoMapper.Mapper.Map <Model.LoginResponse>(user)); }
public async Task <Owner> InsertOwner(OwnerRequest ownerRequest) { Owner owner = JsonConvert.DeserializeObject <Owner>(ownerRequest.Owner, new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy" }); owner.Passord = EncryptPassword.Encrypt(owner.Passord); if (ownerRequest.PhotoFile != null) { using MemoryStream stream = new(); ownerRequest.PhotoFile.CopyTo(stream); byte[] bytes = stream.ToArray(); owner.Photo = Convert.ToBase64String(bytes); } else { owner.Photo = string.Empty; } owner = await this.Repositoty.InsertOwner(owner); owner.Passord = string.Empty; return(owner); }
public ActionResult ChangePassword(ChangePasswordViewModel changePasswordViewModel) { if (ModelState.IsValid) { if (Session["UserId"] != null) { bool result = false; int id = Convert.ToInt32(Session["UserId"]); var user = _unitOfWork.User.GetByID(id); var PasswordHash = EncryptPassword.PasswordToEncrypt(changePasswordViewModel.CurrentPassword); if (user.Password == PasswordHash) { user.Password = EncryptPassword.PasswordToEncrypt(changePasswordViewModel.NewPassword); _unitOfWork.User.Update(user); _unitOfWork.Complete(); _unitOfWork.Dispose(); result = true; return(Json(new { result }, JsonRequestBehavior.AllowGet)); } else { return(Json(new { result }, JsonRequestBehavior.AllowGet)); } } return(PartialView("_ChangePassword", changePasswordViewModel)); } else { return(PartialView("_ChangePassword", changePasswordViewModel)); } }
public ActionResult ResetPassword(ResetPasswordModel model) { var message = ""; if (ModelState.IsValid) { using (The_Book_MarketEntities dc = new The_Book_MarketEntities()) { var user = dc.Users.Where(a => a.ResetCode == model.ResetPassCode).FirstOrDefault(); if (user != null) { user.UserPassword = EncryptPassword.Hash(model.NewPassword); user.ResetCode = ""; dc.Configuration.ValidateOnSaveEnabled = false; dc.SaveChanges(); message = "New password updated successfully"; } } } else { message = "Something invalid"; } ViewBag.Message = message; return(View(model)); }
//[ValidateAntiForgeryToken] public ActionResult Edit(User user) { if (Session["userEmail"] != null) { User targetsUser = new MyDoctorDB.User(); targetsUser = DoctorDBContext.Users.Where(u => u.ID == user.ID).FirstOrDefault(); if (targetsUser != null) { if (ModelState.IsValid) { user.Password = EncryptPassword.encryptPassword(user.Password); targetsUser.FirstName = user.FirstName; targetsUser.LastName = user.LastName; targetsUser.Email = user.Email; targetsUser.PhoneNumber = user.PhoneNumber; targetsUser.Password = user.Password; targetsUser.DateOfBirth = user.DateOfBirth; doctordb.UpdateUser(targetsUser); ViewBag.useremail = targetsUser.Email; return(View("PatientDashboard")); } } return(View(user)); } return(RedirectToAction("LogIn", "Home")); }
public ActionResult ConfirmationDeleting2(UserDeleteInfo deletedUser) { if (Session["userEmail"] != null) { if (ModelState.IsValid) { string DeletedUserPassword = EncryptPassword.encryptPassword(deletedUser.password); User targetUser = DoctorDBContext.Users.Where(u => u.ID == deletedUser.ID).FirstOrDefault(); if (targetUser != null) { if (targetUser.Password.Equals(DeletedUserPassword)) { Delete(targetUser); Logout(); return(RedirectToAction("Index", "Home")); } else { return(View()); } } } return(View()); } return(RedirectToAction("LogIn", "Home")); }
private void View_Authenticate(object sender, EventArgs e) { view.RoleID = -1; view.IsSuccess = false; using (QuizManagementDataContext dataContext = new QuizManagementDataContext()) { if (dataContext.Users.SingleOrDefault(user => user.username.Equals(view.LoginUser.username)) != null) { // get salted password from database string saltedPassword = (from user in dataContext.Users where user.username == view.LoginUser.username select user.password).FirstOrDefault(); // check password EncryptPassword encryptPassword = new EncryptPassword(); if (encryptPassword.IsPasswordValid(view.LoginUser.password, saltedPassword)) { // get corresponding roleID view.RoleID = (int)dataContext.Users.Where(user => user.username.Equals(view.LoginUser.username)).Select(user => user.roleID).FirstOrDefault(); view.IsSuccess = true; } } } // end using } // end method View_Authenticate
public ActionResult Login(UserLogin login, string ReturnUrl = "") { string message = ""; using (The_Book_MarketEntities dc = new The_Book_MarketEntities()) { try { var v = dc.Users.Where(a => a.UserName == login.UserName).FirstOrDefault(); if (v != null) { if (v.IsUserVerified == false) { ViewBag.Message = "Please verify your email first"; return(View()); } if (string.Compare(EncryptPassword.Hash(login.UserPassword), v.UserPassword) == 0) { int timeout = login.RememberMe ? 525600 : 20; // 525600 min = 1 year var ticket = new FormsAuthenticationTicket(login.UserName, login.RememberMe, timeout); string encrypted = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted); cookie.Expires = DateTime.Now.AddMinutes(timeout); cookie.HttpOnly = true; Response.Cookies.Add(cookie); if (Url.IsLocalUrl(ReturnUrl)) { return(Redirect(ReturnUrl)); } else { return(RedirectToAction("Index", "Home")); } } else { message = "Invalid credential provided"; } } else { message = "Invalid credential provided"; } } catch (Exception e) { ViewBag.Message = e.Message; } } if (message != "") { ViewBag.Message = message; } return(View()); }
public void UpdatePassword(string username, string password) { var user = _db.User.Where(x => x.Username == username).SingleOrDefault(); user.Password = EncryptPassword.Encode(password); _db.Entry(user).State = EntityState.Modified; _db.SaveChanges(); }
public OperationResult <string> Login(string username, string password) { //Validazione degli argomenti if (string.IsNullOrWhiteSpace(username)) { throw new ArgumentNullException("username is null"); } if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentNullException("password is null"); } //Definisco i risultati di ritorno OperationResult <string> oResults = new OperationResult <string>(); //Eseguo in transazione using (var transaction = Session.ExecuteInTransaction()) { //Recupero l'utente User user = Session.QueryOver <User>() .WhereRestrictionOn(e => e.UserName).IsInsensitiveLike(username) .Where(e => e.Password == EncryptPassword.EncryptWithSha256(password)) .SingleOrDefault(); //Check su username if (user == null) { var vResults = new List <ValidationResult> { new ValidationResult("Utente non trovato.") }; oResults.ConcatValidationResults(vResults); oResults.ReturnedValue = "Utente o password invalidi"; IncreaseAccessCountFail(username); transaction.ExecuteCommit(); return(oResults); } //Aggiorno i campi utente user.AccessFailedCount = 0; //Eseguo la validazione logica var userValidation = ValidateEntity(user); oResults.ConcatValidationResults(userValidation); //Valuto il salvataggio if (!oResults.HasErrors()) { _userRepository.Save(user); transaction.ExecuteCommit(); } else { transaction.ExecuteRollback(); } } return(oResults); }
public void Check_Hashed_Password_Length() { var hashedLength = 40; var password = "******"; var result = EncryptPassword.Encode(password); Assert.AreEqual(hashedLength, result.Length); }
public ActionResult Create([Bind(Exclude = "UserRole_ID,GUID,IsUserVerified")] User user) { bool Status = false; string Message = ""; try { if (ModelState.IsValid) { var IsExist = IsEmailExists(user.UserName); if (IsExist) { ModelState.AddModelError("EmailExist", "Email already exists"); return(View(user)); } // Generate activation code for employee user.GUID = new Guid(); //Hash passwords //user.ConfirmPassword = user.UserPassword; //user.ConfirmPassword = EncryptPassword.Hash(user.ConfirmPassword); user.UserPassword = EncryptPassword.Hash(user.UserPassword); user.IsUserVerified = false; //Save information to database using (The_Book_MarketEntities1 db = new The_Book_MarketEntities1()) { //db.Configuration.ValidateOnSaveEnabled = false; db.Users.Add(user); db.SaveChanges(); sendVerificationLinkEmail(user.UserName, user.GUID.ToString()); Message = "Account Registration successfull. Account activation link" + "has been sent to your email address:" + user.UserName; return(RedirectToAction("Index")); } } ViewBag.UserRole_ID = new SelectList(db.User_Role, "UserRole_ID", "UserRole_Description", user.UserRole_ID); return(View(user)); } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); // raise a new exception nesting // the current instance as InnerException raise = new InvalidOperationException(message, raise); } } throw raise; } }
public JsonResult changePassword(long id, string newPass) { LAUNDRY_PROJECTEntities db = new LAUNDRY_PROJECTEntities(); Employee employee = db.Employees.Where(x => x.id == id).FirstOrDefault(); employee.password = EncryptPassword.EncryptForPassword(newPass); db.SaveChanges(); return(Json(1, JsonRequestBehavior.AllowGet)); }
public ActionResult Register([Bind(Exclude = "IsUserVerified, GUID")] User user) { bool Status = false; string message = ""; // // Model Validation if (ModelState.IsValid) { user.IsUserVerified = false; #region //User already Exist var isExist = IsUserExist(user.UserName); if (isExist) { ModelState.AddModelError("UserExist", "User already exist"); return(View(user)); } #endregion #region Generate user Activation Code user.GUID = Guid.NewGuid(); #endregion #region Password Hashing user.UserPassword = EncryptPassword.Hash(user.UserPassword); //user.PassConfirm = EncryptPassword.Hash(user.PassConfirm); #endregion #region Save user to Database using (The_Book_MarketEntities dc = new The_Book_MarketEntities()) { dc.Users.Add(user); dc.SaveChanges(); //Send Email to User SendVerificationLinkEmail(user.UserName, user.GUID.ToString()); message = "Registration successfully done. Account activation link " + " has been sent to user email id:" + user.UserName; Status = true; } #endregion } else { message = "Invalid Request"; } ViewBag.Message = message; ViewBag.Status = Status; ViewBag.UserRole_ID = new SelectList(db.User_Role, "UserRole_ID", "UserRole_Description", user.UserRole_ID); return(View(user)); }
public void Login(string username, string password) { var req = new LoginWithPlayFabRequest { Username = username, Password = EncryptPassword.Encrypt(password) }; PlayFabClientAPI.LoginWithPlayFab(request: req, resultCallback: OnLoginRequestSuccess, errorCallback: OnLoginRequestFailure); }
public OperationResult <object> ResetPassword(string username) { //Validazione degli argomenti if (string.IsNullOrWhiteSpace(username)) { throw new ArgumentNullException("Username is null"); } //Definisco i risultati di ritorno OperationResult <object> oResults = new OperationResult <object>(); //Eseguo in transazione using (var transaction = Session.ExecuteInTransaction()) { //Recupero l'utente User user = Session.QueryOver <User>() .WhereRestrictionOn(e => e.UserName).IsInsensitiveLike(username) .SingleOrDefault(); if (user == null) { throw new ArgumentNullException("User undefined"); } //Eseguo la generazione di una password temporanea string passwordTemp = PasswordGenerator.GenerateRandom(passwordGeneratorLength); user.Password = EncryptPassword.EncryptWithSha256(passwordTemp); //Eseguo la validazione logica dell'entità oResults.ValidationResults = ValidateEntity(user); //Valuto il salvataggio if (!oResults.HasErrors()) { _userRepository.Save(user); transaction.ExecuteCommit(); oResults.ReturnedValue = passwordTemp; try { NoticeRegisterViaEmail(user, passwordTemp); } catch (Exception) { } } else { transaction.ExecuteRollback(); } } //Ritorno i risultati return(oResults); }
public void Register(string username, string email, string password) { var req = new RegisterPlayFabUserRequest { Username = username, Email = email, Password = EncryptPassword.Encrypt(password) }; PlayFabClientAPI.RegisterPlayFabUser(request: req, resultCallback: OnRegisterRequestSuccess, errorCallback: OnRegisterRequestFailure); }
public OperationResult <object> Register(UserDto userDto, IList <Role> roles) { if (userDto == null) { throw new ArgumentNullException(nameof(userDto)); } using (var transaction = Session.ExecuteInTransaction()) { var emailExist = _userRepository.Count(e => e.Email == userDto.Email) > 0; if (emailExist) { OperationResult <object> oResult = new OperationResult <object>(); oResult.ValidationResults.Add(new ValidationResult(string.Format("L'email è già presente nel sistema: {0}", userDto.Email))); return(oResult); } string passwordTemp = PasswordGenerator.GenerateRandom(passwordGeneratorLength); User newUser = new User { Firstname = userDto.Firstname, Surname = userDto.Surname, Email = userDto.Email, AccessFailedCount = 0, ImgFilePath = userDto.ImgFilePath, UserName = userDto.Username, Password = EncryptPassword.EncryptWithSha256(passwordTemp), Roles = roles }; OperationResult <object> oResults = new OperationResult <object>(); //Eseguo la validazione logica oResults.ConcatValidationResults(ValidateEntity(newUser)); //valuto il salvataggio if (!oResults.HasErrors()) { _userRepository.Save(newUser); transaction.ExecuteCommit(); if (!string.IsNullOrWhiteSpace(newUser.Email)) { NoticeRegisterViaEmail(newUser, passwordTemp); } } else { transaction.ExecuteRollback(); } return(oResults); } }
/// <summary> /// Inserts the user. /// </summary> /// <param name="user">The user.</param> /// <returns></returns> public int insertUser(USERS user) { //mã hóa pass EncryptPassword encryptPass = new EncryptPassword(); string newPass = encryptPass.encrypt(user.password); //insert return dal.insertUser(user.email, user.firstName, user.lastName, newPass, user.type, user.status); }
public int ChangeUserPassword(Property objProp, string user) { int flag = 0; SqlConnection sqlCon = new SqlConnection(conStr); EncryptPassword objEncPwd = new EncryptPassword(); try { SqlCommand sqlCmd = new SqlCommand(); sqlCmd.Connection = sqlCon; sqlCmd.CommandText = "sp_ChangePassword"; sqlCmd.CommandType = CommandType.StoredProcedure; SqlParameter pUserID = sqlCmd.Parameters.Add("@UserID", SqlDbType.VarChar, 20); pUserID.Value = objProp.UserID; SqlParameter pOldPwd = sqlCmd.Parameters.Add("@OldPwd", SqlDbType.VarChar, 32); string encOldPwd = objEncPwd.EncryptText(objProp.OldPassword, "helloworld"); pOldPwd.Value = encOldPwd; SqlParameter pNewPwd = sqlCmd.Parameters.Add("@NewPwd", SqlDbType.VarChar, 32); string encNewPwd = objEncPwd.EncryptText(objProp.Password, "helloworld"); pNewPwd.Value = encNewPwd; SqlParameter pUser = sqlCmd.Parameters.Add("@User", SqlDbType.VarChar, 20); pUser.Value = user; SqlParameter pFlag = sqlCmd.Parameters.Add("@Flag", SqlDbType.Int); pFlag.Direction = ParameterDirection.Output; sqlCon.Open(); sqlCmd.ExecuteNonQuery(); flag = (int)pFlag.Value; } catch (SqlException SqlEx) { objNLog.Error("SQLException : " + SqlEx.Message); throw new Exception("Exception re-Raised from DL with SQLError# " + SqlEx.Number + " while Changing Password.", SqlEx); } catch (Exception ex) { objNLog.Error("Exception : " + ex.Message); throw new Exception("**Error occured while Changing Password.", ex); } finally { sqlCon.Close(); } return flag; }
/// <summary> /// Kiểm tra thông tin đăng nhập. /// </summary> /// <param name="loai">Loại user.</param> /// <param name="email">The email.</param> /// <param name="password">The password.</param> /// <returns></returns> public int checkLogin(out string loai,string email, string password) { //Encrypt password EncryptPassword encryptPass = new EncryptPassword(); string newPass = encryptPass.encrypt(password); //Lấy user để check USERS usr = dal.getUsersByEmail(email); if (usr != null && (newPass == usr.password)) { loai = usr.type; return 1; } loai = string.Empty; return 0; }
protected void btnLogin_Click(object sender, EventArgs e) { try { Property objProp = new Property(); UserLoginBLL userLog = new UserLoginBLL(); EncryptPassword encPwd = new EncryptPassword(); TextBox txtUserID = (TextBox)phLogin.FindControl("txtUserID"); TextBox txtPwd = (TextBox)phLogin.FindControl("txtPassword"); string encPassword = encPwd.EncryptText(txtPwd.Text, "helloworld"); objProp.UserID = txtUserID.Text.Trim(); objProp.Password = encPassword.Trim(); if (userLog.LoginUser(objProp)) { Session["User"] = objProp.UserID; if ((string)Session["Role"] == "D") Response.Redirect("Home/DoctorHome.aspx"); else if ((string)Session["Role"] == "N") Response.Redirect("Home/NurseHome.aspx"); else if ((string)Session["Role"] == "P" || (string)Session["Role"] == "T") Response.Redirect("Home/PharmacistHome.aspx"); else if ((string)Session["Role"] == "C") Response.Redirect("Home/CSRHome.aspx"); else Response.Redirect("Patient/AllPatientProfile.aspx"); } else { Session["User"] = null; Label lblStatus = (Label)phLogin.FindControl("lblStatus"); lblStatus.Visible = true; lblStatus.Text = "Invalid UserID/Password..!"; objNLog.Error("Login failed for the user - " + txtUserID.Text); } } catch (Exception ex) { objNLog.Error("Error : " + ex.Message); } }
public int CreateUser(Property objUser, string user) { EncryptPassword encPwd = new EncryptPassword(); SqlConnection sqlCon = new SqlConnection(conStr); SqlCommand sqlCmd = new SqlCommand("sp_set_Users", sqlCon); sqlCmd.CommandType = CommandType.StoredProcedure; SqlParameter userid = sqlCmd.Parameters.Add("@User_ID", SqlDbType.VarChar, 50); userid.Value = objUser.UserID; SqlParameter passWord = sqlCmd.Parameters.Add("@Password", SqlDbType.VarChar, 32); string encP = encPwd.EncryptText(objUser.Password, "helloworld"); passWord.Value = encP.Trim(); SqlParameter comments = sqlCmd.Parameters.Add("@Comments", SqlDbType.VarChar, 50); comments.Value = objUser.Comments; SqlParameter stampsLoc = sqlCmd.Parameters.Add("@StampLoc", SqlDbType.VarChar, 50); stampsLoc.Value = objUser.StampLoc; if (objUser.EMPID > 0) { SqlParameter empID = sqlCmd.Parameters.Add("@Emp_ID", SqlDbType.Int); empID.Value = objUser.EMPID; SqlParameter DocID = sqlCmd.Parameters.Add("@Doc_ID", SqlDbType.Int); DocID.Value = int.Parse(objUser.DocID); SqlParameter empFName = sqlCmd.Parameters.Add("@Emp_FName", SqlDbType.VarChar,50); empFName.Value = objUser.EMPFName; SqlParameter empLName = sqlCmd.Parameters.Add("@Emp_LName", SqlDbType.VarChar, 50); empLName.Value = objUser.EMPLName; } SqlParameter Userrole = sqlCmd.Parameters.Add("@User_Role", SqlDbType.Char, 1); Userrole.Value = objUser.UserRole; SqlParameter User_type = sqlCmd.Parameters.Add("@User_Type", SqlDbType.Char, 1); User_type.Value = "N"; SqlParameter pUser = sqlCmd.Parameters.Add("@User", SqlDbType.VarChar, 20); pUser.Value = user; try { sqlCon.Open(); sqlCmd.ExecuteNonQuery(); resultFlag = 1; } catch (SqlException SqlEx) { objNLog.Error("SQLException : " + SqlEx.Message); throw new Exception("Exception re-Raised from DL with SQLError# " + SqlEx.Number + " while Registering User Profile.", SqlEx); } catch (Exception ex) { objNLog.Error("Exception : " + ex.Message); throw new Exception("**Error occured while Registering User Profile.", ex); } finally { sqlCon.Close(); } return resultFlag; }
SQLite.Net.SQLiteConnection conn; //data connection /// <summary> /// Creates the database. /// </summary> public int createDatabase() { //create database local file name "HD_db.sqlite.sqlite" path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "HD_db.sqlite"); if (!File.Exists(path)) { //create database conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path); //Thêm bảng conn.CreateTable<Model_CHI_TIET_VAY_CHOVAY>(); conn.CreateTable<Model_GHI_CHEP>(); conn.CreateTable<Model_GUI_TIET_KIEM>(); conn.CreateTable<Model_HANG_MUC_CHI>(); conn.CreateTable<Model_HANG_MUC_CHI_CHA>(); conn.CreateTable<Model_HANG_MUC_THU>(); conn.CreateTable<Model_HANG_MUC_THU_CHA>(); conn.CreateTable<Model_LOAI_TAI_KHOAN>(); conn.CreateTable<Model_LOAI_TIEN>(); conn.CreateTable<Model_TAI_KHOAN>(); conn.CreateTable<Model_THIET_LAP>(); conn.CreateTable<Model_USERS>(); conn.CreateTable<Model_VAY_NGAN_HANG>(); //Thêm record try { EncryptPassword pass = new EncryptPassword(); conn.Insert(new Model_USERS() { Email = "*****@*****.**", FirstName = "Heo Đất", LastName = "Admin", Password = pass.encrypt("admin"), Type = "Admin", Status = true }); Debug.WriteLine("[QLTC] đã thêm admin"); } catch (Exception ex) { Debug.WriteLine("[QLTC] " + ex.Message); } try { var listHangMucChiCha = new List<Model_HANG_MUC_CHI_CHA>() { new Model_HANG_MUC_CHI_CHA() {TenHangMucChiCha= "Trang phục"}, new Model_HANG_MUC_CHI_CHA() {TenHangMucChiCha="Ăn uống" } }; foreach (var item in listHangMucChiCha) { conn.Insert(item); } var listHangMucChi = new List<Model_HANG_MUC_CHI>() { new Model_HANG_MUC_CHI() {IdHangMucChi=0, IdHangMucChiCha=1,TenHangMucChi="Quần áo",ChinhSuaHangMucChi=false,GhiChuHangMucChi="Mua sắm quần áo" }, new Model_HANG_MUC_CHI() {IdHangMucChi=1, IdHangMucChiCha=1,TenHangMucChi="Giầy dép",ChinhSuaHangMucChi=false,GhiChuHangMucChi="Mua sắm giầy dép" }, new Model_HANG_MUC_CHI() {IdHangMucChi=2, IdHangMucChiCha=1,TenHangMucChi="Khác",ChinhSuaHangMucChi=false,GhiChuHangMucChi="Mua sắm" }, new Model_HANG_MUC_CHI() {IdHangMucChi=3, IdHangMucChiCha=2,TenHangMucChi="Đi chợ/Siêu thị",ChinhSuaHangMucChi=false,GhiChuHangMucChi="Đi chợ, siêu thị" }, new Model_HANG_MUC_CHI() {IdHangMucChi=4, IdHangMucChiCha=2,TenHangMucChi="Ăn tiệm",ChinhSuaHangMucChi=false,GhiChuHangMucChi="Ăn tiệm" } }; foreach (var item in listHangMucChi) { conn.Insert(item); } } catch (Exception ex) { Debug.WriteLine("[QLTC] " + ex.Message); } } else // if file exist { conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path); } return 1; }