Ejemplo n.º 1
0
        public void UpdatePersonalData_ChangePassword_Success(string _email, string _firstName, string _lastName, bool _changePassword, string _newPassword, bool _receiveNewsletterEmail, string _newsletterEmail)
        {
            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            int clientId         = 0;
            var testSessionToken = SessionRepository.StartNewSession(clientId);

            var updatePersonalDataCommand = new UpdatePersonalDataCommand
            {
                sessionToken           = testSessionToken,
                email                  = _email,
                firstName              = _firstName,
                lastName               = _lastName,
                changePassword         = _changePassword,
                newPassword            = _newPassword,
                receiveNewsletterEmail = _receiveNewsletterEmail,
                newsletterEmail        = _newsletterEmail
            };

            var handler = new UpdatePersonalDataCommandHandler();
            var result  = (PersonalDataDto)handler.Handle(updatePersonalDataCommand);

            var foundClient = DatabaseQueryProcessor.GetClient(_email, PasswordEncryptor.encryptSha256(_newPassword));

            DatabaseQueryProcessor.Erase();
            SessionRepository.RemoveSession(testSessionToken);

            Assert.IsNotNull(result);
            Assert.AreEqual(_email, result.email);
            Assert.AreEqual(_firstName, result.firstName);
            Assert.AreEqual(_lastName, result.lastName);
            Assert.AreEqual(_newsletterEmail, result.newsletterEmail);
            Assert.IsNotNull(foundClient);
        }
Ejemplo n.º 2
0
        public JsonResult userLogin([FromBody] JObject data)
        {
            string account  = data.Value <string>("account");
            string password = data.Value <string>("password");

            if (account == null || password == null)
            {
                return(new JsonResult(Return.Error("请填写用户名或密码", StatusCodes.WrongUsernameOrPassword)));
            }

            UserDAL userDal = new UserDAL();
            User    user    = userDal.getUserByAccount(account);

            // 密码加盐
            PasswordEncryptor encryptor    = new PasswordEncryptor();
            string            saltPassword = encryptor.encryptPassword(password, user?.salt);

            if (user == null || saltPassword != user.password)
            {
                return(new JsonResult(Return.Error("用户名或密码错误", StatusCodes.WrongUsernameOrPassword)));
            }

            HttpContext.Session.SetString("userId", user.userId);
            HttpContext.Session.SetString("password", user.password);

            // 不显示敏感信息
            JsonSerializerSettings jsonSettings = new JsonSerializerSettings
            {
                ContractResolver = new LimitPropertiesContractResolver(new string[] { "password", "salt" }, false)
            };

            return(new JsonResult(Return.Success(user), jsonSettings));
        }
Ejemplo n.º 3
0
        public void TestEncryptPasswordReturnsCorrectHash()
        {
            string password = "******";
            string hash     = PasswordEncryptor.EncryptPassword(password);

            Assert.AreEqual("21232F297A57A5A743894A0E4A801FC3", hash);
        }
Ejemplo n.º 4
0
        private async ValueTask <ClaimsIdentity> GetIdentity(string login, string password)
        {
            DataWrapper <AuthorizationDto> authorizationDto = await _repo.GetByLogin(login);

            PasswordEncryptor encryptor = new PasswordEncryptor();

            if (authorizationDto.Data != null)
            {
                if (encryptor.CheckPassword(authorizationDto.Data.Password, password))
                {
                    List <Claim> claims = new List <Claim>()
                    {
                        new Claim(ClaimsIdentity.DefaultNameClaimType, authorizationDto.Data.Login),
                        new Claim(ClaimsIdentity.DefaultRoleClaimType, authorizationDto.Data.Role.Name)
                    };
                    ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
                    return(claimsIdentity);
                }
                else
                {
                    return(null);
                }
            }
            return(null);
        }
Ejemplo n.º 5
0
 public UserService(AppSettingsConfigurations appSettings, IRoleService roleService, PasswordEncryptor passwordEncryptor, AfricanFarmerCommoditiesUnitOfWork unitOfWork)
 {
     _appSettings       = appSettings;
     _roleService       = roleService;
     _passwordEncryptor = passwordEncryptor;
     _unitOfWork        = unitOfWork;
 }
 public void SetUp()
 {
     _httpContextMock = new Mock <HttpContext>()
                        .SetupAllProperties();
     _nextMock          = new Mock <RequestDelegate>();
     _passwordEncryptor = new PasswordEncryptor(next: _nextMock.Object);
 }
Ejemplo n.º 7
0
        public void VerifyHashedPassword_Should_Not_Verify_a_Password_if_the_Hash_is_Empty()
        {
            PasswordEncryptor          hasher = new PasswordEncryptor();
            PasswordVerificationResult result = hasher.VerifyHashedPassword(string.Empty, "PassWord");

            Assert.That(result, Is.EqualTo(PasswordVerificationResult.Failed));
        }
Ejemplo n.º 8
0
        public static List <User> GenerateUsers()
        {
            // a list of users to seed
            List <User> users = new List <User>();


            //!! Can't go over 9, or guid.parse won't work
            for (var i = 0; i < 9; i++)
            {
                int index = i + 1;

                var tempGuid = Guid.Parse($"{index}a8d0bfb-74a5-48f4-a729-0a945011ee4f");
                users.Add(
                    new User
                {
                    //Id = new Guid(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte)index, }),
                    Id           = tempGuid,
                    Email        = $"test{index}@test.com",
                    Password     = PasswordEncryptor.Hash($"Secret{index}").PasswordHash,
                    PasswordSalt = PasswordEncryptor.Hash($"Secret{index}").PasswordSalt,
                    CreatedDate  = DateTime.UtcNow.AddDays(-index)
                });
            }

            return(users);
        }
Ejemplo n.º 9
0
        public async Task <ActionResult> ForgotPassword([Bind(Include = "UserIdentity")] ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var    userService = ServiceFactory.GetUserService();
                    string userEmail   = userService.GetEmailByUserIdentity(model.UserIdentity);
                    int    id          = userService.GetIdOflogin(userEmail);
                    string newPassword = PasswordEncryptor.RendomPassword();
                    if (userService.UpdatePassword(id, newPassword))
                    {
                        string subject = "Ваш пароль был изменен";
                        string body    = "Новый пароль: " + newPassword;
                        if (await MailDispatch.SendingMailAsync(userEmail, subject, body).ConfigureAwait(false))
                        {
                            return(this.RedirectToAction("ForgotPasswordSuccess"));
                        }
                    }
                }
                catch (UserValidationException ex)
                {
                    ModelState.AddModelError(ex.UserProperty, ex.Message);
                    return(View());
                }
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Ошибка восстановления пароля");
                return(View());
            }

            return(View());
        }
        public void RegisterNewClient_CorrectData_Success(string _email, string _firstName, string _lastName, string _password, bool _receiveNewsletterEmail, string _newsletterEmail)
        {
            DatabaseQueryProcessor.Erase();
            Shared.FillTheDatabase();

            var registerNewClient = new RegisterNewClientCommand
            {
                email     = _email,
                firstName = _firstName,
                lastName  = _lastName,
                password  = _password,
                receiveNewsletterEmail = _receiveNewsletterEmail,
                newsletterEmail        = _newsletterEmail
            };

            var handler = new RegisterNewClientCommandHandler();
            var result  = (SuccessInfoDto)handler.Handle(registerNewClient);

            var newClient = DatabaseQueryProcessor.GetClient(_email, PasswordEncryptor.encryptSha256(_password));

            DatabaseQueryProcessor.Erase();

            Assert.IsNotNull(newClient);
            Assert.IsTrue(result.isSuccess);
            Assert.AreEqual(_firstName, newClient.firstName);
            Assert.AreEqual(_lastName, newClient.lastName);
            Assert.AreEqual(_newsletterEmail, newClient.newsletterEmail);
        }
Ejemplo n.º 11
0
        public void RegisterUser(string email, string password, string firstName, string lastName)
        {
            // check duplication
            var dbUser = _dbContext.Users.SingleOrDefault(u => u.Email == email);

            if (dbUser != null)
            {
                throw new DuplicateNameException("You can not use this email address.");
            }
            else
            {
                // encoding password for security
                string encodedPassword = PasswordEncryptor.ComputeHash(password);

                var user = new User()
                {
                    Email        = email,
                    Password     = encodedPassword,
                    FirstName    = firstName,
                    LastName     = lastName,
                    RegisterDate = DateTime.Now
                };

                _dbContext.Users.Add(user);
                _dbContext.SaveChanges();
            }
        }
Ejemplo n.º 12
0
        public ApplicantsViewModel CreateApplicant(CreateInputModel inputModel)
        {
            var applicantModel = _autoMapper.Map <Applicants>(inputModel);

            applicantModel.PasswordSalt = PasswordEncryptor.CreateSalt(5);

            var hashedPassword = PasswordEncryptor.CreatePasswordHash(applicantModel.Password,
                                                                      applicantModel.PasswordSalt);

            applicantModel.Password = hashedPassword;

            //Get the 2 shareholders
            var shareHolderOne = _memberRepository.FindBy(x => x.MembershipID == inputModel.
                                                          ShareHolder1MemberID).SingleOrDefault();


            var shareHolderTwo = _memberRepository.FindBy(x => x.MembershipID == inputModel.
                                                          ShareHolder2MemberID).SingleOrDefault();

            applicantModel.ShareHolder1ID = shareHolderOne.ID;
            applicantModel.ShareHolder2ID = shareHolderTwo.ID;

            applicantModel.RejectionReason = RejectionReason.Other;

            _applicantRepository.Add(applicantModel);
            _applicantRepository.SaveChanges();

            //Send Email To Applicant
            _emailService.sendEmailToApplicant(applicantModel.EmailAddress, applicantModel.FirstName);

            var applicantViewModel = _autoMapper.Map <ApplicantsViewModel>(applicantModel);

            return(applicantViewModel);
        }
Ejemplo n.º 13
0
        public static void UpdateAdminUsername(string newuser, string password)
        {
            SqlConnection con = new DBConnection().getConnection();

            con.Open();
            try
            {
                //check if user  already exist
                AdminLog.CheckUserName(newuser);
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@UserName", newuser);
                cmd.Parameters.AddWithValue("@Password", PasswordEncryptor.Encrypt(password));
                cmd.Parameters.AddWithValue("@ID", Resetuserid);
                cmd.CommandText = "UPDATE Admin SET UserName =@UserName, Password=@Password WHERE ID=@ID";
                cmd.ExecuteNonQuery();
                con.Close();
                AdminLog.Admin     = newuser;
                AdminLog.AdminPass = PasswordEncryptor.Encrypt(password);
            }
            catch (Exception Ex)
            {
                con.Close();
                throw new Exception(Ex.Message + "\nUpdate Not Successful");
            }
        }
        public async Task <IActionResult> PutUserDetail(int id, UserDetail userDetail)
        {
            if (id != userDetail.UserId)
            {
                return(BadRequest());
            }

            userDetail.Email = userDetail.Email.ToLower().Trim();
            if (!string.IsNullOrEmpty(userDetail.Password))
            {
                userDetail.Password = PasswordEncryptor.Encrypt(userDetail.Password);
            }

            _context.Entry(userDetail).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserDetailExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Ejemplo n.º 15
0
        public static void UpdateAdminPass(string password)
        {
            try
            {
                //PASS IN THE USER NAME AND THE NEW PASSWORD
                UserResetPassword.ResetUserPassword(AdminLog.Admin);
                SqlConnection con = new DBConnection().getConnection();
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@ID", UserResetPassword.Resetuserid);

                cmd.Parameters.AddWithValue("@Password", PasswordEncryptor.Encrypt(password));
                cmd.CommandText = "UPDATE Admin SET Password =@Password WHERE ID= @ID ";
                cmd.ExecuteNonQuery();
                con.Close();
                dataAccess.Description = Admin + " updated password";
                dataAccess.Activities();
                AdminPass = PasswordEncryptor.Encrypt(password);
            }
            catch (Exception Ex)
            {
                throw new Exception(Ex.Message + "\nUpdate Not Successful");
            }
        }
Ejemplo n.º 16
0
        public ValidateUserDTO Save(UserSaveDTO user)
        {
            var result = new ValidateUserDTO()
            {
            };

            if (this.userRepository.Exists(user.Login, null))
            {
                var errors = new List <string>()
                {
                    "The given login '" + user.Login + "' is already in use."
                };
                result.OverallErrors = errors;
                return(result);
            }

            var applicationUser = Mapper.Map <ApplicationUser>(user);

            applicationUser.Password = PasswordEncryptor.Encrypt(user.Password);
            applicationUser.Roles    = new ApplicationUserRole[] { new ApplicationUserRole()
                                                                   {
                                                                       Name = "User"
                                                                   } };

            result.ValidatedUser = Mapper.Map <UserDTO>(this.userRepository.Create(applicationUser));
            return(result);
        }
Ejemplo n.º 17
0
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                var dao = new UserDAO();
                var res = dao.Login(model.UserName, PasswordEncryptor.MD5Hash(model.Password));
                if (res == 0)
                {
                    ModelState.AddModelError("", "Tài khoản không tồn tại");
                }
                else
                {
                    if (res == 2)
                    {
                        ModelState.AddModelError("", "Mật khẩu không chính xác");
                    }
                    if (res == -1)
                    {
                        ModelState.AddModelError("", "Tài khoản đã bị khóa");
                    }
                    if (res == 1)
                    {
                        var user        = dao.KiemTraDangNhap(model.UserName);
                        var userSession = new LoginDetail();
                        userSession.UserName = user.UserName;
                        userSession.User     = user;
                        userSession.GroupID  = user.GroupID;

                        Session.Add(CommonConstants.USER_SESSION, userSession);
                        return(RedirectToAction("Index", "TrangChu"));
                    }
                }
            }
            return(View("Index"));
        }
Ejemplo n.º 18
0
        public ValidateUserDTO Update(UserUpdateDTO user)
        {
            var result = new ValidateUserDTO()
            {
            };

            if (this.userRepository.Exists(user.Login, user.Id))
            {
                var errors = new List <string>()
                {
                    "The given login '" + user.Login + "' is already in use."
                };
                result.OverallErrors = errors;
                return(result);
            }

            var applicationUser = this.userRepository.Get(user.Id);

            applicationUser.Name     = user.Name;
            applicationUser.Login    = user.Login;
            applicationUser.Password = PasswordEncryptor.Encrypt(user.Password);
            this.userRepository.Update(applicationUser);
            result.ValidatedUser = this.Get(user.Id);
            return(result);
        }
Ejemplo n.º 19
0
        public void VerifyHashedPassword_Should_Not_Verify_Two_Passwords_That_Are_Not_Equal()
        {
            PasswordEncryptor          hasher = new PasswordEncryptor();
            PasswordVerificationResult result = hasher.VerifyHashedPassword("ADAXH+oycHxLcBpQbDFIyi3HqJKRJsAuzbJGPKEF1AxmKhfjKH14xkXYiPowfoQTRQ==", "PassWord");

            Assert.That(result, Is.EqualTo(PasswordVerificationResult.Failed));
        }
Ejemplo n.º 20
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            string oldPasswordHash     = PasswordEncryptor.EncryptPassword(txtOldPass.Text);
            string newPasswordHash     = PasswordEncryptor.EncryptPassword(txtNewPass.Text);
            string confirmPasswordHash = PasswordEncryptor.EncryptPassword(txtConfirm.Text);

            if (txtOldPass.Enabled)
            {
                if (oldPasswordHash != passwordHash)
                {
                    MessageBox.Show(Program.LanguageManager.GetString(StringResources.PassChange_InvalidOldPassword));
                    DialogResult = System.Windows.Forms.DialogResult.None;
                    return;
                }
            }

            if (newPasswordHash != confirmPasswordHash)
            {
                MessageBox.Show(Program.LanguageManager.GetString(StringResources.PassChange_PasswordsNotMatch));
                DialogResult = System.Windows.Forms.DialogResult.None;
                return;
            }

            NewPasswordHash = newPasswordHash;
            DialogResult    = System.Windows.Forms.DialogResult.OK;
        }
Ejemplo n.º 21
0
        public void Execute()
        {
            try
            {
                viewModel.Admin.Name         = viewModel.Name;
                viewModel.Admin.PasswordHash = PasswordEncryptor.EncryptPassword(viewModel.Password);
                viewModel.Admin.IsActive     = true;
                viewModel.Project.IsActive   = true;
                if (viewModel.Project.WorkstationType != Domain.Entity.Setup.WorkstationType.Mill)
                {
                    viewModel.MillPipeNumberMask = string.Empty;
                }

                firstSetupRepo.BeginTransaction();
                firstSetupRepo.RoleRepo.Save(viewModel.SuperUser);
                firstSetupRepo.UserRepo.Save(viewModel.Admin);
                firstSetupRepo.ProjectRepo.Save(viewModel.Project);
                firstSetupRepo.Commit();
                firstSetupRepo.RoleRepo.Evict(viewModel.SuperUser);
                firstSetupRepo.UserRepo.Evict(viewModel.Admin);
                firstSetupRepo.ProjectRepo.Evict(viewModel.Project);
                viewModel.IsSaved = true;

                var seeder = new InnitialDataSeeder(viewModel);
                seeder.Seed(Program.IsSeed);
            }
            catch (RepositoryException ex)
            {
                log.Error(ex.Message);
            }
        }
Ejemplo n.º 22
0
        public ActionResult CapNhat(User entity)
        {
            if (ModelState.IsValid)
            {
                var dao = new UserDAO();

                var encryptedMd5Pas = PasswordEncryptor.MD5Hash(entity.Password);
                entity.Password = encryptedMd5Pas;

                var result = dao.Update(entity);
                if (result)
                {
                    SetAlert("Cập nhật thông tin người dùng thành công", "success");
                    return(RedirectToAction("Index", "ThanhVien"));
                }
                else
                {
                    SetAlert("Cập nhật thông tin người dùng không thành công", "error");
                    return(RedirectToAction("CapNhat", "ThanhVien"));
                }
            }
            DropdownUsergroup(entity.GroupID);
            DropdownGender(entity.Gender);
            return(View("Index"));
        }
Ejemplo n.º 23
0
        public static async Task <bool> CheckLogin(Action callback, MainWindow mw, Uri ApiUrl)
        {
            if (App.Token == default)
            {
                if (string.IsNullOrWhiteSpace(Settings.Default.Username) || string.IsNullOrWhiteSpace(Settings.Default.Password))
                {
                    mw.Dispatcher.Invoke(() => { LoginDialog ld = new LoginDialog(ApiUrl, callback); });
                    return(false);
                }

                string login  = Settings.Default.Username;
                string passwd = PasswordEncryptor.Decrypt(Settings.Default.Password, login.Trim());

                ObjectResult <LoginContent> result = await WebWrapper.Login(login, passwd, ApiUrl);

                if (result == null || !IsSuccessStatusCode(result.code) || result.content == null || result.content.privileges < 0)
                {
                    mw.Dispatcher.Invoke(() => { LoginDialog ld = new LoginDialog(ApiUrl, callback); });
                    return(false);
                }

                LoginContent loginContent = result.content;
                App.Token = loginContent.token;
            }

            if (!mw.ReportedDLC)
            {
                mw.ReportDLC();
            }

            return(true);
        }
Ejemplo n.º 24
0
        public ActionResult ThemMoi(User entity)
        {
            if (ModelState.IsValid)
            {
                var dao = new UserDAO();

                var encryptedMd5Pas = PasswordEncryptor.MD5Hash(entity.Password);
                entity.Password = encryptedMd5Pas;

                if (dao.CheckUserName(entity.UserName))
                {
                    SetAlert("Tên đăng nhập đã tồn tại", "warning");
                    return(RedirectToAction("ThemMoi", "ThanhVien"));
                }
                else
                {
                    long id = dao.Insert(entity);
                    if (id > 0)
                    {
                        SetAlert("Thêm thông tin người dùng thành công", "success");
                        return(RedirectToAction("Index", "ThanhVien"));
                    }
                    else
                    {
                        SetAlert("Thêm nhân viên không thành công", "error");
                        return(RedirectToAction("ThemMoi", "ThanhVien"));
                    }
                }
            }
            DropdownUsergroup();
            DropdownGender();
            return(View("Index"));
        }
Ejemplo n.º 25
0
 private void txtPassword_KeyDown(object sender, KeyEventArgs e)
 {
     if (e.KeyValue == (char)Keys.Enter)
     {
         try
         {
             AdminLog.LogIn(txtUsername.Text, txtPassword.Text);
             if (txtUsername.Text == AdminLog.Admin && PasswordEncryptor.Encrypt(txtPassword.Text) == AdminLog.AdminPass)
             {
                 //USE ASYNC HERE
                 new Thread(() => { AdminLog.AdminLogs(AdminLog.Admin, btnLogin.Text); }).Start();
                 this.Close();
             }
             else
             {
                 throw new Exception("Incorrect Username or Password");
             }
         }
         catch (Exception Ex)
         {
             MessageBox.Show(Ex.Message, "Admin Login error", MessageBoxButtons.OK,
                             MessageBoxIcon.Information);
         }
     }
 }
Ejemplo n.º 26
0
        public long RegisterUser(UserVM userVM)
        {
            var  encryptedPass = PasswordEncryptor.Encrypt(userVM.Password);
            User user          = new User
            {
                Address     = userVM.Address,
                CompanyName = userVM.CompanyName,
                Email       = userVM.Email,
                Liecnse     = userVM.Liecnse,
                Name        = userVM.Name,
                NID         = userVM.NID,
                Password    = encryptedPass,
                Phone       = userVM.Phone,
                RoleID      = userVM.RoleID
            };

            var addedUser = _dbContext.Users.Add(user);

            _dbContext.SaveChanges();

            if (addedUser.ID > 0)
            {
                return(addedUser.ID);
            }

            return(-1);
        }
Ejemplo n.º 27
0
        }         // LogInAction()

        /// <summary>
        /// Safeguard if developer forget user password. In case of not existing admin1 account new one is created.
        /// </summary>
        public static void AdminExist()
        {
            User user = MainWindowViewModel.Context.Users.FirstOrDefault(u => u.Name == "Admin1");

            if (user == null)
            {
                MainWindowViewModel.NotifyUser("Admin1 accoutn doesn't exist.");

                var tempUser = new User();

                tempUser.Name          = "Admin1";
                tempUser.PasswordSalt  = PasswordEncryptor.GenerateSalt();
                tempUser.Password      = PasswordEncryptor.GeneratePassword("Sauron666", tempUser.PasswordSalt);
                tempUser.Type          = Enumerators.UserTypeEnum.Admin;
                tempUser.AccountActive = true;

                MainWindowViewModel.Context.Users.Add(tempUser);
                MainWindowViewModel.SaveContext();
                UsersListViewModel.Instance.Refresh();
            }

            else
            {
                return;
            }
        }
        public IResult Handle(RegisterNewClientCommand command)
        {
            if (!InputChecker.isValidEmail(command.email) ||
                !InputChecker.isValidName(command.firstName) ||
                !InputChecker.isValidName(command.lastName) ||
                (command.receiveNewsletterEmail &&
                 !InputChecker.isValidEmail(command.newsletterEmail)))
            {
                throw new Exception();
            }

            var clients      = DatabaseQueryProcessor.GetClients();
            var foundClients = clients.FindAll(c => c.email == command.email);

            if (foundClients.Count != 0)
            {
                throw new Exception();
            }

            var clientId = DatabaseQueryProcessor.CreateNewClient(
                command.email,
                command.firstName,
                command.lastName,
                PasswordEncryptor.encryptSha256(command.password),
                command.receiveNewsletterEmail ? command.newsletterEmail : ""
                );

            ThreadPool.QueueUserWorkItem(o => new RegistrationEmail().Send(clientId));


            return(new SuccessInfoDto()
            {
                isSuccess = true
            });
        }
Ejemplo n.º 29
0
        }         // Cancel_button_Click()

        public void SavePassword(object parameters)
        {
            var values               = (object[])parameters;
            var passwordText         = ((PasswordBox)values[0]).Password;
            var passwordConfirmation = ((PasswordBox)values[1]).Password;
            var regexExpression      = new Regex(@"!|@|#|\$|%|\^|&|\*|\(|\)|-|_|=|\+");

            if (passwordText.Any(char.IsDigit) || regexExpression.IsMatch(passwordText))
            {
                if (passwordText.Length >= 8)
                {
                    if (passwordText == passwordConfirmation)
                    {
                        User selectedUser = MainWindowViewModel.Context.Users.FirstOrDefault(u => u.Id == userId);
                        selectedUser.PasswordSalt = PasswordEncryptor.GenerateSalt();
                        selectedUser.Password     = PasswordEncryptor.GeneratePassword(passwordProposition.Password, selectedUser.PasswordSalt);
                        MainWindowViewModel.SaveContext();
                        selectedUser = new User();
                        this.Close();
                    }
                    else
                    {
                        MainWindowViewModel.NotifyUser("Those passwords didn't match. Try again.");
                    }
                }
                else
                {
                    MainWindowViewModel.NotifyUser("Password is to short, should contain at least 8 characters.");
                }
            }
            else
            {
                MainWindowViewModel.NotifyUser("Invalid password. Password should contain at least one number or special character.");
            }
        }         // Save_password()
Ejemplo n.º 30
0
        private void CheckUserArrivalTime(User user, dbDataContext db)
        {
            var decryptedSystemPassword = PasswordEncryptor.Decrypt(user.SystemPassword);
            var decryptedSystemNumber   = PasswordEncryptor.Decrypt(user.SystemNumber);

            var today = DateTime.Today;

            var loginParameters = new HappyHoursLoginParameters()
            {
                Credentials = new HappyHoursCredentials()
                {
                    Username = user.SystemEmail,
                    Password = decryptedSystemPassword,
                    Number   = decryptedSystemNumber
                },
                StartDate = new DateTime(today.Year, today.Month, today.Day),
                EndDate   = new DateTime(today.Year, today.Month, today.Day)
            };

            HappyHoursCoreBL manager       = new HappyHoursCoreBL();
            HappyHourSummary summaryResult = manager.GetSummary(loginParameters);

            var dayHour = summaryResult.DayDetails.FirstOrDefault();

            if (dayHour == null)
            {
                return;
            }

            HandleUserTime(user, dayHour, summaryResult.User, db);
        }