public void GenerateNoParamTest()
        {
            //Arrange
            string password;

            //Act
            password = RandomPassword.Generate();

            //Assert
            Assert.True(password.Count() >= 8 && password.Count() <= 10);
        }
예제 #2
0
        public IPassword Generate()
        {
            var clear = RandomPassword.Generate(PasswordCharactersCount);
            var salt  = cryptoService.GenerateSalt();
            var hash  = cryptoService.Compute(clear, salt);

            return(new Password()
            {
                Clear = clear, Hash = hash, Salt = salt
            });
        }
예제 #3
0
        public ActionResult ResetPassword(ResetNewPasswordViewModel _passwordInfo)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View());
                }

                AuthenticatedUser _authUser;

                using (AuthRepository Repo = new AuthRepository())
                {
                    _authUser = Repo.GetAuthenticatedUserById(CurrentUser.EmployeeInfoId);
                }

                if (_authUser.IsFirstTimeLogin == false)
                {
                    return(RedirectToAction("GeneralInfo", "Profile"));
                }

                if (RijndaelCrypt.DecryptPassword(_authUser.PasswordHash, _authUser.Salt) == _passwordInfo.NewPassword)
                {
                    TempData["Msg"] = AlertMessageProvider.FailureMessage("New password should not be same as current password.");

                    return(View());
                }

                var _accountInfo = new AccountInfo();
                _accountInfo.Id               = CurrentUser.AccountId;
                _accountInfo.Salt             = RandomPassword.Generate(18, 20);
                _accountInfo.PasswordHash     = RijndaelCrypt.EncryptPassword(_passwordInfo.NewPassword, _accountInfo.Salt);
                _accountInfo.IsFirstTimeLogin = false;

                using (AccountRepository Repo = new AccountRepository())
                {
                    Repo.ChangeNewPassword(_accountInfo);
                }

                var ctx         = Request.GetOwinContext();
                var authManager = ctx.Authentication;
                authManager.SignOut("ApplicationCookie");

                TempData["Msg"] = "<span style='color:green; text-align:center;'>Password has been reset successfully.</span>";
                return(RedirectToAction("Login", "Auth", new { area = "" }));
            }

            catch (Exception ex)
            {
                TempData["Msg"] = AlertMessageProvider.FailureMessage(ex.ToString());

                return(View());
            }
        }
        public void GenerateWithLengthTest()
        {
            //Arrange
            string password;
            int    length = 12;

            //Act
            password = RandomPassword.Generate(length);

            //Assert
            Assert.True(password.Count() == length);
        }
예제 #5
0
        public ActionResult ResetPassword(ResetNewPasswordViewModel passwordInfo)
        {
            try
            {
                if (TempData["AccountId"] == null)
                {
                    return(RedirectToAction("Login", "Auth"));
                }

                if (!ModelState.IsValid)
                {
                    return(View());
                }

                int _accountId   = (int)TempData["AccountId"];
                var _accountInfo = new AccountInfo();

                _accountInfo.Id = _accountId;

                _accountInfo.Salt         = RandomPassword.Generate(18, 20);
                _accountInfo.PasswordHash = RijndaelCrypt.EncryptPassword(passwordInfo.NewPassword, _accountInfo.Salt);

                _accountInfo.IsFirstTimeLogin = false;

                using (AccountRepository Repo = new AccountRepository())
                {
                    Repo.ChangeNewPassword(_accountInfo);
                }

                using (AccountConfirmationRepository Repo = new AccountConfirmationRepository())
                {
                    AccountConfirmationInfo _accountConfirmation = null;

                    _accountConfirmation = Repo.GetAccountConfirmationByAccountId(_accountId);

                    if (_accountConfirmation != null)
                    {
                        Repo.DeleteAccountConfirmation(_accountConfirmation.Id);
                    }
                }

                TempData["Msg"] = "<span style='color:green; text-align:center;'>Password has been reset successfully.</span>";

                return(RedirectToAction("Login", "Auth"));
            }

            catch (Exception ex)
            {
                TempData["Msg"] = "<span style='color:red; text-align:center;'>" + ex.Message.ToString() + ".</span>";
                return(View());
            }
        }
예제 #6
0
        public string GeneratePassword()
        {
            var isMatch  = false;
            var password = string.Empty;

            while (!isMatch)
            {
                password = RandomPassword.Generate(8, 8);
                isMatch  = PasswordRegex.IsMatch(password);
            }

            return(password);
        }
        public void GenerateWithTwoLengthTest()
        {
            //Arrange
            string password;
            int    minLength = 12;
            int    maxLength = 16;

            //Act
            password = RandomPassword.Generate(minLength, maxLength);

            //Assert
            Assert.True(password.Count() >= minLength && password.Count() <= maxLength);
        }
예제 #8
0
        public void GeneratesPasswordWithSpecifiedLengthCorrectly()
        {
            // arrange
            const Int32 Length = 15;
            // act
            var result = RandomPassword.Generate(Length);

            // assert
            Assert.True(result.Length == Length, $"Result length {result.Length} is not {Length}.");
            Assert.True(ContainsCharacter(result, _passwordAllowedSpecialCharacters), "Result does not contain any special characters");
            Assert.True(ContainsCharacter(result, _passwordCharactersLowerCase), "Result does not contain any lower case characters");
            Assert.True(ContainsCharacter(result, _passwordCharactersNumeric), "Result does not contain any numeric characters");
            Assert.True(ContainsCharacter(result, _passwordCharactersUpperCase), "Result does not contain any upper case characters");
        }
예제 #9
0
        public ActionResult ChangePassword(ChangePasswordViewModel passwordInfo)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View());
                }

                var _account = new AccountInfo();

                using (AccountRepository Repo = new AccountRepository())
                {
                    _account = Repo.GetEmployeeAccountById(CurrentUser.AccountId);
                }

                string decryptedPassword = RijndaelCrypt.DecryptPassword(_account.PasswordHash, _account.Salt);

                if (decryptedPassword != passwordInfo.CurrentPassword)
                {
                    TempData["Msg"] = AlertMessageProvider.FailureMessage("Current password is invalid.");

                    return(View());
                }

                if (decryptedPassword == passwordInfo.NewPassword)
                {
                    TempData["Msg"] = AlertMessageProvider.FailureMessage("New password should not be same as current password.");

                    return(View());
                }

                _account.Salt         = RandomPassword.Generate(18, 20);
                _account.PasswordHash = RijndaelCrypt.EncryptPassword(passwordInfo.NewPassword, _account.Salt);

                using (AccountRepository Repo = new AccountRepository())
                {
                    Repo.ChangeNewPassword(_account);
                }

                TempData["Msg"] = AlertMessageProvider.SuccessMessage("Password changed successfully.");

                return(View());
            }

            catch (Exception ex)
            {
                return(View("Error", new HandleErrorInfo(ex, "Auth", "ChangePassword")));
            }
        }
예제 #10
0
        //  <appSettings>
        //  <add key = "correoElectronico" value="*****@*****.**"/>
        //  <add key = "contraseniaCorreo" value="contra123"/>
        //</appSettings>

        protected void btnRecuperar_Click(object sender, EventArgs e)
        {
            int varCedula = Convert.ToInt32(cedula.Value.Trim());


            List <Usuarios> allUsers = new List <Usuarios>();

            allUsers = SIRESEP.BS.ManUsuario._Instancia.Mostrar();

            int  largo = Convert.ToInt32(allUsers.Count.ToString());
            bool ok    = false;

            for (int i = 0; i < largo; i++)
            {
                int cedulaForm = Convert.ToInt32(cedula.Value.Trim());
                int cedulaBD   = Convert.ToInt32(allUsers[i]._cedula.ToString());


                if (cedulaForm == cedulaBD)
                {
                    //Se hace nueva contraseña random y se manda al correo
                    ICryptoService cryptoService    = new PBKDF2();
                    string         contraNueva      = RandomPassword.Generate(10, PasswordGroup.Lowercase, PasswordGroup.Uppercase, PasswordGroup.Numeric);
                    string         salt             = cryptoService.GenerateSalt();
                    string         contraEncriptada = cryptoService.Compute(contraNueva);
                    var            query2           = (from a in SIRESEP.BS.ManUsuario._Instancia.Mostrar().AsEnumerable()
                                                       where a._cedula == (cedula.Value)
                                                       select a._correoElectronico);
                    string correeo;
                    correeo = query2.First().Trim();

                    //usuarioo = new Usuarios();
                    usuarioo = new Usuario();
                    usuarioo.correoElectronico = correeo;
                    usuarioo.cedula            = cedula.Value.Trim();
                    usuarioo.contrasena        = contraEncriptada;
                    usuarioo.salt = salt;
                    SIRESEP.BS.ManUsuario._Instancia.ActualizarContra(usuarioo);
                    EnviarEmail(usuarioo.correoElectronico, contraNueva);
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "AlertaUsuario", "window.onload = function(){ alert('Se ha enviado la nueva contrasenia al correo');};", true);
                }
                else
                {
                    //Response.Redirect("FrLogin.aspx");
                    Response.Write("<script>window.location.href='FrLogin.aspx';</script>");
                    // ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "AlertaUsuario", "window.onload = function(){ alert('El usuario no existe');};", true);
                }
            }
        }
예제 #11
0
        public void GeneratesPasswordWithCorrectLengthWithOnlyLowerCaseCharacters()
        {
            // arrange
            const Int32 Length = 15;

            // act
            var result = RandomPassword.Generate(Length, SpecialCharacter.No, DigitCharacter.No, UpperCaseCharacter.No, LowerCaseCharacter.Yes);

            // assert
            Assert.True(result.Length == Length, $"Result length {result.Length} is not {Length}.");
            Assert.False(ContainsCharacter(result, _passwordAllowedSpecialCharacters), "Result contains special characters");
            Assert.True(ContainsCharacter(result, _passwordCharactersLowerCase), "Result does not contain any lower case characters");
            Assert.False(ContainsCharacter(result, _passwordCharactersNumeric), "Result contains numeric characters");
            Assert.False(ContainsCharacter(result, _passwordCharactersUpperCase), "Result contains upper case characters");
        }
예제 #12
0
        public void GeneratesDefaultPasswordCorrectly()
        {
            // arrange

            // act
            var result = RandomPassword.Generate();

            // assert
            Assert.True(result.Length >= _minimumLength, "Result length too short");
            Assert.True(result.Length <= _maximumLength, "Result length too long.");
            Assert.True(ContainsCharacter(result, _passwordAllowedSpecialCharacters), "Result does not contain any special characters");
            Assert.True(ContainsCharacter(result, _passwordCharactersLowerCase), "Result does not contain any lower case characters");
            Assert.True(ContainsCharacter(result, _passwordCharactersNumeric), "Result does not contain any numeric characters");
            Assert.True(ContainsCharacter(result, _passwordCharactersUpperCase), "Result does not contain any upper case characters");
        }
        public IActionResult RecuperarClave(String email)
        {
            string obtenerClave = ConsultaUsuario.Leer_Correo(email);

            if (obtenerClave != null && obtenerClave.Equals(email))
            {
                string clave = RandomPassword.Generate(8);
                ConsultaUsuario.Cambiar_clave(email, clave);
                EmailSender.Send(email, "Cambio de contraseña", "Su nueva contraseña temporal es: " + clave);

                return(RedirectToAction("Login", "Usuario"));
            }
            Console.WriteLine("No envio coreo");
            return(RedirectToAction("Login", "Usuario"));
        }
        public ActionResult RestaurarPassword(int?id)
        {
            if (ModelState.IsValidField("usuario"))
            {
                tbUsuario tbUsuario = db.tbUsuario.Find(id);
                if (tbUsuario != null)
                {
                    string emailsalida    = "*****@*****.**";
                    string passwordsalida = "sistemadeinventari0";
                    string emaildestino   = tbUsuario.usu_Correo;
                    string passwordnueva  = RandomPassword.Generate(8, PasswordGroup.Uppercase, PasswordGroup.Lowercase, PasswordGroup.Numeric);
                    db.Entry(tbUsuario).State = EntityState.Modified;
                    try
                    {
                        IEnumerable <object> List = null;
                        var MsjError = "0";
                        List = db.UDP_Acce_tbUsuario_PasswordRestore(tbUsuario.usu_Id, passwordnueva);
                        foreach (UDP_Acce_tbUsuario_PasswordRestore_Result Usuario in List)
                        {
                            MsjError = Usuario.MensajeError;
                        }

                        Email(emailsalida, passwordsalida, emaildestino, passwordnueva);

                        if (MsjError.StartsWith("-1"))
                        {
                            ModelState.AddModelError("", "No se guardó el registro , contacte al Administrador");
                            return(View(tbUsuario));
                        }
                        else
                        {
                            return(RedirectToAction("Index"));
                        }
                    }
                    catch (Exception Ex)
                    {
                        Ex.Message.ToString();
                        ModelState.AddModelError("", "No se guardó el registro , contacte al Administrador");
                        return(View(tbUsuario));
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "El usuario ingresado no existe");
            }
            return(RedirectToAction("Index"));
        }
예제 #15
0
        /// <summary>
        /// Create a password, associate it with user and send an activation email to that user
        /// </summary>
        private async Task SendActivationEmail(UserCore newUser)
        {
            var password = RandomPassword.Generate();
            await _securityRepo.ChangePasswordAsync(newUser.UserName, password);

            ViewData["password"] = password;
            ViewData["link"]     = ConfigurationManager.AppSettings["domainUrl"];

            var emailBody = this.RenderPartialViewToString("~/Views/Registration/Activation/ConfirmationEmailTemplate.cshtml",
                                                           ViewData);

            _logger.Info($"Sending activation email to {newUser.Email}");
            await _emailService.SendMailAsync(Email.LantmannenFromAddress, new[] { newUser.Email },
                                              new string[0], "Välkommen till LM" + "\xB2", emailBody, _ticketProvider.GetTicket())
            .ConfigureAwait(false);
        }
예제 #16
0
        public void GeneratesPasswordWithSpecifiedMinAndMaxLengthCorrectly()
        {
            // arrange
            const Int32 MinimumLength = 4;
            const Int32 MaximumLength = 20;
            // act
            var result = RandomPassword.Generate(MinimumLength, MaximumLength);

            // assert
            Assert.True(result.Length >= MinimumLength, "Result length too short");
            Assert.True(result.Length <= MaximumLength, "Result length too long.");
            Assert.True(ContainsCharacter(result, _passwordAllowedSpecialCharacters), "Result does not contain any special characters");
            Assert.True(ContainsCharacter(result, _passwordCharactersLowerCase), "Result does not contain any lower case characters");
            Assert.True(ContainsCharacter(result, _passwordCharactersNumeric), "Result does not contain any numeric characters");
            Assert.True(ContainsCharacter(result, _passwordCharactersUpperCase), "Result does not contain any upper case characters");
        }
        //Implementatie van het register command
        private async void Register(object obj)
        {
            NewUser.Role = "user";
            string password = RandomPassword.Generate(12);

            NewUser.Salt     = RandomPassword.Generate(30);
            NewUser.Password = Hasher.ConvertStringToHash(password, NewUser.Salt);
            NewUser.UserId   = dataService.RegisterEmployee(NewUser);

            //Toegevoegd zodat bij het testen er geen dialog word weergegeven, dit gaf een exception
            if (!IsTesting)
            {
                var dialog = new MessageDialog("Id: " + NewUser.UserId + "\nPassword: "******"Created new employee: " + NewUser.FirstName + " " + NewUser.LastName);
                await dialog.ShowAsync();
            }
        }
        public void GenerateCharsetCheck()
        {
            // '-' must be escaped because it has a special meaning in a character class
            // the rest dont need to be escaped because they are in a character class
            string CHARS_SPECIAL = @"*$\-+?_&=!%.,#~/";
            Regex  validChar     = new Regex("^[A-Za-z0-9" + CHARS_SPECIAL + "]$");

            // test with 100 random strings of random length
            for (int i = 0; i < 100; i++)
            {
                int    len = TestInfrastructure.RandomGen.Next(1, 1000);
                string s   = RandomPassword.Generate(len);
                foreach (char c in s)
                {
                    Assert.IsTrue(validChar.IsMatch(c.ToString()));
                }
            }
        }
예제 #19
0
        public void GeneratesPasswordWithCorrectMinimumAndMaximumLengthWithOnlyLowerCaseCharacters()
        {
            // arrange
            const Int32  MinimumLength     = 4;
            const Int32  MaximumLength     = 20;
            const String SpecialCharacters = "$&";

            // act
            var result = RandomPassword.Generate(MinimumLength, MaximumLength, SpecialCharacter.Yes, DigitCharacter.No, UpperCaseCharacter.No, LowerCaseCharacter.No, SpecialCharacters);

            // assert
            Assert.True(result.Length >= MinimumLength, "Result length too short");
            Assert.True(result.Length <= MaximumLength, "Result length too long.");
            Assert.True(ContainsCharacter(result, SpecialCharacters), "Result does contain special characters");
            Assert.False(ContainsCharacter(result, _passwordCharactersLowerCase), "Result contains lower case characters");
            Assert.False(ContainsCharacter(result, _passwordCharactersNumeric), "Result contains numeric characters");
            Assert.False(ContainsCharacter(result, _passwordCharactersUpperCase), "Result contains upper case characters");
        }
예제 #20
0
 public ActionResult Login([Bind(Include = "username,password")] User user, bool rememberMe)
 {
     if (ModelState.IsValid)
     {
         if (IsValid(user.username, user.password))
         {
             user = db.Users.Find(user.username);
             FormsAuthentication.SetAuthCookie(user.username, rememberMe);
             user.attempts        = 0;
             db.Entry(user).State = EntityState.Modified;
             db.SaveChanges();
             genLog("Login", "Logged in", user.username);
             return(RedirectToAction("Profile", "Users"));
         }
         user = db.Users.Find(user.username);
         if (user.locked == true)
         {
             ModelState.AddModelError("LoginMsg", "Account Locked. Follow link in email to unlock");
         }
         else
         {
             user.attempts++;
             if (user.attempts == 5)
             {
                 user.locked = true;
                 string unlKey = "/Unlock?kstr=" + RandomPassword.Generate(44, PasswordGroup.Uppercase, PasswordGroup.Lowercase, PasswordGroup.Numeric);
                 genLog("Login", "Accout Locking, link = " + unlKey, user.username);
                 user.unlString = unlKey;
                 ModelState.AddModelError("LoginMsg", "Account Locked. Follow link in email to unlock");
                 db.Entry(user).State = EntityState.Modified;
                 db.SaveChanges();
             }
             else
             {
                 ModelState.AddModelError("LoginMsg", "Login Data is Incorrect. " + (5 - user.attempts) + " Attempts remaining");
                 db.Entry(user).State = EntityState.Modified;
                 db.SaveChanges();
             }
         }
     }
     user.password = "";
     return(View(user));
 }
예제 #21
0
        //protected override void OnAfterLoadData()		{		}

        /// <summary>
        /// generate a unique reference number for this cart using readble characters
        /// </summary>
        /// <returns></returns>
        public static string GenerateRef()
        {
            string result = "";

            for (int sc = 0; ; sc++)
            {
                if (sc > 20)
                {
                    throw new Exception("ref gen failed");
                }
                result = RandomPassword.Generate(6, 6, "Q", "QWERTYPASDFGHJKLZXBNM", "23456", "2") + "-" + RandomPassword.Generate(3, 3, "W", "WXYZ", "23456", "2");
                if (ShoppingCartOrderList.LoadByOrderRef(result).RecordCount == 0)
                {
                    break;
                }
            }

            return(result);
        }
예제 #22
0
 private void ReplaceSampleSitenameInConfig(string filename, string sitename, string subpath, string theme)
 {
     if (File.Exists(filename))
     {
         string origText        = FileSystem.GetFileContents(filename, false);
         string appsettingsFile = origText;
         //Web.Write(appsettingsFile.FmtPlainTextAsHtml());
         //sitename.beweb.co.nz
         //sitename.co.nz
         //<add key="SiteName" value="sitename"/>
         //[email protected]
         //staging.beweb.co.nz
         //www.sitename.co.nz
         appsettingsFile = appsettingsFile.Replace("clientname/sitename", subpath);
         appsettingsFile = appsettingsFile.Replace("sitename", sitename.ToLower());              // this should correctly do the same as the below (given Replace is case sensitive)
         //appsettingsFile = appsettingsFile.Replace("<add key=\"SiteName\" value=\"sitename\"/>", "<add key=\"SiteName\" value=\"" + sitename.SplitTitleCase() + "\"/>");
         //appsettingsFile = appsettingsFile.Replace("sitename.beweb.co.nz", "" + sitename.ToLower() + ".beweb.co.nz");
         //appsettingsFile = appsettingsFile.Replace("sitename.co.nz", "" + sitename.ToLower() + ".co.nz");
         //appsettingsFile = appsettingsFile.Replace("*****@*****.**", "website@" + sitename.ToLower() + ".co.nz");
         //appsettingsFile = appsettingsFile.Replace("sitename.beweb.co.nz", "" + sitename.ToLower() + ".beweb.co.nz");
         //appsettingsFile = appsettingsFile.Replace("www.sitename.co.nz", "www." + sitename.ToLower() + ".co.nz");
         appsettingsFile = appsettingsFile.Replace(@"key=""Theme"" value=""focus""", @"key=""Theme"" value=""blanktheme""");
         appsettingsFile = appsettingsFile.Replace("blanktheme", theme);
         appsettingsFile = appsettingsFile.Replace("--CryptKey--", RandomPassword.Generate(48, 48,
                                                                                           RandomPassword.PASSWORD_CHARS_LCASE,
                                                                                           RandomPassword.PASSWORD_CHARS_UCASE,
                                                                                           RandomPassword.PASSWORD_CHARS_NUMERIC,
                                                                                           RandomPassword.PASSWORD_CHARS_SPECIAL
                                                                                           )); //jdsjnkjksdioa89493920sdjkasn-1239mflmkkckd$%^*(
         appsettingsFile = appsettingsFile.Replace("BuildStartDate\" value=\"tbd", "BuildStartDate\" value=\"" + Fmt.DateTimeCompressed(DateTime.Now));
         if (appsettingsFile != origText)
         {
             File.WriteAllText(filename, appsettingsFile);
             Log("updated appsetting[" + filename + "] <br />");
         }
         else
         {
             Log("didnt update the appsettings [" + filename + "]<br />");
         }
     }
 }
예제 #23
0
        public UserDO InviteNewUser(string newUserEmail, Guid projectId, Guid invitingUserId)
        {
            var project      = _projectDao.GetById(projectId);
            var invitingUser = _userDao.GetById(invitingUserId);

            var generatedPassword = RandomPassword.Generate();
            var user = new UserDO
            {
                EMail            = newUserEmail,
                IsCompanyAdmin   = false,
                IsPinzSuperAdmin = false,
                CompanyId        = invitingUser.CompanyId,
                Password         = generatedPassword
            };

            user = _userDao.Create(user);
            AddUserToProject(user.UserId, projectId, false);

            InvitationEmailSender.SendProjectInvitation(newUserEmail, invitingUser, project, generatedPassword);

            return(user);
        }
예제 #24
0
        protected void btnReset_Click(object sender, EventArgs e)
        {
            int Code = int.Parse(txtHRCode.Text);

            using (EmployeeDBContext db = new EmployeeDBContext())
            {
                EmployeesMasterData ResetEmployeeMD = (from Employee_tbl in db.EmployeesMasterDatas where Employee_tbl.EmployeeHRCode == Code select Employee_tbl).FirstOrDefault();
                ResetEmployeeMD.EmployeePassword   = RandomPassword.Generate(6, 8);
                ResetEmployeeMD.MustChangePassword = true;
                int roweffected = db.SaveChanges();
                if (roweffected > 0)
                {
                    Clear();
                    lblEmployeeSaveStatus.Text = "The New Password is " + ResetEmployeeMD.EmployeePassword;
                }
                else
                {
                    lblEmployeeSaveStatus.Text = "Error";
                    return;
                }
            }
        }
예제 #25
0
        public String send(String type, String data, String email)
        {
            if (!IsValidEmailAddress(email))
            {
                return("Địa chỉ Email không đúng định dạng!");
            }
            else
            {
                String Ranpassword = RandomPassword.Generate();
                Servies.SysUserServies.UpdatePasswordByEmail(email, Ranpassword);
                //Send Email
                string smtpAddress = "smtp.gmail.com";
                int    portNumber  = 587;
                bool   enableSSL   = true;
                string emailFrom   = "*****@*****.**";
                string password    = "******";
                string emailTo     = email;
                string subject     = "Mật khẩu mới cho email của bạn";
                string body        = "Hello, Mr/Mrs <br>";
                body += "Mật khẩu của bạn : " + Ranpassword;
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress(emailFrom);
                mail.To.Add(email);
                mail.Subject    = subject;
                mail.Body       = body;
                mail.IsBodyHtml = true;
                using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                {
                    smtp.Credentials = new System.Net.NetworkCredential(emailFrom, password);
                    smtp.EnableSsl   = enableSSL;
                    smtp.Send(mail);
                }

                return("Password mới đã được gửi tới hòm thư của bạn!");
            }
        }
예제 #26
0
        public ActionResult Index(sEmployeeModel SE)
        {
            var    connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            string queryString      = "";

            /*Redundant: yes but the rest of the implementation requires references to the staff ID
             * and there was no effective way to enforce that the staff ID be 5 digits as an int*/
            int actualStaffID;

            int.TryParse(SE.staffIDInString, out actualStaffID);
            SE.staffID = actualStaffID;
            /////////////////////////////

            //Validations
            bool hasValidationErrors = false;

            //Check if username already exists
            queryString = "SELECT Employee_ID, User_Name FROM dbo.Employee WHERE dbo.Employee.User_Name = '" + SE.userName + "' OR dbo.Employee.Employee_ID = '" + SE.staffID + "'";
            using (var connection = new SqlConnection(connectionString))
            {
                var command = new SqlCommand(queryString, connection);
                connection.Open();
                using (var reader = command.ExecuteReader())
                {
                    sEmployeeModel tempEmp = (sEmployeeModel)TempData["EmptyEmployee"];
                    while (reader.Read())
                    {
                        int id = (int)reader[0];
                        if (tempEmp.staffID != id && id == SE.staffID)
                        {
                            ModelState.AddModelError("staffID", "Staff ID already exists.");
                            hasValidationErrors = true;
                        }
                        string userName = (string)reader[1];

                        if (!userName.Equals(tempEmp.userName) && userName.Equals(SE.userName))
                        {
                            ModelState.AddModelError("userName", "Username already exists.");
                            hasValidationErrors = true;
                        }
                    }
                }
                //End check if username exists.


                /*Check if the employee is the line manager of a department
                 * Here, I can easily retrieve the department ID and use that to
                 * check if the department ID is assigned to at least one staff member.
                 * But I have not implemented this because it's not clear what I would
                 * or would not do if or if not there is a staff member associated with the
                 * department*/
                queryString = "SELECT Line_Manager_ID " +
                              "FROM dbo.Department " +
                              "WHERE dbo.Department.Line_Manager_ID = '" + SE.staffID + "' " +
                              "AND dbo.Department.Line_Manager_ID IS NOT NULL";
                command = new SqlCommand(queryString, connection);
                using (var reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        if (SE.accountStatus == false)
                        {
                            ModelState.AddModelError("accountStatus", "Cannot deactivate a department's Line Manager.\r\n Please replace the Line Manager first.");
                            hasValidationErrors = true;
                        }
                        if (SE.isAdmin)
                        {
                            ModelState.AddModelError("isAdmin", "The employee the active Line Manager of a department. Adminitrator users do not have the functionalities of a Line Manager.");
                            hasValidationErrors = true;
                        }

                        /*Check if user tried to change the LM Role of an active LM of a department
                         * Normally it's okay to deactivate a person with the LM role if they are not
                         * the active LM of a department.*/
                        Dictionary <int, string> lmCheckRoleOptions = (Dictionary <int, string>)TempData["nonDisplayRoleOptions"];
                        int            lmID         = lmCheckRoleOptions.FirstOrDefault(obj => obj.Value == "LM").Key;
                        sEmployeeModel lmCheckModel = (sEmployeeModel)TempData["EmptyEmployee"];
                        string         lsr;
                        string         rsr;
                        string         losr;
                        string         rosr;
                        if (SE.staffType == null)
                        {
                            lsr = "";
                        }
                        else
                        {
                            lsr = SE.staffType;
                        }
                        if (lmCheckModel.staffType == null)
                        {
                            rsr = "";
                        }
                        else
                        {
                            rsr = lmCheckModel.staffType;
                        }
                        if (SE.optionalStaffType == null)
                        {
                            losr = "";
                        }
                        else
                        {
                            losr = SE.optionalStaffType;
                        }
                        if (lmCheckModel.optionalStaffType == null)
                        {
                            rosr = "";
                        }
                        else
                        {
                            rosr = lmCheckModel.optionalStaffType;
                        }

                        if (lmCheckModel.staffType == lmID.ToString())
                        {
                            if (!lsr.Equals(rsr) && !losr.Equals(rsr))
                            {
                                ModelState.AddModelError("staffType", "The employee is the active line manager of a depaartment. \r\n Please replace the Line Manager first.");
                                hasValidationErrors = true;
                            }
                        }
                        if (lmCheckModel.optionalStaffType == lmID.ToString())
                        {
                            if (!losr.Equals(rosr) && !lsr.Equals(rosr))
                            {
                                ModelState.AddModelError("optionalStaffType", "The employee is the active line manager of a depaartment. \r\n Please replace the Line Manager first.");
                                hasValidationErrors = true;
                            }
                        }
                    }
                }

                connection.Close();
            }



            /*Make sure the selection lists for departments, roles, secondary lm
             * and the non-display role options are persisted. And then redirect to
             * back to the view.*/
            if (hasValidationErrors)
            {
                sEmployeeModel EmptyEmployee = (sEmployeeModel)TempData["EmptyEmployee"];
                SE.staffTypeSelectionOptions      = EmptyEmployee.staffTypeSelectionOptions;
                SE.departmentList                 = EmptyEmployee.departmentList;
                SE.SecondLMSelectionOptions       = EmptyEmployee.SecondLMSelectionOptions;
                TempData["EmptyEmployee"]         = EmptyEmployee;
                TempData["nonDisplayRoleOptions"] = TempData["nonDisplayRoleOptions"];
                return(View(SE));
            }
            // End validations


            //Table insertions
            SE.password = RandomPassword.Generate(7, 7);
            string secondLMtext      = "";
            string secondLmValueText = "";

            if (SE.secondLineManager != null)
            {
                secondLMtext      = ", [2nd_Line_Manager] = '" + SE.secondLineManager + "'";
                secondLmValueText = "', '" + SE.secondLineManager;
            }

            /*Had to use deptname to store the actual department ID because for some
             * reason the view wouldn't store the value of the dropdown for department
             * selection in the deptID int*/
            if (SE.deptName == null)
            {
                queryString = "UPDATE dbo.Employee SET (First_Name, " +
                              "Last_Name, User_Name, Designation, Email, Gender, PH_No, " +
                              "Emp_Start_Date, Account_Status" + secondLMtext + ") VALUES('" + SE.firstName +
                              "', '" + SE.lastName + "', '" + SE.userName +
                              "', '" + SE.designation + "', '" + SE.email +
                              "', '" + SE.gender + "', '" + SE.phoneNo + "', '" + SE.empStartDate +
                              "', '" + SE.accountStatus + secondLmValueText + "') " +
                              "WHERE dbo.Employee.Employee_ID = '" + SE.staffID + "' ";
            }
            else
            {
                queryString = "UPDATE dbo.Employee SET First_Name = '" + SE.firstName + "', " +
                              "Last_Name = '" + SE.lastName + "', User_Name = '" + SE.userName +
                              "', Designation = '" + SE.designation + "', Email = '" + SE.email +
                              "', Gender = '" + SE.gender + "', PH_No = '" + SE.phoneNo + "', " +
                              "Emp_Start_Date = '" + SE.empStartDate.ToString("yyyy-MM-dd") + "', Account_Status = '" + SE.accountStatus +
                              "', Department_ID = '" + SE.deptName + "', Emp_End_Date = '" + SE.empEndDate.ToString("yyyy-MM-dd") + "' " + secondLMtext + " " +
                              "WHERE dbo.Employee.Employee_ID = '" + SE.staffID + "' ";
            }
            using (var connection = new SqlConnection(connectionString))
            {
                var command = new SqlCommand(queryString, connection);
                connection.Open();
                using (var reader = command.ExecuteReader())
                    connection.Close();
            }

            /*Clear the employee's roles before adding the updated ones.
             * Easiest way to make sure that only the updated roles remain.*/
            queryString = "DELETE FROM dbo.Employee_Role " +
                          "WHERE dbo.Employee_Role.Employee_ID = '" + SE.staffID + "' ";
            using (var connection = new SqlConnection(connectionString))
            {
                var command = new SqlCommand(queryString, connection);
                connection.Open();
                using (var reader = command.ExecuteReader())
                    connection.Close();
            }

            /*We are now assuming that all roles except for admin are also a
             *  staff member, so the staff member role will be hard coded */
            Dictionary <int, string> nonDisplayRoleOptions = (Dictionary <int, string>)TempData["nonDisplayRoleOptions"];

            if (SE.isAdmin)
            {
                int adminID = nonDisplayRoleOptions.FirstOrDefault(obj => obj.Value == "Admin").Key;
                queryString = "INSERT INTO dbo.Employee_Role (Employee_ID, Role_ID) " +
                              "VALUES ('" + SE.staffID + "', '" + adminID + "') ";
            }
            else
            {
                int  staffRoleID       = nonDisplayRoleOptions.FirstOrDefault(obj => obj.Value == "Staff").Key;
                bool toAddStaffType    = true;
                bool toAddOptionalType = true;
                if (SE.staffType == null)
                {
                    toAddStaffType = false;
                }
                if (SE.optionalStaffType == null)
                {
                    toAddOptionalType = false;
                }
                if (SE.staffType != null && SE.staffType.Equals(SE.optionalStaffType))
                {
                    queryString = CreateRolesQuery(toAddStaffType, false, SE, staffRoleID);
                }
                else
                {
                    queryString = CreateRolesQuery(toAddStaffType, toAddOptionalType, SE, staffRoleID);
                }
            }

            using (var connection = new SqlConnection(connectionString))
            {
                var command = new SqlCommand(queryString, connection);
                connection.Open();
                using (var reader = command.ExecuteReader())
                    connection.Close();
            }

            //End Insertions

            /*Construct notification e-mail only if the username has been changed*/

            TempData["EmpID"] = SE.staffIDInString;
            string successMessage = "The details of " + SE.firstName + " " + SE.lastName + "have been edited.";

            TempData["SuccessMessage"] = successMessage;
            return(RedirectToAction("Index"));
        }
예제 #27
0
        public void RandomPassword_Generates_Both_Lowercase_And_Uppercase()
        {
            string password = RandomPassword.Generate(PasswordGroup.Uppercase, PasswordGroup.Lowercase);

            Assert.IsTrue(Regex.IsMatch(password, "^[A-Za-z]+$"), "Non-uppercase found in in uppercase only");
        }
예제 #28
0
        public void RandomPassword_Generates_Only_Lowercase()
        {
            string password = RandomPassword.Generate(PasswordGroup.Lowercase);

            Assert.IsTrue(Regex.IsMatch(password, "^[a-z]+$"), "Non-lowercase found in in lowercase only");
        }
예제 #29
0
 public ActionResult GeneratePassword()
 {
     return(Content(RandomPassword.Generate(7, 12)));
 }
 private void NewLogin()
 {
     RandomPassword.SetParams(true, true, false, false);
     User.Login = RandomPassword.Generate(10);
     RandomPassword.Restore();
 }