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.
components/sign-up Component
Go to sign-up/sign-up.component.html & sign-up/sign-up.component.ts and add the below.
components/forgot-password Component
Go to forgot-password/forgot-password.component.html & forgot-password/forgot-password.component.ts and add the below.
components/verify-email Component
Go to verify-email/verify-email.component.html & verify-email/verify-email.component.ts and add the below.
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
2 2