Firebase Authentication Email in Angular

In this article, we discuss how to set up the sign-up & sign-in using email authentication using firebase in Angular. To set up a firebase Project follow the article. After setup angular project we need to set up the sign-in method email display in the below video.

After setup the sign-in method phone we need to whitelist our domain so the request can process. To add “Authorize Domain”
Demo Login/Register With Your Email in Firebase
Go to Firebase > Select your Project > Authentication > Sign in method > Scroll Down -> Add your domain under ‘Authorize Domain’ section. display in below screenshot.



To setup Authentication Email using firebase first, we need to create a component.
Generate Angular Components


ng g c components/sign-up
ng g c components/verify-email
ng g c components/login
ng g c components/forgot-password
ng g c components/dashboard

After creating the component we need to add-in routing file “app-routing.module.ts”


.....
import { AppComponent } from './app.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { LoginComponent } from './components/login/login.component';
import { SignUpComponent } from './components/sign-up/sign-up.component';
import { ForgotPasswordComponent } from './components/forgot-password/forgot-password.component';
import { VerifyEmailComponent } from './components/verify-email/verify-email.component';
.........
// Routes array define component along with the path name for url
const routes: Routes = [
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'register-user', component: SignUpComponent },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'forgot-password', component: ForgotPasswordComponent },
  { path: 'verify-email-address', component: VerifyEmailComponent }
 
];

After setup the routing we need to create a shared Authentication Service using the below command.


//shared service
ng generate s shared/services/auth

//We need to create a user interface
ng generate interface shared/services/user

user interface class is a schema for User object


export interface User {
   uid: string;
   email: string;
   emailVerified: boolean;
}

In Auth service we need to create functions for the SignUp, SignIn, SetUserData, VerificationMail, ForgotPassword & SignOut display in below code.


import { Injectable,NgZone  } from '@angular/core';
import { User } from "./user";
import { auth } from 'firebase/app';
import { AngularFireAuth } from "@angular/fire/auth";
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Router } from "@angular/router";

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  userData: any;

  constructor(
    public afs: AngularFirestore,   // Inject Firestore service
    public afAuth: AngularFireAuth, // Inject Firebase auth service
    public router: Router,
    public ngZone: NgZone // NgZone service to remove outside scope warning
  ) {

    this.afAuth.authState.subscribe(user => {
      if (user) {
        this.userData = user;
        localStorage.setItem('user', JSON.stringify(this.userData));
        JSON.parse(localStorage.getItem('user'));
      } else {
        localStorage.setItem('user', null);
        JSON.parse(localStorage.getItem('user'));
      }
    });

   }


   SignIn(email, password) {
    return this.afAuth.auth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        this.ngZone.run(() => {
          this.router.navigate(['dashboard']);
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message);
      });
  }


  //sign up function
  SignUp(email, password) {
    return this.afAuth.auth.createUserWithEmailAndPassword(email, password)
      .then((result) => {
        /* Call the SendVerificaitonMail() function when new user sign up and returns promise */
        this.SendVerificationMail();
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message);
      });
  }


  //Verification Mail to user
  SendVerificationMail() {
    return this.afAuth.auth.currentUser.sendEmailVerification()
    .then(() => {
      this.router.navigate(['verify-email-address']);
    });
  }

  //Reset Password Function
  ForgotPassword(passwordResetEmail) {
    return this.afAuth.auth.sendPasswordResetEmail(passwordResetEmail)
    .then(() => {
      window.alert('Password reset email sent, check your inbox.');
    }).catch((error) => {
      window.alert(error);
    });
  }


  //check user login
  get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    return (user !== null && user.emailVerified !== false) ? true : false;
  }

  //set full user data we get
   SetUserData(user) {
    const userRef: AngularFirestoreDocument = this.afs.doc(`users/${user.uid}`);
    const userData: User = {
      uid: user.uid,
      email: user.email,
      emailVerified: user.emailVerified
    }
    return userRef.set(userData, {
      merge: true
    });
  }

  // Sign out function
  SignOut() {

    return this.afAuth.auth.signOut().then(() => {
      localStorage.removeItem('user');
      this.router.navigate(['login']);
    });
    
  }


}

we need to assign “AuthService” to our module file so we can use it in all component where we want to use.


//AuthService 
import { AuthService } from "./shared/services/auth.service";

@NgModule({
  .........
  providers: [AuthService],
  .........
})

components/login Component
Let’s add the code in “LoginComponent.ts” & “LoginComponent.html” display in below code.


<div class="displayTable">
    <div class="displayTableCell">
  
      <div class="displayBlock">
        <h3>Firebase Log In</h3>
        <div class="formGroup">
          <input type="text" class="formControl" placeholder="Username" #userName required>
        </div>
  
        <div class="formGroup">
          <input type="password" class="formControl" placeholder="Password" #userPassword required>
        </div>
  
        <!-- Calling Login In Api from AuthService -->
        <div class="formGroup">
          <input type="button" class="btn btnPrimary" value="Log in" (click)="authService.SignIn(userName.value, userPassword.value)">
        </div>
  
          
  
        <div class="forgotPassword">
          <span routerLink="/forgot-password">Forgot Password?</span>
        </div>
      </div>
  
      <div class="redirectToLogin">
        <span>Don't have an account?<span class="redirect" routerLink="/register-user"> Sign Up</span></span>
      </div>
  
    </div>
  </div>


import { Component, OnInit } from '@angular/core';
import { AuthService } from "../../shared/services/auth.service";


@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(
    public authService: AuthService
  ) { }

  ngOnInit() {
  }

}


components/sign-up Component
Go to sign-up/sign-up.component.html & sign-up/sign-up.component.ts and add the below.


<div class="displayTable">
    <div class="displayTableCell">
  
      <div class="displayBlock">
        <h3>Firebase Sign Up</h3>
  
        <div class="formGroup">
          <input type="email" class="formControl" placeholder="Email Address" #userEmail required>
        </div>
  
        <div class="formGroup">
          <input type="password" class="formControl" placeholder="Password" #userPwd required>
        </div>
  
        <div class="formGroup">
          <input type="button" class="btn btnPrimary" value="Sign Up" (click)="authService.SignUp(userEmail.value, userPwd.value)">
        </div>
  
      
        
      </div>
  
      <div class="redirectToLogin">
        <span>Already have an account? <span class="redirect" routerLink="/login">Log In</span></span>
      </div>
    </div>
  
  </div>


import { Component, OnInit } from '@angular/core';
import { AuthService } from "../../shared/services/auth.service";

@Component({
  selector: 'app-sign-up',
  templateUrl: './sign-up.component.html',
  styleUrls: ['./sign-up.component.css']
})
export class SignUpComponent implements OnInit {

  constructor(
    public authService: AuthService
  ) { }

  ngOnInit() {
  }

}




components/forgot-password Component
Go to forgot-password/forgot-password.component.html & forgot-password/forgot-password.component.ts and add the below.


<div class="displayTable">
    <div class="displayTableCell">
      <div class="displayBlock">
        <h3>Firebase Reset Password</h3>
  
        <p class="text-center">Please enter your email address to request a password reset.</p>
  
        <div class="formGroup">
          <input type="email" class="formControl" placeholder="Email Address" #passwordResetEmail required>
        </div>
  

        <div class="formGroup">
          <input type="submit" class="btn btnPrimary" value="Reset Password" (click)="authService.ForgotPassword(passwordResetEmail.value)">
        </div>
      </div>
  
      <div class="redirectToLogin">
        <span>Go back to ? <span class="redirect" routerLink="/login">Log In</span></span>
      </div>
  
    </div>
  </div>


import { Component, OnInit } from '@angular/core';
import { AuthService } from "../../shared/services/auth.service";


@Component({
  selector: 'app-forgot-password',
  templateUrl: './forgot-password.component.html',
  styleUrls: ['./forgot-password.component.css']
})
export class ForgotPasswordComponent implements OnInit {

  constructor(
    public authService: AuthService

  ) { }

  ngOnInit() {
  }

}


components/verify-email Component
Go to verify-email/verify-email.component.html & verify-email/verify-email.component.ts and add the below.


<div class="displayTable">
    <div class="displayTableCell">
  
      <div class="displayBlock">
        <h3>Thank You for Registering</h3>
  
        <div class="formGroup" *ngIf="authService.userData as user">
          <p class="text-center">We have sent a confirmation email to <strong>{{user.email}}</strong>.</p>
          <p class="text-center">Please check your email and click on the link to verfiy your email address.</p>
        </div>
        
        <div class="formGroup">
          <button type="button" class="btn btnPrimary" (click)="authService.SendVerificationMail()">
            <i class="fas fa-redo-alt"></i>
            Resend Verification Email
          </button>
        </div>
  
      </div>
  
      <div class="redirectToLogin">
        <span>Go back to?<span class="redirect" routerLink="/login"> Sign in</span></span>
      </div>
  
    </div>
  </div>


import { Component, OnInit } from '@angular/core';
import { AuthService } from "../../shared/services/auth.service";


@Component({
  selector: 'app-verify-email',
  templateUrl: './verify-email.component.html',
  styleUrls: ['./verify-email.component.css']
})
export class VerifyEmailComponent implements OnInit {

  constructor(
    public authService: AuthService

  ) { }

  ngOnInit() {
  }

}


Use Route Guards secure routes in Angular
For creating guard run below command.


ng generate guard shared/guard/auth

After creating guard “auth.guard.ts” file we need to add the code below.


import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from "../../shared/services/auth.service";
import { Observable } from 'rxjs';


@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements  CanActivate{
  
  constructor(
    public authService: AuthService,
    public router: Router
  ){ 
    
  }
  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable | Promise | boolean {
    if(this.authService.isLoggedIn !== true) {
      this.router.navigate(['login'])
    }
    return true;
  }
}

In Routing file we need to add the below line


//AuthGuard 
import { AuthGuard } from "../../shared/guard/auth.guard";

In path we need to add " canActivate: [AuthGuard] " without login it will not able to login.
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },

Output display in below Video.

Demo Login/Register With Your Email in Firebase

Spread the love
  •  
  •  
  •  
  •  
  • 2
  • 2
  •  
  •