2014-01-15 61 views
0

是否可以通过单击邮件中的按钮进行登录,由laravel Mail::send()发送?通过邮件按钮进行登录

所以我发邮件给Mail::send()的用户。我希望用户打开邮件,点击它中的按钮,他将自动登录,以便他立即看到他的个人资料页面。

你们会怎么建议我这样做?

回答

2

这是我给另一个类似问题的完全相同的答案。

创建一个表来存储login codes

public function up() 
{ 
    Schema::create('login', function($table) { 
     $table->string('id')->primary(); 

     $table->string('user_id'); 

     $table->timestamps(); 
    }); 
} 

你生成一个链接添加一行这个表中的每个时间:

$user = User::find(1); 

$login = Login::create(['id' => Login::generateID(), 'user_id' => $user->id]); 

$url = URL::route('loginByEmail', $login->id); 

Mail::send(...) 

您的登录链接创建路线:

Route::get('loginByEmail/{code}', 
      array('as' => 'loginByEmail', 'uses' =>'[email protected]') 
     ); 

然后,当你的用户点击链接,你可以自动登录他,立即inv alidate该链接并重定向他剖析,这里的控制器方法:

public function loginByEmail() 
{ 
    $login = Login::findOrFail(Input::get('login_id')); 

    $user = User::find($login->user_id); 

    Auth::login($user); 

    $login->delete(); 

    return Redirect::route('profile'); 
} 

,并创建一个工匠命令在该表periodiacally删除旧记录:

Login::where('created_at', '<=', Carbon\Carbon::now()->subDays(2))->delete(); 

作为另一个安全MESURE,你也应该检查该登录代码是否不太旧。

这可以为generateID()的代码,这是一个基本的UUID代码生成:

public static function v4() 
{ 
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', 
     // 32 bits for "time_low" 
     random_mcrypt(), random_mcrypt(), 

     // 16 bits for "time_mid" 
     random_mcrypt(), 

     // 16 bits for "time_hi_and_version", 
     // four most significant bits holds version number 4 
     random_mcrypt(0x0fff) | 0x4000, 

     // 16 bits, 8 bits for "clk_seq_hi_res", 
     // 8 bits for "clk_seq_low", 
     // two most significant bits holds zero and one for variant DCE1.1 
     random_mcrypt(0x3fff) | 0x8000, 

     // 48 bits for "node" 
     random_mcrypt(), random_mcrypt(), random_mcrypt() 
    ); 
} 

连接到系统上的任何这样的字符串。