74.邮箱认证(四)
- 本系列文章为
laracasts.com
的系列视频教程——Let's Build A Forum with Laravel and TDD 的学习笔记。若喜欢该系列视频,可去该网站订阅后下载该系列视频, 支持正版 ;- 视频源码地址:github.com/laracasts/Lets-Build-a-...;
- 本项目为一个 forum(论坛)项目,与本站的第二本实战教程 《Laravel 教程 - Web 开发实战进阶》 类似,可互相参照。
本节说明
- 对应视频教程第 74 小节:Email Confirmation Loose Ends
本节内容
本节我们来做点清理工作。首先我们把 RegisterConfirmation 控制器移到 Auth
目录下并做一些小小的修改:
forum\app\Http\Controllers\Auth\RegisterConfirmationController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
class RegisterConfirmationController extends Controller
{
public function index()
{
$user = User::where('confirmation_token',request('token'))
->first();
if(! $user) {
return redirect(route('threads'))
->with('flash','Unknown token.');
}
$user->confirm();
return redirect(route('threads'))
->with('flash','Your account is now confirmed! You may post to the forum.');
}
}
路由也需要进行更新:
forum\routes\web.php
.
Route::get('/register/confirm','Auth\RegisterConfirmationController@index')->name('register.confirm');
.
接着我们要保证confirmation_token
的值唯一,并且在用户认证之后清空confirmation_token
的值。首先我们修改迁移文件:
forum\database\migrations\2014_10_12_000000_create_users_table.php
.
.
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->string('avatar_path')->nullable();
$table->boolean('confirmed')->default(false);
$table->string('confirmation_token',25)->nullable()->unique();
$table->rememberToken();
$table->timestamps();
});
}
.
.
接着我们修改生成confirmation_token
的逻辑:
forum\app\Http\Controllers\Auth\RegisterController.php
.
.
protected function create(array $data)
{
return User::forceCreate([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'confirmation_token' => str_limit(md5($data['email'] . str_random()),25,'')
]);
}
.
.
然后我们做清空confirmation_token
的处理。我们依旧从修改测试开始:
forum\tests\Feature\RegistrationTest.php
.
.
/** @test */
public function user_can_fully_confirm_their_email_addresses()
{
Mail::fake();
$this->post(route('register'),[
'name' => 'NoNo1',
'email' => 'NoNo1@example.com',
'password' => '123456',
'password_confirmation' => '123456'
]);
$user = User::whereName('NoNo1')->first();
$this->assertFalse($user->confirmed);
$this->assertNotNull($user->confirmation_token);
$this->get(route('register.confirm',['token' => $user->confirmation_token]))
->assertRedirect(route('threads'));
tap($user->fresh(),function($user) {
$this->assertTrue($user->confirmed);
$this->assertNull($user->confirmation_token);
});
}
.
.
我们在认证用户时清空confirmation_token
即可:
forum\app\User.php
.
.
public function confirm()
{
$this->confirmed = true;
$this->confirmation_token = null;
$this->save();
}
.
.
我们运行全部测试: