如何验证FireAuth邮件并按角度导航

问题描述

我已经通过使用电子邮件密码进行注册,然后使用sendEmailVerification()fireAuth来创建用户。我收到了邮件...现在,仅在验证邮件之后才需要输入我的应用程序...。 。在Angular中

authService.ts:

 createuser(user) {
  console.log(user);
  this.afAuth.createuserWithEmailAndPassword( user.email,user.password)
    .then( userCredential => {
      this.newUser = user;
      console.log(userCredential);
      userCredential.user.sendEmailVerification();
      this.router.navigate(['/account/verify']);
      userCredential.user.updateProfile( {
        displayName: user.firstName + ' ' + user.lastName
      });

      this.insertUserData(userCredential)
        .then(() => {
          console.log('the result:',userCredential)
          
        });
    })
    .catch( error => {
      this.eventAuthError.next(error);
    });
}

解决方法

首先,在发送验证链接的同时,传递如下所示的actionCodesettings,以便您可以在成功验证电子邮件时提供重定向URL(项目的URL)。

 createUser(user) {
  console.log(user);
  this.afAuth.createUserWithEmailAndPassword( user.email,user.password)
    .then( userCredential => {
      this.newUser = user;
      console.log(userCredential);
      var actionCodeSettings = {
                url: `${your-project-base-url}/account/verify`
            }
      userCredential.user.sendEmailVerification(actionCodeSettings);
      userCredential.user.updateProfile( {
        displayName: user.firstName + ' ' + user.lastName
      });

      this.insertUserData(userCredential)
        .then(() => {
          console.log('the result:',userCredential)
          
        });
    })
    .catch( error => {
      this.eventAuthError.next(error);
    });
}

现在,为了保护您的应用程序路由,您可以实施保护措施。一个工作警卫的例子如下:

import { Injectable } from '@angular/core';
import { CanActivate,ActivatedRouteSnapshot,RouterStateSnapshot,UrlTree,Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AngularFireAuth } from "@angular/fire/auth";

import { AccountPathNameService } from '../../../shared/services';
@Injectable({
    providedIn: 'root'
})
export class VerifyEmailGuard implements CanActivate {

    constructor(
        private router: Router,public angularfireAuthentication: AngularFireAuth,) {
    }
    canActivate(
        next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
        return new Promise((resolve,reject) => {
            this.angularfireAuthentication.authState.subscribe(user => {
                if (user) {
                    if (user.emailVerified) {
                        resolve(false);
                        
              this.router.navigate([`${your-protected-route-eg.dashboard}`]);
                    } else {
                        resolve(true);
                    }
                } else {
                    resolve(false);
                    this.router.navigate(['/']);
                }
            })

        })
    }
}