Example #1
0
        public bool SignUp(SignUpRequestDto signUpRequest)
        {
            var user = _repository.Get <AppUser>(x => x.Username == signUpRequest.Username || x.Email == signUpRequest.Email);

            if (user == null)
            {
                string salt = PasswordHasher.CreateSalt();
                string hash = PasswordHasher.CreateHashedPassword(signUpRequest.Password, salt);

                _repository.Insert <AppUser>(
                    new AppUser
                {
                    Email    = signUpRequest.Email,
                    Username = signUpRequest.Username,
                    Salt     = salt,
                    Password = hash
                });
                _repository.SaveChanges();
                return(true);
            }
            else
            {
                return(false);
            }
        }
Example #2
0
        /*****************************************************************************/
        /// <summary>
        /// Generates a time-based one-time password (TOTP)
        /// </summary>
        /// <returns>Returns a tuple with generated secret and code  (TOTP). Secret should be persisted (encrypted) for later validation and code should be sent to user's device, e.g. text message</returns>
        public static (byte[] Secret, int Code) GenerateCode()
        {
            var secret = PasswordHasher.CreateSalt(10);  // Create a random set of bytes for the secret
            var code   = TOTPGenerator.GenerateTOTP(secret, DateTime.UtcNow);

            return(secret, code);
        }
Example #3
0
        public Password(Guid systemId, Guid userId, string password)
        {
            var hasher = new PasswordHasher();

            Salt = hasher.CreateSalt(systemId, userId);
            Hash = hasher.HashPassword(Salt, password);
            Date = DateTime.Now;
        }
Example #4
0
 public IActionResult AddStudent([FromBody] Student student)
 {
     student.IndexNumber = $"s{new Random().Next(1, 20000)}";
     student.Salt        = PasswordHasher.CreateSalt();
     student.Password    = PasswordHasher.Create(student.Password, student.Salt);
     studentDbService.AddStudent(student);
     return(Ok(student));
 }
Example #5
0
 private void GenerateNewKeys( )
 {
     if (!IsEIWSProject)
     {
         txtSaltKey2.Text = PasswordHasher.CreateSalt();
     }
     txtPassphrase.Text     = PasswordHasher.CreateSalt();
     txtSaltValue.Text      = PasswordHasher.CreateSalt();
     txtGenerateVector.Text = PasswordHasher.CreateSalt().Substring(0, 16);
 }
Example #6
0
        public void Hashed_Password_Matches()
        {
            var pw   = "thisispassword123";
            var salt = PasswordHasher.CreateSalt();
            var hash = PasswordHasher.CreateHashedPassword(pw, salt);

            var validateResult = PasswordHasher.Validate(pw, salt, hash);

            Assert.IsTrue(validateResult);
        }
Example #7
0
        public void Wrong_Hash_Should_Not_Match()
        {
            var pw   = "thisispassword123";
            var salt = PasswordHasher.CreateSalt();
            var hash = "randomWrongHash";

            var validateResult = PasswordHasher.Validate(pw, salt, hash);

            Assert.IsFalse(validateResult);
        }
Example #8
0
        public void PasswordHasher_CreateInvalidSalt()
        {
            var deriveBytes    = new Rfc2898DeriveBytes(userId.ToByteArray(), new Guid(DeveloperIdentity.DeveloperIdentityId).ToByteArray(), DefaultIterations);
            var expectedHasher = Convert.ToBase64String(deriveBytes.GetBytes(DefaultKeySize + 1));

            passwordHasher = new PasswordHasher();
            var hasher = passwordHasher.CreateSalt(new Guid(DeveloperIdentity.DeveloperIdentityId), userId);

            Assert.AreNotEqual(expectedHasher, hasher);
        }
Example #9
0
        public void PasswordHasher_CreateInvalidSalt()
        {
            var deriveBytes    = new Rfc2898DeriveBytes(_userId.ToByteArray(), Guid.NewGuid().ToByteArray(), DefaultIterations);
            var expectedHasher = Convert.ToBase64String(deriveBytes.GetBytes(DefaultKeySize + 1));

            _passwordHasher = new PasswordHasher();
            var hasher = _passwordHasher.CreateSalt(Guid.NewGuid(), _userId);

            Assert.AreNotEqual(expectedHasher, hasher);
        }
Example #10
0
        public void Hashes_Should_Be_Unique()
        {
            var pw1 = "thisispassword123";
            var pw2 = "thisispassword12";

            var salt  = PasswordHasher.CreateSalt();
            var hash1 = PasswordHasher.CreateHashedPassword(pw1, salt);
            var hash2 = PasswordHasher.CreateHashedPassword(pw2, salt);

            Assert.AreNotEqual(hash1, hash2);
        }
        public async Task <IActionResult> Login([FromForm] ApplicationUser _user)
        {
            if (ModelState.IsValid)
            {
                var user = await _unitOfWork.PhysicalPerson.GetByEmail(_user.Email);

                if (user != null)
                {
                    var salt   = _hasher.CreateSalt();
                    var result = _hasher.VerifyHash(_user.ProvidedPassword, salt, user.PasswordHash);

                    if (result)
                    {
                        var userClaims = new List <Claim>()
                        {
                            //define o cookie
                            new Claim(ClaimTypes.Name, user.UserName),
                            new Claim(ClaimTypes.Email, user.Email),
                            new Claim(ClaimTypes.Role, UserRoleFactory.Role(user.Role)),
                        };
                        var minhaIdentity = new ClaimsIdentity(userClaims, "Usuario");
                        var userPrincipal = new ClaimsPrincipal(new[] { minhaIdentity });
                        //cria o cookie
                        await HttpContext.SignInAsync(userPrincipal);

                        return(RedirectToAction("Index", "Home"));
                    }

                    ViewBag.Message = "Senha incorreta";
                    return(View());
                }
                else
                {
                    ViewBag.Message = "Usuário não encontrado";
                    return(View());
                }
            }

            return(View());
        }
        /// <summary>
        /// Runs the tests.
        /// </summary>
        public bool RunTests()
        {
            try
            {
                EntityManager em = new EntityManager(MetaDatabaseType, MetaDataConnectionString, MetaDataViewName,
                                                     KeyForConnectionStringPassphrase, KeyForConnectionStringSalt, KeyForConnectionStringVector);


                UserDTO possibleUser = new UserDTO();

                possibleUser.UserName = TestUserName;

                PasswordHasher ph   = new PasswordHasher(KeyForUserPasswordSalt);
                string         salt = ph.CreateSalt(possibleUser.UserName);
                possibleUser.PasswordHash = ph.HashPassword(salt, this.Password);

                //  Test 1 - Authenticate user
                UserDTO authUser = em.GetUserForAuthentication(possibleUser);
                // Test 2 -  Get all datasources
                DataTable dtAllDatasources = em.GetAllDatasources(authUser.UserName);

                // Go through each data source
                foreach (DataRow dr in dtAllDatasources.Rows)
                {
                    string datasourceName = dr["DatasourceName"].ToString();
                    string dataTableName  = dr["DatabaseObject"].ToString();
                    //  Test 3 - Get all cols for this data source
                    List <EwavColumn> columnList = em.GetColumnsForDatasource(datasourceName);
                    if (columnList.Count == 0)
                    {
                        throw new Exception("Problem with datasource " + datasourceName);
                    }
                    // Test 4 -  Get raw data
                    Cryptography cy        = new Cryptography();
                    DataTable    dtRawData = em.GetRawDataTable(datasourceName, cy.Decrypt(dataTableName));


                    long f = dtRawData.Rows.Count;
                }


                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Example #13
0
        public UserBO GetUser(UserBO user)
        {
            UserBO         userResponseBO;
            string         keyForUserPasswordSalt = ReadSalt();
            PasswordHasher passwordHasher         = new PasswordHasher(keyForUserPasswordSalt);
            string         salt = passwordHasher.CreateSalt(user.UserName);

            user.PasswordHash = passwordHasher.HashPassword(salt, user.PasswordHash);

            userResponseBO = _userDao.GetUser(user);
            if (userResponseBO != null)
            {
                userResponseBO.UserHighestRole = _userDao.GetUserHighestRole(userResponseBO.UserId);
            }

            return(userResponseBO);
        }
Example #14
0
        public User Create(UserRegisterModel user)
        {
            var existingUser = _userRepository.FindByEmail(user.EmailAddress);

            if (existingUser != null)
            {
                return(existingUser);
            }

            var salt = Convert.ToBase64String(PasswordHasher.CreateSalt(10));

            var createdUserId = _userRepository.Create(new User
            {
                EmailAddress = user.EmailAddress,
                FullName     = user.FullName,
                PasswordHash = PasswordHasher.CreateSHA256Hash(user.Password, salt),
                PasswordSalt = salt
            });

            return(FindById(createdUserId));
        }
Example #15
0
        public bool UpdateUser(UserBO user, OrganizationBO orgBO)
        {
            bool success = false;

            switch (user.Operation)
            {
            case OperationMode.UpdatePassword:
                string password = string.Empty;

                if (user.ResetPassword)
                {
                    password           = user.PasswordHash;
                    user.ResetPassword = false;
                }
                else
                {
                    PasswordGenerator passGen = new PasswordGenerator();
                    password           = passGen.Generate();
                    user.ResetPassword = true;
                }

                string         keyForUserPasswordSalt = ReadSalt();
                PasswordHasher passwordHasher         = new PasswordHasher(keyForUserPasswordSalt);
                string         salt = passwordHasher.CreateSalt(user.UserName);

                user.PasswordHash = passwordHasher.HashPassword(salt, password);
                success           = _userDao.UpdateUserPassword(user);

                if (success)
                {
                    List <string> emailList = new List <string>();
                    emailList.Add(user.UserName);
                    Email email = new Email()
                    {
                        To       = emailList,
                        Password = password
                    };

                    if (user.ResetPassword)
                    {
                        success = SendEmail(email, EmailCombinationEnum.ResetPassword);
                    }
                    else
                    {
                        success = SendEmail(email, EmailCombinationEnum.PasswordChanged);
                    }
                }
                return(success);

            case OperationMode.UpdateUserInfo:
                success = _userDao.UpdateUserInfo(user, orgBO);
                //if (success)
                //{
                //    //List<string> EmailList = new List<string>();
                //    //EmailList.Add(User.EmailAddress);
                //    Email email = new Email();
                //    email.To = new List<string>();
                //    email.To.Add(User.EmailAddress);
                //    success = SendEmail(email, EmailCombinationEnum.UpdateUserInfo);
                //}
                return(success);

            default:
                break;
            }
            return(false);
        }
Example #16
0
        public bool SetUserInfo(UserBO userBO, OrganizationBO orgBO)
        {
            //UserBO ExistingUser; //= GetUser(UserBO);
            //ExistingUser = UserDao.GetUserByEmail(UserBO);
            //ExistingUser.Role = UserDao.GetUserHighestRole(ExistingUser.UserId);

            bool success;

            if (userBO.UserName == null)
            {
                string         keyForUserPasswordSalt = ReadSalt();
                PasswordHasher PasswordHasher         = new PasswordHasher(keyForUserPasswordSalt);
                string         salt = PasswordHasher.CreateSalt(userBO.EmailAddress);
                userBO.ResetPassword = true;
                PasswordGenerator passGen      = new PasswordGenerator();
                string            tempPassword = passGen.Generate();
                userBO.PasswordHash = PasswordHasher.HashPassword(salt, tempPassword);// "PassWord1");
                //UserBO.PasswordHash = PasswordHasher.HashPassword(salt, "PassWord1");
                success = _userDao.InsertUser(userBO, orgBO);
                StringBuilder body   = new StringBuilder();
                var           orgKey = Epi.Common.Security.Cryptography.Decrypt(orgBO.OrganizationKey);
                if (success)
                {
                    Email email = new Email();
                    body.Append("Welcome to Epi Info™ Cloud Enter. \nYour account has now been created for organization - " + orgBO.Organization + ".");
                    body.Append("\n\nEmail: " + userBO.EmailAddress + "\nPassword: "******"\nOrganization Key: " + orgKey);
                    body.Append("\n\nPlease click the link below to launch the Epi Info™ Cloud Enter and log in with your email and temporary password. You will then be asked to create a new password. \n" + AppSettings.GetStringValue(AppSettings.Key.BaseURL));
                    //Add email and temporary password for new user.



                    body.Append("\n\nPlease follow the steps below in order to start publishing forms to the web using Epi Info™ 7.");
                    body.Append("\n\tStep 1: Download and install the latest version of Epi Info™ 7 from:" + AppSettings.GetStringValue(AppSettings.Key.EpiInfoDownloadURL));
                    body.Append("\n\tStep 2: On the Main Menu, click on “Tools” and select “Options”");
                    body.Append("\n\tStep 3: On the Options dialog, click on the “Cloud Enter” Tab.");
                    body.Append("\n\tStep 4: On the Cloud Enter tab, enter the following information.");

                    body.Append("\n\t\t-Endpoint Address:" + AppSettings.GetStringValue(AppSettings.Key.EndpointAddress) + "\n\t\t-Connect using Windows Authentication:  " + AppSettings.GetStringValue(AppSettings.Key.WindowAuthentication));
                    body.Append("\n\t\t-Binding Protocol:" + AppSettings.GetStringValue(AppSettings.Key.BindingProtocol));

                    body.Append("\n\tStep 5:Click “OK’ button.");
                    body.Append("\nOrganization key provided here is to be used in Epi Info™ 7 during publish process.");
                    body.Append("\n\nPlease contact the system administrator for any questions.");

                    email.To = new List <string>();
                    email.To.Add(userBO.EmailAddress);
                    email.Body = body.ToString();
                    success    = SendEmail(email, EmailCombinationEnum.InsertUser);
                }
            }
            else
            {
                //UserBO.Role = UserBO.Role;
                //UserBO.IsActive = UserBO.IsActive;
                success = _userDao.UpdateUserOrganization(userBO, orgBO);
                if (success)
                {
                    Email email = new Email();

                    StringBuilder body = new StringBuilder();

                    body.Append("Welcome to Epi Info™ Cloud Enter. \nYour account has now been created for organization - " + orgBO.Organization + ".");
                    // var orgKey = OrgBO.OrganizationKey;
                    var orgKey = Epi.Common.Security.Cryptography.Decrypt(orgBO.OrganizationKey);
                    body.Append("\n\nOrganization Key: " + orgKey);
                    body.Append("\n\nPlease click the link below to launch Epi Info™ Cloud Enter. \n" + AppSettings.GetStringValue(AppSettings.Key.BaseURL) + "\n\nThank you.");
                    email.Body = body.ToString();
                    email.To   = new List <string>();
                    email.To.Add(userBO.EmailAddress);

                    success = SendEmail(email, EmailCombinationEnum.InsertUser);
                }
            }
            return(success);
        }
        public void InsertOrganizationInfo(OrganizationBO OrganizationBO, UserBO UserBO)
        {
            bool success;

            OrganizationBO.OrganizationKey = Epi.Common.Security.Cryptography.Encrypt(OrganizationBO.OrganizationKey);
            InsertCombination InsertStatus = new InsertCombination();
            // Check if the user Exists
            var    User         = this.OrganizationDao.GetUserByEmail(UserBO);
            string tempPassword = string.Empty;

            if (User != null)
            {
                if (string.IsNullOrEmpty(User.EmailAddress))
                {
                    UserBO.ResetPassword = true;
                    success = this.OrganizationDao.InsertOrganization(OrganizationBO, UserBO);
                }

                else
                {
                    success = this.OrganizationDao.InsertOrganization(OrganizationBO, User.UserId, UserBO.Role);
                }
                if (success)
                {
                    InsertStatus = InsertCombination.ExistingUserNewOrg;
                }
            }
            else
            {
                string         KeyForUserPasswordSalt = SecurityAppSettings.GetStringValue(SecurityAppSettings.Key.KeyForUserPasswordSalt);
                PasswordHasher PasswordHasher         = new PasswordHasher(KeyForUserPasswordSalt);
                string         salt = PasswordHasher.CreateSalt(UserBO.EmailAddress);
                UserBO.ResetPassword = true;
                PasswordGenerator PassGen = new PasswordGenerator();
                tempPassword        = PassGen.Generate();
                UserBO.PasswordHash = PasswordHasher.HashPassword(salt, tempPassword);// "PassWord1");

                success = this.OrganizationDao.InsertOrganization(OrganizationBO, UserBO);
                if (success)
                {
                    InsertStatus = InsertCombination.NewUserNewOrg;
                }
            }
            var OrgKey = Epi.Common.Security.Cryptography.Decrypt(OrganizationBO.OrganizationKey);

            if (success && InsertStatus != InsertCombination.None)
            {
                Email email = new Email();

                StringBuilder Body = new StringBuilder();
                if (InsertStatus == InsertCombination.ExistingUserNewOrg)
                {
                    Body.Append("Your account has now been created for organization - " + OrganizationBO.Organization + ".\n");
                    Body.Append("\nOrganization Key: " + OrgKey);
                    Body.Append("\n\nPlease click the link below to launch Epi Info™ Cloud Enter. \n" + AppSettings.GetStringValue(AppSettings.Key.BaseURL) + "\n\nThank you.");
                }
                else
                {
                    Body.Append("Welcome to Epi Info™ Cloud Enter. \nYour account has now been created for oganization - " + OrganizationBO.Organization + ".");
                    Body.Append("\n\nEmail: " + UserBO.EmailAddress + "\nPassword: "******"\nOrganization Key: " + OrgKey);
                    Body.Append("\n\nPlease click the link below to launch the Epi Info™ Cloud Enter and log in with your email and temporary password. You will then be asked to create a new password. \n" + AppSettings.GetStringValue(AppSettings.Key.BaseURL));
                    //Add email and temporary password for new user.
                }

                //Body.Append("\n" + AppSettings.GetStringValue(AppSettings.Key.BaseURL));

                if (InsertStatus == InsertCombination.NewUserNewOrg)
                {
                    Body.Append("\n\nPlease follow the steps below in order to start publishing forms to the web using Epi Info™ 7.");
                    Body.Append("\n\tStep 1: Download and install the latest version of Epi Info™ 7 from:" + AppSettings.GetStringValue(AppSettings.Key.EpiInfoDownloadURL));
                    Body.Append("\n\tStep 2: On the Main Menu, click on “Tools” and select “Options”");
                    Body.Append("\n\tStep 3: On the Options dialog, click on the “Cloud Enter” Tab.");
                    Body.Append("\n\tStep 4: On the Cloud Enter tab, enter the following information.");

                    //Body.Append("\n\t\t-Endpoint Address:" + AppSettings.GetStringValue(AppSettings.Key.EndpointAddress + "\n\t\t-Connect using Windows Authentication:  " + AppSettings.GetStringValue(AppSettings.Key.WindowAuthentication)));
                    //Body.Append("\n\t\t-Binding Protocol:" + AppSettings.GetStringValue(AppSettings.Key.BindingProtocol));

                    Body.Append("\n\tStep 5:Click “OK’ button.");
                    Body.Append("\nOrganization key provided here is to be used in Epi Info™ 7 during publish process.");
                    Body.Append("\n\nPlease contact the system administrator for any questions.");
                }


                email.Body = Body.ToString();
                email.To   = new List <string>();
                email.To.Add(UserBO.EmailAddress);

                success = SendEmail(email, EmailCombinationEnum.InsertOrganization);
            }
        }