In this episode were going to build an Anonymous Authorization service with Angular 4 and Firebase. This feature will allow a user to start using your app with going through the typical OAuth signin or Email Password registration process. This approach is also called lazy registration or gradual engagement.
It works by creating a session using only a user ID (UID). If the user signs out without updating more account details, they will be unable to log back in.
At this point, it is assumed you have the AngularFire2 package installed and bootstrapped into your app. If not, go to the docs or checkout this video.
STEP 1 - Generate the Auth Service
If starting from scratch, generate the Auth Service. I'm going to be building upon the auth service from my previous OAuth tutorial and I recommend checking that video out first.
STEP 2 - Activate Providers in Firebase
Head over to your firebase project and enable the anonymous provider.
STEP 3 - Building the Service
First, make sure to subscribe to the FirebaseAuthState in the constructor.
Then, write a function to login the user with the Anonymous provider.
Let's also add a TypeScript getter to see if a logged in user is anonymous. This will be useful when displaying content specifically for anonymous users.
STEP 4 - Create a Component
Now we can inject the service into our components to login users anonymously. In this case, we just bind the function to the click event of a button.
STEP 5 - Upgrading the Account
When an anonymous user decides to upgrade, you will need to transfer the account data. The Firebase web API can do this, but you would need to bypass the AngularFire2 package. As an alternative,you can create a new account, then transfer the User's data to it. Assuming your data is nested under a User ID, here's how you could map it to a new account.
This function works by taking a snapshot of the data nested under anonymous ID, then copies it to the new account after the User logs in with google.
That's it for Anonymous Auth. Check out the full article for more details and I'll see you next time.