User authentication with Firebase

In this section, we will learn how to implement user authentication using Firebase.

What is Firebase?

Firebase is a managed service provided by Google. Firebase gives us functionality such as analytics, databases, messaging, and crash reporting, so that we can move quickly and focus on our users. You can learn more about the service at https://firebase.com. Now, let's jump right in and implement Firebase in our Angular app.

The first step is to create an account with Google to use the Firebase service. You can use your Google account to log in to Firebase. Once you have successfully created your Firebase account, you should see the following output:

To create a new project, click on the Add Project link.

You will see the following dialog window, prompting you to enter the project's name; in our case, we are making our project name AutoStop:

Note that Google will assign a unique project ID to your project.

Now, click on the Authentication link on the left-hand-side menu to set up user authentication features, which we can embed and set up in our Angular application:

We can do a lot of other cool stuff here, but we will focus on the Authentication module for now.

Now, click on the Sign-in method tab to set up options for how to allow users to sign in to our Angular application:

In the preceding screenshot, you will notice the following important things:

  • Google Firebase provides various options that we can enable, through which we would want users of our application to sign in.
  • We need to enable each provider option individually .
  • We have enabled Email/Password and Google options in our application.
  • In order to enable Facebook, Twitter, and other apps, we will need to enter the developer API keys provided by the respective services.

Now, scroll down a little bit on the page and you will see an option to set up called Authorised Domains.

We will see two default values set up, that is, localhost and a unique subdomain, on the Firebase application, as shown in the following screenshot:

We have made the required changes. Now, we need to set up Google Firebase's app settings. It's time to implement the user authentication in our Angular application.

Prerequisite: We expect users to have an Angular application up and running.

Open the Angular CLI command prompt; we need to install a few modules. We will need to install Angular Fire2 and Firebase first:

Please note that Angular Fire2 is now Angular Fire.

We will need to run the following command to install Angular Fire in our application:

npm install angularfire2

Upon successful execution of the preceding command, we should see the output shown in the following screenshot:

All set. Now, we need to create a service that will handle our authentication functionality:

ng g service appAuth

Using the ng command, we are generating a new service, named appAuth:

Now, it's time to modify the appAuth.service.ts file and add the following code to it:

import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { auth } from 'firebase/app';
import { Router } from '@angular/router';

@Injectable({
providedIn: 'root'
})
export class AppAuthService {

private authUser:any;
private authState:any;
private loggedInUser = false;
private userToken ='';

constructor(public afAuth: AngularFireAuth, private router :Router) { }

login() {
this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider());

this.loggedInUser = true;

this.afAuth.currentUser.getIdToken(true).then(token => this.userToken = token);

this.afAuth.authState.subscribe((auth) => {
this.authState = auth;
});

this.router.navigate(['/profile']);
}

isLoggedInUser(){
if(this.userToken != '')
return true;
else
return false;
}

logout() {
this.afAuth.auth.signOut();
this.loggedInUser = false;
this.userToken = '';
}

}

In the preceding code, we are making changes to the app-auth.service.ts file. The following important points should be noted:

  • We are importing the required classes, namely AngularFireAuth, Auth, and Router, into the service.
  • Using @Injectable, we are specifying that the service is injected at the root level in the Angular tree structure.
  • We are defining a few private variables that we will use across our application.
  • In the constructor method, we are injecting the AngularFireAuth and Router classes.
  • We are defining three methods: Login, Logout, and isLoggedInUser.
  • In the login method, we are using the this.afAuth instance, calling the signInWithPopup method, and passing the auth.GoogleAuthProvider argument, which we get from the Firebase app that we installed locally:
this.afAuth.auth.signInWithPopup(new auth.GoogleAuthProvider());
  • When this method is invoked, a new window will open up, in which we can see the Google sign-in option, using which we can log in to the app.
  • We are setting the this.loggedInUser variable to true.
  • We are setting the logged-in user's token to the this.userToken variable. 
  • We are also subscribing to get the authState response.
  • Finally, using the router instance and using the navigate method, we are redirecting the user to the profile page.
  • Inside the isLoggedInUser method, we are verifying whether the userToken is set or not. userToken will be set if the user has logged in correctly; otherwise, the method will return false.
  • In the logout method, again using the instance of afauth, we are calling the signout method, which will log the user out.
  • Finally, we are setting the userToken to empty.

Awesome. We have done all the heavy lifting in our app-auth.service.ts file. Now, it's time to call these methods in our components: login, profile, and log out.

In the login.component.html file, we will add the following login form:

<div *ngIf="!_appAuthService.loggedInUser">
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">

<label>
First Name:
<input type="text" formControlName="firstName">
</label>

<label>
Last Name:
<input type="text" formControlName="lastName">
</label>

<button>Login</button>

</form>
</div>

In the preceding code, we are just adding an Angular reactive login form using FormGroup and FormControllers.

The output of the login form is shown in the following screenshot:

And in the profile.component.ts file, we are just making a call to the login method:

onSubmit(){
this._appAuthService.login();
console.warn(this.loginForm.value);
}

Now, in the profile.component.ts file, we add a check to see whether the user is logged in or not:

<div *ngIf="_appAuthService.isLoggedInUser">
<p>
profile works!
</p>

User Token is {{_appAuthService.userToken}}
</div>

When the user navigates to the profile page, if they are logged in, they will see the details; otherwise, the user will be redirected to the login page.

Now, on to the final part; we will have a logout link in our app.component.html file:

<nav>
<a routerLink='/login' *ngIf="!_appAuthService.isLoggedInUser()">Login</a>
<a routerLink='/register'>Register</a>
<a routerLink='/logout' *ngIf="_appAuthService.isLoggedInUser()">Logout</a>
</nav>

We are adding links with *ngIf conditions to show the corresponding links when the user is logged in or not:

 ngOnInit() {
this._appAuthService.logout();
this.router.navigate(['/login']);
}

When the user clicks on the logout link, we are calling the logout method of appAuthService and, on successful logout, we are redirecting the user back to the login page.

Now, let's run the app using the ng serve command. We should see the following output:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.100.180