laravel实现注册邮箱验证功能

臭大佬 2019-12-01 21:25:47 2122
简介 laravel实现注册邮箱验证功能

起因

在做臭大佬前端用户注册的时候,为了实现邮箱验证功能,需要实现发送邮件验证功能,其中就有发送倒计时的功能,截图如下:

流程

  • 用户填写邮箱;
  • 验证邮箱是否唯一;
  • 发送验证码;
  • 开始倒计时;
  • 填写验证码注册。

路由

发送验证码的路由

//发送邮件
Route::post('/tools/getEmailCode', 'Home\ToolsController@getEmailCode');

注册提交

我们使用auth自带的注册

Auth::routes();

控制器方法

发送邮件

如果对于laravel邮件功能不熟的,可以查看之前的文章 laravel任务调度+命令行+邮件发送用例

 /**
     * Description:验证邮箱
     * User: Vijay
     * Date: 2019/12/1
     * Time: 21:39
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getEmailCode(Request $request)
    {
        $email = $request->input('email');
        $info = User::where('email', $email)->first();
        if ($info) {
            $data = [
                'code' => 1,
                'msg' => '该邮箱已被注册',
                'data' => [],
                'create_time' => date('Y-m-d H:i:s', time())
            ];
            return response()->json($data);
        }
        //发送验证码
        $code = mt_rand(1000, 9999);
        Cache::put($email, $code, 60);
        $subject = env('MAIL_FROM_NAME');
        $msg = '【臭大佬】邮箱验证码:' . $code . ',如非本人操作,请忽略本消息。';
        Mail::raw($msg, function ($message) use ($email, $subject) {
            $message->to($email)->subject($subject);
        });
        //错误处理
        if (count(Mail::failures()) < 1) {
            $data = [
                'code' => 0,
                'msg' => '发送邮件成功,请查收!',
                'data' => [],
                'create_time' => date('Y-m-d H:i:s', time())
            ];
            return response()->json($data);
        } else {
            $data = [
                'code' => 1,
                'msg' => '邮箱验证码发送失败,请联系臭大佬(微信:wjf1937832819)',
                'data' => [],
                'create_time' => date('Y-m-d H:i:s', time())
            ];
            return response()->json($data);
        }
    }

这里我们接收前端ajax传过来的email字段,首先判断数据库这个邮箱是否被注册,如果没有被注册,然后设置随机数作为邮箱验证码,此时以这个邮箱字段为key,以随机数作为值,并设置60秒过期Cache::put($email, $code, 60);。调用邮箱发送服务。

注册方法

打开\app\Http\Controllers\Auth\RegisterController.php,

修改里面的代码。

<?php

namespace App\Http\Controllers\Auth;

use App\Models\Category;
use App\Models\Nav;
use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\View;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Show the application registration form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showRegistrationForm()
    {
        $navList = Nav::getMenuTree(Nav::orderBy('sort', 'asc')->get()->toArray());
        $categories = Category::getMenuTree(Category::orderBy('sort', 'asc')->select('id', 'name', 'pid')->get()->toArray());
        View::share([
            'nav_list' => $navList,
            'category_list' => $categories,
        ]);
        return view('auth.register');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    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:5', 'confirmed'],
            'captcha' => ['required', 'captcha'],
            'email_code' => ['required', function ($attribute, $value, $fail) use ($data) {
                $cacheEmail = Cache::get($data['email']);
                if ($cacheEmail != $value) {
                    $fail('邮箱验证失败!');
                }
            }]
        ], [
            'captcha.required' => trans('validation.required'),
            'captcha.captcha' => trans('validation.captcha'),
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'avatar' => $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/images/config/avatar_l.jpg',
            'email_verified_at' => date('Y-m-d H:i:s'),
        ]);
    }

    /**
     * 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());
    }
}

我们调用注册方法的时候会访问register()方法,这里主要是验证器方法里面的内容;

email_code字段就是用户填写的邮箱验证码。如果它和缓存中的值匹配,那就验证成功。

验证成功后,数据库email_verified_at字段设置时间。

前端

邮箱验证字段html

<div class="layui-form-item">
    <label class="layui-form-label">邮箱账号</label>
    <div class="layui-input-block">
        <input type="email" value="{{ old('email') }}" name="email" required lay-verify="email" placeholder="请输入邮箱账号"
               autocomplete="off" class="layui-input">
    </div>
    @if ($errors->has('email'))
    <div class="layui-form-mid layui-word-aux">{{ $errors->first('email') }}</div>
    @endif
</div>
<div class="layui-form-item">
    <label class="layui-form-label">邮箱验证</label>
    <div class="layui-col-xs4">
        <input type="text" required lay-verify="required" placeholder="邮箱验证码" class="layui-input" name="email_code">
    </div>
    <div class="layui-col-xs4">
        <div style="margin-left: 10px;">
            <button type="button" class="layui-btn layui-btn-primary layui-btn-fluid" id="getEmailCode">获取验证码</button>
        </div>
    </div>
    @if ($errors->has('email_code'))
    <div class="layui-form-mid layui-word-aux">{{ $errors->first('email_code') }}</div>
    @endif
</div>

前端定时器倒计时

这里要实现点击发送邮件功能,并且倒计时功能,如图:

js代码

js代码如下:

<script>
    var seconds = 60;
    var disabledClass = 'layui-disabled';
    function countdown(loop){
        seconds--;
        if(seconds < 0){
            $("#getEmailCode").removeClass(disabledClass).html('获取验证码');
            seconds = 60;
            clearInterval(timer);
        } else {
            $("#getEmailCode").addClass(disabledClass).html(seconds + '秒后重获');
        }
        if(!loop){
            timer = setInterval(function(){
                countdown(true);
            }, 1000);
        }
    }
    $('#getEmailCode').click(function () {
        if(seconds != 60)  return false;
        var email =  $("input[name='email']").val();
        if(!email){
            layer.msg('请输入正确的邮箱!');
            return false;
        }
        $.ajax({
            type: 'post',
            dataType: 'json',
            data: {email:email,_token:"{{ csrf_token() }}"},
            url: '/tools/getEmailCode',
            success: function (res) {
                if(res.code === 0){
                    layer.msg(res.msg, {
                        offset: '15px'
                        , icon: 1
                        , time: 1000
                    }, function () {
                        //成功开始倒计时
                        countdown(false);
                    });
                }else{
                    layer.msg(res.msg, {
                        offset: '15px'
                        , icon: 2
                        , time: 1000
                    }, function () {

                    });
                }
            }
        });
    });

</script>

成果

当邮件验证不通过时:

注册成功跳转首页