ahmadbadpey's avatar

two-factor SMS authentication workflow in laravel

I want to make a SMS 2-factor authentication system but I do not know what is workflow in this case and which methods should be used.

I want to use a Boolean field named isTwoFactorActive for user model and when a user attempt to login if it's TRUE then go to a view for enter SMS code that received.

In addition to, I'm using Dingo laravel package to create an API and all this operations should be under API.

I do not know what is best approach and workflow. if any One has knowledge in this case please help me.

0 likes
2 replies
RamjithAp's avatar

First check isTwoFactorActive is true or false in your login function if its true send SMS and give the response to get SMS code which is received. If its false directly return token.

Route::post('auth/login', function () {

    $credentials = Input::only('email', 'password');

    if ( ! $token = JWTAuth::attempt($credentials) )
    {
        // return the 401 response
        return Response::json(['error' => 'invalid_credentials'], 401);
    } 

    if(Auth::user()->isTwoFactorActive) {

    $code = rand(1000,9999);  //generate sms code

    $send_sms = SendSMS($code,Auth::user()->phone);  //write your own code here to send SMS to user mobile

    $data= collect(array('sms_code'=>$code,'token'=>$token));  // save sms_code and token in an array 

    Session::push(Auth::user()->id, $data); // save array into session.

    return Response::json(array('login_status'=>'success','user_id'=>Auth::user()->id,'sms_required'=>'yes'));

    } else {

    return Response::json(array('login_status'=>'success','token'=>$token));

    }
});

Now on your front end check the response if the token present, then go ahead and show homepage or show enter SMS code screen and capture the sms code in a form and then post the details to this API again.

Route::post('sms/verification', function () {

    $user_id = Request::input('user_id');
    $code= Request::input('code');

    $data = Session::get($user_id );
    
    if($data->sms_code == $code) {

    return Response::json(array('status'=>'success','token'=>$data->token));

    } else {
    
   return Response::json(array('status'=>'failed','msg'=>'Invalid sms code!'));
   
   }
});
ahmadbadpey's avatar

thanks for your guide. But the problem that I have now is that beacause I'm working on a API via dingo laravel package seem I can not use session for store some data like created token.

What can I do instead of that ?

Please or to participate in this conversation.