+6

Email Verification With register Laravel

Có một vài trường hợp có lợi để người dùng đăng kí mới trang web cửa bạn với việc xác minh email. Chúng ta có thể xác thực được email để không bị đăng kí rác tài khoản, chúng ta có thể gửi mail thông báo cho khách hàng một vấn đề gì đó ...

1. Tạo migration

Mặc định Table User tạo cho chúng ta (username, email, password, etc.). Nhưng với việc xác thực bằng email chúng ta cần thêm trường confirmed với kiểu boolean để xác định người dùng đã xác thực tài khoản chưa, giá trị mặc định là false. Tiếp theo chúng ta cần thêm trường confirmation_code để chưa chuỗi random string là giá trị duy nhất sau đó chúng ta gửi đến người dùng để xác thực tài khoản với đường dẫn link đến /register/verify/{confirmation_code}. Khi người dùng click dẫn đến link trên chúng ta sẽ search nó với Talbe User để cập nhật lại confirmed thành true đã được xác thực. Dưới đây là migartion tạo Talbe User với trường như đã nêu ở trên :

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateUsersTable extends Migration {

    public function up()
    {
        Schema::create('users', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('username')->unique();
            $table->string('email')->unique();
            $table->string('password');
            $table->boolean('confirmed')->default(0);
            $table->string('confirmation_code')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('users');
    }
}

2. Đăng kí User

Bây giờ Table User đã được thiết lập để có thể bắt đầu để thêm chức năng đăng kí của bạn. Nếu validate thành công thì chúng ta bắt đầu tạo random string gắn với trường confirmation_code. Sau đó chúng ta tạo một mail với đường dẫn register/verify/{confirmation_code} để xác thực tài toàn khoản.

$confirmation_code = time().uniqid(true);
        User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => $request->password,
            'confirmation_code' => $confirmation_code,
            'confirmed' => 0,
        ]);
        Mail::send('email.verify', $confirmation_code, function($message) {
            $message->to($request->email, $request->name))
                ->subject('Verify your email address');
        });
        return redirect(route('login'))->with('status', 'Vui lòng xác nhận tài khoản email');

Đây là đoạn HTML để confirm email :

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <h2>Verify Your Email Address</h2>

        <div>
            Thanks for creating an account with the verification demo app.
            Please follow the link below to verify your email address
            {{ URL::to('register/verify/' . $confirmation_code) }}.<br/>

        </div>

    </body>
</html>

3. Confirm The User

Để hoàn thành việc xác thực email sau khi người dùng click vào liên kết xác thực chúng ta đã gửi mail cho họ . Đầu tiên chúng ta phải đăng kí route :

Route::get('register/verify/{code}', 'Auth\RegisterController@verify');

Trong Auth\RegisterController chúng ta tạo môt method verify :

public function verify($code)
    {
        $user = User::where('confirmation_code', $code);

        if ($user->count() > 0) {
            $user->update([
                'confirmed' => 1,
                'confirmation_code' => null
            ]);
            $notification_status = 'Bạn đã xác nhận thành công';
        } else {
            $notification_status ='Mã xác nhận không chính xác';
        }

        return redirect(route('login'))->with('status', $notification_status);
    }

4. Khi người dùng loggin

Để đăng nhập chúng ta tạo ra một method authenticate :

Route::post('authenticate',  'Auth\LoginController@authenticate');
public function authenticate(Request $request)
    {
        $credentials = [
            'email' => $request->email,
            'password' => $request->password,
            'confirmed' => 1
        ];

        if (!Auth::attempt($credentials)) {
            return redirect()->back()
                    ->withErrors([
                        'email'  =>  'Bạn không thể đăng nhập'
                    ]);
        }
        
        return redirect('/');
    }

Nguồn : http://bensmith.io/email-verification-with-laravel


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí