How to use Laravel with Firebase authentication using REST API basic integration #6

Learn how to use Laravel with Firebase authentication using REST API basic integration. In this chapter, we will learn how to setup authentication in Firebase and its usage in the Laravel using the Firebase Admin PHP SDK.

First of all, click on "Authentication" and open the "Users" tab, click on the "Set up sign-in method". It will redirect to Sign-in method tab.


Then click on status "Disabled" on "Email/Password" row and "Enable" this option. Keep the "Email link (passwordless sign-in)" is disable. We will cover in next chapters.


Click on "Save" and make this option "Enabled".


This will give you option to add users in "Users" tab. Now if you add a user, it will provide a unique user id and can link it with any collection in the Cloud Firestore database by inserting this uid in the fields and can add rules to access by uid.


Now lets setup the Email Templates like Email address verification Password reset. Click on "Templates" tab. You can modify the Project public-facing name to your project name and Project support email to show to the users. Now here we have a limitation, you cannot modify the template for the security purpose. You can add only a continue URL to redirect back to your site.


Email verification mail would like some how as below


So your Firebase Authentication is successfully setup. Now lets move towards its usage in the Laravel.

 try {  
     $email = 'youremailaddress@gmail.com';  
     $password = 'yourpassword';  
     $authRef = app('firebase.auth')->createUser([  
        'email' => $email,  
       'password' => $password  
     ]);  
    $actionCodeSettings = [  
         'continueUrl' => 'www.yoursite.com/home'  
    ];  
     app('firebase.auth')->sendEmailVerificationLink($email, $actionCodeSettings);  
     echo $authRef->uid; //This is unique id of inserted user.  
 }   
 catch (\Kreait\Firebase\Exception\Auth\EmailExists $ex) {  
   echo 'email already exists';  
 }  

Here you have handle all validation by handling exception like if user has been already created by the email.

And you can add data in the database and map this uid for storing further details like address, etc.

 $detailRef = app('firebase.firestore')->collection('UserDetail')->newDocument(); $detailRef ->set([  
     'uid' => $authRef->uid,  
     'address' => 'Street 123'  
 ]);  


In the above code, lets get into the details of actionCodeSettings.
continueUrl = this url is site to your site. But the domain verification is to be done.
And there are many handleCodeInApp, androidInstallApp etc. for more option.

Now lets come to login page and method after user has verified the email.

 try {  
     $email = $request->email;  
     $password = $request->password;  
     $user = app('firebase.auth')->verifyPassword($email,$password);  
     if($user->emailVerified) {  
          echo 'login success';  
     } else {  
         echo 'email verification pending';  
     }  
 } catch (\Kreait\Firebase\Exception\Auth\InvalidPassword $ex) {  
     echo 'Invalid password';  
 }  
Invalid password has to be handles through exception catch. And you check email verified as mentioned above.


You can similar use the password reset option. 
 try {  
   $actionCodeSettings = [  
      'continueUrl' => 'www.yoursite.com/login'  
   ];  
   app('firebase.auth')->sendPasswordResetLink($email, $actionCodeSettings);  
   echo 'mail sent';  
 }  
 catch (\Kreait\Firebase\Auth\SendActionLink\FailedToSendActionLink $ex) {  
      echo 'email not exists';  
 }  


Hope you understand the basic login flow with email/password signin method. We will cover all signin method in upcoming chapters. Please let us know in comments if you have any doubt or want a new chapter on some topic of Firebase.




Post a Comment

32 Comments

  1. Replies
    1. Hi, Thank you for the series. It has been really helpful. however this particular kind assumes we know somethings. Show how you fully implement the register and signin controller. i don't even know where the code excerpt should go. Thank you once again.

      Delete
    2. Ok, we will have a new chapter for this.

      Delete
  2. Please, Which file will i put the laravel code??

    ReplyDelete
    Replies
    1. In any controller file, you can simply access your firebase by

      app('firebase.firestore')->database()

      Delete
  3. Replies
    1. For PHP project, you are not actually maintaining session between your project and firebase. So actually there is no sign in or sign out. You have to laravel \Session variable and check in every route through middleware. You can store uid in session and on logout clear your session

      Delete
    2. Please find a new chapter for Laravel Firebase Sign in and Sign out. Please find this chapter

      https://laravelwithfirebase.blogspot.com/2020/05/chapter-15-laravel-with-firebase-sign-in-maintain-logged-in-session-using-middleware.html

      Delete
  4. Hi.. What About Signup With Form Process. it about Only Cover Sign in Process .

    ReplyDelete
    Replies
    1. Himanshu thanks for reaching us.
      As you read this chapter carefully, there is a method app('firebase.auth')->createUser. So this method is to create/signup a user.

      Thanks for reading. Please follow us to get daily updates and please share

      Delete
  5. Can you modify the laravel's auth and provide the code because laravel already gives secure authatication ( like : https://medium.com/@GaonLabs/laravel-firebase-authentication-complete-guide-7735a1f83a3d ).

    ReplyDelete
    Replies
    1. Thanks for providing this link.

      We are eager to update this. We will look out this post on medium.com and update the chapter or add new one.

      Thanks again for sharing. Till then please follow us by clicking follow button on sidebar. So if we update this chapter, you will get the notification.

      Delete
    2. thanks for the fast reply and the above post ( medium.com ) there are login and regiester page with can be used but i wanted other templates like email verification , password reset ... kindly see if that things are also updated :)

      Delete
    3. Hi

      For customizing Firebase default Email Template, we have already written two chapters on that. Please read and let us know.

      For Firebase custom email verification template:
      https://laravelwithfirebase.blogspot.com/2020/04/chapter-13-implement-custom-firebase-auth-email-verification-template-replace-default-view-using-laravel-php.html

      For Firebase custom password reset email template:
      https://laravelwithfirebase.blogspot.com/2020/05/chapter-14-implement-custom-firebase-auth-forgot-reset-password-template-replace-default-view-using-laravel-php.html

      Hope it helps.

      Delete
    4. Ya I Went through the above links. But couldn't know where to at them as a beginner . If its more specific like where to add or which controller the code belongs to , will make quite easier.

      Other wise this blog is AWESOME ❤️❤️

      Delete
    5. Hi suhasrkms

      $link = app('firebase.auth')->getEmailVerificationLink('someone@example.com');

      This above line is the main one. This will you the verification link.

      Then you have to send this link in email template you build in laravel.

      use Mail;

      $data['link'] = $link;
      Mail::send('email-verification', compact('data'),
      function ($m) {
      $m->to('someone@example.com', 'John Carry')
      ->subject('Email Verification');
      });


      Here Mail:send is basic Laravel method to send any mail. And email-verification.blade.php is your email template html.

      Hope it little bit clear.

      Please follow us. Thanks.

      Delete
    6. its little sorted , is there there any repositary of the project. Where we can change ony firebase creditials ... and all basics can run.

      Delete
    7. As of now, there is no such repository. Will update you if we can.

      Please follow us to notify you. Thanks.

      Delete
  6. Is there any github repository where we can find full code to implement in our laravel project...!!!

    ReplyDelete
    Replies
    1. Hi

      Unfortunately there is no GitHub. Ask any questions. We have made every possible way to cover everything in all chapters. We will happy to answer your question.

      And please follow us. It helps us.

      Delete
    2. i am not able to connect with firestore
      Error:
      Kreait\Firebase\Exception\RuntimeException
      Unable to create a FirestoreClient: Class "Google\Cloud\Firestore\FirestoreClient" not found

      i am not able to solve this...i have added your code $detailRef = app('firebase.firestore')->collection('UserDetail')->newDocument(); $detailRef ->set([
      'uid' => $authRef->uid,
      'email' => $authRef->email,
      ]);

      to create db in firestore but the above error reflected

      Can you help ?

      Delete
    3. Hi

      Thanks for reaching out to us.

      This issue would be occurring, you might not installed the package properly.

      We suggest you follow all steps mentioned in this chapter 5
      https://laravelwithfirebase.blogspot.com/2020/02/chapter-5-integrate-laravel-with-google-firebase-connecting-cloud-firestore.html

      If it helps, click on follow button on top left. It helps us.

      Delete
    4. yes i have seen all the tutorials but getting errors...i have installed grpc extension but and checked that its enabled but why i am getting this error??

      Unable to create a FirestoreClient: The requested client requires the gRPC extension. Please see https://cloud.google.com/php/grpc for installation instructions.

      Delete
    5. Okay.

      There are two place where grpc should be enabled

      One would be main server php.ini and other would cli php ini.

      If you're getting this error while executing commands in terminal, then sure you need it in cli php.ini

      After trying above, still issue persists,
      Try composer update in your project.

      If it helps. Show support to us by clicking follow button.

      Delete
    6. solved grpc error.
      but getting this error
      Call to undefined method Kreait\Firebase\Firestore::collection()

      Delete
    7. Glad. Loved it.

      For collection, hope you are following this
      app('firebase.firestore')->database()->collection('blogs')

      Delete
    8. Thankyou so much for your responses !!!
      Glad to use your Chapter 6

      Delete
    9. Thanks. Can you show your support towards blog by following us. Follow button on bottom and top. and please share our blog.

      Delete
  7. I am using firebase for email verification but emails are not going

    i get error like delivery incomplete
    The response was:
    The recipient server did not accept our requests to connect. Learn more at https://support.google.com/mail/answer/7720 [smtp.gmail.com 74.125.142.109: tls negotiation failed (smtps)] [smtp.gmail.com 2607:f8b0:400e:c08::6d: tls negotiation failed (smtps)]

    what should be done
    can be explain in steps ?

    ReplyDelete
    Replies
    1. Hi
      Thanks for reaching out us.

      The issue is with your SMTP settings. Your are not using Firebase.

      Read this chapter in detail.
      How to send custom firebase template
      https://laravelwithfirebase.blogspot.com/2020/04/chapter-13-implement-custom-firebase-auth-email-verification-template-replace-default-view-using-laravel-php.html

      Delete
  8. smtp settings have to be done or not? i m getting confused

    ReplyDelete
    Replies
    1. SMTP settings only required if you want to send custom email template. If you want to send firebase default simple white text email with link, you can directly send using Firebase functions.

      Now if you want to go other way to send custom template, you need SMTP. Read this chapter https://laravelwithfirebase.blogspot.com/2020/04/chapter-13-implement-custom-firebase-auth-email-verification-template-replace-default-view-using-laravel-php.html

      Hope it helps. Please follow us and share our blog.

      Delete