在Laravel中注册用户时,如何阻止防护?

时间:2018-09-17 21:19:55

标签: laravel authentication

我正在使用默认的Laravel注册,每次注册用户时,系统当前都会登录该用户,这是我不希望的。

出于某种原因,我认为我可以进行此工作,但是现在进行测试,我看到了问题。下面是我的注册控制器:

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Str;
use Mail;
use App\Mail\verifyEmail;
use Illuminate\Support\Facades\Session;

class RegisterController extends Controller
{

    use RegistersUsers;

    protected $redirectTo = '/';

    public function __construct()
    {
        $this->middleware('guest');
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

    protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'verifytoken' => Str::random(40),
            'role_id' => $data['role_id']
        ]);
        $thisUser = User::findOrFail($user->id);
        Session::flush('status', 'Please verify your email for account activation');
        $this->sendEmail($thisUser);

        return $user;
    }

    public function sendEmail($thisUser){
        Mail::to($thisUser['email'])->send(new verifyEmail($thisUser));
    }

    public function sendEmailDone($email, $verifytoken){

        User::where(['email'=>$email, 'verifytoken'=>$verifytoken])->update(['status'=>'1', 'verifytoken'=>NULL]);

        return redirect('/login');

    }

    public function verifyEmail(){
        return view('emails.veryEmail');
    }
}

用户注册后,会向他发送一封带有令牌的电子邮件,只有在他通过电子邮件激活令牌后才允许他登录。

这里唯一的问题是用户当前正在自动登录。

我知道正常情况下会记录用户的防护措施,但我什至没有。

2 个答案:

答案 0 :(得分:1)

特征RegistersUsers定义了注册方法:

/**
 * Handle a registration request for the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function register(Request $request)
{
    $this->validator($request->all())->validate();

    event(new Registered($user = $this->create($request->all())));

    $this->guard()->login($user);

    return $this->registered($request, $user)
                    ?: redirect($this->redirectPath());
}

您需要覆盖它并删除$this->guard()->login($user);行。

答案 1 :(得分:0)

如果您使用的是Laravel 5.7或可以升级您的项目,则可以使用另一个选项,即利用Laravel的新用户电子邮件验证系统。听起来这就是您要手动构建的内容,但是现在它已包含在内。在文档中查看here。我认为它将完全满足您的需求。