Cài đặt và gửi email xác thực trong ứng dụng giống Zhihu với Laravel 5.8

1. Cấu hình hệ thống

1.1 Tạo dự án mới

Mã lệnh tạo dự án:

composer create-project --prefer-dist laravel/laravel zhihuapp '5.8'

1.2 Thiết lập cơ sở dữ liệu

Tập tin .env:

DB_DATABASE=zhihu
DB_USERNAME=root
DB_PASSWORD=123456

1.3 Cấu hình tên miền

Định nghĩa tên miền: test.zhihu.test

Cấu hình nginx:

server {
    listen 80;
    server_name test.zhihu.dev;
    root D:/Entrust/zhihuapp/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;
    charset utf-8;

    location / {
     index index.html index.htm index.php;
    try_files $uri $uri/ /index.php?$query_string;
    }
    
    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000; 
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

1.4 Cập nhật bảng người dùng

Tập tin: \zhihuapp\database\migrations\2014_10_12_000000_create_users_table.php

Thêm các trường mới:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name')->unique();
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->string('confirmationToken', 40);
        $table->tinyInteger('isActivated')->default(0);
        $table->string('profileImage');
        $table->integer('questionCount')->default(0);
        $table->integer('answerCount')->default(0);
        $table->integer('commentCount')->default(0);
        $table->integer('favoriteCount')->default(0);
        $table->integer('likeCount')->default(0);
        $table->integer('followerCount')->default(0);
        $table->integer('followingCount')->default(0);
        $table->json('preferences')->nullable();
        $table->rememberToken();
        $table->timestamps();
    });
}

Chạy migration:

php artisan migrate

2. Triển khai chức năng xác thực email

2.1 Cài đặt hệ thống xác thực

composer require laravel/ui '1.*'
php artisan ui:auth

2.2 Cài đặt thư viện sendcloud

composer require naux/sendcloud
composer require guzzlehttp/guzzle '6.5.5'

2.3 Sử dụng dịch vụ sendcloud để gửi email

2.3.1 Đăng ký dịch vụ email

Địa chỉ đăng ký: https://www.sendcloud.net/doc/product_email/quickin/

Trang quản trị: https://www.sendcloud.net/email/

Nhấp vào nút "Tạo API_KEY", khóa sẽ được gửi đến email đã đăng ký

Gửi email thử nghiệm: https://www.sendcloud.net/email/#/sendAround/sendTest

Kiểm tra hộp thư nhận. Lưu ý không gửi quá nhiều lần vì tài khoản miễn phí có giới hạn hàng ngày.

2.3.2 Cấu hình trong dự án

Tài liệu tham khảo: https://gitee.com/mirrors/Laravel-SendCloud

1. Tập tin .env

Sửa đổi:

MAIL_DRIVER=sendcloud

Thêm hai dòng mới:

SEND_CLOUD_USER=apoxxx_test_xxxx
SEND_CLOUD_KEY=cAnxxxxxxxxx(khóa sẽ được gửi đến email của bạn)

2. Tập tin config/app.php

'providers' => [
    Naux\Mail\SendCloudServiceProvider::class,
];

3. Tập tin \routes\web.php

Route::get('/email/activate/{token}',[
  'as'=>'email.activate',
  'uses'=>'VerificationController@activate'
]);

4. Tập tin \app\Http\Controllers\Auth\RegisterController.php

use Illuminate\Support\Facades\Mail;
use Naux\Mail\SendCloudTemplate;
protected function createUser(array $input)
{
    $newUser = User::create([
      'name' => $input['name'],
      'email' => $input['email'],
      'profileImage' => '/image/avatars/default.jpg',
      'confirmationToken' => Str::random(40),
      'password' => Hash::make($input['password']),
    ]);
    $this->dispatchActivationEmail($newUser);
    return $newUser;
}
private function dispatchActivationEmail($user)
{
    $payload = [
      'activationLink'=>route('email.activate',['token'=>$user->confirmationToken]),
      'userName'=>$user->name
    ];
    
    $emailTemplate = new SendCloudTemplate('test_template_active',$payload);
    Mail::raw($emailTemplate,function ($mailMessage) use ($user){
        $mailMessage->from('apoxxxx@Gxxxxxxxxxyccccc.sendcloud.org','Quản trị viên Zhihu');
        $mailMessage->to($user->email);
    });
}

5. Tập tin \app\Http\Controllers\VerificationController.php

php artisan make:controller VerificationController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class VerificationController extends Controller
{
    public function activate($token)
    {
        $targetUser = User::where('confirmationToken',$token)->first();
        if(empty($targetUser)){
            return redirect('/');
        }
        $targetUser->isActivated = 1;
        $targetUser->confirmationToken = Str::random(40);
        $targetUser->save();
        Auth::login($targetUser);
        return redirect('/home');
    }
}

6. Tập tin \app\Models\User.php

protected $fillable = [
        'name', 'email', 'password', 'profileImage','confirmationToken'
    ];

2.3.4 Kiểm thử chức năng

Truy cập: http://test.zhihu.test/register

Sau khi đăng ký, kiểm tra bảng users trong cơ sở dữ liệu

Xem email nhận được

Sau khi nhấp vào liên kết kích hoạt, kiểm tra lại bảng dữ liệu

3. Tài liệu tham khảo

Ghi chú từ người khác:

https://blog.csdn.net/sinat_37390744/article/details/88738493

https://www.cnblogs.com/dzkjz/p/12370169.html

Hướng dẫn video:

https://www.codecasts.com/series/build-a-zhihu-website-with-laravel

https://www.bilibili.com/video/BV174411X7AS?p=2

4. Lưu trữ mã nguồn

git tag v1.0
git push origin --tags

https://github.com/guainttt/laravel-zhihu/tags

Thẻ: laravel email-verification sendcloud authentication php

Đăng vào ngày 29 tháng 8 lúc 19:12