微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

电子邮件已通过AngularFire Guards的验证

如何解决电子邮件已通过AngularFire Guards的验证

我在我的应用程序上注册用户时遇到问题。实际上,用户可以通过“我”选项卡按钮访问其个人资料(如果已登录,否则将被重定向到“登录页面)。 enter image description here

问题在于,注册后,用户无需验证电子邮件即可访问“个人资料”页面。我不知道如何使用emailVerified管道https://github.com/angular/angularfire/blob/master/docs/auth/router-guards.md。谁能告诉我如何执行此操作?

Tabs.routing.module:

const redirectUnauthorizedToLogin = () => redirectUnauthorizedTo(['tabs/login']);
const routes: Routes = [
  {
    path: 'tabs',component: TabsPage,children: [
      {
        path: 'home',loadChildren: () => import('../home/home.module').then(m => m.HomePageModule)
      },{
        path: 'search',loadChildren: () => import('../search/search.module').then(m => m.SearchPageModule)
      },{
        path: 'profile',loadChildren: () => import('../profile/profile.module').then(m => m.ProfilePageModule),...canActivate(redirectUnauthorizedToLogin),},{
        path: 'login',loadChildren: () => import('../login/login.module').then(m => m.LoginPageModule)
      },{
        path: 'registration',loadChildren: () => import('../registration/registration.module').then(m => m.RegistrationPageModule)
      },{
        path: '',redirectTo: '/tabs/home',pathMatch: 'full'
      }
    ]
  },{
    path: '',pathMatch: 'full'
  }
];

身份验证服务:

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

@Injectable({
  providedIn: 'root'
})

export class AuthenticationService {
  userData: any;

  constructor(
    public afStore: AngularFirestore,public ngFireAuth: AngularFireAuth,public router: Router,public ngzone: ngzone 
  ) {
    this.ngFireAuth.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'));
      }
    })
  }

  // Login in with email/password
  SignIn(email,password) {
    return this.ngFireAuth.signInWithEmailAndPassword(email,password)
  }

  // Register user with email/password
  RegisterUser(email,password) {
    return this.ngFireAuth.createuserWithEmailAndPassword(email,password)
  }

  // Email verification when new user register
  SendVerificationMail() {
    return this.ngFireAuth.currentUser.then(u => u.sendEmailVerification())
    .then(() => {
      this.router.navigate(['tabs/verify-email']);
    })
  }

  // Recover password
  PasswordRecover(passwordResetEmail) {
    return this.ngFireAuth.sendPasswordResetEmail(passwordResetEmail)
    .then(() => {
      window.alert('Password reset email has been sent,please check your inBox.');
    }).catch((error) => {
      window.alert(error)
    })
  }

  // Returns true when user is looged in
  get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    return (user !== null && user.emailVerified !== false) ? true : false;
  }

  // Returns true when user's email is verified
  get isEmailVerified(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    return (user.emailVerified !== false) ? true : false;
  }

  // Sign in with Gmail
  GoogleAuth() {
    return this.AuthLogin(new auth.GoogleAuthProvider());
  }

  // Auth providers
  AuthLogin(provider) {
    return this.ngFireAuth.signInWithPopup(provider)
    .then((result) => {
       this.ngzone.run(() => {
          this.router.navigate(['tabs/home']);
        })
      this.SetUserData(result.user);
    }).catch((error) => {
      window.alert(error)
    })
  }

  // Store user in localStorage
  SetUserData(user) {
    const userRef: AngularFirestoreDocument<any> = this.afStore.doc(`users/${user.uid}`);
    const userData: User = {
      uid: user.uid,email: user.email,displayName: user.displayName,photoURL: user.photoURL,emailVerified: user.emailVerified
    }
    return userRef.set(userData,{
      merge: true
    })
  }

  // Sign-out 
  SignOut() {
    return this.ngFireAuth.signOut().then(() => {
      localStorage.removeItem('user');
      this.router.navigate(['tabs/login']);
    })
  }

}

解决方法

如果您需要在用户未经授权或电子邮件未经验证的情况下重定向到不同的路径,您可以使用内部映射。

for (int i = 0; i < array.size(); i++) {
KeyValueSelectedEntity letter = array.get(i);
if (getContext() != null) {
    Chip chip = new Chip(getContext());
    chip.setId(letter.getId());
    chip.setText(letter.getName());
    chip.setTag(i);
    chip.setCheckable(true);
    chip.setCheckedIconVisible(false);
    chip.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton,boolean selected) {
            Log.d(TAG,"onCheckedChanged");
            int tag = (int) compoundButton.getTag();
            ...
}}
,

我刚刚遇到了同样的问题,并设法像这样解决了它。在您的 Tabs.routing.module 文档中,您从 AngularFire 导入 redirectUnauthorizedTo,它默认检查用户是否已登录,而不是用户是否已登录并经过验证。

相反,您可以像这样编写自己的 redirectUnauthorizedTo 函数,称为 redirectUnverifiedTo。

首先,确保导入 emailVerified 而不是 redirectUnauthorizedTo。

import { AngularFireAuthGuard,emailVerified } from '@angular/fire/auth-guard';

然后定义redirectUnverifiedTo。

const redirectUnverifiedTo = (redirect: any[]) => pipe(emailVerified,map(emailVerified => emailVerified || redirect));
const redirectUnauthorizedToLogin = () => redirectUnverifiedTo(['tabs/login']);

终于可以像平常一样使用redirectUnauthorizedToLogin了!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?