代码之家  ›  专栏  ›  技术社区  ›  Илья Зелень

使用RESTAPI的Laravel电子邮件验证5.7

  •  2
  • Илья Зелень  · 技术社区  · 7 年前

    如何为RESTAPI重新制作Laravel5.7电子邮件验证?

    还是值得从头做起?

    2 回复  |  直到 7 年前
        1
  •  36
  •   Илья Зелень    7 年前

    这个案子适合我。完整项目代码 here .

    验证控制器

    删除了重定向并使 response()->json(...) 响应。

    <?php
    
    namespace App\Http\Controllers\API\Auth;
    
    use App\Http\Controllers\Controller;
    use Illuminate\Foundation\Auth\VerifiesEmails;
    use Illuminate\Http\Request;
    use Illuminate\Auth\Events\Verified;
    
    class VerificationController extends Controller
    {
        use VerifiesEmails;
    
        /**
         * Show the email verification notice.
         *
         */
        public function show()
        {
            //
        }
    
        /**
         * Mark the authenticated user's email address as verified.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return \Illuminate\Http\Response
         */
        public function verify(Request $request)
        {
            // ->route('id') gets route user id and getKey() gets current user id() 
            // do not forget that you must send Authorization header to get the user from the request
            if ($request->route('id') == $request->user()->getKey() &&
                $request->user()->markEmailAsVerified()) {
                event(new Verified($request->user()));
            }
    
            return response()->json('Email verified!');
    //        return redirect($this->redirectPath());
        }
    
        /**
         * Resend the email verification notification.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return \Illuminate\Http\Response
         */
        public function resend(Request $request)
        {
            if ($request->user()->hasVerifiedEmail()) {
                return response()->json('User already have verified email!', 422);
    //            return redirect($this->redirectPath());
            }
    
            $request->user()->sendEmailVerificationNotification();
    
            return response()->json('The notification has been resubmitted');
    //        return back()->with('resent', true);
        }
    
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware('auth');
            $this->middleware('signed')->only('verify');
            $this->middleware('throttle:6,1')->only('verify', 'resend');
        }
    }
    

    use Illuminate\Auth\Notifications\VerifyEmail as VerifyEmailBase;
    
    class VerifyEmail extends VerifyEmailBase
    {
    //    use Queueable;
    
        /**
         * Get the verification URL for the given notifiable.
         *
         * @param  mixed  $notifiable
         * @return string
         */
        protected function verificationUrl($notifiable)
        {
            $prefix = config('frontend.url') . config('frontend.email_verify_url');
            $temporarySignedURL = URL::temporarySignedRoute(
                'verification.verify', Carbon::now()->addMinutes(60), ['id' => $notifiable->getKey()]
            );
    
            // I use urlencode to pass a link to my frontend.
            return $prefix . urlencode($temporarySignedURL);
        }
    }
    

    3) 已添加配置 frontend.php :

    return [
        'url' => env('FRONTEND_URL', 'http://localhost:8080'),
        // path to my frontend page with query param queryURL(temporarySignedRoute URL)
        'email_verify_url' => env('FRONTEND_EMAIL_VERIFY_URL', '/verify-email?queryURL='),
    ];
    

    use App\Notifications\VerifyEmail;
    

    /**
     * Send the email verification notification.
     *
     * @return void
     */
    public function sendEmailVerificationNotification()
    {
        $this->notify(new VerifyEmail); // my notification
    }
    

    5) 添加的路由

    以下路线用于Laravel:

    // Email Verification Routes...
    Route::get('email/verify', 'Auth\VerificationController@show')->name('verification.notice');
    Route::get('email/verify/{id}', 'Auth\VerificationController@verify')->name('verification.verify');
    Route::get('email/resend', 'Auth\VerificationController@resend')->name('verification.resend');
    

    如果使用,它们将添加到应用程序中 Auth::routes(); .

    email/verify restapi不需要控制器中的路由及其方法。

    6) 在我的首页 /verify-email (来自 config)我向参数中包含的地址发出请求 queryURL

    收到的URL如下所示:

    "http://localhost:8000/api/email/verify/6?expires=1537122891&signature=0e439ae2d511f4a04723a09f23d439ca96e96be54f7af322544fb76e3b39dd32"
    

    我的请求(带有授权标头):

    await this.$get(queryURL) // typical get request
    

    该代码完美地验证了电子邮件,我可以抓住错误,如果它已经被验证。我还可以成功地将邮件重新发送到电子邮件。

        2
  •  1
  •   Giacomo    7 年前

    public function __construct()
    {
        $this->middleware('auth')->except(['verify','resend']);
        $this->middleware('signed')->only('verify');
        $this->middleware('throttle:6,1')->only('verify', 'resend');
    }
    

    否则,laravel需要身份验证才能访问验证和重新发送路由