首页 文章

获取密码重置URL

提问于
浏览
1

我正在尝试修改默认的Laravel 5.6 Auth,以便通过电子邮件向新用户发送创建密码的链接,因为这是一个仅限邀请的系统,我不希望通过电子邮件将创建的用户的密码作为明文 .

在5.3中我能够做的是从password_resets表中获取重置令牌,并向他们发送带有“创建密码”按钮的通知 .

在5.6中(不确定何时更改)它似乎是数据库中密码重置令牌的加密版本 . 然后,我如何在自定义通知中调用正确的URL以便用户能够创建密码?

这是我在5.3中所拥有的:

controller

......

$token = strtolower(str_random(64));

DB::table('password_resets')->insert([
    'email'      => $request->email,
    'token'      => $token,
    'created_at' => Carbon::now()
]);

$user->notify(new UserCreated($user));

......

password create email

.....

$token = DB::table('password_resets')->where('email', $user_email)->pluck('token')->first();

$url = url('/password/reset/' . $token);

......

将相同的代码复制到5.6,它告诉我我的重置令牌无效 . 在进行正常的密码重置时,数据库中的令牌似乎不再与URL中的令牌匹配 . 现在它们似乎是加密的还是什么?

我已经在电子邮件中确保了url和令牌在数据库中完全相同,有效期限设置为一周(测试),并且每个令牌都以这种方式创建,它表示无效 .

那么如何为仅限邀请系统进行身份验证,或者如何手动创建重置令牌然后通过自定义电子邮件发送?文档提到能够替换密码重置电子邮件,但我不希望这样,我想补充它 .

2 回答

  • 0

    解决了!

    这是我的新控制器和5.6中的通知,用于手动发送不同的密码创建电子邮件 . 我真正需要做的就是在将令牌存储到数据库之前加密令牌!然后将未加密的令牌传递给url的电子邮件,该邮件检查数据库中的加密邮件 .

    controller

    .....
    
    $random_token    = strtolower(str_random(60));
    $encrypted_token = bcrypt($random_token);
    
    DB::table('password_resets')->insert([
        'email'      => $request->email,
        'token'      => $encrypted_token,
        'created_at' => Carbon::now()
    ]);
    
    $user->notify(new AccountCreated($user, $random_token));
    
    .....
    

    email 我只是导入用户和令牌......

    .....
    
    public $user;
    public $token;
    
    public function __construct(User $user, $token)
    {
        $this->user  = $user;
        $this->token = $token;
    }
    
    .....
    
  • 0

    使用内置功能可以在一行中创建和保存令牌 . 花了我一个小时和惊人的使用 dd() 搞清楚了,但我把它添加到我的 User 型号:

    <?php
    
    namespace App;
    
    use App\Notifications\AccountCreated;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Support\Facades\Hash;
    
    class User extends Authenticatable
    {
        use Notifiable;
    
        public function generatePassword()
        {
            $this->password = Hash::make(str_random(32));
        }
    
        public function sendWelcomeEmail()
        {
            // Generate a new reset password token and save it to the database
            $token = app("Password")::getRepository()->create($this);
    
            // Send notification
            $this->notify(new AccountCreated($this, $token));
        }
    }
    

    通知获取用户和令牌,与您的代码相同,以便它们可以包含在电子邮件文本中 . 然后在 UserController::store() 我可以这样做:

    $user = new User($request->all());
        $user->generatePassword();
        $user->save();
        $user->sendWelcomeEmail();
    

    在电子邮件通知中,您可以使用它来获取实际的URL:

    $url = route("password.reset", $token)
    

相关问题