Как включить истечение срока действия ссылки для подтверждения электронной почты после проверки в API laravel 6, реализованном с помощью функции VerizesEmail? - PullRequest
2 голосов
/ 23 января 2020

Я реализовал Laravel 6 API и использовал встроенный Laravel Illuminate\Foundation\Auth\VerifiesEmails на основе учебного руководства здесь , но ссылка для проверки электронной почты не устарела и по-прежнему доступна после успешной проверки электронной почты. Я нашел много учебных пособий, касающихся laravel внешнего интерфейса, но как реализовать его в API.

VerificationApiController

class VerificationApiController extends Controller
{
    use VerifiesEmails;

    /**
     * Mark the authenticated user's email address as verified.
     * @param  Request  $request
     * @return JsonResponse
     */
    public function verify(Request $request): JsonResponse
    {
        $userID = $request['id'];
        $user = User::findOrFail($userID);
        $date = date('Y-m-d g:i:s');

        // to enable the “email_verified_at field of that
        // user be a current time stamp by mimicking the
        // must verify email feature
        $user->email_verified_at = $date;
        $user->save();

        return response()->json('Email verified!');
    }

    /**
     * Resend the email verification notification.
     * @param  Request  $request
     * @return JsonResponse|Response
     */
    public function resend(Request $request)
    {
        if ($request->user()->hasVerifiedEmail()) {
            return response()->json('User already have verified email!', 422);

        }
        $request->user()->sendEmailVerificationNotification();

        return response()->json('The notification has been resubmitted');
        // return back()->with(‘resent’, true);
    }
}

Модель пользователя

class User extends Authenticatable implements MustVerifyEmail
{
    use HasApiTokens, Notifiable;

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

    /**
     * The attributes that should be hidden for arrays.
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * Send email verification notification
     */
    public function sendApiEmailVerificationNotification()
    {
        $this->notify(new VerifyApiEmail); // my notification
    }
}

Вот маршруты проверки API

Route::get(‘email/verify/{id}’, ‘VerificationApiController@verify’)->name(‘verificationapi.verify’);
Route::get(‘email/resend’, ‘VerificationApiController@resend’)->name(‘verificationapi.resend’)

Здесь UsersApiController

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Hash;
use Auth;
use Validator;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Auth\Events\Verified;
class UsersApiController extends Controller
{
use VerifiesEmails;
public $successStatus = 200;
/**
* login api
*
* @return \Illuminate\Http\Response
*/
public function login(){
if(Auth::attempt([‘email’ => request(‘email’), ‘password’ => request(‘password’)])){
$user = Auth::user();
if($user->email_verified_at !== NULL){
$success[‘message’] = “Login successfull”;
return response()->json([‘success’ => $success], $this-> successStatus);
}else{
return response()->json([‘error’=>’Please Verify Email’], 401);
}
}
else{
return response()->json([‘error’=>’Unauthorised’], 401);
}
}
/**
* Register api
*
* @return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
‘name’ => ‘required’,
‘email’ => ‘required|email’,
‘password’ => ‘required’,
‘c_password’ => ‘required|same:password’,
]);
if ($validator->fails()) {
return response()->json([‘error’=>$validator->errors()], 401);
}
$input = $request->all();
$input[‘password’] = Hash::make($input[‘password’]);
$user = User::create($input);
$user->sendApiEmailVerificationNotification();
$success[‘message’] = ‘Please confirm yourself by clicking on verify user button sent to you on your email’;
return response()->json([‘success’=>$success], $this-> successStatus);
}
/**
* details api
*
* @return \Illuminate\Http\Response
*/
public function details()
{
$user = Auth::user();
return response()->json([‘success’ => $user], $this-> successStatus);
}
}

Вот маршруты пользователя и аутентификации

Route::post(‘login’, ‘UsersApiController@login’);
Route::post(‘register’, ‘UsersApiController@register’);
Route::group([‘middleware’ => ‘auth:api’], function(){
Route::post(‘details’, ‘UsersApiController@details’)->middleware(‘verified’);
}); // will work only when user has verified the email

поэтому проблема в том, что когда я нажимаю на ссылку подтверждения по электронной почте, пользователь проверяется, но срок действия ссылки не истек. Я хочу, чтобы срок действия ссылки истек, как только пользователь будет подтвержден. Как это сделать?

1 Ответ

0 голосов
/ 17 февраля 2020

Вы реализовали класс VerifyApiEmail?

namespace App\Notifications;

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\URL;
use Illuminate\Auth\Notifications\VerifyEmail as VerifyEmailBase;

class VerifyApiEmail extends VerifyEmailBase
{
    protected function verificationUrl($notifiable)
    {
        return URL::temporarySignedRoute(
        'api.auth.verify', Carbon::now()->addMinutes(60), ['id' => $notifiable->getKey()]
        );
    }
}

Здесь вы можете добавить время истечения в минутах, секундах или часах.

...