the-road-to-react-with-firebase / react-firebase-authentication

πŸ”₯ Boilerplate Project for Authentication with Firebase in React.
https://www.robinwieruch.de
1.02k stars 298 forks source link

Unhandled Rejection (TypeError): Cannot read property 'roles' of null #24

Open eldyvoon opened 5 years ago

eldyvoon commented 5 years ago

this block of code in firebase.js is throwing an error:

//if (!dbUser.roles) {...}

error Unhandled Rejection (TypeError): Cannot read property 'roles' of null

edguerrade commented 5 years ago

As I can see, dbUser can't be null if there is authUser, so this error shouldn't happen if you don't remove the user data while it is authenticated

eldyvoon commented 5 years ago

@edguerrade I didn't remove the user, the user exist in my db. But after I delete and reauth the user now it worked.

joni43 commented 5 years ago

@edguerrade I didn't remove the user, the user exist in my db. But after I delete and reauth the user now it worked.

Hello, I'm a beginner in firebase, and have the same issue. DId you remove the user in firebase db to solve it?

rwieruch commented 5 years ago

I guess this bug happens when you are in between of the implementation of the authentication user and database user. My advice is to start from a clean slate by

screen shot 2019-02-06 at 13 29 37
eldyvoon commented 5 years ago

Correct. I deleted everything and start over and it worked. I can't remember how to reproduce the bug though.

On Wed, Feb 6, 2019, 1:33 PM Robin Wieruch <notifications@github.com wrote:

I guess this bug happens when you are in between of the implementation of the authentication user and database user. My advice is to start from a clean slate by

  • deleting the user in the Authentication Database (see Authentication Tab on Firebase Dashboard)
  • deleting the user in the Realtime Database (see Database Tab on Firebase Dashboard)
  • busting the cache of the application, because of local-storage (see screenshot)

[image: screen shot 2019-02-06 at 13 29 37] https://user-images.githubusercontent.com/2479967/52322331-bcb16b80-2a13-11e9-8e38-4fafb3b27d68.png

β€” You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/the-road-to-react-with-firebase/react-firebase-authentication/issues/24#issuecomment-460906298, or mute the thread https://github.com/notifications/unsubscribe-auth/ACqqnUKxnO9PmNRYp---FIKD7Qlct6P0ks5vKmkmgaJpZM4ahJ_K .

alfieqashwa commented 5 years ago

I had an issue and have been fixed by the start from a clean slate's guide. Danke.

error-firebase-authentication

oximer commented 5 years ago

I'm having the same issue

rwieruch commented 5 years ago

Did you try https://github.com/the-road-to-react-with-firebase/react-firebase-authentication/issues/24#issuecomment-460906298 @oximer ?

Parv3sh commented 5 years ago

Tried. But doesn’t work. Followed all 3 steps. Still getting the same error. Although I started with a clean slate.

Parv3sh commented 5 years ago
Screen Shot 2019-04-18 at 10 39 41 am

Can't purge the entire cache for some reasons.

Parv3sh commented 5 years ago

Figured it out. Instead of defining the roles in Sign Up like roles[ROLES.ADMIN] = ROLES.ADMIN; do roles.push(ROLES.ADMIN); And also initiate roles like const roles = []; instead of {};

eltel commented 5 years ago

Hi guys

None of these fixes are working for me, it all started with Facebook login - is anyone aware of any other fixes??

I'm even having the same problem using the author's code :(

edit: Currently backtracking to before adding FB login

Thanks

Terry

eltel commented 5 years ago

Right, still the same bug - this is a big problem - I've followed the code to the letter and keep coming back to the same issue. I have users in my DB - the problem appears to be 'roles' crashing the app every time - does anybody have a workaround for this? I've basically lost 15+ hours trying to resolve this.

Any tips most welcomed.

rwieruch commented 5 years ago

Can you share your code? Any link to a GitHub project? Otherwise we can just guess what's going on.

eltel commented 5 years ago

Hi Robin

Thanks for getting back to me, I think it's resolved now - I went back to one of my earlier commits and went through it all again - the part where we refactored the App/Index component back to a functional component - copying over the functionality to the withAuthentication component was what got me, I didn't clear everything out so (I think) the app component kept resetting user to null.

Apologies for not posting code, I saw a 'bug' tag applied to the thread and just wondered if it had been resolved - it's been a long day, wasn't thinking straight...lol

Thoroughly enjoying the course, learning a lot and will definitely be recommending it.

Thanks again

Terry

On Wed, 24 Apr 2019 at 17:53, Robin Wieruch notifications@github.com wrote:

Can you share your code? Any link to a GitHub project? Otherwise we can just guess what's going on :(

β€” You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/the-road-to-react-with-firebase/react-firebase-authentication/issues/24#issuecomment-486421443, or mute the thread https://github.com/notifications/unsubscribe-auth/ABDQULA7YHUCRW7SNQSUPBTPSDCDLANCNFSM4GUET7FA .

eltel commented 5 years ago

HI Robin

So, it seems I was mistaken - after retracing my steps and literally recreating the whole application the same error occurred at exactly the same point again - the Facebook authentication - upon attempting to log in with FB it threw exactly the same error message. [image: image.png] I even tried replacing my firebase.js with yours to see if it was my code and no change. Here's a link to my Github repo:

https://github.com/eltel/reactFirebase

Many thanks

Terry

On Wed, 24 Apr 2019 at 19:04, Terry Mitchell djterrymitchell@gmail.com wrote:

Hi Robin

Thanks for getting back to me, I think it's resolved now - I went back to one of my earlier commits and went through it all again - the part where we refactored the App/Index component back to a functional component - copying over the functionality to the withAuthentication component was what got me, I didn't clear everything out so (I think) the app component kept resetting user to null.

Apologies for not posting code, I saw a 'bug' tag applied to the thread and just wondered if it had been resolved - it's been a long day, wasn't thinking straight...lol

Thoroughly enjoying the course, learning a lot and will definitely be recommending it.

Thanks again

Terry

On Wed, 24 Apr 2019 at 17:53, Robin Wieruch notifications@github.com wrote:

Can you share your code? Any link to a GitHub project? Otherwise we can just guess what's going on :(

β€” You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/the-road-to-react-with-firebase/react-firebase-authentication/issues/24#issuecomment-486421443, or mute the thread https://github.com/notifications/unsubscribe-auth/ABDQULA7YHUCRW7SNQSUPBTPSDCDLANCNFSM4GUET7FA .

eltel commented 5 years ago

So, after spending many more hours trying to work around this, I've still had no joy - the current GH repo has @Parv3sh solution:

Figured it out. Instead of defining the roles in Sign Up like roles[ROLES.ADMIN] = ROLES.ADMIN; do roles.push(ROLES.ADMIN); And also initiate roles like const roles = []; instead of {};

but that didn't change anything, my original code followed the book:

const roles = {}; if (isAdmin) { roles[ROLES.ADMIN] = ROLES.ADMIN; }

Here is my current repo again:

https://github.com/eltel/reactFirebase

I even tried pasting in Robin's code and no change. I'm literally losing what little hair I've got left over this, I rebuilt from scratch just to reach the exact same error :(

If anyone has a working repo I can compare with I'd be eternally grateful if you could share.

Thanks

Terry

eltel commented 5 years ago

Hi @rwieruch - is there any news on this yet? I posted my repo and have hit a brick wall with this course.

Many thanks

Terry

eltel commented 5 years ago

So, I gave up on getting Facebook to work - once I removed FB auth from the equation I managed to get the app to work with Twitter and Google login - but this is happening with both mine and @rwieruch 's code with exactly the same error message, I followed all the instructions to the letter and have had no trouble getting FB auth to work in other projects - so it would appear that it's definitely an issue with the 'roles' code as that's the exact same error being thrown with both of our code - is anybody else having this problem?? How did you get around it?

Parv3sh commented 5 years ago

@eltel Did you try getting rid of roles prop where ever you're using it to sign in a user using facebook? Since you're not assigning an Admin role to that. I think this should work for you.

Parv3sh commented 5 years ago

@eltel I tried giving a hit on your code. Couldn't reproduce the error though. Try above-mentioned solution first, hence or otherwise, walk me through for reproducing the error.

Parv3sh commented 5 years ago

@eltel my suggestion at https://github.com/the-road-to-react-with-firebase/react-firebase-authentication/issues/24#issuecomment-488521255 might still not work for you since you're getting the error in firebase.js. Update: I used your code. It's working totally fine at my end. I'm able to log in, using Facebook.

Couple things, you might want to look into.

  1. Clear database
  2. Clear authenticated users.
  3. Check that the firebase API keys are correctly configured in the firebase.js
  4. Check if the database rules are set to false. Which should be set true for both read, write initially. (I have got a hunch you missed this part)
  5. Check if the facebook is also correctly configured as suggested by @rwieruch here https://www.robinwieruch.de/firebase-facebook-login/.

If above doesn't work. Try below, which I did.

I used your code. changed nothing but firebase config since I created a new project for it.

  1. Set authentication for email, google and facebook as per your project requirements.
  2. Set Realtime database and not Firestore
  3. Set the rules for the above database to test mode.
  4. Login. And boom. I'm in.

If nothing works, then the way

if (!dbUser.roles) {
     dbUser.roles = [];
}

is defined, needs to be changed. Nonetheless, it's working totally fine at my end using your code.

Closes: #24

eltel commented 5 years ago

Thanks, man, I'd done all of these beforehand - but the fact that it's only Facebook login that was giving me grief made it clear that there is where the problem was. I had followed @rwieruch 's post (https://www.robinwieruch.de/firebase-facebook-login/) to the letter...However, after recreating the Facebook app and following your first set of instructions - to quote your good self - 'boom! I'm in!!

You just got a whole heap of karma points mate, many thanks once again!! :)

Parv3sh commented 5 years ago

Glad to help. πŸ‘

rwieruch commented 5 years ago

Super thankful for your help @Parv3sh It's so difficult for me to go through all issues for my projects recently, because there is only so much time I can put in to help with individual bugs and the lists of my open source projects keeps growing... That's why I am so grateful when I see the community sticking together to work on such issues. Thank you again and sorry @eltel for not being able to help here. I do my best to keep up with everything, but sometimes I cannot reply in time for issues :(

eltel commented 5 years ago

Thanks to both of you, no worries Robin, I completely understand - @Parv3sh https://github.com/Parv3sh helped loads and I found the course immensely useful/educational and am now using the book and code from the course for reference/scaffold for my own projects.

On Mon, 6 May 2019 at 10:46, Robin Wieruch notifications@github.com wrote:

Super thankful for your help @Parv3sh https://github.com/Parv3sh It's so difficult for me to go through all issues for my projects recently, because there is only so much time I can put in to help with individual bugs and the lists of my open source projects keeps growing... That's why I am so grateful when I see the community sticking together to work on such issues. Thank you again and sorry @eltel https://github.com/eltel for not being able to help here. I do my best to keep up with everything, but sometimes I cannot reply in time for issues :(

β€” You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/the-road-to-react-with-firebase/react-firebase-authentication/issues/24#issuecomment-489626420, or mute the thread https://github.com/notifications/unsubscribe-auth/ABDQULDFOO24X54LFBYUPUTPUAZEVANCNFSM4GUET7FA .

xai1983kbu commented 5 years ago

I encountered the same issue the version of the book - 08 July 2019

I've recorded a video and it helped me figured out the source of error

road_to_firebase_error

As we can see before we getting the error

Unhandled Rejection (TypeError): Cannot read property 'roles' of null

we getting an error from the firebase 226 we can also find that error in console with help of React Tab (React Developer Tools) 4

The temporary fix I've made - commented out a line of code which invokes that error

class SignInFacebookBase extends Component {
    ...
    onSubmit = event => {this.props.firebase
      .doSignInWithFacebook()
      .then(socialAuthUser => {
        // Create a user in your Firebase Realtime Database too
        return this.props.firebase.user(socialAuthUser.user.uid).set({
          username: socialAuthUser.additionalUserInfo.profile.name,
          //email: socialAuthUser.additionalUserInfo.profile.email,
          roles: {}
        })
      })
      ...

After that change, I am getting Facebook User in my Real Time Database but without email and roles. By the way the same situation for Google User, I don't see email and roles in my Real Time Database.

vr1e commented 4 years ago

Basically all three (Google, Facebook and Twitter) do the same for socialAuthUser.additionalUserInfo.profile.email.

It seems that email is not even inside additionalUserInfo but instead in socialAuthUser.user.email and the value is null for all three.

xai1983kbu commented 4 years ago

@vr1e did you fill Auth consent screen? github.com/flutter/flutter/issues/33393#issuecomment-510395178 It seems after I've added all needed info (including privacy policy link) I managed to use socialAuthUser.additionalUserInfo.profile.email without getting an error.

vr1e commented 4 years ago

It seems that google and facebook logins somehow sorted themselves. Maybe it needed some time... Twitter has it's own case. You have to enter Terms of service URL and Privacy policy URL in your App details page on https://developer.twitter.com. Then you can check Request email address from users on Permissions page.

image

kewarrie commented 4 years ago

Hi. I know this is an old issue, but I am currently facing this problem.

I have only setup one method for authentication i.e. Email / Password.

Steps to reproduce

  1. Sign In with an existing user, then Sign Out immediately.
  2. Without refreshing your browser, head over to the Sign Up page and create a new user.

Expected behavior

User is successfully signed up & signed in, then authUser is updated successfully after being merged with dbUser which is read from the database in firebase.js, i.e.

...

// *** Merge authUser & dbUser API ***
  onAuthUserListener = (next, fallback) =>
    this.auth.onAuthStateChanged(authUser => {
      if(authUser) {
        this.user(authUser.uid)
          .get()
          .then(doc => {
            const dbUser = doc.data();

            // if no roles, default to empty roles
            if (!dbUser.roles) {
              dbUser.roles = {};
            }

            // merge authUser & dbUser
            authUser = {
              uid: authUser.uid,
              email: authUser.email,
              displayName: authUser.displayName,
              emailVerified: authUser.emailVerified,
              providerData: authUser.providerData,
              ...dbUser,
            };

            next(authUser);
          });
      } else {
        fallback();
      }
    });
...

Actual behavior

Error: Unhandled Rejection (TypeError): Cannot read property 'roles' of undefined

From my personal investigation, it seems as though dbUser is not being read from the database.

This causes the dbUser variable to be undefined which throws the above error.

I'm not able to figure out why.

Current workaround

It seems as though refreshing the browser after you Sign Out, BUT, before you Sign Up a new user prevents the above error from happening.

Repository

A repository with the code that gives me the above error is available here.

* UPDATE

This seems to be a Firebase JS SDK issue as there are a few related issues raised on the official Github repository, e.g. here.

phuhuutin commented 3 years ago

i just fixed it. firebase if (!dbUser.roles) { dbUser.roles = []; } signup const roles =[]; if (isAdmin) { roles.push(ROLES.ADMIN); }; and most importantly, signing .set({ username: socialAuthUser.user.displayName, email: socialAuthUser.user.email, roles: [], // this one. }); after changing roles into array you have to correct all of components that use roles as object so it can work with array. like: Nav {authUser.roles.includes(ROLES.ADMIN) && (

        )}

Admin

     const condition = authUser => authUser && authUser.roles.includes(ROLES.ADMIN);