コード例 #1
0
        /// <summary>
        /// Apenas reseta a senha de acesso do usuário para a senha padrão.
        /// </summary>
        /// <param name="id">Código do usuário que terá a senha resetada</param>
        /// <returns></returns>
        public Usuario ResetarSenha(int id)
        {
            using (var context = new DatabaseContext())
            {
                var entity = context.Usuario.FirstOrDefault(a => a.IdUsuario == id);
                if (entity == null)
                {
                    throw new BusinessException("Usuário não encontrado");
                }

                entity.Senha              = PasswordHash.CreateHash(DEFAULT_PASSWORD);
                entity.SenhaSalt          = PasswordHash.CreateSalt();
                entity.DataHoraAlteracao  = DateTime.Now;
                entity.IdUsuarioAlteracao = GetLoggedUser().IdUsuario;
                entity.PrimeiroAcesso     = true;

                context.Entry(entity).State = EntityState.Modified;

                var result = context.SaveChanges() > 0;
                if (result)
                {
                    RegistrarLogAtividade(entity, RESETAR_SENHA);
                }

                return(entity);
            }
        }
コード例 #2
0
        /// <summary>
        /// Changes a user's password. Allows an admin to resets a user's password without a current password.
        /// </summary>
        /// <param name="userName">Username of the user.</param>
        /// <param name="newPassword">The new password.</param>
        /// <returns>The change password result.</returns>
        public async Task <ChangePasswordResult> ResetPassword(string userName, string newPassword)
        {
            var strongPassword = IsStrongPassword(newPassword);
            var result         = new ChangePasswordResult();

            if (!strongPassword)
            {
                result.PasswordNotStrong = true;
                return(result);
            }

            var user = await GetUser(userName, false);

            var passwordCheckHash = PasswordHash.CreateHashSameSalt(user.PasswordHash, newPassword);

            user.PasswordHash       = PasswordHash.CreateHash(newPassword);
            user.PasswordHistory   += $"\n{passwordCheckHash}";
            user.LastLogin          = DateTime.Now;
            user.FailedLoginCount   = 0;
            user.MustChangePassword = false;

            await _userData.UpdateAsync(user);

            result.User = user;
            _adminLogService.LogNeutral($"Password reset for {user.UserName} succeeded.", LogCategory.Security);

            return(result);
        }
コード例 #3
0
        /// <summary>
        /// Registers a specified user.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="password">The password.</param>
        /// <returns>A registration result.</returns>
        public async Task <RegisterResult> Register(User user, string password)
        {
            var result = new RegisterResult();

            var strongPassword = IsStrongPassword(password);

            if (!strongPassword)
            {
                result.PasswordNotStrong = true;
                return(result);
            }

            var existingUser = await _userData.GetUser(user.UserName);

            if (existingUser != null)
            {
                result.UserNameTaken = true;
                return(result);
            }

            var newUser = new User(user);

            newUser.PasswordHash = PasswordHash.CreateHash(password);
            newUser.Enabled      = false;

            await _userData.InsertAsync(newUser);

            _adminLogService.LogNeutral($"New user registration for {user.UserName} succeeded.", LogCategory.Security);

            return(result);
        }
コード例 #4
0
        public async Task <BaseApiResponse> ResetPassword(ResetPasswordRequest request)
        {
            var admin = _adminQueryService.Find(request.Id);

            if (admin == null)
            {
                return(new BaseApiResponse {
                    Code = 400, Message = "未找到账户"
                });
            }
            var pasword      = "Abc123456";
            var passwordHash = PasswordHash.CreateHash(pasword);
            var command      = new UpdatePasswordCommand(passwordHash)
            {
                AggregateRootId = request.Id
            };
            var result = await ExecuteCommandAsync(command);

            if (!result.IsSuccess())
            {
                return(new BaseApiResponse {
                    Code = 400, Message = "命令没有执行成功:{0}".FormatWith(result.GetErrorMessage())
                });
            }

            //添加操作记录
            var currentAdmin = _contextService.GetCurrentAdmin(HttpContext.Current);

            RecordOperat(currentAdmin.AdminId.ToGuid(), "重置管理员密码", request.Id, "管理员:{0}".FormatWith(admin.Name));

            return(new BaseApiResponse());
        }
コード例 #5
0
ファイル: PasswordHashTests.cs プロジェクト: openzones/OMI
        public void PasswordHash_Test()
        {
            string s1 = PasswordHash.CreateHash("123");
            string s2 = PasswordHash.CreateHash("123");

            Assert.IsTrue(PasswordHash.ValidatePassword("123", s2));
        }
コード例 #6
0
        public HttpResponseMessage AddUser(User model)
        {
            try
            {
                var check = CommandService.UnitOfWork.UserRepository.Get(e => e.Email == model.Email);
                if (check != null && check.Any())
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Email Exist"));
                }
                var vs = CommandService.Executer.Execute(new AddUser
                {
                    Id       = Guid.NewGuid(),
                    Name     = model.Name,
                    Email    = model.Email,
                    Password = PasswordHash.CreateHash(model.Password),
                    Role     = model.Role
                });

                if (vs.IsValid)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, "Done"));
                }
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, vs));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
コード例 #7
0
        public async Task <BaseApiResponse> Add(AddAdminRequest request)
        {
            request.CheckNotNull(nameof(request));

            var newadminid = GuidUtil.NewSequentialId();
            var command    = new CreateAdminCommand(
                newadminid,
                request.Name,
                request.LoginName,
                request.Portrait,
                PasswordHash.CreateHash(request.Password),
                request.Role,
                request.IsLocked
                );
            var result = await ExecuteCommandAsync(command);

            if (!result.IsSuccess())
            {
                return(new BaseApiResponse {
                    Code = 400, Message = "命令没有执行成功:{0}".FormatWith(result.GetErrorMessage())
                });
            }

            //添加操作记录
            var currentAdmin = _contextService.GetCurrentAdmin(HttpContext.Current);

            RecordOperat(currentAdmin.AdminId.ToGuid(), "添加管理员", newadminid, "管理员:{0}".FormatWith(request.Name));

            return(new BaseApiResponse());
        }
コード例 #8
0
        private void enviarCorreo()
        {
            string random_String = getRandomPassword();
            string password      = PasswordHash.CreateHash(random_String);
            string email         = txtCorreo.Text;


            try
            {
                int result = gestor.recuperarPassword(email, password);

                if (result == 1)
                {
                    Cartero cartero = new Cartero {
                        ReceiversAddress = email, subject = "Nueva Contraseña", body = "Su nueva contraseña es: " + random_String
                    };
                    cartero.enviarCarta();
                    MessageBox.Show("Por favor revise su correo, se ha enviado una nueva contraseña ", "Recuperar Contraseña");
                }
                else
                {
                    MessageBox.Show("Correo invalido", "Error.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Recuperar Contraseña", MessageBoxButtons.OK);
            }
        }
コード例 #9
0
ファイル: UserController.cs プロジェクト: mqjohnston69/tran2
        public HttpResponseMessage UpdatePwd(UserDTO userDTO)
        {
            try
            {
                var curDateTime = DateTime.UtcNow;

                var user = _IUserService.GetUser(userDTO.id);
                if (user != null)
                {
                    if (user.InviteDate != null)
                    {
                        user.InviteDate = null;
                        _IUserService.UpdateUser(user);
                    }
                    _IUserService.UpdatePassword(user.UserName, PasswordHash.CreateHash(userDTO.password));
                }
                else
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "UserName could not be found"));
                }
            }
            catch (Exception e)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            return(Request.CreateResponse <bool>(HttpStatusCode.OK, true));
        }
コード例 #10
0
        public static bool ProcessUser(User user)
        {
            //maybe later encrypt credentials here

            user.passwordhash = PasswordHash.CreateHash(user.passwordhash);
            return(DbConnector.AddUserToDB(user));
        }
コード例 #11
0
ファイル: Account.cs プロジェクト: AnkoBG/KEKChat
        public static bool Register(string username, string password)
        {
            using (UsersDB db = new UsersDB())
            {
                User user = db.Users
                            .SingleOrDefault(n => n.Username == username);

                if (user == null)
                {
                    string[] hashes = PasswordHash.CreateHash(password);

                    db.Users.Add(new User {
                        Username       = username,
                        PasswordHash   = hashes[0],
                        HashSalt       = hashes[1],
                        HashIterations = hashes[2]
                    });
                    db.SaveChanges();

                    return(true);
                }

                return(false);
            }
        }
コード例 #12
0
ファイル: AccountController.cs プロジェクト: nosratiz/Mergen
        public async Task <ActionResult> ResetPassword(ResetPasswordInputModel inputModel,
                                                       CancellationToken cancellationToken)
        {
            var existingAccount = await _accountManager.GetAsync(int.Parse(inputModel.AccountId), cancellationToken);

            if (existingAccount == null)
            {
                return(BadRequest("invalid_account_id", "Account not found."));
            }

            if (existingAccount.ResetPasswordToken != inputModel.Token)
            {
                return(BadRequest("invalid_code", "Link is not valid."));
            }

            if (existingAccount.ResetPasswordTokenGenerationTime?.AddHours(48) < DateTime.UtcNow)
            {
                return(BadRequest("expired_code", "Link is expired."));
            }

            existingAccount.PasswordHash       = PasswordHash.CreateHash(inputModel.NewPassword);
            existingAccount.ResetPasswordToken = null;
            existingAccount.ResetPasswordTokenGenerationTime = null;
            await _accountManager.SaveAsync(existingAccount, cancellationToken);

            return(Ok());
        }
コード例 #13
0
        public HttpResponseMessage add(Customer post)
        {
            // Check for errors
            if (post == null)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The post is null"));
            }
            else if (Language.MasterPostExists(post.language_id) == false)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The language does not exist"));
            }
            else if (Country.MasterPostExists(post.invoice_country) == false)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The invoice country does not exist"));
            }
            else if (Country.MasterPostExists(post.delivery_country) == false)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The delivery country does not exist"));
            }

            // Make sure that the data is valid
            post.email               = AnnytabDataValidation.TruncateString(post.email, 100);
            post.customer_password   = PasswordHash.CreateHash(post.customer_password);
            post.org_number          = AnnytabDataValidation.TruncateString(post.org_number, 20);
            post.vat_number          = AnnytabDataValidation.TruncateString(post.vat_number, 20);
            post.contact_name        = AnnytabDataValidation.TruncateString(post.contact_name, 100);
            post.phone_number        = AnnytabDataValidation.TruncateString(post.phone_number, 100);
            post.mobile_phone_number = AnnytabDataValidation.TruncateString(post.mobile_phone_number, 100);
            post.invoice_name        = AnnytabDataValidation.TruncateString(post.invoice_name, 100);
            post.invoice_address_1   = AnnytabDataValidation.TruncateString(post.invoice_address_1, 100);
            post.invoice_address_2   = AnnytabDataValidation.TruncateString(post.invoice_address_2, 100);
            post.invoice_post_code   = AnnytabDataValidation.TruncateString(post.invoice_post_code, 100);
            post.invoice_city        = AnnytabDataValidation.TruncateString(post.invoice_city, 100);
            post.delivery_name       = AnnytabDataValidation.TruncateString(post.delivery_name, 100);
            post.delivery_address_1  = AnnytabDataValidation.TruncateString(post.delivery_address_1, 100);
            post.delivery_address_2  = AnnytabDataValidation.TruncateString(post.delivery_address_2, 100);
            post.delivery_post_code  = AnnytabDataValidation.TruncateString(post.delivery_post_code, 100);
            post.delivery_city       = AnnytabDataValidation.TruncateString(post.delivery_city, 100);
            post.facebook_user_id    = AnnytabDataValidation.TruncateString(post.facebook_user_id, 50);
            post.google_user_id      = AnnytabDataValidation.TruncateString(post.google_user_id, 50);

            // Get a customer on the email address
            Customer customerOnEmail = Customer.GetOneByEmail(post.email);

            // Check if the email exists
            if (customerOnEmail != null && post.id != customerOnEmail.id)
            {
                return(Request.CreateResponse <string>(HttpStatusCode.BadRequest, "The email is not unique"));
            }

            // Add the post
            Int32 insertId = (Int32)Customer.Add(post);

            // Update the password
            Customer.UpdatePassword(insertId, post.customer_password);

            // Return the success response
            return(Request.CreateResponse <string>(HttpStatusCode.OK, "The post has been added"));
        } // End of the add method
コード例 #14
0
        public void CreateHashTest()
        {
            // Arrange
            var hash = PasswordHash.CreateHash("Abcd1234");

            // Assert
            Assert.IsNotNull(hash);
        }
コード例 #15
0
ファイル: User.cs プロジェクト: zlepper/WhoNeedsHelp
        public string GenerateResetKey()
        {
            ResetExpiresAt = DateTime.Now.AddHours(2);
            string key = Guid.NewGuid().ToString();

            ResetKey = PasswordHash.CreateHash(key);
            return(key);
        }
コード例 #16
0
        public void see_it_in_action()
        {
            var hash = new PasswordHash();
            var password = "******";

            for (int i = 0; i < 50; i++)
            {
                Debug.WriteLine(hash.CreateHash(password));
            }

                hash.CreateHash(password).ShouldEqual(hash.CreateHash(password));
            hash.CreateHash(password).ShouldEqual(hash.CreateHash(password));
            hash.CreateHash(password).ShouldEqual(hash.CreateHash(password));
            hash.CreateHash(password).ShouldEqual(hash.CreateHash(password));

            hash.CreateHash(password).ShouldNotEqual(password);
        }
コード例 #17
0
        public void PasswordHashFixedIterations()
        {
            var hash = PasswordHash.CreateHash(TestString, 101);

            Assert.IsNotEmpty(hash);
            Assert.IsTrue(Regex.IsMatch(hash, "^\\d+:[A-Za-z0-9+/=]+:[A-Za-z0-9+/=]+$"));
            Assert.IsTrue(PasswordHash.ValidatePassword(TestString, hash));
        }
コード例 #18
0
        public void see_it_in_action()
        {
            var hash     = new PasswordHash();
            var password = "******";

            for (var i = 0; i < 50; i++)
            {
                Debug.WriteLine(hash.CreateHash(password));
            }

            hash.CreateHash(password).ShouldBe(hash.CreateHash(password));
            hash.CreateHash(password).ShouldBe(hash.CreateHash(password));
            hash.CreateHash(password).ShouldBe(hash.CreateHash(password));
            hash.CreateHash(password).ShouldBe(hash.CreateHash(password));

            hash.CreateHash(password).ShouldNotBe(password);
        }
コード例 #19
0
        public void PasswordHash_ExtractHashPassword()
        {
            string pwd  = PasswordHash.CreateHash("password");
            string hash = PasswordHash.ExtractHashPassword(pwd);

            Assert.AreNotEqual(pwd, hash);
            Assert.IsTrue(pwd.Contains(hash));
        }
コード例 #20
0
        public void PasswordHashFixedIterationsOutputSalt()
        {
            string salt;
            var    hash = PasswordHash.CreateHash(TestString, 102, out salt);

            Assert.IsNotEmpty(hash);
            Assert.IsTrue(PasswordHash.ValidatePassword(TestString, "102:" + salt + ":" + hash));
        }
コード例 #21
0
        public void PasswordHash_ValidatePassword()
        {
            string pwd = PasswordHash.CreateHash("password");

            Assert.IsTrue(PasswordHash.ValidatePassword("password", pwd));
            Assert.IsFalse(PasswordHash.ValidatePassword("abc", pwd));
            Assert.IsFalse(PasswordHash.ValidatePassword("password", "abc"));
            Assert.IsFalse(PasswordHash.ValidatePassword("password", "1:c"));
        }
コード例 #22
0
ファイル: Map.cs プロジェクト: sebastiencrevier/Warsim
 private Map(string ownerId, string title, string description, string password = "")
 {
     this.OwnerId      = ownerId;
     this.Title        = title;
     this.Description  = description;
     this.Password     = PasswordHash.CreateHash(password);
     this.SceneObjects = new List <Node>();
     this.Id           = Guid.NewGuid();
 }
コード例 #23
0
        public void ValidatePasswordTest()
        {
            string heslo     = "P&ssw0rd";
            string hashHeslo = PasswordHash.CreateHash(heslo);

            bool isValid = PasswordHash.ValidatePassword(heslo, hashHeslo);

            Assert.IsTrue(isValid = true);
        }
コード例 #24
0
ファイル: UserService.cs プロジェクト: edirosolini/MyAccess
 public ResponseModel Insert(UserEntity entity)
 {
     entity.Password = PasswordHash.CreateHash(entity.Password);
     this.dao.Insert(entity);
     return(new ResponseModel()
     {
         Status = true, Menssage = "Inserted user"
     });
 }
コード例 #25
0
        public async Task <bool> CreateTeacher(TeacherEx teacher)
        {
            teacher.Lastlogin = DateTime.Now;
            teacher.Password  = PasswordHash.CreateHash(teacher.Birthdate); // spørgsmålet er om det hele ikke bare skal være på webservicen?? altså genereing af pass og lastlogin.

            await ServiceProxy.Instance.InsertTeacher(teacher);

            return(true);
        }
コード例 #26
0
        public User save(User u)
        {
            var db = new UserContext();

            u.password = PasswordHash.CreateHash(u.password); // Hashing password
            User savedUser = db.Users.Add(u);

            return(savedUser);
        }
コード例 #27
0
        protected void ButtonAgregar_Click(object sender, EventArgs e)
        {
            SQLInjects        inject         = new SQLInjects();
            ProcsTableAdapter procedimientos = new ProcsTableAdapter();

            if (txtNombre_usuario.Text != "" && txtHash_usuario.Text != "" && txtCorreo_usuario.Text != "" && txtApellido_usuario.Text != "")
            {
                string nombre     = inject.Remover(txtNombre_usuario.Text);
                string correo     = inject.Remover(txtCorreo_usuario.Text);
                string apellido   = inject.Remover(txtApellido_usuario.Text);
                string area       = inject.Remover(DDLArea_usuario.SelectedValue.ToString());
                string nivel      = inject.Remover(DDLNivel_usuario.SelectedValue.ToString());
                string hash       = PasswordHash.CreateHash(txtHash_usuario.Text);
                bool   activacion = CheckBoxActivacion.Checked;
                if ((bool)Session["Editar"])
                {
                    {
                        int id = int.Parse(labelIDUsuario.InnerHtml);
                        try
                        {
                            procedimientos.update_usuario
                            (
                                id,
                                nombre,
                                apellido,
                                correo,
                                hash,
                                nivel,
                                area,
                                activacion,
                                false
                            );
                        }
                        catch (Exception ex)
                        {
                            lbl_error_correo.Text = ex.ToString();
                        }
                    }
                }
                else
                {
                    try
                    {
                        procedimientos.agregar_usuarios(nombre, apellido, correo, hash, nivel, area, activacion, false);
                    }
                    catch (Exception ex)
                    {
                        lbl_error_correo.Text = ex.ToString();
                    }
                }
            }
            else
            {
                lbl_error_correo.Text = "Hay campos vacios";
            }
        }
コード例 #28
0
        public async Task <AccountEntity> RegisterNewAccount(AccountEntity account)
        {
            var hashedPass = PasswordHash.CreateHash(account.GetPropertyValue <string>("userPassword"));

            account.SetPropertyValue("userPassword", hashedPass);
            account.Id = Guid.NewGuid().ToString();
            return(await Task.FromResult <AccountEntity>(account));

            //return await _dataAccess.Save(account, true);
        }
コード例 #29
0
ファイル: PasswordHashTests.cs プロジェクト: moonpyk/higgins
        public void CreateHashTest()
        {
            var hash   = PasswordHash.CreateHash("password");
            var reHash = PasswordHash.CreateHash("password");

            Console.WriteLine(hash);
            Console.WriteLine(reHash);
            //
            Assert.NotEqual(hash, reHash);
        }
コード例 #30
0
        public void Update(int id, string name, bool isActive, string role, string password)
        {
            var user = Session.Get <User>(id);

            user.Name         = name;
            user.IsActive     = isActive;
            user.Role         = role;
            user.PasswordHash = PasswordHash.CreateHash(password);
            Session.Save(user);
        }
コード例 #31
0
        public async Task <bool> CreateParent(ParentEx parent)
        {
            parent.Lastlogin = DateTime.Now;
            parent.Password  = PasswordHash.CreateHash(parent.Birthdate);

            await ServiceProxy.Instance.InsertParent(parent);


            return(true);
        }