首页 > 解决方案 > 未注册用户可以登录我的 Firebase 应用

问题描述

我已经实现了一个带有密码和电子邮件输入的登录方法。但即使是未注册的电子邮件也可以登录。有一条警告消息说该电子邮件与数据库中的任何条目都不对应,但我仍然进入主页:

身份验证服务:

login(email, password) {
    return this.afAuth.auth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        this.router.navigate(['/home']);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

登录组件 TS:

 ngOnInit() {
    this.loginForm = this.fb.group({
      email: ['', Validators.required],
      password: ['', Validators.required]
    });

  }
  get email() { return this.loginForm.get('email') }
  get password() { return this.loginForm.get('password') }



  onSubmit() {
    if (this.loginForm.invalid)
      return;

    this.authService.login(this.email.value, this.password.value)
      .then(data => {
        let returnUrl = this.route.snapshot.queryParamMap.get('returnUrl');
        this.router.navigate([returnUrl || '/home']);
        console.log(data)

      }).catch(error => {
        console.log(error)
      })
  }

和 HTML

 <form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
        <div class="form-row">
          <div class="col-md-6">
            <label for="email">Email</label>
            <input type="text" formControlName="email" class="form-control">
            <div *ngIf="email.touched && email.invalid" class="alert alert-danger">
              <div *ngIf="email.errors.required">email is required</div>
            </div>
          </div>
          <div class="col-md-6">
            <label for="password">Password</label>
            <input type="password" formControlName="password" class="form-control">
            <div *ngIf="password.touched && password.invalid" class="alert alert-danger">
              <div *ngIf="password.errors.required">Password is required</div>
            </div>
            <div *ngIf="errorMessage" class="alert alert-danger">
              Username or password is incorrect
            </div>
          </div>
          <div class="col-md-12 text-center">
            <button class="btn btn-primary btn-block text-center" type="submit" style="font-weight:bold">Log in</button>
          </div>
        </div>
      </form>

有什么遗漏吗?为什么用户没有被屏蔽?

标签: angularfirebasefirebase-authentication

解决方案


您正在捕获内部错误authService.login,因此从外部函数的角度来看,它不再是错误,即使登录失败, .thenin也会运行。onSubmit

只需删除.catchin authService.login(如果警报仅用于测试)或添加throw error如下window.alert

login(email, password) {
    return this.afAuth.auth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        this.router.navigate(['/home']);
      }).catch((error) => {
        window.alert(error.message)
        throw error // <<< Rethrow! Otherwise, the error won't make it to the outside!
      })
  }

推荐阅读