OurBG
OurBG

Reputation: 597

Laravel OTP with email only

I am trying to ingrate this flow of authentication in a Laravel 7 applciation:

If on a later stage the user tries to enter the same email - same thing happens with a new code. No passwords or whatever.

Is there any way to achieve that out of the box (or with a package) or should I write it myself?

Upvotes: 1

Views: 11976

Answers (1)

user10498792
user10498792

Reputation:

Yes, the efficient way to do is to inherit the laravel auth methods and change them accordingly. Make a resource controller by any name ex- UserController and write this code--

public $successStatus = 200;

public function login(Request $request){
    Log::info($request);
    if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
        return view('home');
    }
    else{
        return Redirect::back ();
    }
}

public function loginWithOtp(Request $request){
    Log::info($request);
    $user  = User::where([['email','=',request('email')],['otp','=',request('otp')]])->first();
    if( $user){
        Auth::login($user, true);
        User::where('email','=',$request->email)->update(['otp' => null]);
        return view('home');
    }
    else{
        return Redirect::back ();
    }
}

public function sendOtp(Request $request){

    $otp = rand(1000,9999);
    Log::info("otp = ".$otp);
    $user = User::where('email','=',$request->email)->update(['otp' => $otp]);
    // send otp to email using email api
    return response()->json([$user],200);
}

then add these routes to your routes file--

    Route::post('login', 'UserController@login')->name('newlogin');

Route::post('loginWithOtp', 'UserController@loginWithOtp')->name('loginWithOtp');
Route::get('loginWithOtp', function () {
    return view('auth/OtpLogin');
})->name('loginWithOtp');

Route::any('sendOtp', 'UserController@sendOtp');

and then add OtpLogin.blade.php view and you are good to go

Upvotes: 2

Related Questions