php - 使用 Eloquent 模型类从数据库中选择记录时,如何在 Laravel 4 中解密密码?

标签 php mysql sql encryption laravel

我有一个小型应用程序,用户可以在其中创建帐户并编辑帐户(包括密码)。我想使用 value="value here" 选项将从数据库中选择的帐户的所有记录插入到编辑表单的输入中。

案例是我使用一个Validator来验证用户的输入,这个Validator与创建和编辑帐户相同:

class Account extends Validator {
    public static $rules = [
        'name' => 'required|alpha|min:2',
        'secondname' => 'alpha_spaces|min:2',
        'lastname' => 'required|alpha|min:2',
        'email' => 'required|email|unique:accounts',
        'password' => 'required|alpha_num|between:6,12|confirmed',
        'password_confirmation' => 'required|alpha_num|between:6,12'
    ];
}

这是我的编辑表单: This is my edit-form

这是我从数据库中选择记录的代码:

$q = Input::get('query');
$result = Account::where('id', '=', $q)->get();

在这种情况下,密码将以散列形式插入到输入中。因此,当用户甚至不想更改其密码时,它就会更改,因为散列密码将再次被散列。

所以我需要以某种方式选择未散列的密码,这样当用户不想编辑他的密码时它就保持不变。

有人可以帮我吗?

最佳答案

如果我理解正确的话,您只想更改用户输入的密码,如果是这样,我会这样做。

  1. 我会删除 password 规则的 alpha_num Betweenconfirmed 。删除它可以得到更安全的密码。
  2. 我会将 same:password_confirmation 添加到 password 规则中,这样可以确保两个字段相等。
  3. 我会删除 password_confirmation 的规则,same:password_confirmation 已经解决了这个问题。

所以最后你的数组应该是这样的:

public static $rules = [
    'name' => 'required|alpha|min:2',
    'secondname' => 'alpha_spaces|min:2',
    'lastname' => 'required|alpha|min:2',
    'email' => 'required|email|unique:accounts',
    'password' => ['required', 'same:password_confirmation']
];

当您创建新用户时,这可以正常工作,但是如果我们编辑用户(您当前的问题),这将运行密码要求检查。要解决此问题,我们必须从 password 中删除 required。因为我们现在将 password 规则作为数组,并且我们知道 required 是该数组的第一项,所以我们可以在更新密码时运行验证之前将其删除。用户。

我们还需要确保不要插入空的密码,并在用户键入更改密码时对其进行哈希处理。

$input = Input::all();

// make sure not to insert empty password
if (empty($input['password']))
  unset($input['password']);

// remove the requirement of password
unset(Account::$rules['password'][0]);

// validate our rules
$validator = Validation::make($input, Account::$rules);
if ($validator->fails()) {
  // do something if error
}

// hash if new password
if ( ! empty($input['password']))
    $input['password'] = Hash::make($input['password']);

Account::find($accountId)->update($input);

关于php - 使用 Eloquent 模型类从数据库中选择记录时,如何在 Laravel 4 中解密密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24219215/

相关文章:

php - 如何跟踪 Magento 从哪里调用模板?

php - 如何使 php session 永不过期(在conf文件中,没有代码)

php - 如何解决 facebook og title 属性中的双引号问题

mysql - 如何为开发环境转储 MySQL 数据库中所有表的最近 1000 行?

php - 简单的加权链接旋转?

PHP MySQL 合并表问题,读取 fetch

php - 自定义变量可以像 super 全局变量一样在每个页面上使用吗?

c# - 获取异常 "not all code path return a value"

sql - 加密 SQL Server 中现有的列数据

mysql - 规范化为 3nf 和函数依赖二