lundi 31 août 2020

how to authenticate web login page by api in laravel

I created an API for login in laravel. In postman it is working properly. Now I want to use that api in my web form. I have an login form and fill email and password then click on button then my login api should be run and should be redirect on dashboard.

API route is (in, routes/api.php):

Route::post('login', 'apifolder\AuthController@login');

controller for api is:

public function login(Request $request)
{
    $request->validate([
        'email' => 'required|string|email',
        'password' => 'required|string',
        'remember_me' => 'boolean'
    ]);

    $credentials = request(['email', 'password']);
    if(!Auth::attempt($credentials))
        return response()->json([
            'message' => 'Unauthorized',
            'status' => '401',
        ], 401);

    $user = $request->user();
    
    $tokenResult = $user->createToken('Personal Access Token');
    $token = $tokenResult->token;
    if ($request->remember_me)
        $token->expires_at = Carbon::now()->addWeeks(1);
    $token->save();
    return response()->json([
        'access_token' => $tokenResult->accessToken,
        'token_type' => 'Bearer',
        'expires_at' => Carbon::parse(
            $tokenResult->token->expires_at
        )->toDateTimeString(),
            'status' => '200',
    ]);
}

Above API is working properly in postman.

Now I want to use it from my web form.

routes are(in, routes/web.php):

Route::get('/','loginController@index')->name('login');
Route::POST('/login','loginController@login_submit')->name('login.submit');
Route::get('/dashboard','loginController@dashboard')->name('dashboard');

controller is:

public function login_submit(Request $request)
{
   $data1 = [
       'email' => $request->email, 
       'password' => $request->password,
   ];

   $curl = curl_init();

   curl_setopt_array($curl, array(
       CURLOPT_URL => "http://localhost/interview_assign/public/api/auth/login",
       CURLOPT_RETURNTRANSFER => true,
       CURLOPT_ENCODING => "",
       CURLOPT_MAXREDIRS => 10,
       CURLOPT_TIMEOUT => 30000,
       CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
       CURLOPT_CUSTOMREQUEST => "POST",
       CURLOPT_POSTFIELDS => json_encode($data1),
       CURLOPT_HTTPHEADER => array(
           "accept: */*",
           "accept-language: en-US,en;q=0.8",
           "content-type: application/json",
            "X-Requested-With: XMLHttpRequest"
       ),
   ));

   $response = curl_exec($curl);
   $err = curl_error($curl);

   curl_close($curl);

   if ($err) {
       echo "cURL Error #:" . $err;
   } else {
   $response = json_decode($response);
   
        if($response->status == '200')
        {
            return redirect()->route('dashboard');
        }
        else
        {
            return view('login',compact('response'));
        }
   }

}    

public function dashboard()
{
    return view('dashboard');
}

login blade is:

 <form action="" method="post">
    @csrf
    <div class="input-group mb-3">
      <input type="email" class="form-control" name="email" placeholder="Email">
      <div class="input-group-append">
        <div class="input-group-text">
          <span class="fas fa-envelope"></span>
        </div>
      </div>
    </div>
    <div class="input-group mb-3">
      <input type="password" class="form-control" name="password" placeholder="Password">
      <div class="input-group-append">
        <div class="input-group-text">
          <span class="fas fa-lock"></span>
        </div>
      </div>
    </div>
    <div class="row">
      <!-- /.col -->
      <div class="col-4">
        <button type="submit" class="btn btn-primary btn-block">Sign In</button>
      </div>
      <!-- /.col -->
    </div>
  </form>

When I login, then I got correct response. and also redirect on dashboard. But how to use response api token to authenticate my dashboard. Means, if I am not logged in then dashboard should not be access. Dashboard should be access only when I am logged in.

In postman after login, i got token then I copy token and paste in key in dashboard api and get the dashboard data. But how to authenticate in my web login and dashboard?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/34MthXX
via IFTTT

Aucun commentaire:

Enregistrer un commentaire