, ,

Angular 7/6 Firebase Login with Email & Google / Gmail Account with Reset Password

In this article, we will implement Firebase Authentication service in Angular Application to enable Login/ Registration simply with Email/ Password as well as Google account. We will create a new Angular Project with the current version of CLI 7.2.5. Let’s get started! Create an Angular Project First, create a new Angular Application using ng CLI,…

By.

min read

In this article, we will implement Firebase Authentication service in Angular Application to enable Login/ Registration simply with Email/ Password as well as Google account.

We will create a new Angular Project with the current version of CLI 7.2.5.

Let’s get started!

Create an Angular Project

First, create a new Angular Application using ng CLI, make sure you have installed the latest Angular CLI version installed

$ npm install @angular/cli -g

then run following commands

$ ng new Angular7Firebase
$ cd Angular7Firebase

Integrate Firebase in Angular Application

If you already have Firebase project go with it or follow these steps to get credentials which we will add in our Angular Application.

Step 1) Visit Firebase here then click on Get Started if you have not created an account yet.

Step 2) Click on “Add project” then enter app related information click on “create”

Step 3) Next click on “Web App” icon to get configuration text with app secret info which we will add in our Application to communicate with services related to this Firebase project.

Step 4) As we are going to add Email & Google registration, let’s enable Email authentication by clicking on “Authentication” link on left sidebar then click on “Sign-in method” tab. After that enable the “Email/Password” and “Google” option.

 

Install AngularFire2 in Application

Next, install Firebase and Angular Fire package in the application. Run following npm command in CLI to install the latest version.

$ npm install firebase @angular/fire --save

In app.module.ts file import these packages and also add Firebase project configuration. After adding file will look like this:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { AngularFireModule } from "@angular/fire";
import { AngularFireAuthModule } from "@angular/fire/auth";
import { FormsModule } from '@angular/forms';



var config = {
  apiKey: "AIzaSyADiXXXXXXXXXXXXXXHT-IY",
  authDomain: "ionic-4-fireXXXXXXXXXXeapp.com",
  databaseURL: "https://ionic-4-fireXXXXXXXXXXXXeio.com",
  projectId: "ionic-4-fiXXXXXXXXXXXn",
  storageBucket: "ionic-4-firXXXXXXXXXXXpot.com",
  messagingSenderId: "9253XXXXXXX324"
};

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(config),
    AngularFireAuthModule,
    FormsModule

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Here we have also added FormsModule which is required for using ngModel in the Login/ Registration form. Replace with your Firebase Credentials above.

Firebase Authentication Service

We are creating an Authentication service to connect with Firebase. Run following CLI command.

$ ng generate service service/authentication

In the authentication.service.ts file, we will import Firebase auth service then create some methods like

login: Call signInWithEmailAndPassword method; Send email/ password to firebase to login user if registered.

register: Call createUserWithEmailAndPassword; Send email/ password to firebase and register details if not already registered.

sendEmailVerification: Send a link on registered email for verification.

sendPasswordResetEmail: If a user clicks on Forgot Password, then a link is sent on registered email to reset the password.

logout: Call signOut method to close the session with the current logged in user.

isUserLoggedIn: Local method to check is LocalStorege is having user details.

loginWithGoogle: Call GoogleAuthProvider using signInWithPopup method (Can also be used for Facebook, Twitter, Github Logins as well)

import { Injectable } from '@angular/core';

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

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

  constructor(
    public angularFireAuth: AngularFireAuth,
    public router: Router
  ) {
    this.angularFireAuth.authState.subscribe(userResponse => {
      if (userResponse) {
        localStorage.setItem('user', JSON.stringify(userResponse));
      } else {
        localStorage.setItem('user', null);
      }
    })
  }


  async login(email: string, password: string) {
    return await this.angularFireAuth.auth.signInWithEmailAndPassword(email, password);
  }

  async register(email: string, password: string) {
    return await this.angularFireAuth.auth.createUserWithEmailAndPassword(email, password)
  }

  async sendEmailVerification() {
    return await this.angularFireAuth.auth.currentUser.sendEmailVerification();
  }

  async sendPasswordResetEmail(passwordResetEmail: string) {
    return await this.angularFireAuth.auth.sendPasswordResetEmail(passwordResetEmail);
  }

  async logout() {
    return await this.angularFireAuth.auth.signOut();
  }


  isUserLoggedIn() {
    return JSON.parse(localStorage.getItem('user'));
  }

  async  loginWithGoogle() {
    return await this.angularFireAuth.auth.signInWithPopup(new auth.GoogleAuthProvider())
  }




}

 

Login/ Registration with Email and Google

The final step is to add Login/ Registration HTML and Component code in app.component.html and app.component.ts file. To keep tutorial simple and easy to understand we have not created any new Login/ Register component but real application it is always advisable to have separate components.

Replace following code in app.component.ts file, we are calling method in Authentication service. We have added inline comments to explain method usage.

import { Component } from '@angular/core';
import { AuthenticationService } from './service/authentication.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'firebaseLogin';

  selectedVal: string;
  responseMessage: string = '';
  responseMessageType: string = '';
  emailInput: string;
  passwordInput: string;
  isForgotPassword: boolean;
  userDetails: any;


  constructor(
    private authService: AuthenticationService
  ) {
    this.selectedVal = 'login';
    this.isForgotPassword = false;

  }

  // Comman Method to Show Message and Hide after 2 seconds
  showMessage(type, msg) {
    this.responseMessageType = type;
    this.responseMessage = msg;
    setTimeout(() => {
      this.responseMessage = "";
    }, 2000);
  }

  // Called on switching Login/ Register tabs
  public onValChange(val: string) {
    this.showMessage("", "");
    this.selectedVal = val;
  }

  // Check localStorage is having User Data
  isUserLoggedIn() {
    this.userDetails = this.authService.isUserLoggedIn();
  }

  // SignOut Firebase Session and Clean LocalStorage
  logoutUser() {
    this.authService.logout()
      .then(res => {
        console.log(res);
        this.userDetails = undefined;
        localStorage.removeItem('user');
      }, err => {
        this.showMessage("danger", err.message);
      });
  }

  // Login user with  provided Email/ Password
  loginUser() {
    this.responseMessage = "";
    this.authService.login(this.emailInput, this.passwordInput)
      .then(res => {
        console.log(res);
        this.showMessage("success", "Successfully Logged In!");
        this.isUserLoggedIn();
      }, err => {
        this.showMessage("danger", err.message);
      });
  }

  // Register user with  provided Email/ Password
  registerUser() {
    this.authService.register(this.emailInput, this.passwordInput)
      .then(res => {

        // Send Varification link in email
        this.authService.sendEmailVerification().then(res => {
          console.log(res);
          this.isForgotPassword = false;
          this.showMessage("success", "Registration Successful! Please Verify Your Email");
        }, err => {
          this.showMessage("danger", err.message);
        });
        this.isUserLoggedIn();


      }, err => {
        this.showMessage("danger", err.message);
      });
  }

  // Send link on given email to reset password
  forgotPassword() {
    this.authService.sendPasswordResetEmail(this.emailInput)
      .then(res => {
        console.log(res);
        this.isForgotPassword = false;
        this.showMessage("success", "Please Check Your Email");
      }, err => {
        this.showMessage("danger", err.message);
      });
  }

  // Open Popup to Login with Google Account
  googleLogin() {
    this.authService.loginWithGoogle()
      .then(res => {
        console.log(res);
        this.showMessage("success", "Successfully Logged In with Google");
        this.isUserLoggedIn();
      }, err => {
        this.showMessage("danger", err.message);
      });
  }

}

Add following HTML in the app.component.html file

<div class="row">
  <div class="text-center" style="width: 100%;margin: 20px;">
    <h4>Angular 7 Email/ Password & Google Login Using Firebase Demo</h4>
  </div>
  <div class="" style="width: 500px; margin: auto">

    <div class="card">
      <!-- When Uses is Not Logged In -->
      <div class="card-body" *ngIf="!userDetails">
        <div class="row">
          <div class="col-sm-12 text-center">
            <div class="btn-group">
              <button type="button" class="btn" [ngClass]="{'btn-primary
                active': selectedVal == 'login' }"
                (click)="onValChange('login')"><strong>Login</strong></button>
              <button type="button" class="btn" [ngClass]="{'btn-primary
                active': selectedVal == 'register' }"
                (click)="onValChange('register')"><strong>Register</strong></button>
            </div>

          </div>
        </div>

        <div class="form-group">
          <label for="email">Email</label>
          <input type="email" class="form-control" [(ngModel)]="emailInput"
            id="email" placeholder="Email">
        </div>
        <div class="form-group" *ngIf="!isForgotPassword">
          <label for="password">Password</label>
          <input type="password" class="form-control"
            [(ngModel)]="passwordInput" id="password" placeholder="Password">
        </div>
        <div class="form-group" *ngIf="!isForgotPassword">

          <span *ngIf="selectedVal == 'login'; else elseBlock">
            <button type="button" class="btn btn-primary" (click)="loginUser()">Log
              In</button>
          </span>
          <ng-template #elseBlock>
            <button type="button" class="btn btn-primary"
              (click)="registerUser()">Register</button>
          </ng-template>
          &nbsp;
          &nbsp;
          &nbsp;
          <a href="javascript:void(0)" (click)="this.isForgotPassword= true;">Forgot
            Password?</a>

        </div>
        <div class="form-group" *ngIf="isForgotPassword">

          <button type="button" class="btn" (click)="this.isForgotPassword=
            false;">Cancel</button>
          <button type="button" class="btn btn-primary"
            (click)="forgotPassword()">Get email to reset passowrd</button>
        </div>
        <div class="form-group text-center">
          <img src="../assets/images/googlebtn.png" alt="" srcset=""
            (click)="googleLogin()" style="cursor: pointer;">
        </div>

      </div>

      <!-- When Uses is Logged In using Email or Google Account -->
      <div class="card-body" *ngIf="userDetails">
        <div class="row">
          <div class="col-sm-12">
            <ul class="list-group">
              <li class="list-group-item">Display Name:
                {{userDetails['displayName']}}</li>
              <li class="list-group-item">Email: {{userDetails['email']}}</li>
              <li class="list-group-item">Is Email Varified:
                {{userDetails['emailVerified']}}</li>
              <li class="list-group-item">
                <button type="button" class="btn btn-danger"
                  (click)="logoutUser()">Logout</button>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    <div class="alert alert-{{responseMessageType}}" role="alert"
      *ngIf="responseMessage.length">
      {{responseMessage}}
    </div>
  </div>
</div>

That’s it now you can run the application using $ ng serve –open command in CLI after that it will look like this

 

 

 

3 responses to “Angular 7/6 Firebase Login with Email & Google / Gmail Account with Reset Password”

  1. soleh Avatar
    soleh

    ERROR in ./src/app/app.component.ts
    Module not found: Error: Can’t resolve ‘./app.component.scss’ in ‘C:\Users\soleh\AngularLogin\src\app’
    ** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
    i 「wdm」: Failed to compile.

  2. vico Avatar
    vico

    hi i love your tutorial, its works. but can you tell me how to add guard with this tutorial? i found guard tutorial on your site, but i don’t know how to combine them , i’am newbie please teach me.

Leave a Reply

Your email address will not be published. Required fields are marked *