版权声明:http://www.itchuan.net https://blog.csdn.net/sinat_37390744/article/details/88738493
准备:
1、sendcloud发送邮件 https://blog.csdn.net/sinat_37390744/article/details/88738359
2、flash消息提示 https://blog.csdn.net/sinat_37390744/article/details/88738171
步骤
1、使用自带的users migration,增加几个字段
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('email')->unique();
$table->string('password');
$table->string('confirmation_token')->default('');//存储Token
$table->smallInteger('is_active')->default(0); //判断用户是否通过邮件激活
$table->rememberToken();
$table->timestamps();
});
}
2、迁移生产users表
php artisan migrate
3、开启auth
php artisan make:auth
4、此时打开首页,出现导航条,右上角有Login Register
5、验证路由
Route::get('/email/verify/{token}',['as'=>'email.verify','uses'=>'EmailController@verify']);
5、打开Controllers\Auth\RegisterController.php
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'confirmation_token' => str_random(40),//生成激活的token值存入数据库
'password' => bcrypt($data['password']),//密码加密后存入数据库
]);
//将用户信息存入数据库后开始发送验证邮件,此时数据库中is_active默认为0,未激活
$this->sendVerifyEmailTo($user);
return $user;
}
private function sendVerifyEmailTo($user){
$data = [
'url'=>route('email.verify',['token'=>$user->confirmation_token]),
'name'=>$user->name,
];
$template =new SendCloudTemplate('****',$data);
\Mail::raw($template,function ($message) use ($user){
$message->from('***@***','***');
$message->to($user->email);
});
}
6、此时用户收到激活邮件,并点击邮件中的激活链接,进入到EmailController中verify方法中
激活链接形式为http://abc.com/email/verify/RGMonUgeeGbxOr6ziLkTmrHoIFTqUId11DS2JPmy
email/verify/RGMonUgeeGbxOr6ziLkTmrHoIFTqUId11DS2JPmy
对应EmailController中verify方法,后面为40位的token
7、EmailController
public function verify($token){
//数据库中匹配Token
$user = \App\User::where('confirmation_token',$token)->first();
//如果不存在
if(is_null($user)){
flash('邮箱验证失败','danger');
return redirect('/');
}
//如果存在,则将数据库is_active字段设置为1,表示已激活;并重新生成新的token
$user->is_active = 1;
$user->confirmation_token = str_random(40);
$user->save();
flash('邮箱验证成功','success');
//自动登录,并跳转到首页
\Auth::login($user);
return redirect('/home');
}
8、重写\Auth::login方法,在LoginController中
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
//加入提示消息,用户体验较好
flash('欢迎回来','success')->important();
return $this->sendLoginResponse($request);
}
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
protected function attemptLogin(Request $request)
{
//将creadentials数组增加一个元素is_active,若is_active为1,即表示已经激活们可以登录,
//否则提示错位消息
$credentials = array_merge($this->credentials($request),['is_active'=>1]);
return $this->guard()->attempt(
$credentials, $request->has('remember')
);
}