如何验证 FireAuth 邮件并在 angular 中导航

How to verify FireAuth mail and navigate in angular

我通过使用电子邮件和密码注册然后使用 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);
    });
}

首先,在发送验证 link 时,传递如下 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(['/']);
                }
            })

        })
    }
}